diff --git a/.gitignore b/.gitignore index 5c74f0592..194eb2922 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,16 @@ uv.lock.tmp # Local build outputs (e.g. make generate-books-manifest → build/books-manifest.json) build/ +# Node / Turborepo (site lives under apps/site) +node_modules/ +.turbo/ +**/.next/ +**/out/ +apps/site/data/build-manifest-lock.json +npm-debug.log* +yarn-debug.log* +yarn-error.log* + # Portfolio-audit snapshots (regenerate per docs/portfolio-audit/data/README.md) docs/portfolio-audit/data/books-manifest.json docs/portfolio-audit/data/semantic-manifest.json diff --git a/.npmrc b/.npmrc new file mode 100644 index 000000000..394374ec5 --- /dev/null +++ b/.npmrc @@ -0,0 +1,2 @@ +# Workspace installs for apps/site + future packages. +fund=false diff --git a/README.md b/README.md index cce2f486b..4baf386c2 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,29 @@ # After Certainty +This repository is the **corpus and publishing** home for After Certainty. It also hosts the public website under [`apps/site/`](apps/site/) (imported from [`ksteffe/after-certainty-site`](https://github.com/ksteffe/after-certainty-site); see the [monorepo migration plan](docs/roadmaps/monorepo-migration-plan.md)). + +**Corpus layout is unchanged:** books and semantic YAML stay at the repository root. The site is a workspace app; production still deploys from the standalone site repository until a later migration phase. + +## Toolchains + +| Area | Tooling | Common commands | +|------|---------|-----------------| +| Corpus / semantic / publishing | Python 3.12+, [uv](https://github.com/astral-sh/uv), Make | `uv sync --frozen` · `make check` · `make generate-semantic-manifest` | +| Website (`apps/site`) | Node 20+, npm workspaces, thin [Turborepo](https://turbo.build) | `npm ci` · `npm run site:dev` · `npm run site:test` · `npm run site:lint` | + +From the repo root after both installs: + +```bash +uv sync --frozen # corpus +npm ci # site workspace +npm run site:dev # Next.js (still uses remote/fallback semantic manifest in Phase 1) +make generate-semantic-manifest # local corpus artifact under build/ +``` + +Phase notes: [`docs/migrations/monorepo-phase-0/`](docs/migrations/monorepo-phase-0/) · [`docs/migrations/monorepo-phase-1/`](docs/migrations/monorepo-phase-1/). + +## Books and publishing + This repository holds **several independent books** as parallel projects under [`books/`](books/): each publishable manuscript folder includes an `index.md` plus a `book.yml` spec. They share **one publishing pipeline**—local Make targets and a GitHub Actions workflow—that assembles each enabled book into **DOCX**, **EPUB**, and **PDF** for distribution. ## Publishing pipeline diff --git a/apps/site/.cursor/rules/git-workflow.md b/apps/site/.cursor/rules/git-workflow.md new file mode 100644 index 000000000..a51a34c26 --- /dev/null +++ b/apps/site/.cursor/rules/git-workflow.md @@ -0,0 +1,96 @@ +# Git Workflow Rules + +## MANDATORY: Always Use Feature Branches + +**NEVER commit directly to `main` branch.** + +### Before Making Any Changes + +1. **Check current branch:** + + ```bash + git branch --show-current + ``` + +2. **If on `main`, create a feature branch immediately:** + ```bash + git checkout -b cursor/-bb0e + ``` + +### Branch Naming Convention + +**Required format:** `cursor/-bb0e` + +**Examples:** + +- `cursor/add-json-ld-api-bb0e` +- `cursor/fix-relationship-arrows-bb0e` +- `cursor/update-footer-metadata-bb0e` + +**Rules:** + +- Prefix: Always start with `cursor/` +- Suffix: Always end with `-bb0e` +- Description: Use kebab-case (lowercase with hyphens) +- Be descriptive: Name should indicate the feature/fix + +### Workflow Steps + +1. **Create branch** from `main`: + + ```bash + git checkout main + git pull origin main + git checkout -b cursor/-bb0e + ``` + +2. **Make changes and commit frequently:** + + ```bash + git add + git commit -m "feat: description" + ``` + +3. **Push to feature branch:** + + ```bash + git push -u origin cursor/-bb0e + ``` + +4. **Create Pull Request:** + - Use `ManagePullRequest` tool + - Base branch: `main` + - Create as draft by default + - Include detailed description + +5. **After approval, merge via GitHub UI** + +### Pre-Commit Checklist + +Before ANY git commit: + +- [ ] Confirm not on `main` branch +- [ ] Branch name follows `cursor/*-bb0e` pattern +- [ ] Changes are tested (tests passing) +- [ ] Build succeeds +- [ ] Commit message follows conventional commits format + +### Emergency Direct Commits to Main + +**Only allowed for:** + +- Critical security hotfixes (with immediate notification) +- Deployment configuration emergencies +- **Must be discussed with team first** + +### Enforcement + +This rule is enforced by: + +1. Cursor agent reading this file before any git operations +2. Manual verification before each commit +3. Branch protection rules on GitHub (if configured) + +--- + +**Last Updated:** 2026-07-06 diff --git a/apps/site/.cursor/skills/ga-trends/SKILL.md b/apps/site/.cursor/skills/ga-trends/SKILL.md new file mode 100644 index 000000000..6360a192b --- /dev/null +++ b/apps/site/.cursor/skills/ga-trends/SKILL.md @@ -0,0 +1,159 @@ +--- +name: ga-trends +description: >- + Pulls Google Analytics 4 trend reports for After Certainty via the analytics + MCP (user-analytics-mcp). Use when the user asks for GA trends, traffic + updates, analytics reports, weekly metrics, or to run a regular analytics + check. +--- + +# GA4 trends (After Certainty) + +## Prerequisites + +- MCP server: `user-analytics-mcp` (Google `analytics-mcp`) +- Read tool schemas under `mcps/user-analytics-mcp/tools/` before calling +- **Property ID for reports:** `properties/497528828` (not measurement ID `G-H7FSEF4WLW`) +- Timezone in reports: America/Denver + +If MCP auth fails, tell the user to run `gcloud auth application-default login` (ADC expires after ~7 days in testing mode). + +## When the user runs this skill + +1. **Batch all `run_report` / `run_realtime_report` calls in one parallel tool batch** (do not serialize). +2. Use date range **`7daysAgo` → `today`** for weekly trends unless the user asks otherwise. +3. For week-over-week comparison, add a second range **`14daysAgo` → `8daysAgo`** with empty `dimensions` (GA returns a `dateRange` column automatically). +4. If a report returns **zero rows**, retry the same query with `end_date: "today"` (excluding today often yields empty data on low-traffic properties). + +## Standard report pack + +Run these every time unless the user narrows scope: + +| # | Report | Tool | Purpose | +|---|--------|------|---------| +| 1 | Overview + WoW | `run_report` | sessions, users, page views, engagement | +| 2 | Daily trend | `run_report` | `date` dimension | +| 3 | Channels | `run_report` | `sessionDefaultChannelGroup` | +| 4 | Top pages | `run_report` | `pagePath`, limit 15 | +| 5 | Events | `run_report` | `eventName`, limit 25 | +| 6 | Devices | `run_report` | `deviceCategory` | +| 7 | Geography | `run_report` | `country`, limit 10 | +| 8 | Realtime pulse | `run_realtime_report` | active users + top screens | +| 9 | Device OS | `run_report` | `deviceCategory` + `operatingSystem` (you vs not you) | +| 10 | Mobile models | `run_report` | `mobileDeviceBranding` + `mobileDeviceModel` (mobile only) | +| 11 | Session source | `run_report` | `sessionSourceMedium` (Facebook, Vercel, Tag Assistant) | + +Exact JSON arguments: [reports.md](reports.md) + +## Estimated you vs not you + +Run reports **9–11** every time. Compute from **sessions** (not users). This is a **heuristic** until GA4 **internal traffic** (IP) is configured in Admin. + +**Owner device profile** (default for After Certainty): Macintosh desktop + iPhone (model often missing; treat `iPhone 13` when present as a strong “you” signal). + +### Inputs (from reports) + +| Input | How to read | +|-------|-------------| +| `total` | Sessions from overview (Last7Days) | +| `definite_not_you` | Sum sessions where `operatingSystem` is **Android**, **Linux**, or **Windows** (report 9) | +| `mac_ios_pool` | Sum sessions where OS is **Macintosh** or **iOS** (report 9) | +| `social_referral` | Sum sessions where `sessionSourceMedium` contains `facebook.com` or `m.facebook.com` (report 11) | +| `tooling_you` | Sum sessions where source is `vercel.com` or `tagassistant.google.com` (report 11) | +| `iphone13_you` | Sessions with `mobileDeviceModel` = `iPhone 13` (report 10) | +| `macintosh_sessions` | Sessions with `operatingSystem` = `Macintosh` (report 9) | + +### Estimates + +1. **Floor — definitely not you:** `definite_not_you` (wrong OS for Mac + iPhone). +2. **You signals (additive, cap at `mac_ios_pool`):** + `you_signals = tooling_you + iphone13_you + round(macintosh_sessions × 0.65)` + (`0.65` = default share of Mac desktop sessions attributed to the site owner; not precise.) +3. **Middle — estimated you:** `you_mid = min(mac_ios_pool, you_signals)` + **Middle — estimated not you:** `not_you_mid = total - you_mid` +4. **Range (show all three):** + - **Low not you / high you:** `not_you_low = definite_not_you`, `you_high = total - not_you_low` + - **High not you / low you:** `not_you_high = definite_not_you + social_referral`, `you_low = total - not_you_high` + (Facebook overlap with mobile OS is possible; note in output.) + - **Middle:** use step 3. + +Always state that **GA does not label “you”** without internal traffic; recommend **Admin → Data streams → Define internal traffic** for a definitive split. + +Call out in the block: generic **iPhone** (no model) may still be the owner; **Nexus 5X** / **Linux** are usually bots or cloud, not readers. + +## Custom events to highlight + +After consent, the site sends (see `lib/analytics/events.ts`): + +| Event | Meaning | +|-------|---------| +| `select_content` | Observatory focus / entity engagement (`content_type`, `item_id`, `method`) | +| `file_download` | Book EPUB/PDF/DOCX | +| `click` | Outbound CTA (`outbound: true`, `location`, `platform`) | +| `generate_lead` | Newsletter (future) | + +In the events report, call out whether these appear. Absence usually means low traffic, consent denied, or non-production. + +## Optional deep dives (user must ask or say "full") + +- **28-day totals:** `28daysAgo` → `today`, no dimensions +- **Explore/Observatory:** filter `pagePath` contains `/explore` or events `select_content` +- **Funnel:** `run_funnel_report` — home → explore → select_content (see reports.md) +- **Conversions:** `run_conversions_report` if key events are marked in GA4 Admin + +## Output template + +Deliver a single markdown brief: + +```markdown +# GA trends — After Certainty +**Property:** properties/497528828 · **Range:** [dates] · **Pulled:** [today] + +## Headline +[1–2 sentences: up/down/flat vs prior week, caveats if all traffic is one day] + +## Overview +| Metric | This period | Prior period (if any) | +|--------|------------:|----------------------:| + +## Daily +| Date | Sessions | Users | Page views | + +## Channels / Pages / Events +[tables] + +## Estimated you vs not you +Heuristic only (owner devices: Mac + iPhone). Configure internal traffic in GA4 for a definitive split. + +| | Sessions | % of total | +|---|----------:|-----------:| +| **Definitely not you** (Android / Linux / Windows) | N | % | +| Mac + iOS pool (mixed) | N | % | +| — Tooling (Vercel, Tag Assistant) | N | | +| — iPhone 13 (model reported) | N | | +| **Estimated you (middle)** | N | % | +| **Estimated not you (middle)** | N | % | + +Range: not you **low**–**high** = [definite_not_you] – [definite_not_you + social_referral]; you the complement. + +Device/OS table + top `sessionSourceMedium` rows. One-line caveat on overlap and iPhone model masking. + +## Realtime +Active users now: N + +## Notes +- Consent / custom events / data quality caveats +- Suggested follow-ups (1–3 bullets) +``` + +## Interpretation guardrails + +- **Low volume:** do not over-interpret single-day spikes; say when the entire window is one date. +- **Channel totals** can exceed session counts (attribution quirks); prefer sessions for channel ranking. +- **Unassigned** channel often means missing UTM / direct app traffic — note, don't panic. +- **Engagement rate** near 0 with few sessions is noisy. +- **You vs not you:** never present the middle estimate as exact; show the range and recommend internal-traffic IP filters. iPhone model is often `(not set)` or generic `iPhone` even for the owner's device. + +## Property discovery + +Only run `get_account_summaries` if property ID is unknown or user asks about accounts. Default to `properties/497528828`. diff --git a/apps/site/.cursor/skills/ga-trends/reports.md b/apps/site/.cursor/skills/ga-trends/reports.md new file mode 100644 index 000000000..4b8fc01bc --- /dev/null +++ b/apps/site/.cursor/skills/ga-trends/reports.md @@ -0,0 +1,261 @@ +# GA4 MCP report payloads + +Property: `properties/497528828` + +Copy these into `CallMcpTool` with `server: "user-analytics-mcp"`. + +## 1. Overview + week-over-week + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [ + { "start_date": "7daysAgo", "end_date": "today", "name": "Last7Days" }, + { "start_date": "14daysAgo", "end_date": "8daysAgo", "name": "Prior7Days" } + ], + "dimensions": [], + "metrics": [ + "sessions", + "activeUsers", + "totalUsers", + "newUsers", + "screenPageViews", + "engagedSessions", + "engagementRate", + "averageSessionDuration", + "eventCount" + ] + } +} +``` + +Rows include `dateRange` = `Last7Days` / `Prior7Days` when both ranges have data. + +## 2. Daily trend + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [{ "start_date": "7daysAgo", "end_date": "today", "name": "Last7Days" }], + "dimensions": ["date"], + "metrics": ["sessions", "activeUsers", "screenPageViews"], + "order_bys": [{ "dimension": { "dimension_name": "date", "order_type": 1 }, "desc": false }] + } +} +``` + +Format `YYYYMMDD` dates as `YYYY-MM-DD` in the output table. + +## 3. Channels + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [{ "start_date": "7daysAgo", "end_date": "today", "name": "Last7Days" }], + "dimensions": ["sessionDefaultChannelGroup"], + "metrics": ["sessions", "activeUsers", "engagedSessions"], + "order_bys": [{ "metric": { "metric_name": "sessions" }, "desc": true }], + "limit": 10 + } +} +``` + +## 4. Top pages + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [{ "start_date": "7daysAgo", "end_date": "today", "name": "Last7Days" }], + "dimensions": ["pagePath"], + "metrics": ["screenPageViews", "activeUsers"], + "order_bys": [{ "metric": { "metric_name": "screenPageViews" }, "desc": true }], + "limit": 15 + } +} +``` + +## 5. Events + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [{ "start_date": "7daysAgo", "end_date": "today", "name": "Last7Days" }], + "dimensions": ["eventName"], + "metrics": ["eventCount"], + "order_bys": [{ "metric": { "metric_name": "eventCount" }, "desc": true }], + "limit": 25 + } +} +``` + +## 6. Devices + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [{ "start_date": "7daysAgo", "end_date": "today", "name": "Last7Days" }], + "dimensions": ["deviceCategory"], + "metrics": ["sessions", "activeUsers"], + "order_bys": [{ "metric": { "metric_name": "sessions" }, "desc": true }] + } +} +``` + +## 7. Geography + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [{ "start_date": "7daysAgo", "end_date": "today", "name": "Last7Days" }], + "dimensions": ["country"], + "metrics": ["sessions", "activeUsers"], + "order_bys": [{ "metric": { "metric_name": "sessions" }, "desc": true }], + "limit": 10 + } +} +``` + +## 9. Device OS (you vs not you) + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [{ "start_date": "7daysAgo", "end_date": "today", "name": "Last7Days" }], + "dimensions": ["deviceCategory", "operatingSystem"], + "metrics": ["sessions", "activeUsers"], + "order_bys": [{ "metric": { "metric_name": "sessions" }, "desc": true }], + "limit": 25 + } +} +``` + +## 10. Mobile device models (you vs not you) + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [{ "start_date": "7daysAgo", "end_date": "today", "name": "Last7Days" }], + "dimensions": ["deviceCategory", "mobileDeviceBranding", "mobileDeviceModel"], + "metrics": ["sessions", "activeUsers"], + "dimension_filter": { + "filter": { + "field_name": "deviceCategory", + "string_filter": { "match_type": 2, "value": "mobile", "case_sensitive": true } + } + }, + "order_bys": [{ "metric": { "metric_name": "sessions" }, "desc": true }], + "limit": 20 + } +} +``` + +## 11. Session source / medium (you vs not you) + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [{ "start_date": "7daysAgo", "end_date": "today", "name": "Last7Days" }], + "dimensions": ["sessionSourceMedium"], + "metrics": ["sessions", "activeUsers"], + "order_bys": [{ "metric": { "metric_name": "sessions" }, "desc": true }], + "limit": 15 + } +} +``` + +## 8. Realtime + +```json +{ + "toolName": "run_realtime_report", + "arguments": { + "property_id": "properties/497528828", + "dimensions": [], + "metrics": ["activeUsers", "eventCount"] + } +} +``` + +Optional top screens: + +```json +{ + "toolName": "run_realtime_report", + "arguments": { + "property_id": "properties/497528828", + "dimensions": ["unifiedScreenName"], + "metrics": ["activeUsers"], + "order_bys": [{ "metric": { "metric_name": "activeUsers" }, "desc": true }], + "limit": 10 + } +} +``` + +## Optional: 28-day rollup + +```json +{ + "toolName": "run_report", + "arguments": { + "property_id": "properties/497528828", + "date_ranges": [{ "start_date": "28daysAgo", "end_date": "today", "name": "Last28Days" }], + "dimensions": [], + "metrics": ["sessions", "activeUsers", "screenPageViews", "eventCount"] + } +} +``` + +## Optional: Explore page filter + +Filter pages under `/explore` using `dimension_filter`: + +```json +{ + "filter": { + "field_name": "pagePath", + "string_filter": { "match_type": 6, "value": "/explore", "case_sensitive": false } + } +} +``` + +(`match_type` 6 = CONTAINS in the Data API enum.) + +## Optional: select_content only + +```json +{ + "filter": { + "field_name": "eventName", + "string_filter": { "match_type": 2, "value": "select_content", "case_sensitive": true } + } +} +``` + +## Alternate ranges + +| User asks | `date_ranges` | +|-----------|----------------| +| Last 30 days | `30daysAgo` → `today` | +| Yesterday only | `yesterday` → `yesterday` | +| This month | `YYYY-MM-01` → `today` | +| Custom | ISO dates with `name` label | diff --git a/apps/site/.cursor/skills/refresh-manifest/SKILL.md b/apps/site/.cursor/skills/refresh-manifest/SKILL.md new file mode 100644 index 000000000..422b29b7e --- /dev/null +++ b/apps/site/.cursor/skills/refresh-manifest/SKILL.md @@ -0,0 +1,262 @@ +--- +name: refresh-manifest +description: >- + Pull the latest semantic-manifest.json from the after-certainty content + repository release and update the bundled fallback. Use when manifest + changes are deployed upstream and need to be synced to the site repo. +--- + +# Refresh Semantic Manifest + +## Purpose + +Sync the bundled [`data/semantic-manifest.json`](../../data/semantic-manifest.json) +with the latest release from `ksteffe/after-certainty`. + +Upstream schema and rollout are documented in +[semantic-thinkers-sources-migration.md](https://github.com/ksteffe/after-certainty/blob/main/docs/semantic-thinkers-sources-migration.md) +(landed in [after-certainty#252](https://github.com/ksteffe/after-certainty/pull/252)). + +## Prerequisites + +- GitHub CLI (`gh`) authenticated +- Write access to the site repo +- Node dependencies installed (`npm ci`) + +## When to use this skill + +Use when: + +- The user asks to "refresh the manifest" or "pull latest semantic manifest" +- Upstream content changes have been published to the after-certainty repo +- You need to sync the bundled fallback with production data +- Enriched sources (`creatorSlugs`) or manifest v2 `thinkers[]` have shipped upstream + +## Manifest versions (what to expect) + +| Version | `manifestVersion` | `schemaVersion` | Typical upstream state | +| -------- | ----------------- | --------------- | -------------------------------------------------------------- | +| Legacy | `1` or absent | absent | Pre-enrichment sources | +| v1.5 | `1` | absent / early | Enriched `sources[]` | +| v2 | `2` | `2.1`–`2.2` | Thinkers + discovery collections | +| **v2.3** | `2` | **`2.3`** | Roles, grounding, chapter enrichment — **intended production** | + +Prefer `npm run sync:semantic-manifest` (alias `sync:semantic-manifest-fallback`). +Production ISR fetches the release URL; the bundled file is the offline/CI fallback. +After sync, `data/intended-manifest-release.json` pins release identity for parity checks. + +Optional v1.5 source fields the site consumes: `sourceKind`, `creatorNames`, `creatorSlugs`, `title`, `citation`, `year`, `publisher`, `institution`, `url`, `whyThisMatters`. Legacy `name`, `type`, and `summary` remain required fallbacks. + +## Steps + +### 1. Fetch latest release asset + +```bash +gh release download latest \ + --repo ksteffe/after-certainty \ + --pattern "semantic-manifest.json" \ + --dir /tmp \ + --clobber +``` + +If this fails, check: + +- GitHub CLI authentication (`gh auth status`) +- Repository exists and is accessible +- Release `latest` exists with the manifest asset + +### 2. Validate the downloaded manifest + +```bash +jq empty /tmp/semantic-manifest.json +``` + +If invalid JSON, stop and report — check the release manually on GitHub. + +### 3. Compare manifest metadata and graph counts + +Capture baseline from the bundled file, then compare against the download: + +```bash +manifest_stats() { + jq '{ + manifestVersion: (.manifestVersion // 1), + generatedAt, + sources: (.sources | length), + enrichedSources: ([.sources[]? | select((.creatorSlugs // []) | length) > 0)] | length), + thinkers: ((.thinkers // []) | length), + relationships: (.relationships | length), + concepts: (.glossary | length), + patterns: (.patterns | length), + books: (.books | length) + }' "$1" +} + +echo "=== Bundled (current) ===" +manifest_stats data/semantic-manifest.json +echo "=== Upstream (latest release) ===" +manifest_stats /tmp/semantic-manifest.json +``` + +**Sanity checks before replacing:** + +- `manifestVersion` should be `1` or `2` (not a higher unexpected value). +- If the site already ships enriched UI, `enrichedSources` should not drop to zero unless upstream intentionally reverted enrichment. +- When upstream adds `semantic/thinkers/` YAML, expect `manifestVersion: 2` and `thinkers > 0`. +- `generatedAt` on the download should generally be newer than the bundled copy. + +Optionally diff relationship predicates: + +```bash +jq -r '.relationships[].relationship' /tmp/semantic-manifest.json | sort -u > /tmp/new-types.txt +jq -r '.relationships[].relationship' data/semantic-manifest.json | sort -u > /tmp/old-types.txt +comm -13 /tmp/old-types.txt /tmp/new-types.txt +``` + +### 4. Validate against site Zod schema (required) + +Run manifest tests **before** committing. This catches upstream fields the site schema does not yet accept: + +```bash +cp /tmp/semantic-manifest.json data/semantic-manifest.json +npm test -- lib/graph/manifest.test.ts +``` + +If tests fail: + +- Read the Zod error output — it names the failing path (e.g. `sources[12].url`, `thinkers[0].type`). +- Compare the offending entry in `/tmp/semantic-manifest.json` with [`lib/graph/schemas.ts`](../../lib/graph/schemas.ts). +- If upstream added a valid field the site should accept, extend the schema and add a test in [`lib/graph/manifest.test.ts`](../../lib/graph/manifest.test.ts) in a separate PR — do not commit a bundled manifest that fails validation. +- If upstream data is malformed, stop and report to the content repo; restore the previous bundled file if you already copied. + +### 5. Commit and push + +Only after step 4 passes: + +```bash +git add data/semantic-manifest.json +git commit -m "Update semantic manifest from upstream release + +- manifestVersion: [OLD] → [NEW] +- Enriched sources: [OLD] → [NEW] +- Thinkers: [OLD] → [NEW] +- Relationships: [OLD] → [NEW] +- Source: ksteffe/after-certainty@latest" +git push -u origin $(git branch --show-current) +``` + +Use a feature branch named `cursor/refresh-manifest-76be` (or similar) — do not commit directly to `main`. + +## Output template + +Report to the user: + +```markdown +✅ Semantic manifest updated successfully + +**Manifest:** + +- manifestVersion: [OLD] → [NEW] +- generatedAt: [OLD] → [NEW] + +**Graph counts:** + +- Sources: [OLD] → [NEW] (enriched with creatorSlugs: [OLD] → [NEW]) +- Thinkers: [OLD] → [NEW] +- Relationships: [OLD] → [NEW] ([+/-N]) + +**New relationship types (if any):** + +- [list any new predicates] + +**Tests:** `npm test -- lib/graph/manifest.test.ts` — passed + +**Commit:** [SHA] + +**Next steps:** + +1. Spot-check `/explore/sources`, `/explore/thinkers`, and a book detail page locally +2. Run broader tests if relationship types changed: `npm test` +3. Deploy when ready; production ISR fetches the release URL (bundled is dev/offline fallback) +``` + +## Post-update verification + +After replacing the bundled manifest: + +| Area | What to check | +| -------------- | ------------------------------------------------------------------------------------------------------------- | +| Sources index | `/explore/sources` loads; enriched cards show citation/title when present | +| Thinkers index | `/explore/thinkers` lists derived or explicit thinkers | +| Thinker detail | e.g. `/explore/thinkers/john-dewey` — works list and JSON-LD | +| Book pages | Thinkers section vs research sources split on enriched books | +| Stale ISR | [`pickSemanticGraph()`](../../lib/graph/manifest.ts) prefers bundled when remote lacks enrichment or is older | + +With offline dev: + +```bash +SEMANTIC_MANIFEST_OFFLINE=1 npm run dev +``` + +E2E smoke (optional): + +```bash +SEMANTIC_MANIFEST_OFFLINE=1 npx playwright test e2e/thinkers.spec.ts e2e/navigation.spec.ts +``` + +## Notes + +- This skill only updates the **bundled fallback** at `data/semantic-manifest.json`. +- Prefer the npm script when available: `npm run sync:semantic-manifest`. +- Production deployments fetch from the GitHub release URL via ISR (see [`lib/graph/manifest.ts`](../../lib/graph/manifest.ts)). +- The bundled manifest ensures dev/offline mode and CI have latest data when `SEMANTIC_MANIFEST_OFFLINE=1`. +- Selection is remote-first; see [`docs/semantic-manifest.md`](../../docs/semantic-manifest.md). +- v1 manifests without `thinkers[]` are valid — the site calls `deriveThinkersFromSources()` when sources have `creatorSlugs`. +- If new **relationship** types are added, you may also need to: + - Add visual styling in `lib/graph/relationshipVisuals.ts` + - Classify in taxonomy at `lib/graph/relationshipTaxonomy.ts` + - Add test coverage + +## Troubleshooting + +**"release not found"** + +- Check that the `latest` release exists: `gh release list --repo ksteffe/after-certainty` +- If using a specific tag, replace `latest` with that tag + +**"asset not found"** + +- Verify the release contains `semantic-manifest.json`: `gh release view latest --repo ksteffe/after-certainty` +- The asset name must match exactly (case-sensitive) + +**JSON validation fails (`jq empty`)** + +- The upstream file may be truncated or corrupted +- Re-download or inspect the release on GitHub web UI + +**`npm test -- lib/graph/manifest.test.ts` fails (Zod validation)** + +- Bundled manifest failed [`semanticGraphSchema`](../../lib/graph/schemas.ts) — do not commit +- Common causes: invalid `url` on a source, unknown `thinker.type`, malformed `sourceKind` +- Fix upstream in after-certainty, or extend the site schema if the upstream shape is intentional +- Restore previous bundle: `git checkout -- data/semantic-manifest.json` + +**Enriched source count dropped unexpectedly** + +- Upstream may have regressed metadata — compare a few known slugs (e.g. `john-dewey` sources) +- Check whether `creatorSlugs` backfill ran in the content repo + +**Thinkers index empty but sources are enriched** + +- Expected for v1 manifests — thinkers are derived at runtime from `creatorSlugs` +- If `manifestVersion: 2` and `thinkers` is empty, upstream thinker YAML may not have shipped yet + +**Merge conflicts** + +- If the bundled manifest has local changes, resolve manually +- Prefer upstream release content unless local changes were intentional experiments + +**Site shows stale thinker/source data in production but bundled is current** + +- ISR may be serving an older remote release — bundled fallback logic in `pickSemanticGraph()` only applies when remote is poorer +- Trigger cache revalidation via the site's revalidate route or wait for `SEMANTIC_MANIFEST_REVALIDATE_SECONDS` diff --git a/apps/site/.env.example b/apps/site/.env.example new file mode 100644 index 000000000..39f5ebc21 --- /dev/null +++ b/apps/site/.env.example @@ -0,0 +1,43 @@ +# Copy to `.env.local` and fill in secret values. `.env.local` is gitignored. + +# Public site URL — canonical links, Open Graph, RSS, JSON-LD (`NEXT_PUBLIC_SITE_URL`). +# Production (example): https://www.after-certainty.com +# Local dev — optional; metadata falls back to http://localhost:3000 if unset. +NEXT_PUBLIC_SITE_URL=http://localhost:3000 + +# Podcast — server-side RSS fetch for `/podcast` (ISR ~1h). Falls back to `data/podcast-episodes.json` if unset or unreachable. +PODCAST_RSS_URL= + +# On-demand cache refresh — POST /api/cache/revalidate with `Authorization: Bearer `. +# Revalidates podcast RSS and semantic graph manifest fetches. Set in production only. +# CACHE_REVALIDATE_SECRET= + +# Semantic graph — server-side fetch of `semantic-manifest.json` from GitHub releases (ISR). See `lib/graph/manifest.ts`. +# SEMANTIC_MANIFEST_URL= +# SEMANTIC_MANIFEST_REVALIDATE_SECONDS=3600 +# SEMANTIC_MANIFEST_OFFLINE=1 +# SEMANTIC_MANIFEST_FALLBACK_STALE_DAYS=30 +# VALIDATE_FALLBACK_STRICT=1 +# WRITE_MANIFEST_BUILD_LOCK=1 + +# Optional listening / directory links (shown on `/podcast`). Defaults exist for Spotify / RSS / GitHub when unset. +# NEXT_PUBLIC_PODCAST_SPOTIFY_URL= +# NEXT_PUBLIC_PODCAST_APPLE_URL= +# NEXT_PUBLIC_PODCAST_YOUTUBE_URL= +# NEXT_PUBLIC_GITHUB_DISCUSSIONS_URL= + +# Site footer social icons (`resolveSiteSocialLinks`). Optional overrides: +# NEXT_PUBLIC_SOCIAL_GITHUB_URL= +# NEXT_PUBLIC_SOCIAL_MEDIUM_URL= +# NEXT_PUBLIC_SOCIAL_LINKEDIN_URL= +# NEXT_PUBLIC_SOCIAL_YOUTUBE_URL= + +# Google Analytics 4 — measurement ID (public). Defaults to G-H7FSEF4WLW when unset. +# Loaded in production only; analytics cookies require Accept on the cookie banner. +# NEXT_PUBLIC_GA_MEASUREMENT_ID=G-H7FSEF4WLW +# +# GA4 Admin checklist: +# - Data streams → enable Consent Mode on the web stream +# - Enhanced measurement: page views on; "Page changes based on browser history events" on (Next.js App Router) +# - Consent defaults: analytics denied in EEA/UK/CH until Accept; granted elsewhere (see lib/consent/consent-defaults-script.ts) +# - DebugView: verify regulated regions stay denied until Accept; non-EEA traffic shows granted without Accept diff --git a/apps/site/.github/dependabot.yml b/apps/site/.github/dependabot.yml new file mode 100644 index 000000000..e82f5c90e --- /dev/null +++ b/apps/site/.github/dependabot.yml @@ -0,0 +1,62 @@ +# Dependabot version updates for npm packages and GitHub Actions. +# Security alerts / security-update PRs are enabled in the repo's +# GitHub Settings → Code security → Dependabot (not via this file). +# +# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates + +version: 2 + +updates: + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + day: monday + open-pull-requests-limit: 10 + labels: + - dependencies + commit-message: + prefix: deps + include: scope + # Bundle routine bumps; leave major version updates as individual PRs. + groups: + production-minor-patch: + dependency-type: production + update-types: + - minor + - patch + development-minor-patch: + dependency-type: development + update-types: + - minor + - patch + # Delay non-security version bumps so compromised releases can be yanked. + cooldown: + default-days: 3 + semver-major-days: 7 + ignore: + # TypeScript 7 has no programmatic API yet; typescript-eslint peer is + # `typescript <6.1.0`, and Next.js `next build` crashes under TS 7 + # (`getCurrentDirectory`). Stay on TypeScript 5 until the toolchain + # supports a newer major (typescript-eslint#12518, TS 7.1+ API). + - dependency-name: typescript + update-types: + - version-update:semver-major + + # Keep SHA-pinned Actions current (pairs with pinning in workflows). + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + day: monday + open-pull-requests-limit: 5 + labels: + - dependencies + - github-actions + commit-message: + prefix: ci + include: scope + groups: + github-actions: + patterns: + - "*" diff --git a/apps/site/.github/workflows/ci.yml b/apps/site/.github/workflows/ci.yml new file mode 100644 index 000000000..72a571bdd --- /dev/null +++ b/apps/site/.github/workflows/ci.yml @@ -0,0 +1,62 @@ +name: CI + +on: + pull_request: + push: + branches: + - main + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + build-and-test: + runs-on: ubuntu-latest + timeout-minutes: 20 + + steps: + - name: Checkout + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - name: Setup Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: "20" + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Audit dependencies + run: npm audit --audit-level=high + + - name: Lint + run: npm run lint + + - name: Test + run: npm run test + + - name: Validate fallback manifest + run: npm run validate:fallback + + - name: Validate public corpus integrity + run: npm run validate:public-corpus + + - name: Build + run: npm run build + env: + SEMANTIC_MANIFEST_OFFLINE: "1" + + - name: Install Playwright browsers + run: npx playwright install --with-deps chromium + + - name: E2E tests + run: npm run test:e2e + env: + CI: true + SEMANTIC_MANIFEST_OFFLINE: "1" + NEXT_PUBLIC_SITE_URL: http://127.0.0.1:3000 diff --git a/apps/site/.gitignore b/apps/site/.gitignore new file mode 100644 index 000000000..53932f33c --- /dev/null +++ b/apps/site/.gitignore @@ -0,0 +1,52 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# Environment files — keep `.env.example` tracked as documentation only. +.env +.env.* +!.env.example + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts + +# Build-time semantic corpus lock (regenerated on production build) +/data/build-manifest-lock.json +/data/semantic-manifest.json.bak +/data/.semantic-manifest.json.tmp diff --git a/apps/site/.husky/README.md b/apps/site/.husky/README.md new file mode 100644 index 000000000..bc695dea0 --- /dev/null +++ b/apps/site/.husky/README.md @@ -0,0 +1,68 @@ +# Git Hooks (Husky) + +This project uses [Husky](https://typicode.github.io/husky/) for Git hooks to maintain code quality and prevent CI failures. + +## Pre-commit Hook + +The pre-commit hook runs automatically before each commit and executes [lint-staged](https://github.com/lint-staged/lint-staged) to validate staged files. + +### What runs on commit: + +**For JavaScript/TypeScript files (`.js`, `.jsx`, `.ts`, `.tsx`):** + +- `eslint --fix` - Auto-fix linting issues +- `prettier --write` - Format code + +**For JSON, Markdown, CSS files:** + +- `prettier --write` - Format code + +**For test files (`.test.ts`, `.test.tsx`):** + +- `vitest related --run` - Run related tests + +### Benefits + +✅ **Prevents CI failures** from linting/formatting issues +✅ **Auto-fixes** common issues before commit +✅ **Runs only on staged files** (fast) +✅ **Ensures consistent code quality** across the team + +## Setup + +Hooks are automatically installed when running: + +```bash +npm install +``` + +The `prepare` script in `package.json` runs `husky` to set up the hooks. + +## Skipping Hooks (Emergency Use Only) + +If you absolutely need to skip the pre-commit hook: + +```bash +git commit --no-verify -m "Your message" +``` + +**⚠️ Warning:** Only use `--no-verify` in emergencies. Skipped validations will fail in CI. + +## Troubleshooting + +**Hook not running?** + +1. Check `.husky/pre-commit` exists and is executable +2. Run `npx husky` to reinstall hooks +3. Verify you're in a git repository + +**Lint-staged failing?** + +- Check the error message - it's usually a linting or test failure +- Fix the issue in your code +- Stage the fix and commit again + +**Need to update hook behavior?** + +- Edit `.husky/pre-commit` for hook commands +- Edit `lint-staged` config in `package.json` for file-specific tasks diff --git a/apps/site/.husky/pre-commit b/apps/site/.husky/pre-commit new file mode 100644 index 000000000..2312dc587 --- /dev/null +++ b/apps/site/.husky/pre-commit @@ -0,0 +1 @@ +npx lint-staged diff --git a/apps/site/.prettierignore b/apps/site/.prettierignore new file mode 100644 index 000000000..b5e1d13ce --- /dev/null +++ b/apps/site/.prettierignore @@ -0,0 +1,5 @@ +.next +node_modules +package-lock.json +out +build diff --git a/apps/site/.prettierrc b/apps/site/.prettierrc new file mode 100644 index 000000000..b301a5b17 --- /dev/null +++ b/apps/site/.prettierrc @@ -0,0 +1,7 @@ +{ + "semi": true, + "singleQuote": false, + "trailingComma": "all", + "printWidth": 100, + "plugins": [] +} diff --git a/apps/site/AGENTS.md b/apps/site/AGENTS.md new file mode 100644 index 000000000..8bd0e3908 --- /dev/null +++ b/apps/site/AGENTS.md @@ -0,0 +1,5 @@ + +# This is NOT the Next.js you know + +This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices. + diff --git a/apps/site/CLAUDE.md b/apps/site/CLAUDE.md new file mode 100644 index 000000000..43c994c2d --- /dev/null +++ b/apps/site/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/apps/site/README.md b/apps/site/README.md new file mode 100644 index 000000000..55e436349 --- /dev/null +++ b/apps/site/README.md @@ -0,0 +1,111 @@ +# After Certainty · Site + +Intellectual commons surface for **After Certainty** — books metadata, podcast hub, patterns library, and collaboration entry points. Corpus YAML lives in the monorepo root (`books/`, `semantic/`); this app consumes `semantic-manifest.json` (remote release today, same-checkout generation in a later phase). + +> **Monorepo note:** This tree lives at `apps/site/` inside [`ksteffe/after-certainty`](https://github.com/ksteffe/after-certainty). Prefer installing from the repository root (`npm ci`). The standalone [`after-certainty-site`](https://github.com/ksteffe/after-certainty-site) repository remains the production deploy source until cutover. + +## Stack + +- **Next.js** (App Router, React Server Components by default) +- **TypeScript** +- **Tailwind CSS v4** with `@tailwindcss/typography` +- **MDX** via `@next/mdx` + `remark-gfm` +- **next-themes** for appearance (defaults to dark; light tokens included) + +## Getting started + +From the **monorepo root**: + +```bash +npm ci +cp apps/site/.env.example apps/site/.env.local # optional — see NEXT_PUBLIC_SITE_URL +npm run site:dev +``` + +Or from this directory after a root `npm ci` (workspace hoisting): + +```bash +npm run dev +``` + +Open [http://localhost:3000](http://localhost:3000). + +### Scripts + +| Command | Purpose | +| ---------------- | ---------------------- | +| `npm run dev` | Local development | +| `npm run build` | Production build | +| `npm run start` | Serve production build | +| `npm run lint` | ESLint | +| `npm run format` | Prettier write | + +## Environment + +Set **`NEXT_PUBLIC_SITE_URL`** to your canonical domain so metadata, Open Graph, RSS links, and `sitemap.xml` resolve correctly. Production: `https://www.after-certainty.com` (see `.env.example`). + +## Content architecture + +| Kind | Location / notes | +| ---------------- | ----------------------------------------------------------- | +| Typed models | `types/content.ts` | +| Sample manifests | `data/*.json` — replace or sync from CI / books repo output | +| MDX pages | `content/mdx/*.mdx`, imported from routes under `app/` | +| Site copy config | `lib/site-config.ts` | + +Wire real manifests by swapping JSON under `data/` or pointing loaders in `lib/content-data.ts` at generated artifacts. + +## Dependency updates & security + +Keeping libraries and CI Actions current: + +| Mechanism | What it does | +| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Dependabot version updates** | Weekly PRs for npm and GitHub Actions (see `.github/dependabot.yml`). Minor/patch bumps are grouped; majors stay separate. TypeScript major upgrades are ignored until the ESLint/Next toolchain supports them. | +| **Dependabot alerts & security updates** | Enable under GitHub → **Settings → Code security** (Dependabot alerts + Dependabot security updates). Security PRs are not controlled by `dependabot.yml`. | +| **CI `npm audit`** | Fails the build on high+ severity advisories (`.github/workflows/ci.yml`). | + +After merging the Dependabot config, confirm those Code security toggles are on so alerts and automatic security-fix PRs work. + +Optional: once **Dependency graph** is enabled in the same settings page, you can add GitHub’s [Dependency Review Action](https://github.com/actions/dependency-review-action) to fail PRs that introduce high+ severity vulnerable packages. It cannot run until that setting is on. + +## Deployment (Vercel) + +1. Connect the repository. +2. Set **NEXT_PUBLIC_SITE_URL** to `https://www.after-certainty.com` in project Environment Variables. +3. Defaults assume Node build (`next build`); output is static-first with prerendered routes. + +The podcast RSS URL is `siteConfig.podcastRssUrl` (Anchor). The site **fetches that feed on the server** (`lib/podcast/rss.ts`, cached + **revalidated every hour** via `fetch`); episode lists and the home “latest episode” block use that data. If the feed is unreachable (offline dev, CI, etc.), lists fall back to `data/podcast-episodes.json`. `/feed.xml` still redirects to Anchor for podcast apps. + +Explore surfaces (books, patterns, glossary, observatory, questions, trails) load +**`semantic-manifest.json`** from the [after-certainty](https://github.com/ksteffe/after-certainty) +GitHub release (`latest`), with hourly ISR and a bundled fallback at +`data/semantic-manifest.json`. See [`docs/semantic-manifest.md`](docs/semantic-manifest.md) +for remote/fallback provenance, content-type normalization, and +`npm run sync:semantic-manifest` / `validate:fallback` / `validate:public-corpus`. +After each `main` release, CI POSTs to **`/api/cache/revalidate`** with target +**`semantic`** to refresh the graph immediately. + +1. Set **`CACHE_REVALIDATE_SECRET`** in Vercel (production) — a long random string. +2. Add the same value as repository secret **`CACHE_REVALIDATE_SECRET`** on `ksteffe/after-certainty` (used by the book export workflow). +3. Optional: set repository variable **`SITE_REVALIDATE_URL`** (default `https://www.after-certainty.com/api/cache/revalidate`). + +Example manual refresh: + +```bash +curl -sS -X POST "https://www.after-certainty.com/api/cache/revalidate" \ + -H "Authorization: Bearer $CACHE_REVALIDATE_SECRET" \ + -H "Content-Type: application/json" \ + -d '{"targets":["semantic"]}' +``` + +## Design notes + +- **Serif display**: Cormorant Garamond (`--font-display-serif`) +- **Sans body**: Source Sans 3 (`--font-sans-body`) +- **Accent**: restrained gold via CSS tokens in `styles/tokens.css` +- Layout primitives: `components/ui/*`, shell in `components/layout/*` + +## License + +Site content and configuration follow the project policy you adopt for the commons; attribute remixes under **CC BY-SA** where noted in the footer. diff --git a/apps/site/app/about/page.tsx b/apps/site/app/about/page.tsx new file mode 100644 index 000000000..842e89862 --- /dev/null +++ b/apps/site/app/about/page.tsx @@ -0,0 +1,32 @@ +import type { Metadata } from "next"; +import { AboutAuthor } from "@/components/about/about-author"; +import { AboutClosingQuote } from "@/components/about/about-closing-quote"; +import { AboutHero } from "@/components/about/about-hero"; +import { AboutPublishing } from "@/components/about/about-publishing"; +import { AboutStructure } from "@/components/about/about-structure"; +import { AboutVision } from "@/components/about/about-vision"; +import { AboutWhy } from "@/components/about/about-why"; +import { JsonLd } from "@/components/seo/json-ld"; +import { siteConfig } from "@/lib/site-config"; +import { createPageMetadata } from "@/lib/metadata"; +import { buildAboutPageJsonLd } from "@/lib/seo/json-ld"; + +export const metadata: Metadata = createPageMetadata({ + title: "About", + description: `${siteConfig.name}—why the project exists, how it is published, and the orientation behind the work. A reflective introduction, not a pitch.`, +}); + +export default function AboutPage() { + return ( + <> + + + + + + + + + + ); +} diff --git a/apps/site/app/api/cache/revalidate/route.test.ts b/apps/site/app/api/cache/revalidate/route.test.ts new file mode 100644 index 000000000..234257f89 --- /dev/null +++ b/apps/site/app/api/cache/revalidate/route.test.ts @@ -0,0 +1,84 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { POST } from "./route"; +import { resetRateLimitBuckets } from "@/lib/security/rate-limit"; + +vi.mock("@/lib/cache/revalidate", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + revalidateCacheTargets: vi.fn(), + }; +}); + +import { revalidateCacheTargets } from "@/lib/cache/revalidate"; + +function postRequest(init?: { body?: string; authorization?: string }): Request { + const headers: Record = { "Content-Type": "application/json" }; + if (init?.authorization) { + headers.Authorization = init.authorization; + } + return new Request("http://localhost/api/cache/revalidate", { + method: "POST", + headers, + body: init?.body ?? "", + }); +} + +describe("POST /api/cache/revalidate", () => { + let prevSecret: string | undefined; + + beforeEach(() => { + prevSecret = process.env.CACHE_REVALIDATE_SECRET; + process.env.CACHE_REVALIDATE_SECRET = "route-test-secret"; + vi.mocked(revalidateCacheTargets).mockClear(); + resetRateLimitBuckets(); + }); + + afterEach(() => { + process.env.CACHE_REVALIDATE_SECRET = prevSecret; + resetRateLimitBuckets(); + }); + + it("returns 503 when secret is not configured", async () => { + delete process.env.CACHE_REVALIDATE_SECRET; + const res = await POST(postRequest({ authorization: "Bearer x" })); + expect(res.status).toBe(503); + }); + + it("returns 401 without a valid bearer token", async () => { + const res = await POST(postRequest()); + expect(res.status).toBe(401); + }); + + it("revalidates all default targets with a valid bearer token", async () => { + const res = await POST(postRequest({ authorization: "Bearer route-test-secret" })); + expect(res.status).toBe(200); + expect(revalidateCacheTargets).toHaveBeenCalledWith(["podcast", "semantic"]); + await expect(res.json()).resolves.toEqual({ + ok: true, + revalidated: ["podcast", "semantic"], + }); + }); + + it("revalidates only requested targets from the body", async () => { + const res = await POST( + postRequest({ + authorization: "Bearer route-test-secret", + body: JSON.stringify({ targets: ["podcast"] }), + }), + ); + expect(res.status).toBe(200); + expect(revalidateCacheTargets).toHaveBeenCalledWith(["podcast"]); + }); + + it("returns 400 for invalid JSON", async () => { + const res = await POST( + postRequest({ + authorization: "Bearer route-test-secret", + body: "not-json", + }), + ); + expect(res.status).toBe(400); + }); +}); diff --git a/apps/site/app/api/cache/revalidate/route.ts b/apps/site/app/api/cache/revalidate/route.ts new file mode 100644 index 000000000..cb3b30f4d --- /dev/null +++ b/apps/site/app/api/cache/revalidate/route.ts @@ -0,0 +1,76 @@ +import { NextResponse } from "next/server"; + +import { + isCacheRevalidateAuthorized, + isCacheRevalidateConfigured, + parseCacheRevalidateTargets, + revalidateCacheTargets, +} from "@/lib/cache/revalidate"; +import { checkRateLimit } from "@/lib/security/rate-limit"; + +const UNAUTH_RATE_LIMIT = 20; +const UNAUTH_WINDOW_MS = 15 * 60 * 1000; + +function clientIp(request: Request): string { + const forwarded = request.headers.get("x-forwarded-for"); + if (forwarded) { + const first = forwarded.split(",")[0]?.trim(); + if (first) return first; + } + const realIp = request.headers.get("x-real-ip")?.trim(); + if (realIp) return realIp; + return "unknown"; +} + +export async function POST(request: Request) { + if (!isCacheRevalidateConfigured()) { + return NextResponse.json( + { error: "Cache revalidation is not configured on this deployment." }, + { status: 503 }, + ); + } + + if (!isCacheRevalidateAuthorized(request)) { + const ipLimit = checkRateLimit(`revalidate:unauth:${clientIp(request)}`, { + limit: UNAUTH_RATE_LIMIT, + windowMs: UNAUTH_WINDOW_MS, + }); + if (!ipLimit.ok) { + return NextResponse.json( + { error: "Too many requests. Please try again shortly." }, + { + status: 429, + headers: { "Retry-After": String(ipLimit.retryAfterSeconds) }, + }, + ); + } + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + let body: unknown = null; + try { + const text = await request.text(); + if (text.length > 0) { + body = JSON.parse(text) as unknown; + } + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const rawTargets = + body && typeof body === "object" && body !== null && "targets" in body + ? (body as { targets: unknown }).targets + : undefined; + + const targets = parseCacheRevalidateTargets(rawTargets); + if (!targets) { + return NextResponse.json( + { error: 'Expected optional JSON body { "targets": ["podcast", "semantic"] }' }, + { status: 400 }, + ); + } + + revalidateCacheTargets(targets); + + return NextResponse.json({ ok: true, revalidated: targets }, { status: 200 }); +} diff --git a/apps/site/app/api/json-ld/books/[slug]/route.ts b/apps/site/app/api/json-ld/books/[slug]/route.ts new file mode 100644 index 000000000..8488476f4 --- /dev/null +++ b/apps/site/app/api/json-ld/books/[slug]/route.ts @@ -0,0 +1,43 @@ +import { NextResponse } from "next/server"; +import { buildGraphIndex } from "@/lib/graph/graph"; +import { getBookBySlug } from "@/lib/graph/graphQueries"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { buildBookPageJsonLd } from "@/lib/seo/json-ld"; +import { explorePaths } from "@/lib/graph/explorePaths"; + +type RouteContext = { + params: Promise<{ slug: string }>; +}; + +/** + * GET /api/json-ld/books/[slug] + * Returns JSON-LD structured data for a book as pure JSON + */ +export async function GET(_request: Request, context: RouteContext) { + const { slug } = await context.params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const book = getBookBySlug(index, slug); + + if (!book) { + return NextResponse.json({ error: "Book not found" }, { status: 404 }); + } + + const bookBreadcrumbs = [ + { label: "Explore", href: explorePaths.home }, + { label: "Books", href: explorePaths.books }, + { label: book.title }, + ]; + + const jsonLd = buildBookPageJsonLd({ + book, + breadcrumbs: bookBreadcrumbs, + }); + + return NextResponse.json(jsonLd, { + headers: { + "Content-Type": "application/ld+json", + "Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400", + }, + }); +} diff --git a/apps/site/app/api/json-ld/concepts/[slug]/route.ts b/apps/site/app/api/json-ld/concepts/[slug]/route.ts new file mode 100644 index 000000000..bbf58deca --- /dev/null +++ b/apps/site/app/api/json-ld/concepts/[slug]/route.ts @@ -0,0 +1,55 @@ +import { NextResponse } from "next/server"; +import { buildGraphIndex } from "@/lib/graph/graph"; +import { getConceptBySlug } from "@/lib/graph/graphQueries"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { + buildConceptPageJsonLd, + conceptRelationshipUrls, + relatedBookUrls, + relatedPatternUrls, +} from "@/lib/seo/json-ld"; +import { explorePaths } from "@/lib/graph/explorePaths"; + +type RouteContext = { + params: Promise<{ slug: string }>; +}; + +/** + * GET /api/json-ld/concepts/[slug] + * Returns JSON-LD structured data for a concept as pure JSON + */ +export async function GET(_request: Request, context: RouteContext) { + const { slug } = await context.params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const concept = getConceptBySlug(index, slug); + + if (!concept) { + return NextResponse.json({ error: "Concept not found" }, { status: 404 }); + } + + const conceptBreadcrumbs = [ + { label: "Explore", href: explorePaths.home }, + { label: "Concepts", href: explorePaths.concepts }, + { label: concept.title }, + ]; + + const relatedUrls = [ + ...relatedBookUrls(index, concept.relatedBooks), + ...relatedPatternUrls(index, concept.relatedPatterns), + ...conceptRelationshipUrls(index, concept.id), + ]; + + const jsonLd = buildConceptPageJsonLd({ + concept, + breadcrumbs: conceptBreadcrumbs, + relatedUrls, + }); + + return NextResponse.json(jsonLd, { + headers: { + "Content-Type": "application/ld+json", + "Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400", + }, + }); +} diff --git a/apps/site/app/api/json-ld/patterns/[slug]/route.ts b/apps/site/app/api/json-ld/patterns/[slug]/route.ts new file mode 100644 index 000000000..df7c70fab --- /dev/null +++ b/apps/site/app/api/json-ld/patterns/[slug]/route.ts @@ -0,0 +1,44 @@ +import { NextResponse } from "next/server"; +import { buildGraphIndex } from "@/lib/graph/graph"; +import { getPatternBySlug } from "@/lib/graph/graphQueries"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { buildPatternPageJsonLd, relatedConceptUrls } from "@/lib/seo/json-ld"; +import { explorePaths } from "@/lib/graph/explorePaths"; + +type RouteContext = { + params: Promise<{ slug: string }>; +}; + +/** + * GET /api/json-ld/patterns/[slug] + * Returns JSON-LD structured data for a pattern as pure JSON + */ +export async function GET(_request: Request, context: RouteContext) { + const { slug } = await context.params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const pattern = getPatternBySlug(index, slug); + + if (!pattern) { + return NextResponse.json({ error: "Pattern not found" }, { status: 404 }); + } + + const patternBreadcrumbs = [ + { label: "Explore", href: explorePaths.home }, + { label: "Patterns", href: explorePaths.patterns }, + { label: pattern.title }, + ]; + + const jsonLd = buildPatternPageJsonLd({ + pattern, + breadcrumbs: patternBreadcrumbs, + relatedConceptUrls: relatedConceptUrls(index, pattern.relatedConcepts), + }); + + return NextResponse.json(jsonLd, { + headers: { + "Content-Type": "application/ld+json", + "Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400", + }, + }); +} diff --git a/apps/site/app/api/search/index/route.test.ts b/apps/site/app/api/search/index/route.test.ts new file mode 100644 index 000000000..53caac037 --- /dev/null +++ b/apps/site/app/api/search/index/route.test.ts @@ -0,0 +1,53 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { GET } from "./route"; +import type { SearchIndexPayload } from "@/lib/search/indexPayload"; + +vi.mock("@/lib/search/indexPayload", () => ({ + getSearchIndexPayload: vi.fn(), +})); + +import { getSearchIndexPayload } from "@/lib/search/indexPayload"; + +describe("GET /api/search/index", () => { + beforeEach(() => { + vi.mocked(getSearchIndexPayload).mockReset(); + }); + + it("returns the search index payload with cache headers", async () => { + const payload: SearchIndexPayload = { + version: 1, + generatedAt: "2026-07-19T00:00:00.000Z", + documentCount: 1, + documents: [ + { + id: "concept-certainty", + entityType: "concept", + slug: "certainty", + title: "Certainty", + resultLabel: "Concept", + canonicalUrl: "/explore/concepts/certainty", + visibility: "listed", + searchText: "Certainty", + aliases: [], + boostWeight: 1.2, + sourceArtifact: "semantic", + }, + ], + aliasConfig: { version: 1, entries: [] }, + }; + vi.mocked(getSearchIndexPayload).mockResolvedValue(payload); + + const res = await GET(); + expect(res.status).toBe(200); + expect(res.headers.get("Cache-Control")).toContain("s-maxage=3600"); + await expect(res.json()).resolves.toEqual(payload); + }); + + it("returns 503 when the payload cannot be built", async () => { + vi.mocked(getSearchIndexPayload).mockRejectedValue(new Error("boom")); + const res = await GET(); + expect(res.status).toBe(503); + await expect(res.json()).resolves.toEqual({ error: "Search index unavailable" }); + }); +}); diff --git a/apps/site/app/api/search/index/route.ts b/apps/site/app/api/search/index/route.ts new file mode 100644 index 000000000..038dbbffe --- /dev/null +++ b/apps/site/app/api/search/index/route.ts @@ -0,0 +1,23 @@ +import { NextResponse } from "next/server"; + +import { getSearchIndexPayload } from "@/lib/search/indexPayload"; + +/** + * GET /api/search/index + * + * Public JSON search corpus for client-side MiniSearch. + * Built from the same ISR loaders as Explore (semantic + books + podcast + aliases). + */ +export async function GET() { + try { + const payload = await getSearchIndexPayload(); + return NextResponse.json(payload, { + headers: { + "Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400", + }, + }); + } catch (err) { + console.error("[search-index] failed to build payload", err); + return NextResponse.json({ error: "Search index unavailable" }, { status: 503 }); + } +} diff --git a/apps/site/app/api/security-assessment.dynamic.test.ts b/apps/site/app/api/security-assessment.dynamic.test.ts new file mode 100644 index 000000000..3850a9739 --- /dev/null +++ b/apps/site/app/api/security-assessment.dynamic.test.ts @@ -0,0 +1,155 @@ +/** + * Defensive security dynamic tests (post–Beehiiv removal). + * Outbound services (GitHub, RSS) are mocked or offline — no non-local hosts required. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { POST as revalidatePost } from "@/app/api/cache/revalidate/route"; +import { GET as feedGet } from "@/app/feed.xml/route"; +import { resetRateLimitBuckets } from "@/lib/security/rate-limit"; + +vi.mock("@/lib/cache/revalidate", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + revalidateCacheTargets: vi.fn(), + }; +}); + +import { revalidateCacheTargets } from "@/lib/cache/revalidate"; + +function revalidateRequest(init?: { + body?: string; + authorization?: string; + forwardedFor?: string; +}): Request { + const headers: Record = { "Content-Type": "application/json" }; + if (init?.authorization) { + headers.Authorization = init.authorization; + } + if (init?.forwardedFor) { + headers["x-forwarded-for"] = init.forwardedFor; + } + return new Request("http://localhost/api/cache/revalidate", { + method: "POST", + headers, + body: init?.body ?? "", + }); +} + +describe("security assessment — POST /api/cache/revalidate", () => { + let prevSecret: string | undefined; + + beforeEach(() => { + prevSecret = process.env.CACHE_REVALIDATE_SECRET; + process.env.CACHE_REVALIDATE_SECRET = "route-test-secret"; + vi.mocked(revalidateCacheTargets).mockClear(); + resetRateLimitBuckets(); + }); + + afterEach(() => { + process.env.CACHE_REVALIDATE_SECRET = prevSecret; + resetRateLimitBuckets(); + }); + + it("returns 503 when secret unset", async () => { + delete process.env.CACHE_REVALIDATE_SECRET; + const res = await revalidatePost(revalidateRequest({ authorization: "Bearer anything" })); + expect(res.status).toBe(503); + expect(revalidateCacheTargets).not.toHaveBeenCalled(); + }); + + it("returns 401 for missing Authorization", async () => { + const res = await revalidatePost(revalidateRequest()); + expect(res.status).toBe(401); + }); + + it("returns 401 for malformed Authorization schemes", async () => { + for (const authorization of [ + "route-test-secret", + "Basic route-test-secret", + "Bearer", + "Bearer ", + "Bearer wrong-secret", + "bearer route-test-secret", + ]) { + const res = await revalidatePost(revalidateRequest({ authorization })); + expect(res.status, authorization).toBe(401); + } + expect(revalidateCacheTargets).not.toHaveBeenCalled(); + }); + + it("rate-limits repeated unauthorized attempts", async () => { + const statuses: number[] = []; + for (let i = 0; i < 25; i++) { + const res = await revalidatePost( + revalidateRequest({ + authorization: "Bearer wrong-secret", + forwardedFor: "203.0.113.50", + }), + ); + statuses.push(res.status); + } + expect(statuses.slice(0, 20).every((s) => s === 401)).toBe(true); + expect(statuses[20]).toBe(429); + expect(revalidateCacheTargets).not.toHaveBeenCalled(); + }); + + it("rejects invalid JSON body", async () => { + const res = await revalidatePost( + revalidateRequest({ + authorization: "Bearer route-test-secret", + body: "{not-json", + }), + ); + expect(res.status).toBe(400); + }); + + it("rejects unknown targets and empty targets array", async () => { + const unknown = await revalidatePost( + revalidateRequest({ + authorization: "Bearer route-test-secret", + body: JSON.stringify({ targets: ["podcast", "evil"] }), + }), + ); + expect(unknown.status).toBe(400); + + const empty = await revalidatePost( + revalidateRequest({ + authorization: "Bearer route-test-secret", + body: JSON.stringify({ targets: [] }), + }), + ); + expect(empty.status).toBe(400); + }); + + it("rejects oversized targets array", async () => { + const targets = Array.from({ length: 500 }, (_, i) => (i === 0 ? "podcast" : `t${i}`)); + const res = await revalidatePost( + revalidateRequest({ + authorization: "Bearer route-test-secret", + body: JSON.stringify({ targets }), + }), + ); + expect(res.status).toBe(400); + expect(revalidateCacheTargets).not.toHaveBeenCalled(); + }); + + it("authorizes correct bearer and revalidates", async () => { + const res = await revalidatePost( + revalidateRequest({ authorization: "Bearer route-test-secret" }), + ); + expect(res.status).toBe(200); + expect(revalidateCacheTargets).toHaveBeenCalledWith(["podcast", "semantic"]); + }); +}); + +describe("security assessment — GET /feed.xml", () => { + it("redirects to configured/default RSS without using request input", () => { + const res = feedGet(); + expect(res.status).toBe(307); + const location = res.headers.get("location"); + expect(location).toBeTruthy(); + expect(location!.startsWith("http")).toBe(true); + }); +}); diff --git a/apps/site/app/collaborators/page.tsx b/apps/site/app/collaborators/page.tsx new file mode 100644 index 000000000..4df007a3d --- /dev/null +++ b/apps/site/app/collaborators/page.tsx @@ -0,0 +1,34 @@ +import type { Metadata } from "next"; +import { CollaboratorsClosing } from "@/components/collaborators/collaborators-closing"; +import { CollaboratorsContributorsSection } from "@/components/collaborators/collaborators-contributors-section"; +import { CollaboratorsFuture } from "@/components/collaborators/collaborators-future"; +import { CollaboratorsGithub } from "@/components/collaborators/collaborators-github"; +import { CollaboratorsHero } from "@/components/collaborators/collaborators-hero"; +import { CollaboratorsParticipate } from "@/components/collaborators/collaborators-participate"; +import { CollaboratorsPhilosophy } from "@/components/collaborators/collaborators-philosophy"; +import { CollaboratorsQuote } from "@/components/collaborators/collaborators-quote"; +import { getContributors } from "@/lib/content-data"; +import { createPageMetadata } from "@/lib/metadata"; + +export const metadata: Metadata = createPageMetadata({ + title: "Collaborators", + description: + "An open invitation into collaborative inquiry—writing, patterns, critique, and shared publishing—without recruitment hype or certainty theater.", +}); + +export default function CollaboratorsPage() { + const contributors = getContributors(); + + return ( + <> + + + + + + + + + + ); +} diff --git a/apps/site/app/explore/(browse)/books/[slug]/page.tsx b/apps/site/app/explore/(browse)/books/[slug]/page.tsx new file mode 100644 index 000000000..6c356ecd3 --- /dev/null +++ b/apps/site/app/explore/(browse)/books/[slug]/page.tsx @@ -0,0 +1,185 @@ +import type { Metadata } from "next"; +import { notFound, permanentRedirect } from "next/navigation"; + +import { BookDetailLegacyLayout } from "@/components/books/book-detail-legacy-layout"; +import { BookOverviewLayout } from "@/components/books/book-overview-layout"; +import { RelatedTrailsSection } from "@/components/trails/related-trails-section"; +import { bookPublicationStatus } from "@/lib/books/book-metadata"; +import { buildBookOverviewViewModel } from "@/lib/books/book-overview-view-model"; +import { resolveBookCanonicalSlug } from "@/lib/books/book-slugs"; +import { getPublicationRegistryFromGraph } from "@/lib/books/load-publication-registry"; +import { publicStatusLabel } from "@/lib/books/public-status"; +import { findPublishedQuestionsForBook } from "@/lib/books/related-questions-for-book"; +import { resolveWorkEdition } from "@/lib/books/resolve-work-edition"; +import { + getOrderedBookActions, + getSemanticBookActionLinkItems, +} from "@/lib/books/semantic-book-action-links"; +import { findWhatsNewEventsForBook } from "@/lib/whats-new/findEventsForBook"; +import { buildPublicWhatsNewEvents } from "@/lib/whats-new/publicEvents"; +import { getPublishedQuestions } from "@/lib/questions/loadQuestions"; +import { + buildCoverImageBySlugLookup, + resolveCoverForGraphBookSlug, +} from "@/lib/explore/graph-book-covers"; +import { + booksSortedForExploreIndex, + exploreBookAdjacentInIndexOrder, +} from "@/lib/explore/explore-books-order"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { explorePaths } from "@/lib/graph/explorePaths"; +import { buildGraphIndex } from "@/lib/graph/graph"; +import { getBookBySlug as getGraphBookBySlug } from "@/lib/graph/graphQueries"; +import { relatedContentForBook } from "@/lib/graph/relatedContent"; +import { resolveThinkersForBook } from "@/lib/graph/bookThinkers"; +import { entityHasSemanticRelationships } from "@/lib/graph/relationshipTaxonomy"; +import { createPageMetadata } from "@/lib/metadata"; + +type PageProps = { params: Promise<{ slug: string }> }; + +export async function generateMetadata({ params }: PageProps): Promise { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const book = getGraphBookBySlug(index, slug); + if (!book) return {}; + const overview = buildBookOverviewViewModel(book, graph); + const description = + overview?.overview.centralQuestion ?? book.summary ?? book.subtitle ?? book.title; + if (!book.openGraphImage) { + return createPageMetadata({ title: book.title, description }); + } + return createPageMetadata({ + title: book.title, + description, + openGraph: { + images: [{ url: book.openGraphImage, alt: book.title }], + }, + twitter: { + images: [book.openGraphImage], + }, + }); +} + +export default async function ExploreBookDetailPage({ params }: PageProps) { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const canonicalSlug = resolveBookCanonicalSlug(slug, graph.books); + if (canonicalSlug && canonicalSlug !== slug) { + permanentRedirect(`${explorePaths.books}/${canonicalSlug}`); + } + const index = buildGraphIndex(graph); + const book = getGraphBookBySlug(index, slug); + if (!book) notFound(); + + const coverLookup = buildCoverImageBySlugLookup(graph.books); + const coverSrc = + resolveCoverForGraphBookSlug(coverLookup, graph.books, book.slug) ?? book.coverImage; + + const related = relatedContentForBook(index, book); + const bookThinkerContent = resolveThinkersForBook(index, book, graph); + const inventory = { + concepts: related.concepts, + patterns: related.patterns, + thinkers: bookThinkerContent.thinkers, + researchSources: bookThinkerContent.researchSources, + useLegacyThinkersSection: bookThinkerContent.useLegacyThinkersSection, + }; + const hasRelationships = entityHasSemanticRelationships(index, book.id); + + const registry = getPublicationRegistryFromGraph(graph); + const resolved = resolveWorkEdition(book, graph.books, registry); + const registryEdition = registry.editions.find((e) => e.bookId === book.id); + const status = bookPublicationStatus(book); + const upcomingLabel = publicStatusLabel(status); + + const relatedSlug = + resolved.relationship === "superseded" + ? resolved.supersededBySlug + : resolved.relationship === "companion" + ? resolved.companionOfSlug + : undefined; + const relatedEdition = relatedSlug ? graph.books.find((b) => b.slug === relatedSlug) : undefined; + + const companionEdition = + resolved.relationship === "primary" + ? graph.books.find( + (b) => + (book.companionBooks?.includes(b.slug) ?? false) || + resolveWorkEdition(b, graph.books, registry).companionOfSlug === book.slug, + ) + : undefined; + + const bookBreadcrumbs = [ + { label: "Explore", href: explorePaths.home }, + { label: "Books", href: explorePaths.books }, + { label: book.title }, + ]; + + const overviewVm = buildBookOverviewViewModel(book, graph); + const relatedWhatsNew = findWhatsNewEventsForBook(book.id, { + limit: 3, + events: buildPublicWhatsNewEvents({ changeEvents: graph.changeEvents }), + }); + const relatedQuestions = findPublishedQuestionsForBook(book.id, 2, getPublishedQuestions(graph)); + + if (overviewVm) { + const actions = getOrderedBookActions({ + book, + relationship: resolved.relationship, + preference: overviewVm.primaryActionPreference, + currentEditionHref: relatedEdition + ? `${explorePaths.books}/${relatedEdition.slug}` + : undefined, + currentEditionTitle: relatedEdition?.title, + }); + + return ( + } + /> + ); + } + + const booksInListOrder = booksSortedForExploreIndex(graph.books); + const { prev: prevBook, next: nextBook } = exploreBookAdjacentInIndexOrder( + booksInListOrder, + book.slug, + ); + + return ( + + ); +} diff --git a/apps/site/app/explore/(browse)/books/page.tsx b/apps/site/app/explore/(browse)/books/page.tsx new file mode 100644 index 000000000..4b13ea39b --- /dev/null +++ b/apps/site/app/explore/(browse)/books/page.tsx @@ -0,0 +1,115 @@ +import type { Metadata } from "next"; + +import { BooksCatalogAnalytics } from "@/components/books/books-catalog-analytics"; +import { BooksCatalogControls } from "@/components/books/books-catalog-controls"; +import { BooksShelfSection } from "@/components/books/books-shelf-section"; +import { ExploreIndexHero } from "@/components/explore/explore-hero"; +import { Section } from "@/components/ui/section"; +import { applyCatalogQuery, buildFilterOptions } from "@/lib/books/catalog-query"; +import { buildCatalogViewModel } from "@/lib/books/catalog-view-model"; +import { hasActiveCatalogFilters, parseCatalogUrlState } from "@/lib/books/catalog-url-state"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { createPageMetadata } from "@/lib/metadata"; + +type BooksPageProps = { + searchParams?: Promise<{ + shelf?: string; + type?: string; + status?: string; + availability?: string; + sort?: string; + q?: string; + editions?: string; + }>; +}; + +export default async function ExploreBooksIndexPage({ searchParams }: BooksPageProps) { + const { graph } = await getExploreSemanticGraph(); + const viewModel = buildCatalogViewModel(graph); + const filterOptions = buildFilterOptions(viewModel, graph); + const knownShelfSlugs = filterOptions.shelves.map((s) => s.slug); + const urlState = parseCatalogUrlState(searchParams ? await searchParams : {}, knownShelfSlugs); + const { shelves, results, showShelfSections } = applyCatalogQuery(viewModel, urlState, graph); + const filteredView = hasActiveCatalogFilters(urlState); + + const featuredShelfSections = shelves.filter( + ({ shelf }) => shelf.featured && shelf.slug !== "start-here", + ); + const startHereSection = shelves.find(({ shelf }) => shelf.slug === "start-here"); + + return ( +
+ + + + {showShelfSections && startHereSection ? ( + + ) : null} + + {showShelfSections + ? featuredShelfSections.map(({ shelf, books, totalCount }) => ( + + )) + : null} + +
+
+

+ {filteredView ? "Filtered catalog" : "Complete catalog"} +

+

+ {filteredView + ? "Refine by shelf, type, availability, or title search. Share the URL to preserve your view." + : "Every published volume — filter, sort, or search when you know what you are looking for."} +

+
+
+ +
+
+
+ ); +} + +export async function generateMetadata({ searchParams }: BooksPageProps): Promise { + const base = createPageMetadata({ + title: "Books", + description: + "Browse the After Certainty library by shelf — start here, core volumes, trust, systems, fiction, and the complete catalog.", + }); + + const sp = searchParams ? await searchParams : {}; + const hasFilters = Boolean( + sp.shelf || sp.type || sp.status || sp.availability || sp.q || sp.sort || sp.editions, + ); + + if (!hasFilters) return base; + + return { + ...base, + alternates: { + canonical: "/explore/books", + }, + }; +} diff --git a/apps/site/app/explore/(browse)/concepts/[slug]/page.tsx b/apps/site/app/explore/(browse)/concepts/[slug]/page.tsx new file mode 100644 index 000000000..72407de3b --- /dev/null +++ b/apps/site/app/explore/(browse)/concepts/[slug]/page.tsx @@ -0,0 +1,197 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { JsonLd } from "@/components/seo/json-ld"; +import { BreadcrumbTrail } from "@/components/explore/breadcrumb-trail"; +import { ExploreEntityDetailActions } from "@/components/explore/explore-entity-detail-actions"; +import { ExploreAdjacentNav } from "@/components/explore/explore-adjacent-nav"; +import { GraphNeighborhoodCards } from "@/components/explore/graph-neighborhood-cards"; +import { RelatedContentGrid } from "@/components/explore/related-content-grid"; +import { RelatedTrailsSection } from "@/components/trails/related-trails-section"; +import { SemanticRelationshipsSection } from "@/components/explore/semantic-relationships-section"; +import { entityHasSemanticRelationships } from "@/lib/graph/relationshipTaxonomy"; +import { LinkifiedText } from "@/components/ui/linkified-text"; +import { Section } from "@/components/ui/section"; +import { + conceptsSortedForExploreIndex, + exploreConceptAdjacentInIndexOrder, +} from "@/lib/explore/explore-concepts-order"; +import { explorePaths } from "@/lib/graph/explorePaths"; +import { buildGraphIndex } from "@/lib/graph/graph"; +import { getAdjacentSourcesFromRelationships, getConceptBySlug } from "@/lib/graph/graphQueries"; +import { getConnectedGraphNeighborhood } from "@/lib/graph/graphTraversal"; +import { relatedContentForConcept } from "@/lib/graph/relatedContent"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { createPageMetadata } from "@/lib/metadata"; +import { + buildConceptPageJsonLd, + conceptRelationshipUrls, + relatedBookUrls, + relatedPatternUrls, +} from "@/lib/seo/json-ld"; +import { getConceptFullDefinition } from "@/lib/graph/conceptFormatting"; +import { buildPublicGroundingViewModel } from "@/lib/graph/grounding"; +import { SemanticGroundingDisclosure } from "@/components/explore/semantic-grounding-disclosure"; + +type PageProps = { params: Promise<{ slug: string }> }; + +export async function generateMetadata({ params }: PageProps): Promise { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const concept = getConceptBySlug(index, slug); + if (!concept) return {}; + return createPageMetadata({ + title: concept.title, + description: getConceptFullDefinition(concept), + }); +} + +export default async function ExploreConceptDetailPage({ params }: PageProps) { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const concept = getConceptBySlug(index, slug); + if (!concept) notFound(); + + const related = relatedContentForConcept(index, concept); + const adjacentSources = getAdjacentSourcesFromRelationships(index, concept.id); + + const mergedSources = [...related.sources]; + const sourceIds = new Set(mergedSources.map((s) => s.id)); + for (const s of adjacentSources) { + if (!sourceIds.has(s.id)) { + sourceIds.add(s.id); + mergedSources.push(s); + } + } + + const conceptsInListOrder = conceptsSortedForExploreIndex(graph.glossary); + const { prev: prevConcept, next: nextConcept } = exploreConceptAdjacentInIndexOrder( + conceptsInListOrder, + concept.slug, + ); + + const hasRelated = + related.concepts.length + + related.patterns.length + + related.books.length + + related.thinkers.length + + mergedSources.length > + 0; + const hasRelationships = entityHasSemanticRelationships(index, concept.id); + + // Get neighborhood and deduplicate against related sections + const allNeighbors = getConnectedGraphNeighborhood( + index, + { kind: "concept", id: concept.id, slug: concept.slug }, + { maxDepth: 1, maxNodes: 20 }, + ); + + // Build set of IDs already shown in related sections + const alreadyShownIds = new Set([ + ...related.concepts.map((c) => c.id), + ...related.patterns.map((p) => p.id), + ...related.books.map((b) => b.id), + ...related.thinkers.map((t) => t.id), + ...mergedSources.map((s) => s.id), + ]); + + // Filter neighbors to only those not already shown + const uniqueNeighbors = allNeighbors.filter((node) => !alreadyShownIds.has(node.id)); + const hasNeighborhood = uniqueNeighbors.length > 0; + + const conceptBreadcrumbs = [ + { label: "Explore", href: explorePaths.home }, + { label: "Concepts", href: explorePaths.concepts }, + { label: concept.title }, + ]; + const relatedUrls = [ + ...relatedBookUrls(index, concept.relatedBooks), + ...relatedPatternUrls(index, concept.relatedPatterns), + ...conceptRelationshipUrls(index, concept.id), + ]; + const grounding = buildPublicGroundingViewModel(concept.grounding, graph); + + return ( +
+ +
+ +

Concept

+

+ {concept.title} +

+
+

+ +

+
+ {grounding ? : null} + + +
+ + + + {hasRelated ? ( +
+
+ + + + +
+
+ ) : null} + + {hasRelationships ? ( +
+ +
+ ) : null} + + {hasNeighborhood ? ( +
+ +
+ ) : null} +
+ ); +} diff --git a/apps/site/app/explore/(browse)/concepts/page.tsx b/apps/site/app/explore/(browse)/concepts/page.tsx new file mode 100644 index 000000000..d15768825 --- /dev/null +++ b/apps/site/app/explore/(browse)/concepts/page.tsx @@ -0,0 +1,123 @@ +import type { Metadata } from "next"; +import { ConceptCard } from "@/components/explore/concept-card"; +import { ExploreIndexHero } from "@/components/explore/explore-hero"; +import { ExploreIndexPagination } from "@/components/explore/explore-index-pagination"; +import { ExploreIndexSearch } from "@/components/explore/explore-index-search"; +import { Section } from "@/components/ui/section"; +import { + filterExploreIndexItems, + paginateExploreIndexItems, + parseExploreIndexPage, + type ExploreIndexItem, +} from "@/lib/explore/explore-index-browse"; +import { conceptsSortedForExploreIndex } from "@/lib/explore/explore-concepts-order"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { getConceptDisplayDefinition } from "@/lib/graph/conceptFormatting"; +import { explorePaths } from "@/lib/graph/explorePaths"; +import { createPageMetadata } from "@/lib/metadata"; +import type { GlossaryConcept } from "@/types/semanticGraph"; + +export const metadata: Metadata = createPageMetadata({ + title: "Concepts", + description: + "Glossary concepts in the After Certainty semantic graph — definitions and traversable relationships.", +}); + +type ExploreConceptsIndexPageProps = { + searchParams?: Promise<{ q?: string; page?: string }>; +}; + +function conceptBrowseItem(concept: GlossaryConcept): ExploreIndexItem { + return { + id: concept.id, + slug: concept.slug, + label: concept.title, + href: `${explorePaths.concepts}/${concept.slug}`, + searchText: [ + concept.title, + concept.slug, + concept.layer, + getConceptDisplayDefinition(concept), + concept.shortDefinition, + ] + .filter(Boolean) + .join(" "), + }; +} + +function conceptSuggestionItem(concept: GlossaryConcept): ExploreIndexItem { + return { + id: concept.id, + slug: concept.slug, + label: concept.title, + href: `${explorePaths.concepts}/${concept.slug}`, + searchText: [concept.title, concept.slug, concept.layer].filter(Boolean).join(" "), + }; +} + +export default async function ExploreConceptsIndexPage({ + searchParams, +}: ExploreConceptsIndexPageProps) { + const sp = searchParams ? await searchParams : {}; + const q = typeof sp.q === "string" ? sp.q : ""; + const requestedPage = parseExploreIndexPage(typeof sp.page === "string" ? sp.page : undefined); + + const { graph } = await getExploreSemanticGraph(); + const concepts = conceptsSortedForExploreIndex(graph.glossary); + const browseItems = concepts.map(conceptBrowseItem); + const filteredItems = filterExploreIndexItems(browseItems, q); + const slice = paginateExploreIndexItems(filteredItems, requestedPage); + const conceptById = new Map(concepts.map((c) => [c.id, c])); + const pageConcepts = slice.items + .map((item) => conceptById.get(item.id)) + .filter((c): c is GlossaryConcept => c != null); + + return ( +
+ +
+ {concepts.length === 0 ? ( +

No concepts are published in the manifest yet.

+ ) : ( + <> + +

+ {q.trim() + ? `${slice.totalItems} match${slice.totalItems === 1 ? "" : "es"} for “${q.trim()}”` + : `${slice.totalItems} concepts`} +

+ {pageConcepts.length === 0 ? ( +

No concepts match that search.

+ ) : ( +
+ {pageConcepts.map((c) => ( + + ))} +
+ )} + + + )} +
+
+ ); +} diff --git a/apps/site/app/explore/(browse)/layout.tsx b/apps/site/app/explore/(browse)/layout.tsx new file mode 100644 index 000000000..5b2bea4a6 --- /dev/null +++ b/apps/site/app/explore/(browse)/layout.tsx @@ -0,0 +1,6 @@ +import type { ReactNode } from "react"; +import { ExploreLayout } from "@/components/explore/explore-layout"; + +export default function ExploreBrowseLayout({ children }: { children: ReactNode }) { + return {children}; +} diff --git a/apps/site/app/explore/(browse)/patterns/[slug]/page.tsx b/apps/site/app/explore/(browse)/patterns/[slug]/page.tsx new file mode 100644 index 000000000..f8d118283 --- /dev/null +++ b/apps/site/app/explore/(browse)/patterns/[slug]/page.tsx @@ -0,0 +1,128 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { JsonLd } from "@/components/seo/json-ld"; +import { BreadcrumbTrail } from "@/components/explore/breadcrumb-trail"; +import { ExplorePatternMedia } from "@/components/explore/explore-pattern-media"; +import { ExploreEntityDetailActions } from "@/components/explore/explore-entity-detail-actions"; +import { ExploreAdjacentNav } from "@/components/explore/explore-adjacent-nav"; +import { RelatedContentGrid } from "@/components/explore/related-content-grid"; +import { RelatedTrailsSection } from "@/components/trails/related-trails-section"; +import { SemanticRelationshipsSection } from "@/components/explore/semantic-relationships-section"; +import { entityHasSemanticRelationships } from "@/lib/graph/relationshipTaxonomy"; +import { LinkifiedText } from "@/components/ui/linkified-text"; +import { Section } from "@/components/ui/section"; +import { + explorePatternAdjacentInIndexOrder, + patternsSortedForExploreIndex, +} from "@/lib/explore/explore-patterns-order"; +import { explorePaths } from "@/lib/graph/explorePaths"; +import { buildGraphIndex } from "@/lib/graph/graph"; +import { getPatternBySlug } from "@/lib/graph/graphQueries"; +import { relatedContentForPattern } from "@/lib/graph/relatedContent"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { createPageMetadata } from "@/lib/metadata"; +import { buildPatternPageJsonLd, relatedConceptUrls } from "@/lib/seo/json-ld"; +import { buildPublicGroundingViewModel } from "@/lib/graph/grounding"; +import { SemanticGroundingDisclosure } from "@/components/explore/semantic-grounding-disclosure"; + +type PageProps = { params: Promise<{ slug: string }> }; + +export async function generateMetadata({ params }: PageProps): Promise { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const pattern = getPatternBySlug(index, slug); + if (!pattern) return {}; + return createPageMetadata({ + title: pattern.title, + description: pattern.summary, + }); +} + +export default async function ExplorePatternDetailPage({ params }: PageProps) { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const pattern = getPatternBySlug(index, slug); + if (!pattern) notFound(); + + const related = relatedContentForPattern(index, pattern); + const patternsInListOrder = patternsSortedForExploreIndex(graph.patterns); + const { prev: prevPattern, next: nextPattern } = explorePatternAdjacentInIndexOrder( + patternsInListOrder, + pattern.slug, + ); + + const hasRelated = related.concepts.length + related.books.length > 0; + const hasRelationships = entityHasSemanticRelationships(index, pattern.id); + const grounding = buildPublicGroundingViewModel(pattern.grounding, graph); + + const patternBreadcrumbs = [ + { label: "Explore", href: explorePaths.home }, + { label: "Patterns", href: explorePaths.patterns }, + { label: pattern.title }, + ]; + + return ( +
+ +
+ +

Pattern

+

+ {pattern.title} +

+

+ +

+ {grounding ? : null} + + + +
+ + + + {hasRelated ? ( +
+
+ + +
+
+ ) : null} + + {hasRelationships ? ( +
+ +
+ ) : null} +
+ ); +} diff --git a/apps/site/app/explore/(browse)/patterns/page.tsx b/apps/site/app/explore/(browse)/patterns/page.tsx new file mode 100644 index 000000000..7d556cc46 --- /dev/null +++ b/apps/site/app/explore/(browse)/patterns/page.tsx @@ -0,0 +1,41 @@ +import type { Metadata } from "next"; +import { ExploreIndexHero } from "@/components/explore/explore-hero"; +import { ExplorePatternsPlaylistCallout } from "@/components/explore/explore-patterns-playlist-callout"; +import { PatternCard } from "@/components/explore/pattern-card"; +import { Section } from "@/components/ui/section"; +import { patternsSortedForExploreIndex } from "@/lib/explore/explore-patterns-order"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { createPageMetadata } from "@/lib/metadata"; + +export const metadata: Metadata = createPageMetadata({ + title: "Patterns", + description: "Patterns in the After Certainty semantic graph — systemic structures linked to concepts and books.", +}); + +export default async function ExplorePatternsIndexPage() { + const { graph } = await getExploreSemanticGraph(); + const patterns = patternsSortedForExploreIndex(graph.patterns); + + return ( +
+ +
+ + {patterns.length === 0 ? ( +

No patterns are published in the manifest yet.

+ ) : ( +
+ {patterns.map((p) => ( + + ))} +
+ )} +
+
+ ); +} diff --git a/apps/site/app/explore/(browse)/situations/[slug]/page.tsx b/apps/site/app/explore/(browse)/situations/[slug]/page.tsx new file mode 100644 index 000000000..005fec99a --- /dev/null +++ b/apps/site/app/explore/(browse)/situations/[slug]/page.tsx @@ -0,0 +1,123 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { JsonLd } from "@/components/seo/json-ld"; +import { BreadcrumbTrail } from "@/components/explore/breadcrumb-trail"; +import { ExploreEnrichmentSections } from "@/components/explore/explore-enrichment-sections"; +import { ExploreEntityDetailActions } from "@/components/explore/explore-entity-detail-actions"; +import { ExploreAdjacentNav } from "@/components/explore/explore-adjacent-nav"; +import { RelatedContentGrid } from "@/components/explore/related-content-grid"; +import { LinkifiedText } from "@/components/ui/linkified-text"; +import { Section } from "@/components/ui/section"; +import { explorePaths } from "@/lib/graph/explorePaths"; +import { buildGraphIndex } from "@/lib/graph/graph"; +import { getSituationBySlug } from "@/lib/graph/graphQueries"; +import { relatedContentForSituation } from "@/lib/graph/relatedContent"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { createPageMetadata } from "@/lib/metadata"; +import { buildSituationPageJsonLd, relatedConceptUrls } from "@/lib/seo/json-ld"; +import type { Situation } from "@/types/semanticGraph"; + +type PageProps = { params: Promise<{ slug: string }> }; + +function situationsSorted(situations: readonly Situation[]): Situation[] { + return [...situations].sort((a, b) => + a.title.localeCompare(b.title, undefined, { sensitivity: "base" }), + ); +} + +function adjacentSituation( + ordered: readonly Situation[], + slug: string, +): { prev?: Situation; next?: Situation } { + const index = ordered.findIndex((s) => s.slug === slug); + if (index < 0) return {}; + return { + prev: index > 0 ? ordered[index - 1] : undefined, + next: index < ordered.length - 1 ? ordered[index + 1] : undefined, + }; +} + +export async function generateMetadata({ params }: PageProps): Promise { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const situation = getSituationBySlug(index, slug); + if (!situation) return {}; + return createPageMetadata({ + title: situation.title, + description: situation.summary, + }); +} + +export default async function ExploreSituationDetailPage({ params }: PageProps) { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const situation = getSituationBySlug(index, slug); + if (!situation) notFound(); + + const related = relatedContentForSituation(index, situation); + const ordered = situationsSorted(graph.situations ?? []); + const { prev, next } = adjacentSituation(ordered, situation.slug); + + const hasRelated = related.concepts.length + related.patterns.length + related.books.length > 0; + + const breadcrumbs = [ + { label: "Explore", href: explorePaths.home }, + { label: "Situations", href: explorePaths.situations }, + { label: situation.title }, + ]; + + return ( +
+ +
+ +

Situation

+

+ {situation.title} +

+

+ +

+ + +
+ +
+ +
+ + {hasRelated ? ( +
+
+ + + +
+
+ ) : null} +
+ ); +} diff --git a/apps/site/app/explore/(browse)/situations/page.tsx b/apps/site/app/explore/(browse)/situations/page.tsx new file mode 100644 index 000000000..39d7a5ed4 --- /dev/null +++ b/apps/site/app/explore/(browse)/situations/page.tsx @@ -0,0 +1,41 @@ +import type { Metadata } from "next"; +import { ExploreIndexHero } from "@/components/explore/explore-hero"; +import { SituationCard } from "@/components/explore/situation-card"; +import { Section } from "@/components/ui/section"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { createPageMetadata } from "@/lib/metadata"; + +export const metadata: Metadata = createPageMetadata({ + title: "Situations", + description: + "Situations in the After Certainty semantic graph — lived scenarios where patterns and concepts show up together.", +}); + +export default async function ExploreSituationsIndexPage() { + const { graph } = await getExploreSemanticGraph(); + const situations = [...(graph.situations ?? [])].sort((a, b) => + a.title.localeCompare(b.title, undefined, { sensitivity: "base" }), + ); + + return ( +
+ +
+ {situations.length === 0 ? ( +

No situations are published in the manifest yet.

+ ) : ( +
+ {situations.map((situation) => ( + + ))} +
+ )} +
+
+ ); +} diff --git a/apps/site/app/explore/(browse)/sources/[slug]/page.tsx b/apps/site/app/explore/(browse)/sources/[slug]/page.tsx new file mode 100644 index 000000000..9d3b0addb --- /dev/null +++ b/apps/site/app/explore/(browse)/sources/[slug]/page.tsx @@ -0,0 +1,166 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { JsonLd } from "@/components/seo/json-ld"; +import { BreadcrumbTrail } from "@/components/explore/breadcrumb-trail"; +import { ExploreEntityDetailActions } from "@/components/explore/explore-entity-detail-actions"; +import { ExploreAdjacentNav } from "@/components/explore/explore-adjacent-nav"; +import { RelatedContentGrid } from "@/components/explore/related-content-grid"; +import { SemanticRelationshipsSection } from "@/components/explore/semantic-relationships-section"; +import { entityHasSemanticRelationships } from "@/lib/graph/relationshipTaxonomy"; +import { LinkifiedText } from "@/components/ui/linkified-text"; +import { Section } from "@/components/ui/section"; +import { + exploreSourceAdjacentInIndexOrder, + sourcesSortedForExploreIndex, +} from "@/lib/explore/explore-sources-order"; +import { explorePaths } from "@/lib/graph/explorePaths"; +import { buildGraphIndex } from "@/lib/graph/graph"; +import { getSourceBySlug } from "@/lib/graph/graphQueries"; +import { relatedContentForSource } from "@/lib/graph/relatedContent"; +import { + sourceCreatorThinkerLinks, + sourceDisplayBody, + sourceDisplayLabel, + sourceDisplayTitle, + thinkerHref, +} from "@/lib/graph/sourceDisplay"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { createPageMetadata } from "@/lib/metadata"; +import { buildSourcePageJsonLd } from "@/lib/seo/json-ld"; + +type PageProps = { params: Promise<{ slug: string }> }; + +export async function generateMetadata({ params }: PageProps): Promise { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const source = getSourceBySlug(index, slug); + if (!source) return {}; + const description = + sourceDisplayBody(source) ?? `${sourceDisplayTitle(source)} — ${sourceDisplayLabel(source)}`; + return createPageMetadata({ + title: sourceDisplayTitle(source), + description, + }); +} + +export default async function ExploreSourceDetailPage({ params }: PageProps) { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const index = buildGraphIndex(graph); + const source = getSourceBySlug(index, slug); + if (!source) notFound(); + + const related = relatedContentForSource(index, source); + const sourcesInListOrder = sourcesSortedForExploreIndex(graph.sources); + const { prev: prevSource, next: nextSource } = exploreSourceAdjacentInIndexOrder( + sourcesInListOrder, + source.slug, + ); + + const hasRelated = related.concepts.length + related.patterns.length + related.books.length > 0; + const hasRelationships = entityHasSemanticRelationships(index, source.id); + const creatorThinkers = sourceCreatorThinkerLinks(graph, source); + const displayTitle = sourceDisplayTitle(source); + const displayLabel = sourceDisplayLabel(source); + const displayBody = sourceDisplayBody(source); + + const sourceBreadcrumbs = [ + { label: "Explore", href: explorePaths.home }, + { label: "Sources", href: explorePaths.sources }, + { label: displayTitle }, + ]; + + return ( +
+ +
+ +

{displayLabel}

+

+ {displayTitle} +

+ {creatorThinkers.length > 0 ? ( +
+ {creatorThinkers.map((thinker) => ( + + {thinker.name} + + ))} +
+ ) : null} + {displayBody ? ( +

+ +

+ ) : null} + {source.whyThisMatters ? ( +
+

Why this matters

+

+ +

+
+ ) : null} + + +
+ + {hasRelated ? ( +
+
+ + + +
+
+ ) : null} + + {hasRelationships ? ( +
+

+ Intellectual lineage +

+

+ {/* Extension: curated lineage fields, preserves/threatens chains, school-of-thought tags, secondary literature. */} + Lineage views will layer on top of typed relationships. For now, traverse incoming and + outgoing edges below to see how this voice is positioned in the graph. +

+
+ +
+
+ ) : null} +
+ ); +} diff --git a/apps/site/app/explore/(browse)/sources/page.tsx b/apps/site/app/explore/(browse)/sources/page.tsx new file mode 100644 index 000000000..76875c6d0 --- /dev/null +++ b/apps/site/app/explore/(browse)/sources/page.tsx @@ -0,0 +1,138 @@ +import type { Metadata } from "next"; +import { ExploreIndexHero } from "@/components/explore/explore-hero"; +import { ExploreIndexPagination } from "@/components/explore/explore-index-pagination"; +import { ExploreIndexSearch } from "@/components/explore/explore-index-search"; +import { SourceCard } from "@/components/explore/source-card"; +import { Section } from "@/components/ui/section"; +import { + filterExploreIndexItems, + paginateExploreIndexItems, + parseExploreIndexPage, + type ExploreIndexItem, +} from "@/lib/explore/explore-index-browse"; +import { sourcesSortedForExploreIndex } from "@/lib/explore/explore-sources-order"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { explorePaths } from "@/lib/graph/explorePaths"; +import { + sourceDisplayBody, + sourceDisplayLabel, + sourceDisplayTitle, +} from "@/lib/graph/sourceDisplay"; +import { createPageMetadata } from "@/lib/metadata"; +import type { Source } from "@/types/semanticGraph"; + +export const metadata: Metadata = createPageMetadata({ + title: "Sources", + description: + "Bibliographic sources in the After Certainty semantic graph — books, articles, reports, and other research works.", +}); + +type ExploreSourcesIndexPageProps = { + searchParams?: Promise<{ q?: string; page?: string }>; +}; + +function sourceBrowseItem(source: Source): ExploreIndexItem { + return { + id: source.id, + slug: source.slug, + label: sourceDisplayTitle(source), + href: `${explorePaths.sources}/${source.slug}`, + searchText: [ + sourceDisplayTitle(source), + source.name, + source.slug, + sourceDisplayLabel(source), + source.type, + source.sourceKind, + sourceDisplayBody(source), + ...(source.creatorNames ?? []), + ] + .filter(Boolean) + .join(" "), + }; +} + +function sourceSuggestionItem(source: Source): ExploreIndexItem { + return { + id: source.id, + slug: source.slug, + label: sourceDisplayTitle(source), + href: `${explorePaths.sources}/${source.slug}`, + searchText: [ + sourceDisplayTitle(source), + source.name, + source.slug, + sourceDisplayLabel(source), + ...(source.creatorNames ?? []), + ] + .filter(Boolean) + .join(" "), + }; +} + +export default async function ExploreSourcesIndexPage({ + searchParams, +}: ExploreSourcesIndexPageProps) { + const sp = searchParams ? await searchParams : {}; + const q = typeof sp.q === "string" ? sp.q : ""; + const requestedPage = parseExploreIndexPage(typeof sp.page === "string" ? sp.page : undefined); + + const { graph } = await getExploreSemanticGraph(); + const sources = sourcesSortedForExploreIndex(graph.sources); + const browseItems = sources.map(sourceBrowseItem); + const filteredItems = filterExploreIndexItems(browseItems, q); + const slice = paginateExploreIndexItems(filteredItems, requestedPage); + const sourceById = new Map(sources.map((s) => [s.id, s])); + const pageSources = slice.items + .map((item) => sourceById.get(item.id)) + .filter((s): s is Source => s != null); + + return ( +
+ +
+ {sources.length === 0 ? ( +

No sources are published in the manifest yet.

+ ) : ( + <> + +

+ {q.trim() + ? `${slice.totalItems} match${slice.totalItems === 1 ? "" : "es"} for “${q.trim()}”` + : `${slice.totalItems} sources`} +

+ {pageSources.length === 0 ? ( +

No sources match that search.

+ ) : ( +
+ {pageSources.map((s) => ( + + ))} +
+ )} + + + )} +
+
+ ); +} diff --git a/apps/site/app/explore/(browse)/thinkers/[slug]/page.tsx b/apps/site/app/explore/(browse)/thinkers/[slug]/page.tsx new file mode 100644 index 000000000..02980aab8 --- /dev/null +++ b/apps/site/app/explore/(browse)/thinkers/[slug]/page.tsx @@ -0,0 +1,127 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { JsonLd } from "@/components/seo/json-ld"; +import { BreadcrumbTrail } from "@/components/explore/breadcrumb-trail"; +import { ExploreEntityDetailActions } from "@/components/explore/explore-entity-detail-actions"; +import { ExploreAdjacentNav } from "@/components/explore/explore-adjacent-nav"; +import { RelatedContentGrid } from "@/components/explore/related-content-grid"; +import { LinkifiedText } from "@/components/ui/linkified-text"; +import { Section } from "@/components/ui/section"; +import { + exploreThinkerAdjacentInIndexOrder, + thinkersSortedForExploreIndex, +} from "@/lib/explore/explore-thinkers-order"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { explorePaths } from "@/lib/graph/explorePaths"; +import { buildGraphIndex } from "@/lib/graph/graph"; +import { getThinkerBySlug } from "@/lib/graph/graphQueries"; +import { relatedContentForThinker } from "@/lib/graph/relatedContent"; +import { createPageMetadata } from "@/lib/metadata"; +import { buildThinkerPageJsonLd } from "@/lib/seo/json-ld"; +import type { Thinker } from "@/types/semanticGraph"; + +type PageProps = { params: Promise<{ slug: string }> }; + +function thinkerTypeLabel(type: Thinker["type"]): string { + return type === "organization" ? "Organization" : "Person"; +} + +export async function generateMetadata({ params }: PageProps): Promise { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const thinker = getThinkerBySlug(graph, slug); + if (!thinker) return {}; + return createPageMetadata({ + title: thinker.name, + description: + thinker.summary ?? + thinker.whyThisMatters ?? + `${thinker.name} — ${thinkerTypeLabel(thinker.type)}`, + }); +} + +export default async function ExploreThinkerDetailPage({ params }: PageProps) { + const { slug } = await params; + const { graph } = await getExploreSemanticGraph(); + const thinker = getThinkerBySlug(graph, slug); + if (!thinker) notFound(); + + const index = buildGraphIndex(graph); + const related = relatedContentForThinker(index, thinker); + const thinkersInListOrder = thinkersSortedForExploreIndex(graph); + const { prev: prevThinker, next: nextThinker } = exploreThinkerAdjacentInIndexOrder( + thinkersInListOrder, + thinker.slug, + ); + + const hasRelated = + related.works.length + + related.concepts.length + + related.patterns.length + + related.books.length > + 0; + + const thinkerBreadcrumbs = [ + { label: "Explore", href: explorePaths.home }, + { label: "Thinkers", href: explorePaths.thinkers }, + { label: thinker.name }, + ]; + + return ( +
+ +
+ +

+ {thinkerTypeLabel(thinker.type)} +

+

+ {thinker.name} +

+ {thinker.summary ? ( +

+ +

+ ) : null} + {thinker.whyThisMatters ? ( +
+

Why this matters

+

+ +

+
+ ) : null} + + +
+ + {hasRelated ? ( +
+
+ + + + +
+
+ ) : null} +
+ ); +} diff --git a/apps/site/app/explore/(browse)/thinkers/page.tsx b/apps/site/app/explore/(browse)/thinkers/page.tsx new file mode 100644 index 000000000..9c33b4d71 --- /dev/null +++ b/apps/site/app/explore/(browse)/thinkers/page.tsx @@ -0,0 +1,117 @@ +import type { Metadata } from "next"; +import { ExploreIndexHero } from "@/components/explore/explore-hero"; +import { ExploreIndexPagination } from "@/components/explore/explore-index-pagination"; +import { ExploreIndexSearch } from "@/components/explore/explore-index-search"; +import { ThinkerCard } from "@/components/explore/thinker-card"; +import { Section } from "@/components/ui/section"; +import { + filterExploreIndexItems, + paginateExploreIndexItems, + parseExploreIndexPage, + type ExploreIndexItem, +} from "@/lib/explore/explore-index-browse"; +import { thinkersSortedForExploreIndex } from "@/lib/explore/explore-thinkers-order"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { explorePaths } from "@/lib/graph/explorePaths"; +import { createPageMetadata } from "@/lib/metadata"; +import type { Thinker } from "@/types/semanticGraph"; + +export const metadata: Metadata = createPageMetadata({ + title: "Thinkers", + description: + "People and institutions in the After Certainty semantic graph — intellectual voices anchored to works, concepts, and books.", +}); + +type ExploreThinkersIndexPageProps = { + searchParams?: Promise<{ q?: string; page?: string }>; +}; + +function thinkerBrowseItem(thinker: Thinker): ExploreIndexItem { + return { + id: thinker.id, + slug: thinker.slug, + label: thinker.name, + href: `${explorePaths.thinkers}/${thinker.slug}`, + searchText: [thinker.name, thinker.slug, thinker.type, thinker.summary, thinker.whyThisMatters] + .filter(Boolean) + .join(" "), + }; +} + +function thinkerSuggestionItem(thinker: Thinker): ExploreIndexItem { + return { + id: thinker.id, + slug: thinker.slug, + label: thinker.name, + href: `${explorePaths.thinkers}/${thinker.slug}`, + searchText: [thinker.name, thinker.slug, thinker.type].join(" "), + }; +} + +export default async function ExploreThinkersIndexPage({ + searchParams, +}: ExploreThinkersIndexPageProps) { + const sp = searchParams ? await searchParams : {}; + const q = typeof sp.q === "string" ? sp.q : ""; + const requestedPage = parseExploreIndexPage(typeof sp.page === "string" ? sp.page : undefined); + + const { graph } = await getExploreSemanticGraph(); + const thinkers = thinkersSortedForExploreIndex(graph); + const browseItems = thinkers.map(thinkerBrowseItem); + const suggestionItems = thinkers.map(thinkerSuggestionItem); + const filteredItems = filterExploreIndexItems(browseItems, q); + const slice = paginateExploreIndexItems(filteredItems, requestedPage); + const thinkerById = new Map(thinkers.map((t) => [t.id, t])); + const pageThinkers = slice.items + .map((item) => thinkerById.get(item.id)) + .filter((t): t is Thinker => t != null); + + return ( +
+ +
+ {thinkers.length === 0 ? ( +

No thinkers are published in the manifest yet.

+ ) : ( + <> + +

+ {q.trim() + ? `${slice.totalItems} match${slice.totalItems === 1 ? "" : "es"} for “${q.trim()}”` + : `${slice.totalItems} thinkers`} +

+ {pageThinkers.length === 0 ? ( +

No thinkers match that search.

+ ) : ( +
+ {pageThinkers.map((thinker) => ( + + ))} +
+ )} + + + )} +
+
+ ); +} diff --git a/apps/site/app/explore/layout.tsx b/apps/site/app/explore/layout.tsx new file mode 100644 index 000000000..1ab75bc06 --- /dev/null +++ b/apps/site/app/explore/layout.tsx @@ -0,0 +1,6 @@ +import type { ReactNode } from "react"; + +/** Thin parent: list/detail pages use `(browse)/layout` with ExploreLayout; `/explore` observatory is full-bleed. */ +export default function ExploreRootLayout({ children }: { children: ReactNode }) { + return children; +} diff --git a/apps/site/app/explore/page.tsx b/apps/site/app/explore/page.tsx new file mode 100644 index 000000000..2b1056a1a --- /dev/null +++ b/apps/site/app/explore/page.tsx @@ -0,0 +1,80 @@ +import type { Metadata } from "next"; +import { ExploreObservatory } from "@/components/explore/observatory/ExploreObservatory"; +import { buildExploreCoverBySlug } from "@/lib/explore/buildExploreCoverBySlug"; +import { getExploreSemanticGraph } from "@/lib/explore/exploreSemanticGraph"; +import { + isValidExploreFocusKind, + resolveExploreFocusCanonicalId, +} from "@/lib/explore/resolveExploreFocus"; +import { buildGraphIndex } from "@/lib/graph/graph"; +import { isExplorePathwayKind, pathwayFromSearchParams } from "@/lib/graph/explorePaths"; +import { pathwayGraphNodeIds, resolvePathwayStepIndex } from "@/lib/observatory/pathwayFromContent"; +import { resolveExplorePathway } from "@/lib/observatory/resolvePathway"; +import { createPageMetadata } from "@/lib/metadata"; + +export const metadata: Metadata = createPageMetadata({ + title: "Explore", + description: + "A semantic observatory for the After Certainty graph — traverse concepts, patterns, books, and thinkers as a calm, navigable landscape.", +}); + +type ExplorePageProps = { + searchParams?: Promise<{ + focusKind?: string; + focusSlug?: string; + pathwayKind?: string; + pathwaySlug?: string; + pathwayStep?: string; + }>; +}; + +export default async function ExploreObservatoryPage({ searchParams }: ExplorePageProps) { + const { graph } = await getExploreSemanticGraph(); + const coverBySlug = buildExploreCoverBySlug(graph, graph.books); + + const sp = searchParams ? await searchParams : {}; + let initialFocusCanonicalId: string | null = null; + const fk = sp.focusKind; + const fs = sp.focusSlug; + if (typeof fk === "string" && typeof fs === "string" && isValidExploreFocusKind(fk)) { + const index = buildGraphIndex(graph); + initialFocusCanonicalId = resolveExploreFocusCanonicalId(index, fk, fs, graph.books); + } + + const pathwayParams = pathwayFromSearchParams( + new URLSearchParams( + Object.entries(sp) + .filter(([, value]) => typeof value === "string") + .map(([key, value]) => [key, value as string]), + ), + ); + let initialPathway = null; + if ( + pathwayParams && + isExplorePathwayKind(pathwayParams.kind) && + typeof pathwayParams.slug === "string" + ) { + initialPathway = await resolveExplorePathway({ + kind: pathwayParams.kind, + slug: pathwayParams.slug, + }); + if (initialPathway && !initialFocusCanonicalId) { + const stepIndex = resolvePathwayStepIndex(initialPathway, pathwayParams.step); + const step = initialPathway.steps[stepIndex]; + initialFocusCanonicalId = + step?.canonicalId ?? pathwayGraphNodeIds(initialPathway)[0] ?? initialFocusCanonicalId; + } + } + + return ( +
+ +
+ ); +} diff --git a/apps/site/app/favicon.ico b/apps/site/app/favicon.ico new file mode 100644 index 000000000..718d6fea4 Binary files /dev/null and b/apps/site/app/favicon.ico differ diff --git a/apps/site/app/feed.xml/route.test.ts b/apps/site/app/feed.xml/route.test.ts new file mode 100644 index 000000000..68308676d --- /dev/null +++ b/apps/site/app/feed.xml/route.test.ts @@ -0,0 +1,23 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { GET } from "./route"; + +describe("GET /feed.xml", () => { + let prevRssUrl: string | undefined; + + beforeEach(() => { + prevRssUrl = process.env.PODCAST_RSS_URL; + process.env.PODCAST_RSS_URL = "https://feeds.integration-test.example/podcast.xml"; + }); + + afterEach(() => { + process.env.PODCAST_RSS_URL = prevRssUrl; + }); + + it("returns 307 redirect to the resolved podcast RSS URL", () => { + const res = GET(); + + expect(res.status).toBe(307); + expect(res.headers.get("location")).toBe("https://feeds.integration-test.example/podcast.xml"); + }); +}); diff --git a/apps/site/app/feed.xml/route.ts b/apps/site/app/feed.xml/route.ts new file mode 100644 index 000000000..cc69570a8 --- /dev/null +++ b/apps/site/app/feed.xml/route.ts @@ -0,0 +1,10 @@ +import { NextResponse } from "next/server"; +import { resolvePodcastRssUrl } from "@/lib/site-config"; + +/** + * Legacy path from early stubs — redirect to the live podcast RSS so subscribers and + * podcast apps still resolve a stable URL on this domain if needed. + */ +export function GET() { + return NextResponse.redirect(resolvePodcastRssUrl(), 307); +} diff --git a/apps/site/app/globals.css b/apps/site/app/globals.css new file mode 100644 index 000000000..c337222df --- /dev/null +++ b/apps/site/app/globals.css @@ -0,0 +1,78 @@ +@import "tailwindcss"; +@plugin "@tailwindcss/typography"; + +/* next-themes adds class `light` on ; mirror the built-in `dark` variant for utilities */ +@custom-variant light (&:where(.light, .light *)); + +@import "../styles/tokens.css"; +@import "../styles/explore-observatory.css"; +@import "../styles/atmosphere.css"; + +@theme inline { + --color-bg: var(--bg); + --color-bg-elevated: var(--bg-elevated); + --color-fg: var(--fg); + --color-muted: var(--muted); + --color-border: var(--border); + --color-accent: var(--accent); + --color-accent-soft: var(--accent-soft); + --color-glow: var(--glow); + --font-sans: var(--font-sans-body); + --font-display: var(--font-display-serif); +} + +@layer base { + html { + scroll-behavior: smooth; + } + + body { + background-color: transparent; + color: var(--fg); + font-family: var(--font-sans-body), ui-sans-serif, system-ui, sans-serif; + } + + html.light body { + background-color: var(--bg); + } + + ::selection { + background: var(--accent-soft); + color: var(--fg); + } + + :focus-visible { + outline: 2px solid var(--accent); + outline-offset: 3px; + } +} + +@layer utilities { + .text-balance { + text-wrap: balance; + } + + @keyframes start-reveal { + from { + opacity: 0; + transform: translateY(12px); + } + to { + opacity: 1; + transform: translateY(0); + } + } + + .animate-start-reveal { + opacity: 0; + animation: start-reveal 1.1s ease-out forwards; + } + + @media (prefers-reduced-motion: reduce) { + .animate-start-reveal { + animation: none; + opacity: 1; + transform: none; + } + } +} diff --git a/apps/site/app/layout.tsx b/apps/site/app/layout.tsx new file mode 100644 index 000000000..1ff18d029 --- /dev/null +++ b/apps/site/app/layout.tsx @@ -0,0 +1,59 @@ +import type { Metadata } from "next"; +import { Cormorant_Garamond, Source_Sans_3 } from "next/font/google"; +import { Analytics } from "@vercel/analytics/next"; +import { SpeedInsights } from "@vercel/speed-insights/next"; +import "./globals.css"; +import { GoogleAnalyticsLoader } from "@/components/analytics/google-analytics"; +import { ConsentProvider } from "@/components/consent/consent-provider"; +import { CookieBanner } from "@/components/consent/cookie-banner"; +import { ThemeProvider } from "@/components/theme-provider"; +import { SiteShell } from "@/components/layout/site-shell"; +import { buildConsentDefaultsInlineScript } from "@/lib/consent/consent-defaults-script"; +import { defaultMetadata } from "@/lib/metadata"; +import { texturePreloadHrefs } from "@/lib/textures"; + +const display = Cormorant_Garamond({ + variable: "--font-display-serif", + subsets: ["latin"], + display: "swap", +}); + +const sans = Source_Sans_3({ + variable: "--font-sans-body", + subsets: ["latin"], + display: "swap", +}); + +export const metadata: Metadata = defaultMetadata; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + + {texturePreloadHrefs.map((href) => ( + + ))} + knowing.', + }), + ); + expect(snippet?.text).toContain("