diff --git a/.agents/skills/design-taste-frontend/SKILL.md b/.agents/skills/design-taste-frontend/SKILL.md new file mode 100644 index 0000000..b72132f --- /dev/null +++ b/.agents/skills/design-taste-frontend/SKILL.md @@ -0,0 +1,1206 @@ +--- +name: design-taste-frontend +description: Anti-slop frontend skill for landing pages, portfolios, and redesigns. The agent reads the brief, infers the right design direction, and ships interfaces that do not look templated. Real design systems when applicable, audit-first on redesigns, strict pre-flight check. +--- + +# tasteskill: Anti-Slop Frontend Skill + +> Landing pages, portfolios, and redesigns. Not dashboards, not data tables, not multi-step product UI. +> Every rule below is **contextual**. None of it fires automatically. First read the brief, then pull only what fits. + +--- + +## 0. BRIEF INFERENCE (Read the Room Before Anything Else) + +Before touching code or tweaking dials, **infer what the user actually wants**. Most LLM design output is bad because the model jumps to a default aesthetic instead of reading the room. + +### 0.A Read these signals first +1. **Page kind** - landing (SaaS / consumer / agency / event), portfolio (dev / designer / creative studio), redesign (preserve vs overhaul), editorial / blog. +2. **Vibe words** the user used - "minimalist", "calm", "Linear-style", "Awwwards", "brutalist", "premium consumer", "Apple-y", "playful", "serious B2B", "editorial", "agency-y", "glassy", "dark tech". +3. **Reference signals** - URLs they linked, screenshots they pasted, products they named, brands they're competing with. +4. **Audience** - B2B procurement panel vs. design-conscious consumer vs. recruiter scanning a portfolio. The audience picks the aesthetic, not your taste. +5. **Brand assets that already exist** - logo, color, type, photography. For redesigns, these are starting material, not optional input (see Section 11). +6. **Quiet constraints** - accessibility-first audiences, public-sector, regulated industries, trust-first commerce, kids' products. These constraints OVERRIDE aesthetic preference. + +### 0.B Output a one-line "Design Read" before generating +Before any code, state in one line: **"Reading this as: \ for \, with a \ language, leaning toward \."** + +Example reads: +- *"Reading this as: B2B SaaS landing for technical buyers, with a Linear-style minimalist language, leaning toward Tailwind utilities + Geist + restrained motion."* +- *"Reading this as: solo designer portfolio for hiring managers, with an editorial / kinetic-type language, leaning toward native CSS + scroll-driven animation + custom typography."* +- *"Reading this as: redesign of a public-sector service site, with a trust-first language, leaning toward GOV.UK Frontend or USWDS."* + +### 0.C If the brief is ambiguous, ask one question, do not guess +Ask exactly **one** clarifying question - never a multi-question dump - and only when the design read genuinely diverges. Example: *"Should this feel closer to Linear-clean or Awwwards-experimental?"* + +If you can confidently infer from context, **do not ask**. Just declare the design read and proceed. + +### 0.D Anti-Default Discipline +Do not default to: AI-purple gradients, centered hero over dark mesh, three equal feature cards, generic glassmorphism on everything, infinite-loop micro-animations everywhere, Inter + slate-900. These are the LLM defaults. Reach past them deliberately based on the design read. + +--- + +## 1. THE THREE DIALS (Core Configuration) + +After the design read, set three dials. Every layout, motion, and density decision below is gated by these. + +* **`DESIGN_VARIANCE: 8`** - 1 = Perfect Symmetry, 10 = Artsy Chaos +* **`MOTION_INTENSITY: 6`** - 1 = Static, 10 = Cinematic / Physics +* **`VISUAL_DENSITY: 4`** - 1 = Art Gallery / Airy, 10 = Cockpit / Packed Data + +**Baseline:** `8 / 6 / 4`. Use these unless the design read overrides them. Do not ask the user to edit this file - overrides happen conversationally. + +### 1.A Dial Inference (design read → dial values) +| Signal | VARIANCE | MOTION | DENSITY | +|---|---|---|---| +| "minimalist / clean / calm / editorial / Linear-style" | 5-6 | 3-4 | 2-3 | +| "premium consumer / Apple-y / luxury / brand" | 7-8 | 5-7 | 3-4 | +| "playful / wild / Dribbble / Awwwards / experimental / agency" | 9-10 | 8-10 | 3-4 | +| "landing page / portfolio / marketing site (default)" | 7-9 | 6-8 | 3-5 | +| "trust-first / public-sector / regulated / accessibility-critical" | 3-4 | 2-3 | 4-5 | +| "redesign - preserve" | match existing | +1 | match existing | +| "redesign - overhaul" | +2 | +2 | match existing | + +### 1.B Use-Case Presets +| Use case | VARIANCE | MOTION | DENSITY | +|---|---|---|---| +| Landing (SaaS, mainstream) | 7 | 6 | 4 | +| Landing (Agency / creative) | 9 | 8 | 3 | +| Landing (Premium consumer) | 7 | 6 | 3 | +| Portfolio (Designer / studio) | 8 | 7 | 3 | +| Portfolio (Developer) | 6 | 5 | 4 | +| Editorial / Blog | 6 | 4 | 3 | +| Public-sector service | 3 | 2 | 5 | +| Redesign - preserve | match | match+1 | match | +| Redesign - overhaul | +2 | +2 | match | + +### 1.C How the Dials Drive Output +Use these (or user-overridden values) as global variables. Cross-references throughout this document refer to these exact variable names - never invent aliases like `LAYOUT_VARIANCE` or `ANIM_LEVEL`. + +--- + +## 2. BRIEF → DESIGN SYSTEM MAP + +Once you have the design read (Section 0) and dials (Section 1), pick the right foundation. Do not invent CSS for things that have an official package. Do not pretend an aesthetic trend is an official system. + +### 2.A When to reach for a real design system (use official packages) +| Brief reads as… | Reach for | Why | +|---|---|---| +| Microsoft / enterprise SaaS / dashboards | `@fluentui/react-components` or `@fluentui/web-components` | Official Fluent UI, Microsoft tokens, accessibility done | +| Google-ish UI, Material-flavored product | `@material/web` + Material 3 tokens | Official, theme-able via Material Theming | +| IBM-style B2B / enterprise analytics | `@carbon/react` + `@carbon/styles` | Official Carbon, mature data-density patterns | +| Shopify app surfaces | `polaris.js` web components / Polaris React | Required for Shopify admin UI | +| Atlassian / Jira-style product | `@atlaskit/*` + `@atlaskit/tokens` | Official Atlassian DS | +| GitHub-style devtool / community page | `@primer/css` or `@primer/react-brand` | Official Primer; Brand variant for marketing | +| Public-sector UK service | `govuk-frontend` | Legally / regulatorily expected | +| US public-sector / trust-first | `uswds` | Same | +| Fast local-business / agency MVP | Bootstrap 5.3 | Boring, fast, works | +| Modern accessible React foundation | `@radix-ui/themes` | Primitives + polished theme | +| Modern SaaS where you own the components | shadcn/ui (`npx shadcn@latest add ...`) | You own the code, easy to customise; never ship default state | +| Tailwind-based modern SaaS / AI marketing | Tailwind v4 utilities + `dark:` variant | Default for indie + small team builds | + +**Honesty rule:** if the brief reads as one of the systems above, install and use the **official** package. Do not recreate its CSS by hand. Do not import a system's tokens but then override 90% of them. + +**One system per project.** Do not mix Fluent React with Carbon in the same tree. Do not import shadcn/ui components into a Material 3 app. + +### 2.B When the brief is an aesthetic, not a system +For these directions, there is **no single official package**. Build with native CSS + Tailwind + a maintained component library. Be honest in code comments about what is borrowed inspiration vs. official material. + +| Aesthetic | Honest implementation | +|---|---| +| Glassmorphism / "frosted glass" | `backdrop-filter`, layered borders, highlight overlays. Provide solid-fill fallback for `prefers-reduced-transparency`. | +| Bento (Apple-style tile grids) | CSS Grid with mixed cell sizes. No single library owns this. | +| Brutalism | Native CSS, monospace, raw borders. No library. | +| Editorial / magazine | Serif type, asymmetric grid, generous whitespace. No library. | +| Dark tech / hacker | Mono + accent neon, terminal motifs. No library. | +| Aurora / mesh gradients | SVG or layered radial gradients. No library. | +| Kinetic typography | Native CSS animations, scroll-driven animations, GSAP for hijacks. No library. | +| **Apple Liquid Glass** | Apple documents this for Apple platforms only. **There is no official `liquid-glass.css`.** Web implementations are approximations using `backdrop-filter` + layered borders + highlights. Label clearly as approximation. | + +--- + +## 3. DEFAULT ARCHITECTURE & CONVENTIONS + +Unless the design read picks a real design system (Section 2.A), these are the defaults: + +### 3.A Stack +* **Framework:** React or Next.js. Default to Server Components (RSC). + * **RSC SAFETY:** Global state works ONLY in Client Components. In Next.js, wrap providers in a `"use client"` component. + * **INTERACTIVITY ISOLATION:** Any component using Motion, scroll listeners, or pointer physics MUST be an isolated leaf with `'use client'` at the top. Server Components render static layouts only. +* **Styling:** **Tailwind v4** (default). Tailwind v3 only if the existing project demands it. + * For v4: do NOT use `tailwindcss` plugin in `postcss.config.js`. Use `@tailwindcss/postcss` or the Vite plugin. +* **Animation:** **Motion** (the library formerly known as Framer Motion). Import from `motion/react` (`import { motion } from "motion/react"`). The `framer-motion` package still works as a legacy alias - prefer `motion/react` in new code. +* **Fonts:** Always use `next/font` (Next.js) or self-host with `@font-face` + `font-display: swap`. Never link Google Fonts via `` in production. + +### 3.B State +* Local `useState` / `useReducer` for isolated UI. +* Global state ONLY for deep prop-drilling avoidance - Zustand, Jotai, or React context. +* **NEVER** use `useState` to track continuous values driven by user input (mouse position, scroll progress, pointer physics, magnetic hover). Use Motion's `useMotionValue` / `useTransform` / `useScroll`. `useState` re-renders the React tree on every change and collapses on mobile. + +### 3.C Icons +* **Allowed libraries (priority order):** `@phosphor-icons/react`, `hugeicons-react`, `@radix-ui/react-icons`, `@tabler/icons-react`. +* **Discouraged:** `lucide-react`. Acceptable only when the user explicitly asks for it or the project already depends on it. +* **NEVER hand-roll SVG icons.** If a glyph is missing, install a second library or compose from primitives - do not draw icon paths from scratch. +* **One family per project.** Do not mix Phosphor with Lucide in the same component tree. +* **Standardize `strokeWidth` globally** (e.g. `1.5` or `2.0`). + +### 3.D Emoji Policy +Discouraged by default in code, markup, and visible text. Replace symbols with icon-library glyphs. **Override:** allow emojis only when the user explicitly asks for a playful / chat-style / social-native vibe - and even then use them sparingly with intent. + +### 3.E Responsiveness & Layout Mechanics +* Standardize breakpoints (`sm 640`, `md 768`, `lg 1024`, `xl 1280`, `2xl 1536`). +* Contain page layouts using `max-w-[1400px] mx-auto` or `max-w-7xl`. +* **Viewport Stability:** NEVER use `h-screen` for full-height Hero sections. ALWAYS use `min-h-[100dvh]` to prevent layout jumping on mobile (iOS Safari address bar). +* **Grid over Flex-Math:** NEVER use complex flexbox percentage math (`w-[calc(33%-1rem)]`). ALWAYS use CSS Grid (`grid grid-cols-1 md:grid-cols-3 gap-6`). + +### 3.F Dependency Verification (mandatory) +Before importing ANY 3rd-party library, check `package.json`. If the package is missing, output the install command first. **Never** assume a library exists. + +--- + +## 4. DESIGN ENGINEERING DIRECTIVES (Bias Correction) + +LLMs default to clichés. Override these defaults proactively. Each rule has a context-aware override path. + +### 4.1 Typography +* **Display / Headlines:** Default `text-4xl md:text-6xl tracking-tighter leading-none`. +* **Body / Paragraphs:** Default `text-base text-gray-600 leading-relaxed max-w-[65ch]`. +* **Sans font choice:** + * **Discouraged as default:** `Inter`. Pick `Geist`, `Outfit`, `Cabinet Grotesk`, `Satoshi`, or a brand-appropriate serif first. + * **Override:** Inter is acceptable when the user explicitly asks for a neutral / standard / Linear-style feel, or when the brief is a public-sector / accessibility-first site. +* **Pairings to know:** `Geist` + `Geist Mono`, `Satoshi` + `JetBrains Mono`, `Cabinet Grotesk` + `Inter Tight`, `GT America` + `IBM Plex Mono`. + +* **SERIF DISCIPLINE (VERY DISCOURAGED AS DEFAULT):** + * Serif is **very discouraged as the default font for any project.** "It feels creative / premium / editorial" is NOT a reason to reach for serif. The agent's default mental model that "creative brief = serif" is the single most-tested AI tell in production rounds. + * **Serif is only acceptable when ONE of these is explicitly true:** + - The brand brief literally names a serif font, OR + - The aesthetic family is genuinely editorial / luxury / publication / manuscript / heritage / vintage AND you can articulate why this specific serif fits this specific brand + * For everything else (creative agency, design studio, modern brand, premium consumer, portfolio, lifestyle), **default sans-serif display** (Geist Display, ABC Diatype, Söhne Breit, Cabinet Grotesk Display, Migra Sans, GT Walsheim, Inter Display, PP Neue Montreal). Sans display fonts are not "boring" — they are the default for the same reason black is the default in fashion. + * **EMPHASIS RULE (related):** When you want to emphasize a word within a headline (the kinetic "and `spatial` design" type move), use **italic or bold of the SAME font**. Do NOT inject a random serif word into a sans headline (or vice versa) just to add visual interest. Mixed-family emphasis is amateur. Italic/bold emphasis in the same family is the right move. + * **Specifically BANNED as defaults:** `Fraunces` and `Instrument_Serif` (the two LLM-favorite display serifs). + * **If a serif is justified** (rare, per the above), rotate from this pool, do NOT reuse the same serif across consecutive projects: PP Editorial New, GT Sectra Display, Cardinal Grotesque, Reckless Neue, Tiempos Headline, Recoleta, Cormorant Garamond, Playfair Display, EB Garamond, IvyPresto, Migra, Editorial Old, Saol Display, Söhne Breit Kursiv, Domaine Display, Canela, Schnyder, Tobias, NB Architekt, ITC Galliard. + +* **ITALIC DESCENDER CLEARANCE (mandatory):** When italic is used in display type and the word contains a descender letter (`y g j p q`), `leading-[1]` or `leading-none` will clip the descender. Use `leading-[1.1]` minimum and add `pb-1` or `mb-1` reserve on the wrapping element. Audit every italic word in display headlines before shipping. + +### 4.2 Color Calibration +* Max 1 accent color. Saturation < 80% by default. +* **THE LILA RULE:** The "AI Purple / Blue glow" aesthetic is discouraged as a default. No automatic purple button glows, no random neon gradients. Use neutral bases (Zinc / Slate / Stone) with high-contrast singular accents (Emerald, Electric Blue, Deep Rose, Burnt Orange, etc.). +* **Override:** if the brand or brief explicitly asks for purple / violet / lila, embrace it. But execute with intent: consistent palette, harmonised neutrals, restrained gradients. Not generic AI gradient slop. +* **One palette per project.** Do not fluctuate between warm and cool grays within the same project. +* **COLOR CONSISTENCY LOCK (mandatory):** Once an accent color is chosen for a page, it is used on the WHOLE page. A warm-grey site does not suddenly get a blue CTA in section 7. A rose-accented site does not get a teal status badge in the footer. Pick one accent, lock it, audit every component before shipping. + +* **PREMIUM-CONSUMER PALETTE BAN (mandatory, second-most-recurring AI-tell):** + * For premium-consumer briefs (cookware, wellness, artisan, luxury, heritage craft, DTC home goods, etc.) the LLM default is **warm beige/cream + brass/clay/oxblood/ochre + espresso/ink dark text**. Concretely banned hex families as default backgrounds and accents: + - Backgrounds: `#f5f1ea`, `#f7f5f1`, `#fbf8f1`, `#efeae0`, `#ece6db`, `#faf7f1`, `#e8dfcb` (all "warm paper / cream / chalk / bone") + - Accents: `#b08947`, `#b6553a`, `#9a2436`, `#9c6e2a`, `#bc7c3a`, `#7d5621` (all "brass / clay / oxblood / ochre") + - Text: `#1a1714`, `#1a1814`, `#1b1814` (all "espresso / warm near-black") + * This palette is BANNED as the default reach for premium-consumer briefs. Every premium-consumer site you have ever shipped uses this exact palette. The brand becomes invisible. + * **Default alternatives (rotate, do not reuse):** + - **Cold Luxury:** silver-grey + chrome + smoke (think Tesla, Apple Watch Hermes-without-the-leather) + - **Forest:** deep green + bone + amber accent (think Filson, Patagonia premium) + - **Black and Tan:** true off-black + warm tan, sharp contrast, no beige + - **Cobalt + Cream:** saturated blue against a single neutral, no brass + - **Terracotta + Slate:** warm rust against cool grey, no brass + - **Olive + Brick + Paper:** muted olive plus brick-red accent + - **Pure monochrome + single saturated pop:** off-white + off-black + one bright accent (electric blue, emerald, hot pink, etc.) + * **Palette-rotation rule:** if the previous premium-consumer project you generated used the beige+brass family, this one MUST use a different family. Do not ship the same warm-craft palette twice in a row. + * **Override:** the beige+brass+espresso palette is acceptable ONLY when the brand brief explicitly names those colors, or when the brand identity is genuinely vintage / artisan / warm-craft AND you can articulate why this specific palette fits this specific brand. Default-reaching for it because "this is a cookware brief" is banned. + +### 4.3 Layout Diversification +* **ANTI-CENTER BIAS:** Centered Hero / H1 sections are avoided when `DESIGN_VARIANCE > 4`. Force "Split Screen" (50/50), "Left-aligned content / right-aligned asset", "Asymmetric white-space", or scroll-pinned structures. +* **Override:** centered hero is OK for editorial / manifesto / launch-announcement briefs where the message itself is the design. + +### 4.4 Materiality, Shadows, Cards +* Use cards ONLY when elevation communicates real hierarchy. Otherwise group with `border-t`, `divide-y`, or negative space. +* When a shadow is used, tint it to the background hue. No pure-black drop shadows on light backgrounds. +* For `VISUAL_DENSITY > 7`: generic card containers are banned. Data metrics breathe in plain layout. +* **SHAPE CONSISTENCY LOCK (mandatory):** Pick ONE corner-radius scale for the page and stick to it. Options: all-sharp (radius 0), all-soft (radius 12-16px), all-pill (full radius for interactive). Mixed systems are allowed only when there is a documented rule (e.g. "buttons are full-pill, cards are 16px, inputs are 8px") and that rule is followed everywhere. Round buttons in a square layout, or square cards on a pill-button page, is broken design. + +### 4.5 Interactive UI States +LLMs default to "static successful state only." Always implement full cycles: +* **Loading:** Skeletal loaders matching the final layout's shape. Avoid generic circular spinners. +* **Empty States:** Beautifully composed; indicate how to populate. +* **Error States:** Clear, inline (forms), or contextual (toasts only for transient). +* **Tactile Feedback:** On `:active`, use `-translate-y-[1px]` or `scale-[0.98]` to simulate a physical push. +* **BUTTON CONTRAST CHECK (mandatory, a11y):** Before shipping any button, verify the button text is readable against the button background. White button + white text, `bg-white` CTA with `text-white` label, transparent button against the page background with no border → all banned. Audit every CTA: contrast ratio WCAG AA min (4.5:1 for body, 3:1 for large text 18px+). Same rule applies to ghost buttons over photographic backgrounds (use a backdrop, scrim, or stroke). +* **CTA BUTTON WRAP BAN (mandatory):** Button text MUST fit on one line at desktop. If a label like "VIEW SELECTED WORK" wraps to 2 or 3 lines, the button is broken. Fix by EITHER shortening the label (3 words max for primary CTAs, ideally 1-2) OR widening the button (do not artificially constrain `max-width` on CTAs). Wrapped CTAs at desktop are a Pre-Flight Fail. +* **NO DUPLICATE CTA INTENT (mandatory):** Two CTAs with the same intent on one page is a Pre-Flight Fail. Examples of same intent: "Get in touch" + "Contact us" + "Let's talk" + "Start a project" + "Start something" + "Reach out" = all "contact" intent → pick ONE label and use it everywhere on the page (nav, hero, footer). Same for "Try free" + "Get started" + "Sign up free" (all "signup" intent) and "View work" + "See selected work" + "Browse projects" (all "portfolio" intent). One label per intent. +* **FORM CONTRAST CHECK (mandatory, a11y):** Form inputs, placeholder text, focus rings, helper text, and error text all pass WCAG AA contrast against the section background. Light placeholders on a near-white form, white form on white page section, form labels grayer than 4.5:1 contrast → all banned. Audit every form before shipping. + +### 4.6 Data & Form Patterns +* Label ABOVE input. Helper text optional but present in markup. Error text BELOW input. Standard `gap-2` for input blocks. +* No placeholder-as-label. Ever. + +### 4.7 Layout Discipline (Hard Rules. Failing any of these is shipping broken work) + +* **Hero MUST fit in the initial viewport.** Headline max 2 lines on desktop, subtext max **20 words** AND max 3-4 lines, CTAs visible without scroll. If the copy is too long: reduce font scale OR cut copy. If you cannot describe the value-prop in 20 words of subtext, the value-prop is unclear, not the rule too tight. Never let the hero overflow and force scroll to find the CTA. +* **Hero font-scale discipline.** Plan font size and image size *together*. If the hero asset is large and the headline is more than 6 words, do not start at `text-7xl/text-8xl`. Default sensible range: `text-4xl md:text-5xl lg:text-6xl` for most heroes; `text-6xl md:text-7xl` only when the headline is 3-5 words. A 4-line hero headline is always a font-size error, never a copy-length error. +* **HERO TOP PADDING CAP (mandatory):** Hero top padding max `pt-24` (≈6rem) at desktop. More than that means the hero content floats halfway down the viewport and reads as a layout bug, not as intentional space. If your hero needs more breathing room, increase font scale or asset size, not top padding. +* **HERO STACK DISCIPLINE (max 4 text elements).** The hero is a single moment, not a feature list. Allowed text elements, max 4 in total: + 1. Eyebrow (small uppercase label) OR brand strip OR neither - pick zero or one + 2. Headline (max 2 lines, see above) + 3. Subtext (max 20 words, max 4 lines) + 4. CTAs (1 primary + max 1 secondary) + - **BANNED in the hero:** tiny tagline below CTAs ("Works with GitHub, GitLab, and self-hosted Git"), trust micro-strip ("Used by engineering teams at..."), pricing teaser ("Free for solo, $10/user for teams"), feature bullet list, social-proof avatar row. All of those move to dedicated sections directly below the hero. + - If you have an eyebrow AND a tagline below CTAs in the same hero, drop the tagline. If you have a brand strip AND a tagline, drop the tagline. One small text element per hero, max. +* **"Used by" / "Trusted by" logo wall belongs UNDER the hero, never inside it.** The hero is for the value prop and primary CTA. The logo wall is a separate section directly below. Do not stuff trust logos into the same flex row as the hero copy. +* **Navigation MUST render on a single line on desktop.** If items don't fit at `lg` (1024px), condense labels, drop secondary items, or move to a hamburger. A two-line nav at desktop is broken design. +* **Navigation height cap: 80px max desktop, default 64-72px.** No huge "agency" nav bars that eat 15% of the viewport. +* **Bento grids MUST have rhythm, not one-sided repetition.** Do not stack 6 left-image / right-text rows. Vary the composition: alternate full-width feature rows, asymmetric tile sizes, vertical breaks. +* **BENTO CELL COUNT RULE (mandatory):** A bento grid has EXACTLY as many cells as you have content for. 3 items → 3 cells (1+2 split, or 2+1, or asymmetric trio). 5 items → 5 cells (2+3, 3+2, hero+4, etc.). If your grid has an empty cell in the middle or at the end, you planned wrong. Re-shape the grid; do not paste a blank tile. +* **Section-Layout-Repetition Ban.** Once you use a layout family for a section (e.g., 3-column-image-cards, full-width-quote, split-text-image), that family can appear at most ONCE on the page. "Selected commissions" must not look like "What we do." A landing page with 8 sections must use at least 4 different layout families. +* **ZIGZAG ALTERNATION CAP (mandatory).** Alternating "left-image + right-text" then "left-text + right-image" zigzag layout = banal. Max 2 sections in a row with this image+text-split pattern. The 3rd consecutive image+text split is a Pre-Flight Fail. Break the pattern with a full-width section, a vertical-stack section, a bento grid, a marquee, or a different layout family. +* **EYEBROW RESTRAINT (mandatory, the #1 violated rule in production tests).** An "eyebrow" is the small uppercase wide-tracking label sitting above a section headline (e.g. `FOUR COLORWAYS`, `SELECTED WORK`, `THE HARDWARE`, `Git-native task management`). Typical CSS signature: `text-[11px] uppercase tracking-[0.18em]`, `font-mono text-[10.5px] uppercase tracking-[0.22em]`. Every AI-built site puts an eyebrow above EVERY section header, producing the same templated rhythm. Hard rule: + - **Maximum 1 eyebrow per 3 sections.** Hero counts as 1. So a page with 9 sections may use at most 3 eyebrows total. + - If section A has an eyebrow, the next 2 sections cannot have one. + - **Pre-Flight Check is mechanical:** count instances of `uppercase tracking` (or similar small-caps mono labels above headlines) across all section components. If count > ceil(sectionCount / 3), the output fails. + - **What to do instead of an eyebrow:** drop it entirely. The headline alone is enough. If you need to categorize a section, the section's location on the page already categorizes it; no label needed. +* **SPLIT-HEADER BAN (mandatory).** The pattern "left big headline + right small explainer paragraph" as a section header (left col-span-7/8, right col-span-4/5 with a small body paragraph floating in the right column) is **banned as default**. Sections should have ONE focused message. If you genuinely need both a headline and an explainer paragraph, stack them vertically (headline on top, body below, max-width 65ch). Reach for the split-header pattern only when there is a real compositional reason (e.g., the right column carries a visual or interactive element, not just filler text). +* **Bento Background Diversity (mandatory).** Bento and feature-grid sections cannot be 6 white-on-white cards with text inside. At least 2-3 cells in any multi-cell grid need real visual variation: a real image, a brand-appropriate gradient (not AI-purple), a pattern, a tinted background. A cream-on-cream bento with only typography inside reads as boring AI default, even when the rest of the page is good. +* **Mobile collapse must be explicit per section.** For every multi-column layout, declare the `< 768px` fallback in the same component. No "it'll work, Tailwind handles it" assumptions. + +### 4.8 Image & Visual Asset Strategy + +Landing pages and portfolios are **visual products**. Text-only pages with fake-screenshot divs are slop. + +**Priority order for visual assets:** +1. **Image-generation tool first.** If ANY image-gen tool is available in the environment (`generate_image`, MCP image tool, IDE-integrated gen, OpenAI image tools, etc.) you MUST use it to create section-specific assets: hero photography, product shots, texture backgrounds, mood images. Generate at the right aspect ratio for the section. Do not skip this step because hand-rolled CSS feels faster. +2. **Real web images second.** When no gen tool is available, use real photography sources. Acceptable defaults: + * `https://picsum.photos/seed/{descriptive-seed}/{w}/{h}` for placeholder photography (seed should describe the section, e.g. `marrow-cookware-kitchen`) + * Actual stock or brand URLs when the brief provides them + * Open-license sources (Unsplash via direct URL, Pexels) if explicitly allowed +3. **Last resort: tell the user.** If neither is possible, do NOT fill the page with hand-rolled SVG illustrations or div-based "fake screenshots." Instead, leave clearly-labeled placeholder slots (``) and at the end of the response say: *"This page needs real images at: \[list of placements\]. Please generate or provide them."* + +**Even minimalist sites need real images.** A pure-text page is not minimalism. It is incomplete work. Even an editorial Linear-style site needs at least 2-3 real images (hero, one product/lifestyle shot, one supporting image). Generate B&W minimalist photography if the brief is restrained; do not skip images entirely because the dial is low. + +**Real company logos for social proof.** When the brief calls for a "Trusted by / Used by / Customers" logo wall, do NOT default to plain text wordmarks (`Acme Co` styled in a row). Use real SVG logos: +* **Source: Simple Icons** (`https://cdn.simpleicons.org/{slug}/ffffff` for any color, or `simple-icons` npm package). Covers most known brands. +* **Alternative: devicon** for tech-stack logos (`@svgr/cli` or CDN). +* **Make-up the brand name? Then make-up an SVG mark too.** Generate a simple monogram (one letter in a circle, two-letter ligature, abstract glyph) rendered as an inline `` matching the page style. Plain text wordmarks for invented brand names look generic. +* **Always** ensure logos render in both light and dark mode (white-on-dark, black-on-light, or single-color theme variable). +* **LOGO-ONLY rule (mandatory):** logo wall = logos and nothing else. Do NOT print industry / category labels below each logo (no `Vercel` + `hosting` underneath, no `Stripe` + `payments`, no `Cloudflare` + `infra`). The logo is the credibility, the label adds nothing the user does not already know. Optional: brand name as alt-text for screen readers, optional link to the brand's site. That is it. + +**Hand-rolled illustrations:** +* SVG icons from libraries: fine (see Section 3.C). +* Hand-rolled decorative SVGs (custom illustrations, logos, marks): **strongly discouraged**, never as default. Acceptable only when: + - The brief explicitly calls for it ("draw me an SVG logo") + - It's a single, simple geometric mark (a square, a circle, a wordmark in display type) + - You're confident in the output quality + +**Div-based fake screenshots are banned.** A "hand-built product preview" rendered with `
` rectangles, fake task lists, fake dashboards, fake terminal windows is a Tell. If you need to show a product: +* Use a real screenshot URL if one exists +* Generate one via image tool +* Use a real component preview (an actual mini-version of the UI inside the page) +* Or skip the preview entirely and use editorial photography + +**Hero needs a real visual.** Text + gradient blob is not a hero - it's a placeholder. + +### 4.9 Content Density + +Landing pages live on the **first impression**, not the full read. Cut ruthlessly. + +* **Default content shape per section:** short headline (≤ 8 words) + short sub-paragraph (≤ 25 words) + one visual asset OR one CTA. Anything more must be justified by the section's job. +* **No data-dump sections.** A 20-row publication table, a 30-row award list, a giant pricing matrix on a marketing page = wrong layout. Use: + - Top 3-5 highlights + "View full list" link + - Marquee / carousel for breadth + - Different page entirely if the data is the product +* **Long lists need a different UI component, not a longer list.** Default `
    ` with bullets / `divide-y` rows is the lazy choice. If you have > 5 items, reach for one of these instead: + - 2-column split with grouped items + - Card grid with image + label per item + - Tabs / accordion if items are categorisable + - Horizontal scroll-snap pills + - Carousel for breadth-heavy lists (testimonials, logos, capabilities) + - Marquee for "lots-of-things-that-don't-need-individual-attention" + A spec sheet with 10 rows + a hairline under every row is the WORST default. Either group rows into 2-3 chunks with sparse dividers, or move to a card-per-spec layout. +* **Spec sheets specifically (the Marrow-cookware pattern).** A long product specification table with `border-b` on every row is the AI default for cookware / hardware / apparel / artisan-goods briefs. Banned. Concrete alternatives: + - **2-col card grid:** each spec gets its own card with the spec name, the value (large display number), and a one-line "why it matters" body. Cards arranged 2-col on desktop, 1-col mobile. + - **Scroll-snap horizontal pills:** each spec is a pill, user can flick through. + - **Grouped chunks:** group 10 specs into 3 logical clusters (e.g. "Materials", "Cooking", "Warranty"), each cluster gets ONE soft divider and a cluster heading. + - **Featured-vs-rest:** 3-4 hero specs visualised as large display tiles, the rest collapsed under a "View full specifications" disclosure. + +* **COPY SELF-AUDIT (mandatory before ship):** Before declaring any task done, re-read every visible string on the page (headlines, subheads, eyebrows, button labels, body copy, captions, alt text, footer text, error messages). Flag any string that is: + - **Grammatically broken** ("free on its past", "two plans but one is honest", "to put it on the table" out of context) + - **Has unclear referents** ("we plan to stay that way" without prior context) + - **Sounds like AI hallucination** (cute-but-wrong wordplay, forced metaphors that don't track, "elegant nothing" phrases) + - **Reads like an LLM trying to sound thoughtful** (passive-aggressive humility, fake-craftsman labels, mock-poetic micro-meta) + Rewrite every flagged string. If unsure whether a string makes sense, replace it with a plain functional sentence. AI-generated cute copy is worse than boring copy. +* **Fake-precise numbers are flagged.** Numbers like `92%`, `4.1×`, `48k`, `5.8 mm`, `13.4 lb` either: + - Come from real data (brief, brand guidelines, public metrics) - fine + - Are explicitly labeled as mock (``, "example", "sample data") - fine + - Are AI-invented spec aesthetics - banned. Don't fake engineering precision the brand doesn't claim. +* **One copy register per page.** Don't mix technical mono ("47 tasks · 0.6 ctx-switches/day"), editorial prose, and marketing punch in the same composition unless the brand voice explicitly calls for it. + +### 4.10 Quotes & Testimonials + +* **Max 3 lines** of quote body. Never 6. If the original quote is longer → cut it. A landing-page quote is a snippet, not the full review. +* For very small font sizes (e.g. footer-style testimonials), the line cap can stretch slightly. Spirit: "fits in a glance." +* **No em-dashes inside the quote text** as design flourish (long pauses, kinetic em-dashes, em-dash-bullets). See Section 9.G - em-dash is completely banned. +* Attribution: name + role + (optionally) company. Never name only ("- Sarah"). +* Quote marks: use real typographic quotes ( " " ) or none at all. Not straight ASCII ( " ). + +### 4.11 Page Theme Lock (Light / Dark Mode Consistency) + +The page has ONE theme. Sections do not invert. + +* If the page is dark mode, ALL sections are dark mode. No light-mode-warm-paper section sandwiched between dark sections (or vice versa). The user must not feel they walked into a different website mid-scroll. +* The exception: if the brief explicitly calls for a "Color Block Story" or "Theme Switch on Scroll" device AND that is a deliberate composition (one full theme switch with a strong transition, not random alternation), it is allowed once per page. +* Default behaviour: pick light, dark, or auto (`prefers-color-scheme`) at the page level and lock it. Section-level background tints within the same theme family are fine (`bg-zinc-950` next to `bg-zinc-900`); flipping to `bg-amber-50` in the middle of a `bg-zinc-950` page is broken. +* When using a design system with built-in theming (Radix Themes, shadcn/ui with ``), set the theme ONCE in `layout.tsx` or the page root. Do not let individual sections override. + +--- + +## 5. CONTEXT-AWARE PROACTIVITY + +These are tools, not defaults. Use them when the design read calls for them. **None of these fire automatically.** + +* **Liquid Glass / Glassmorphism:** Appropriate for premium consumer, Apple-adjacent, luxury brand, or media-overlay vibes. Inappropriate for dashboards, public-sector, or "boring B2B." When used, go beyond `backdrop-blur`: add a 1px inner border (`border-white/10`) and a subtle inner shadow (`shadow-[inset_0_1px_0_rgba(255,255,255,0.1)]`) for physical edge refraction. Provide a solid-fill fallback under `prefers-reduced-transparency`. +* **Magnetic Micro-physics:** Use when `MOTION_INTENSITY > 5` AND the brief reads premium / playful / agency. Implement EXCLUSIVELY with Motion's `useMotionValue` / `useTransform` outside the React render cycle. Never `useState`. See Section 3.B. +* **Perpetual Micro-Interactions** (Pulse, Typewriter, Float, Shimmer, Carousel): Use when `MOTION_INTENSITY > 5` AND the section actively benefits from motion (status indicators, live feeds, AI-feel). **Not every card needs an infinite loop.** If a section is informational, leave it still. Apply Spring Physics (`type: "spring", stiffness: 100, damping: 20`) - no linear easing. +* **"Motion claimed, motion shown."** If `MOTION_INTENSITY > 4`, the page must actually move: entry transitions on hero, scroll-reveal on key sections, hover physics on CTAs, at minimum. A static page that claims `MOTION_INTENSITY: 7` is broken. Conversely, if you cannot ship working motion in the available scope, drop the dial to 3 and ship a clean static page. Never half-build motion that breaks (cut-off ScrollTriggers, jumpy enters, missing cleanups). +* **MOTION MUST BE MOTIVATED (mandatory).** Before adding any animation, ask: "what does this animation communicate?" Valid answers: hierarchy (drawing attention to the right thing), storytelling (revealing content in sequence that matches a narrative), feedback (acknowledging a user action), state transition (showing something changed). Invalid answer: "it looked cool". GSAP everywhere because GSAP is available is amateur. Each ScrollTrigger, each marquee, each pinned section needs a reason. If you cannot articulate the reason in one sentence, drop the animation. +* **MARQUEE MAX-ONE-PER-PAGE (mandatory).** Horizontal scrolling text marquees ("logos endlessly scrolling", "manifesto scrolling sideways", "kinetic word strip") are appropriate at most ONCE per page. Two or more marquees on the same page reads as lazy filler. Pick the one section where the marquee actually serves the content; the others get a different layout. +* **GSAP Sticky-Stack Pattern (when scroll-stack is used).** A "card stack on scroll" must be a REAL sticky-stack, not a sequential reveal list. See Section 5.A below for the canonical code skeleton. Common failure: trigger fires halfway through scroll instead of pinning at viewport top. Fix: `start: "top top"` not `start: "top center"` or `"top 80%"`. +* **GSAP Horizontal-Pan Pattern (when horizontal scroll-hijack is used).** See Section 5.B below for the canonical skeleton. Common failure: animation starts before the section is pinned, so the user sees half a slide. Same fix: `start: "top top"`, pin the wrapper, scrub the inner track. + +### 5.A Sticky-Stack - Canonical Skeleton + +```tsx +"use client"; +import { useRef, useEffect } from "react"; +import { gsap } from "gsap"; +import { ScrollTrigger } from "gsap/ScrollTrigger"; +import { useReducedMotion } from "motion/react"; + +gsap.registerPlugin(ScrollTrigger); + +export function StickyStack({ cards }: { cards: React.ReactNode[] }) { + const ref = useRef(null); + const reduce = useReducedMotion(); + + useEffect(() => { + if (reduce || !ref.current) return; + const ctx = gsap.context(() => { + const cardEls = gsap.utils.toArray(".stack-card"); + cardEls.forEach((card, i) => { + if (i === cardEls.length - 1) return; + ScrollTrigger.create({ + trigger: card, + start: "top top", // pin at viewport top + endTrigger: cardEls[cardEls.length - 1], + end: "top top", + pin: true, + pinSpacing: false, + }); + gsap.to(card, { + scale: 0.92, + opacity: 0.55, + ease: "none", + scrollTrigger: { + trigger: cardEls[i + 1], + start: "top bottom", + end: "top top", + scrub: true, + }, + }); + }); + }, ref); + return () => ctx.revert(); + }, [reduce]); + + return ( +
    + {cards.map((card, i) => ( +
    + {card} +
    + ))} +
    + ); +} +``` + +Critical points: `start: "top top"`, `pin: true`, every card except the last is pinned, the scale/opacity transform is driven by the NEXT card's scroll trigger (so previous card shrinks as next one arrives). + +### 5.B Horizontal-Pan - Canonical Skeleton + +```tsx +"use client"; +import { useRef, useEffect } from "react"; +import { gsap } from "gsap"; +import { ScrollTrigger } from "gsap/ScrollTrigger"; +import { useReducedMotion } from "motion/react"; + +gsap.registerPlugin(ScrollTrigger); + +export function HorizontalPan({ children }: { children: React.ReactNode }) { + const wrap = useRef(null); + const track = useRef(null); + const reduce = useReducedMotion(); + + useEffect(() => { + if (reduce || !wrap.current || !track.current) return; + const ctx = gsap.context(() => { + const distance = track.current!.scrollWidth - window.innerWidth; + gsap.to(track.current, { + x: -distance, + ease: "none", + scrollTrigger: { + trigger: wrap.current, + start: "top top", // pin starts when section top hits viewport top + end: () => `+=${distance}`, // scroll distance = track width minus viewport + pin: true, + scrub: 1, + invalidateOnRefresh: true, + }, + }); + }, wrap); + return () => ctx.revert(); + }, [reduce]); + + return ( +
    +
    + {children} +
    +
    + ); +} +``` + +Critical points: `start: "top top"`, `pin: true`, `end: "+=${distance}"` (scroll length = horizontal travel needed), `scrub: 1`. The wrapper is pinned, the inner track slides horizontally as the user scrolls vertically. + +### 5.C Scroll-Reveal Stagger - Canonical Skeleton (lighter alternative) + +For simple "items appear as they enter viewport" (no pinning), prefer Motion's `whileInView` over GSAP - lighter, no ScrollTrigger needed: + +```tsx +"use client"; +import { motion, useReducedMotion } from "motion/react"; + +export function RevealStagger({ items }: { items: string[] }) { + const reduce = useReducedMotion(); + return ( +
      + {items.map((item, i) => ( + + {item} + + ))} +
    + ); +} +``` + +Use this for: feature lists, testimonial grids, logo walls, anything that just needs "enter on scroll." Save GSAP for actual pin/scrub work. + +### 5.D Forbidden Animation Patterns + +* **`window.addEventListener("scroll", ...)`** is banned. It runs on every scroll frame, jank-prone, no batching. Use Motion's `useScroll()`, GSAP's `ScrollTrigger`, IntersectionObserver, or CSS `scroll-driven animations` (`animation-timeline: view()`). +* **Custom scroll progress calculations using `window.scrollY`** in React state. Same reason. Re-renders on every frame. +* **`requestAnimationFrame` loops that touch React state.** Use motion values (`useMotionValue` + `useTransform`) instead. +* **Layout Transitions:** Use Motion's `layout` and `layoutId` props for visible state changes (re-ordering lists, expanding modals, shared elements between routes). Do not wrap static content in `layout` props "for safety" - it costs measurement work. +* **Staggered Orchestration:** Use `staggerChildren` (Motion) or CSS cascade (`animation-delay: calc(var(--index) * 100ms)`) for reveal moments where sequence matters. For `staggerChildren`, parent (`variants`) and children MUST share the same Client Component tree. + +--- + +## 6. PERFORMANCE & ACCESSIBILITY GUARDRAILS + +### 6.A Hardware Acceleration +* Animate ONLY `transform` and `opacity`. Never animate `top`, `left`, `width`, `height`. +* Use `will-change: transform` sparingly - only on elements that will actually animate. + +### 6.B Reduced Motion (mandatory) +* **Any motion above `MOTION_INTENSITY > 3` MUST honor `prefers-reduced-motion`.** This is non-negotiable. +* In Motion: wrap with `useReducedMotion()` and degrade to static. +* In CSS: gate animations behind `@media (prefers-reduced-motion: no-preference)` or provide an override block under `@media (prefers-reduced-motion: reduce)` that disables. +* Infinite loops, parallax, scroll-hijack, and magnetic physics MUST collapse to static / instant under reduced motion. + +### 6.C Dark Mode (mandatory for any consumer-facing page) +* Design for **both modes from the start**. Never ship light-only or dark-only without explicit user instruction. +* Use Tailwind `dark:` variant OR CSS variables for tokens. Pick one strategy per project. +* **Do not prescribe specific dark-mode colors here.** The brief decides. Maintain visual hierarchy, brand identity, and WCAG AA contrast (AAA for body) across both modes. +* Respect `prefers-color-scheme: dark`. Default to system preference unless the brand insists on one mode. + +### 6.D Core Web Vitals Targets +* **LCP** < 2.5s. Hero image must be `next/image priority` or preloaded. +* **INP** < 200ms. Heavy work off main thread. +* **CLS** < 0.1. Reserve space for images, fonts, embeds. +* Run Lighthouse before declaring a page done. + +### 6.E DOM Cost +* Apply grain / noise filters EXCLUSIVELY to fixed, `pointer-events-none` pseudo-elements (e.g., `fixed inset-0 z-[60] pointer-events-none`). NEVER on scrolling containers - continuous GPU repaints destroy mobile FPS. +* Be aware of bundle size. Motion is not tiny. Three.js is large. Lazy-load anything that's not above-the-fold. + +### 6.F Z-Index Restraint +NEVER spam arbitrary `z-50` or `z-10`. Use z-index strictly for systemic layer contexts (sticky navbars, modals, overlays, grain). Document the z-index scale in a project constants file. + +--- + +## 7. DIAL DEFINITIONS (Technical Reference) + +### DESIGN_VARIANCE (Level 1-10) +* **1-3 (Predictable):** Symmetrical CSS Grid (12-col, equal fr-units), equal paddings, centered alignment. +* **4-7 (Offset):** `margin-top: -2rem` overlaps, varied image aspect ratios (4:3 next to 16:9), left-aligned headers over center-aligned data. +* **8-10 (Asymmetric):** Masonry layouts, CSS Grid with fractional units (`grid-template-columns: 2fr 1fr 1fr`), massive empty zones (`padding-left: 20vw`). +* **MOBILE OVERRIDE:** For levels 4-10, asymmetric layouts above `md:` MUST collapse to strict single-column (`w-full`, `px-4`, `py-8`) on viewports `< 768px`. + +### MOTION_INTENSITY (Level 1-10) +* **1-3 (Static):** No automatic animations. CSS `:hover` and `:active` states only. `prefers-reduced-motion` is the default mode anyway. +* **4-7 (Fluid CSS):** `transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1)`. `animation-delay` cascades for load-ins. Focus on `transform` and `opacity`. +* **8-10 (Advanced Choreography):** Complex scroll-triggered reveals, parallax, scroll-driven animation (CSS `animation-timeline` or GSAP ScrollTrigger). Use Motion hooks. **NEVER use `window.addEventListener('scroll')`** - it is a hard ban, not a "prefer-not." See Section 5.D for the allowed alternatives. + +### VISUAL_DENSITY (Level 1-10) +* **1-3 (Art Gallery):** Lots of white space. Huge section gaps (`py-32` to `py-48`). Expensive, clean. +* **4-7 (Daily App):** Standard web app spacing (`py-16` to `py-24`). +* **8-10 (Cockpit):** Tight paddings. No card boxes; 1px lines separate data. Mandatory: `font-mono` for all numbers. + +--- + +## 8. DARK MODE PROTOCOL + +Dual-mode by default. Never assume light-only unless the brief is print-emulating editorial. + +### 8.A Token Strategy (pick one, stick to it) +* **Tailwind `dark:` variant** (default for utility-first projects): every color utility paired with its dark variant (`bg-white dark:bg-zinc-950`, `text-gray-900 dark:text-gray-100`). +* **CSS variables** (for shadcn/ui, Radix Themes, or component libraries with theming): define semantic tokens (`--surface`, `--surface-elevated`, `--text-primary`, `--accent`) and swap values under `[data-theme="dark"]` or `@media (prefers-color-scheme: dark)`. + +### 8.B Do Not Prescribe Specific Colors Here +The brief and brand decide. This skill enforces only: +* **Contrast** - WCAG AA minimum for body text, AAA target for hero copy. +* **Hierarchy parity** - visual hierarchy that works in light must work in dark. If a CTA pops in light, it pops in dark. +* **Brand fidelity** - primary brand color stays recognisable. Don't desaturate the brand into a dark mode. +* **No pure `#000000` and no pure `#ffffff`** - use off-black (zinc-950, near-black warm gray) and off-white. Pure values kill depth. + +### 8.C Default Mode +Respect `prefers-color-scheme` unless the brand insists. Add a manual toggle if either mode would lose key brand expression. + +### 8.D Test in Both Modes Before Finishing +Open the page in both modes during development. Do not ship a page you've only seen in one mode. + +--- + +## 9. AI TELLS (Forbidden Patterns) + +Avoid these signatures unless the brief explicitly asks for them. + +### 9.A Visual & CSS +* **NO neon / outer glows** by default. Use inner borders or subtle tinted shadows. +* **NO pure black (`#000000`).** Off-black, zinc-950, or charcoal. +* **NO oversaturated accents.** Desaturate to blend with neutrals. +* **NO excessive gradient text** for large headers. +* **NO custom mouse cursors.** Outdated, accessibility-hostile, perf-hostile. + +### 9.B Typography +* **AVOID Inter as default.** See Section 4.1. Override path exists. +* **NO oversized H1s** that just scream. Control hierarchy with weight + color, not raw scale. +* **Serif constraints:** Serif for editorial / luxury / publication. Not for dashboards. + +### 9.C Layout & Spacing +* **Mathematically perfect** padding and margins. No floating elements with awkward gaps. +* **NO 3-column equal feature cards.** The generic "three identical cards horizontally" feature row is banned. Use 2-column zig-zag, asymmetric grid, scroll-pinned, or horizontal-scroll alternative. + +### 9.D Content & Data ("Jane Doe" Effect) +* **NO generic names.** "John Doe", "Sarah Chan", "Jack Su" → use creative, realistic, locale-appropriate names. +* **NO generic avatars.** No SVG "egg" or Lucide user icons → use believable photo placeholders or specific styling. +* **NO fake-perfect numbers.** Avoid `99.99%`, `50%`, `1234567`. Use organic, messy data (`47.2%`, `+1 (312) 847-1928`). +* **NO startup-slop brand names.** "Acme", "Nexus", "SmartFlow", "Cloudly" → invent contextual, premium names that sound real. +* **NO filler verbs.** "Elevate", "Seamless", "Unleash", "Next-Gen", "Revolutionize" → concrete verbs only. + +### 9.E External Resources & Components +* **NO hand-rolled SVG icons.** Use Phosphor / HugeIcons / Radix / Tabler. Lucide on explicit request only. +* **Hand-rolled decorative SVGs strongly discouraged** as default (see Section 4.8). +* **NO div-based fake screenshots.** Never build a fake product UI out of `
    ` rectangles to simulate a screenshot. Use real images, generated images, or skip the preview. +* **NO broken Unsplash links.** Use `https://picsum.photos/seed/{descriptive-string}/{w}/{h}`, or generated photo placeholders, or actual assets. +* **shadcn/ui customization:** Allowed, but NEVER in default state. Customize radii, colors, shadows, typography to the project aesthetic. +* **Production-Ready Cleanliness:** Code visually clean, memorable, meticulously refined. + +### 9.F Production-Test Tells (banned outright) + +These patterns came out of real LLM-generated landing-page tests. They are the signatures the model defaults to when it tries to "look designed." Treat them as hard bans unless the brief explicitly calls for one. + +**Hero & top-of-page** +* **NO version labels in the hero.** `V0.6`, `v2.0`, `BETA`, `INVITE-ONLY PREVIEW`, `EARLY ACCESS`, `ALPHA` - banned as default eyebrows. Only acceptable when the brief is explicitly about a product launch / preview status. +* **NO "Brand · No. 01"-style sub-eyebrows.** "Marrow · No. 01 · The 6-quart" type micro-meta lines. Skip them. + +**Section numbering & micro-labels** +* **NO section-number eyebrows.** `00 / INDEX`, `001 · Capabilities`, `002 · Featured commission`, `06 · how it works`, `05 · The honest table` - banned. Eyebrows should name the topic in plain language, not enumerate. +* **NO `01 / 4`-style pagination on images or bento tiles.** If the user can count, they don't need the label. +* **NO `Scroll · 001 Capabilities`-style scroll cues.** A simple arrow or "Scroll" is enough; no section-number prefix. +* **NO "Index of Work, 2018 - 2026"-style range labels** as eyebrows. Just say what the section is. + +**Separators & dots** +* **The middle-dot (`·`) is rationed.** Maximum 1 per line in metadata strips. Do NOT use it as the default separator for everything ("foo · bar · baz · qux · quux"). If you need a separator family, prefer line breaks, hairlines, or columns. +* **NO decorative colored status dots on every list/nav/badge.** A colored dot before "ONE Q4 SLOT OPEN" or before every nav link, or every task row - banned by default. Acceptable only when the dot conveys actual semantic state (a server status, an availability flag) and is used sparingly. + +**Em-dashes & typography flourishes** +* **NO em-dash (`—`) as a design element OR anywhere else.** See Section 9.G below for the complete, non-negotiable ban. The em-dash character is forbidden in headlines, eyebrows, pills, body copy, quotes, attribution, captions, button text, and alt text. Use the regular hyphen (`-`). +* **NO `
    `-broken-and-italicized headlines** as a default "design move." "for thirty\*years.*" type splits. Headlines should read naturally first, get clever only when the brief demands it. +* **NO vertical rotated text** ("INDEX OF WORK, 2018 - 2026" rotated 90°). Agency-portfolio cliché. Use it only when the brief is explicitly agency / Awwwards / experimental AND it serves a real composition purpose. +* **NO crosshair / hairline grid lines as decoration.** Vertical and horizontal lines drawn just to make the page "feel designed" - banned. Use them only when they organize real content. + +**Fake product previews** +* **NO div-based fake product UI in the hero** (fake task list, fake terminal, fake dashboard built from styled divs). It is the #1 LLM-design Tell. Use a real screenshot, a generated image, a real component preview, or none at all. +* **NO fake version footers** ("v0.6.2-rc.1", "last sync 4s ago · main") inside fake screenshots. Adds nothing, screams AI. + +**Marketing-copy Tells** +* **NO "Quietly in use at" / "Quietly trusted by"** social-proof headers. Use natural language: "Trusted by", "Used at", "Customers include", or skip the heading entirely if the logos speak. +* **NO "From the field" / "Field notes" / "Currently on the bench" / "On our desks" / "Loose plates" style poetic labels** on quote, blog, or sidebar sections. Reads as performative-craftsman. Use plain functional labels ("Testimonials", "Latest writing", "Now working on") or skip the label. +* **NO "We respect the French ones"-style** mock-humble industry-references in body copy. Cute and AI-y. +* **NO weather / locale strips** ("LIS 14:23 · 18°C") in headers/footers unless the brief is explicitly about a place / time-zone-distributed studio. +* **NO micro-meta-sentences under eyebrows.** Sentences like *"Each of these is a feature we ship today, not a roadmap promise. The list will stay short on purpose."* sitting under a section heading are clutter. Eyebrow + Headline + Body is enough. +* **NO generic step labels.** "Stage 1 / Stage 2 / Stage 3", "Step 1 / Step 2 / Step 3", "Phase 01 / Phase 02 / Phase 03", "Pass One / Pass Two / Pass Three". Banned. The actual step content is the label. If you must show progression, use the verb-noun directly ("Install", "Configure", "Ship") not "Stage 1: Install". + +**Pills, labels and version stamps** +* **NO pills/labels/tags overlaid on images.** No `` overlays on photos with tags like `Brand · 02`, `PLATE · BRAND`, `Field notes - journal`. Either let the image speak alone, or add a caption directly below (outside the image). +* **NO photo-credit captions as decoration.** Strings like `Field study no. 12 · Ines Caetano`, `Plate 03 · House archive`, `Frame XII · 35mm` under stock/picsum images are pretentious. Photo credit is allowed ONLY when there is a real photographer being credited for a real photo (with permission). Otherwise: skip the caption or use a one-line functional caption ("The 6-quart, in Sage."). +* **NO version footers on marketing pages.** Footer strings like `v1.4.2`, `Build 0048`, `last sync 4s ago · main` are CLI / devtool fixtures, not landing-page content. Banned on marketing/landing/portfolio pages. +* **NO "Reservation 412 of 800"-style live-stock counters** as decoration. Only if the brief is explicitly a limited-run waitlist with real data. + +**Decoration text strips** +* **NO decoration text strip at hero bottom.** Patterns like `BRAND. MOTION. SPATIAL.`, `TYPE / FORM / MOTION`, `DESIGN · BUILD · SHIP`, `ESTD. 2018 · LISBON · BRAND. MOTION. SPATIAL.` as a small mono-caps strip across the bottom of the hero are an agency-portfolio cliché. Banned by default. Only acceptable when the strip carries real, navigable links (sticky bottom nav) or real status info (cookie banner, build info on a docs site). +* **NO floating top-right sub-text in section headings.** Pattern: section has a giant left-aligned headline; in the top-right corner of the same section header there is a small explainer paragraph floating with no clear alignment to anything else. That floater is the Tell. Either put the sub-text directly under the headline, or build a clean 2-column header (left: headline, right: aligned body), but not a tiny corner paragraph. + +**Lists, dividers and scoring** +* **NO `border-t` + `border-b` on every row of a long list / spec table.** Pick one (bottom-border between rows OR top-border above the group) and use it sparsely. A 10-row spec table with hairlines under each row is the laziest layout - see Section 4.9 for alternative UI components. +* **NO scoring/progress bars with filled background tracks** as comparison visuals. If you need to show "X out of Y" comparisons, prefer a number + small icon, or a tiny inline bar WITHOUT a background track. Big filled `bg-zinc-200` tracks with a partial fill on top are dashboard-UI clutter on a landing page. + +**Locale, time, scroll cues** +* **Locale / city-name / time / weather strips are banned for 99% of briefs.** "Lisbon, working with founders" in the hero, "1200-690 Lisbon, Portugal" in the footer, "Lisbon 14:23 · 18°C" in the nav. These are agency-portfolio decoration tells. Allowed ONLY when: the brief explicitly describes a globally-distributed studio with timezone-relevant work, OR a travel-focused brand, OR a real-world physical venue. A single contact-address mention in the footer is fine; an atmospheric locale strip is not. +* **Scroll cues are banned.** `Scroll`, `↓ scroll`, `Scroll to explore`, `Scroll to walk through it`, animated mouse-wheel icons. If the user has not scrolled yet, they are looking at the hero. They know what scroll is. The bottom of the viewport does not need a label. +* **ZERO decorative status dots by default.** A coloured dot before nav items, before list rows, before badges, before status labels is a Tell. Only acceptable when conveying real semantic state (a live indicator on actual server status, a live availability flag) and limited to one per page section. + +### 9.G EM-DASH BAN (the single most-violated Tell) + +**Em-dash (`—`) is COMPLETELY banned.** It is the LLM's signature stylistic crutch and it is the #1 visual Tell in production tests. There is no "limited use" allowance, no "natural language frequency" allowance, no "in body copy is fine" allowance. None. + +* **Banned in headlines.** Use a period or a comma. +* **Banned in eyebrows / labels / pills / button text / image captions / nav items.** Replace with line breaks, columns, or hairlines. +* **Banned in body copy.** Restructure the sentence: two sentences with a period, OR a comma, OR parentheses, OR a colon. +* **Banned in quote attribution.** Use a normal hyphen with spaces (` - `) or a line break + smaller-weight name. +* **Banned in en-dash form too (`–`) when used as a separator.** Date ranges (`2018-2026`) use a hyphen. Number ranges (`€40-80k`) use a hyphen. + +The ONLY permitted dash characters on the page are: +* Regular hyphen `-` (for compound words, ranges, line dividers in markup) +* Minus sign in math (`-5°C`) + +If your output contains a single `—` or `–` anywhere visible to the user, the output fails the Pre-Flight Check and must be rewritten. + +This rule is non-negotiable. The agent has historically ignored em-dash limits when phrased as "use sparingly." The phrasing here is binary: zero em-dashes. + +--- + +## 10. REFERENCE VOCABULARY (Pattern Names the Agent Should Know) + +This is a vocabulary, not a library. The agent should KNOW these pattern names to communicate about them, design with them in mind, and reach for them when the design read calls for them. **Implementations and code sketches live in the Block Library (Section 12), which is populated iteratively.** + +### Hero Paradigms +* **Asymmetric Split Hero** - Text on one side, asset on the other, generous white space. +* **Editorial Manifesto Hero** - Large type, no asset, almost-poster. +* **Video / Media Mask Hero** - Type cut out as mask over video background. +* **Kinetic-Type Hero** - Animated typography as the primary visual. +* **Curtain-Reveal Hero** - Hero parts on scroll like a curtain. +* **Scroll-Pinned Hero** - Hero stays pinned while content scrolls behind. + +### Navigation & Menus +* **Mac OS Dock Magnification** - Edge nav, icons scale fluidly on hover. +* **Magnetic Button** - Pulls toward cursor. +* **Gooey Menu** - Sub-items detach like viscous liquid. +* **Dynamic Island** - Morphing pill for status / alerts. +* **Contextual Radial Menu** - Circular menu expanding at click point. +* **Floating Speed Dial** - FAB springing into curved secondary actions. +* **Mega Menu Reveal** - Full-screen dropdown, stagger-fade content. + +### Layout & Grids +* **Bento Grid** - Asymmetric tile grouping (Apple Control Center). +* **Masonry Layout** - Staggered grid, no fixed row height. +* **Chroma Grid** - Borders / tiles with subtle animating gradients. +* **Split-Screen Scroll** - Two halves sliding in opposite directions. +* **Sticky-Stack Sections** - Sections that pin and stack on scroll. + +### Cards & Containers +* **Parallax Tilt Card** - 3D tilt tracking mouse coordinates. +* **Spotlight Border Card** - Borders illuminate under cursor. +* **Glassmorphism Panel** - Frosted glass with inner refraction. +* **Holographic Foil Card** - Iridescent rainbow shift on hover. +* **Tinder Swipe Stack** - Physical card stack, swipe-away. +* **Morphing Modal** - Button expands into its own dialog. + +### Scroll Animations +* **Sticky Scroll Stack** - Cards stick and physically stack. +* **Horizontal Scroll Hijack** - Vertical scroll → horizontal pan. +* **Locomotive / Sequence Scroll** - Video / 3D sequence tied to scrollbar. +* **Zoom Parallax** - Central background image zooming on scroll. +* **Scroll Progress Path** - SVG line drawing along scroll. +* **Liquid Swipe Transition** - Page transition like viscous liquid. + +### Galleries & Media +* **Dome Gallery** - 3D panoramic gallery. +* **Coverflow Carousel** - 3D carousel with angled edges. +* **Drag-to-Pan Grid** - Boundless draggable canvas. +* **Accordion Image Slider** - Narrow strips expanding on hover. +* **Hover Image Trail** - Mouse leaves popping image trail. +* **Glitch Effect Image** - RGB-channel shift on hover. + +### Typography & Text +* **Kinetic Marquee** - Endless text bands reversing on scroll. +* **Text Mask Reveal** - Massive type as transparent window to video. +* **Text Scramble Effect** - Matrix-style decoding on load / hover. +* **Circular Text Path** - Text curving along spinning circle. +* **Gradient Stroke Animation** - Outlined text with running gradient. +* **Kinetic Typography Grid** - Letters dodging the cursor. + +### Micro-Interactions & Effects +* **Particle Explosion Button** - CTA shatters into particles on success. +* **Liquid Pull-to-Refresh** - Reload indicator like detaching droplets. +* **Skeleton Shimmer** - Shifting light reflection across placeholders. +* **Directional Hover-Aware Button** - Fill enters from cursor's exact side. +* **Ripple Click Effect** - Wave from click coordinates. +* **Animated SVG Line Drawing** - Vectors drawing themselves in real time. +* **Mesh Gradient Background** - Organic lava-lamp blobs. +* **Lens Blur Depth** - Background UI blurred to focus foreground action. + +### Animation Library Choice +* **Motion (`motion/react`)** - default for UI / Bento / state-change motion. +* **GSAP + ScrollTrigger** - for full-page scrolltelling and scroll hijacks. Isolate in dedicated leaf components with `useEffect` cleanup. +* **Three.js / WebGL** - for canvas backgrounds and 3D scenes. Same isolation rule. +* **NEVER mix GSAP / Three.js with Motion in the same component tree.** They fight over the same frames. + +--- + +## 11. REDESIGN PROTOCOL + +This skill handles **greenfield builds AND redesigns**. Misclassifying the mode is the single biggest source of bad redesign output. + +### 11.A Detect the Mode (first action) +* **Greenfield** - no existing site, or full overhaul approved. Dial baseline from Section 1. +* **Redesign - Preserve** - modernise without breaking the brand. Audit first, extract brand tokens, evolve gradually. +* **Redesign - Overhaul** - new visual language on top of existing content. Treat as greenfield for visuals; preserve content and IA. + +If ambiguous, ask **once**: *"Should this redesign preserve the existing brand, or are we starting visually from scratch?"* + +### 11.B Audit Before Touching +Document the current state before proposing changes: +* **Brand tokens** - primary / accent colors, type stack, logo treatment, radii. +* **Information architecture** - page tree, primary nav, key conversion paths. +* **Content blocks** - what exists, what's doing work, what's filler. +* **Patterns to preserve** - signature interactions, recognisable hero, copy voice. +* **Patterns to retire** - AI-slop tells, broken layouts, dead links, generic stock imagery, perf traps. +* **Dial reading of the existing site** - infer current `DESIGN_VARIANCE` / `MOTION_INTENSITY` / `VISUAL_DENSITY`. That's your starting point, not the baseline. +* **SEO baseline** - current ranking pages, meta titles, structured data, OG cards. **SEO migration is the #1 redesign risk.** + +### 11.C Preservation Rules +* **Do not change information architecture** unless asked. Keep page slugs, anchor IDs, primary nav labels stable for SEO and muscle memory. +* **Extract brand colors before applying Section 4.2.** A brand that is already purple stays purple - apply the LILA RULE's override. +* **Preserve copy voice** unless asked for a rewrite. Visual modernisation ≠ content rewrite. +* **Honor existing accessibility wins.** Do not regress focus states, alt text, keyboard nav, contrast. +* **Respect existing analytics events.** Do not rename buttons, form fields, section IDs that downstream tracking depends on. + +### 11.D Modernisation Levers (priority order) +Apply in order - stop when the brief is satisfied: +1. **Typography refresh** - biggest visual lift per unit of risk. +2. **Spacing & rhythm** - increase section padding, fix vertical rhythm. +3. **Color recalibration** - desaturate, unify neutrals, keep brand accent. +4. **Motion layer** - add `MOTION_INTENSITY`-appropriate micro-interactions to existing components. +5. **Hero & key-section recomposition** - restructure top-of-funnel using Section 10 vocabulary. +6. **Full block replacement** - only when the existing block is unsalvageable. + +### 11.E Decision Tree: Targeted Evolution vs Full Redesign +* IA, content, and SEO sound → **targeted evolution** (Levers 1-4). ~70% of value at ~40% of risk. +* Visual debt is structural (broken IA, no design system, broken mobile) → **full redesign** with strict content preservation. +* Brand itself is changing → **greenfield**. + +### 11.F What Never Changes Silently +Never modify without explicit user approval: +* URL structure / route slugs. +* Primary nav labels. +* Form field names or order (breaks analytics + autofill). +* Brand logo or wordmark. +* Existing legal / consent / cookie copy. + +--- + +## 12. THE BLOCK LIBRARY (Contract - Implementations Land Here Iteratively) + +The Reference Vocabulary (Section 10) names patterns. The Block Library implements them with real props, real motion specs, and real code sketches. + +**Status:** schema defined here. Blocks will be added iteratively. Do not freelance new blocks without following this schema. + +### 12.A File Location +``` +skills/taste-skill/blocks/ + hero/ + asymmetric-split.md + editorial-manifesto.md + kinetic-type.md + ... + feature/ + bento-grid.md + sticky-scroll-stack.md + zig-zag.md + ... + social-proof/ + pricing/ + cta/ + footer/ + navigation/ + portfolio/ + transition/ +``` + +### 12.B Required Frontmatter +```yaml +--- +name: asymmetric-split-hero +category: hero +dial_compatibility: + variance: [6, 10] + motion: [3, 10] + density: [2, 5] +when_to_use: "Landing pages with one strong asset and one strong message. Default hero for SaaS, agency, premium consumer." +not_for: "Editorial / manifesto launches where the message IS the design." +stack: ["react", "next", "tailwind", "motion"] +--- +``` + +### 12.C Required Body Sections +1. **Visual sketch** - short ASCII or description of the layout. +2. **Props API** - the component's interface. +3. **Code sketch** - minimal working implementation (Server Component default, Client island for motion). +4. **Mobile fallback** - explicit collapse rules for `< 768px`. +5. **Motion variants** - one variant per `MOTION_INTENSITY` band (1-3, 4-7, 8-10). Reduced-motion fallback explicit. +6. **Dark-mode notes** - token strategy specific to this block. +7. **Anti-patterns** - common ways this block goes wrong. +8. **References** - links to real examples in production. + +### 12.D Block-Library Discipline +* One block per file. No multi-block files. +* Every block must work standalone (drop it into a page, it renders). +* Every block must pass the Pre-Flight Check (Section 14). +* Blocks that depend on a design system from Section 2.A live under `blocks//--.md` (e.g. `feature/bento-grid--material.md`). + +--- + +## 13. OUT OF SCOPE + +This skill is NOT for: +* Dashboards / dense product UI / admin panels (use Fluent, Carbon, Atlassian, or Polaris from Section 2.A). +* Data tables (use TanStack Table or AG Grid). +* Multi-step forms / wizards (use Form-specific patterns; this skill won't make them better). +* Code editors (use Monaco / CodeMirror with their official skinning). +* Native mobile (use Apple HIG / Material directly). +* Realtime collab UIs (presence, cursors, OT-aware - different problem class). + +If the brief is one of the above, **say so explicitly**, point to the right tool, and only apply this skill's marketing-page / about-page / landing-page parts to the surfaces where they apply. + +--- + +## 14. FINAL PRE-FLIGHT CHECK + +Run this matrix before outputting code. This is the last filter. + +**THIS IS NOT OPTIONAL. Run every box. If any box fails, the output is not done.** + +- [ ] **Brief inference** declared (Section 0.B one-liner)? +- [ ] **Dial values** explicit and reasoned from the brief, not silently using baseline? +- [ ] **Design system** chosen from Section 2 if applicable, or aesthetic labeled honestly? +- [ ] **Redesign mode** detected and audit performed (if applicable, Section 11)? +- [ ] **ZERO em-dashes (`—`) anywhere on the page.** Headlines, eyebrows, pills, body, quotes, attribution, captions, buttons, alt text. Zero. (Section 9.G - non-negotiable.) +- [ ] **Page Theme Lock**: ONE theme (light, dark, or auto) for the whole page. No section flips to inverted mode mid-page (Section 4.11)? +- [ ] **Color Consistency Lock**: one accent color used identically across all sections (Section 4.2)? +- [ ] **Shape Consistency Lock**: one corner-radius system applied consistently (Section 4.4)? +- [ ] **Button Contrast Check**: every CTA text is readable against its background (no white-on-white, WCAG AA 4.5:1)? +- [ ] **CTA Button Wrap**: no CTA label wraps to 2+ lines at desktop? +- [ ] **Form Contrast Check**: form inputs, placeholders, focus rings, labels all pass WCAG AA against the section background? +- [ ] **Serif discipline**: if a serif is used, it is NOT Fraunces or Instrument_Serif (or it is, with explicit brand justification)? Different serif from your previous project? +- [ ] **Premium-consumer palette check**: if the brief is premium-consumer (cookware / wellness / artisan / luxury), the palette is NOT the AI-default beige+brass+oxblood+espresso family? Different family from your previous premium-consumer project? +- [ ] **Italic descender clearance**: every italic word with `y g j p q` has `leading-[1.1]` min + `pb-1` reserve? +- [ ] **Hero fits the viewport**: headline ≤ 2 lines, subtext ≤ 20 words AND ≤ 4 lines, CTA visible without scroll, font scale planned around image? +- [ ] **Hero top padding**: max `pt-24` at desktop, hero content does not float halfway down the viewport? +- [ ] **Hero stack discipline**: max 4 text elements in hero (eyebrow OR brand strip, headline, subtext, CTAs)? No tiny tagline below CTAs, no trust micro-strip in hero? +- [ ] **EYEBROW COUNT (mechanical)**: count instances of `uppercase tracking` micro-labels above section headlines across all components. Count ≤ ceil(sectionCount / 3)? Hero counts as 1. +- [ ] **Split-Header Ban**: no "left big headline + right small explainer paragraph" pattern as a section header (vertical stack instead)? +- [ ] **Zigzag Alternation Cap**: no 3+ consecutive sections with the same image+text-split layout? +- [ ] **No Duplicate CTA Intent**: no two CTAs with the same intent ("Get in touch" + "Let's talk" both on page = Fail)? +- [ ] **Logo wall = logo only**: no industry / category labels printed below logos? +- [ ] **Bento Background Diversity**: at least 2-3 bento cells have real visual variation (image, gradient, pattern), not all white-on-white text cards? +- [ ] **"Used by / Trusted by" logo wall** lives UNDER the hero, not inside it, uses REAL SVG logos (Simple Icons / devicon) or generated SVG marks, NOT plain text wordmarks? +- [ ] **Copy Self-Audit**: every visible string re-read, no grammatically-broken or AI-hallucinated phrases ("free on its past" type) shipped? +- [ ] **Motion motivated**: every animation can be justified in one sentence (hierarchy / storytelling / feedback / state transition), no GSAP-for-show? +- [ ] **Marquee max-one-per-page**: no two horizontal marquees on the same page? +- [ ] **Navigation on ONE line** at desktop, height ≤ 80px? +- [ ] **Section-Layout-Repetition** check: no two sections share the same layout family (at least 4 different families across 8 sections)? +- [ ] **Bento has rhythm AND exact cell count** (N items → N cells, no empty cells in middle or at end)? +- [ ] **Long lists use the right UI component** (not default `
      ` with `divide-y` for > 5 items - see Section 4.9 alternatives)? +- [ ] **Real images used** (gen-tool first, then Picsum-seed, then explicit placeholder slots) - NO div-based fake screenshots, NO hand-rolled decorative SVGs, NO pure-text minimalism? +- [ ] **No pills/labels overlaid on images** (no `Plate · Brand`, no `Field notes - journal`)? +- [ ] **No photo-credit captions as decoration** (`Field study no. 12 · Ines Caetano`)? +- [ ] **No version footers** (`v1.4.2`, `Build 0048`) on marketing pages? +- [ ] **No micro-meta-sentences** under eyebrows ("Each of these is a feature we ship today...")? +- [ ] **No decoration text strip at hero bottom** (`BRAND. MOTION. SPATIAL.`)? +- [ ] **No floating top-right sub-text** in section headings? +- [ ] **No scoring/progress bars with filled background tracks** as comparison visuals? +- [ ] **No locale / city-name / time / weather strips** unless brief is genuinely globally-distributed or place-focused? +- [ ] **No scroll cues** (`Scroll`, `↓ scroll`, `Scroll to explore`)? +- [ ] **No version labels in hero** (V0.6, BETA, INVITE-ONLY) unless the brief is a launch? +- [ ] **No section-numbering eyebrows** (`00 / INDEX`, `001 · Capabilities`, `06 · how it works`)? +- [ ] **No decorative dots** (zero by default, only for real semantic state)? +- [ ] **No `border-t` + `border-b` on every row** of long lists / spec tables? +- [ ] **Content density** sane: no 20-row data tables, no fake-precise specs without justification, ≤ 25-word sub-paragraphs by default? +- [ ] **Quotes ≤ 3 lines** of body, attribution clean (no em-dash)? +- [ ] **Motion claimed = motion shown**: if `MOTION_INTENSITY > 4`, page actually animates, not just claimed? +- [ ] **GSAP sticky-stack / horizontal-pan** implemented per Section 5.A / 5.B canonical skeleton (`start: "top top"`, `pin: true`, correct scrub)? +- [ ] **No `window.addEventListener('scroll')`** - using Motion `useScroll()` / ScrollTrigger / IntersectionObserver / CSS scroll-driven animations only? +- [ ] **Reduced motion** wrapped for everything `MOTION_INTENSITY > 3`? +- [ ] **Dark mode** tokens defined and tested in both modes? +- [ ] **Mobile collapse** explicit (`w-full`, `px-4`, `max-w-7xl mx-auto`) for high-variance layouts? +- [ ] **Viewport stability**: `min-h-[100dvh]`, never `h-screen`? +- [ ] **`useEffect` animations** have strict cleanup functions? +- [ ] **Empty / loading / error** states provided? +- [ ] **Cards omitted** in favor of spacing where possible? +- [ ] **Icons** from an allowed library only (Phosphor / HugeIcons / Radix / Tabler), no hand-rolled SVG paths? +- [ ] **Motion** isolated in client-leaf components with `'use client'` at the top, memoized? +- [ ] **No AI Tells** from Section 9 (Inter as default, AI-purple, three-equal cards, Jane Doe, Acme, "Quietly in use at")? +- [ ] **Core Web Vitals** plausibly hit (LCP < 2.5s, INP < 200ms, CLS < 0.1)? +- [ ] **One design system** per project (no Material + shadcn mixed)? + +If a single checkbox cannot be honestly ticked, the page is not done. Fix it before delivering. + +--- + +# APPENDICES - Real Source-Backed Reference Material + +The sections below are vendored reference content. They give the agent real install commands, real canonical doc links, and real working starter snippets for each design system named in Section 2. Use them to ground decisions in production reality, not training-data fiction. + +## Appendix A - Install Commands per Design System + +```bash +# Material Web (Material 3) +npm install @material/web + +# Fluent UI React (v9) +npm install @fluentui/react-components + +# Fluent UI Web Components (framework-free) +npm install @fluentui/web-components @fluentui/tokens + +# IBM Carbon +npm install @carbon/react @carbon/styles + +# Radix Themes +npm install @radix-ui/themes + +# shadcn/ui (open code, owned components) +npx shadcn@latest init +npx shadcn@latest add button card badge separator input + +# Primer CSS (GitHub product/devtool UI) +npm install --save @primer/css + +# Primer Brand (GitHub marketing UI) +npm install @primer/react-brand + +# GOV.UK Frontend +npm install govuk-frontend + +# USWDS (US Web Design System) +npm install uswds + +# Atlassian Design System (Atlaskit) +yarn add @atlaskit/css-reset @atlaskit/tokens @atlaskit/button @atlaskit/badge @atlaskit/section-message @atlaskit/card + +# Bootstrap 5.3 +npm install bootstrap + +# Shopify Polaris Web Components (Shopify apps only) +# Add this to your app HTML head: +# +# +``` + +## Appendix B - Canonical Sources (read these before reinventing) + +### Material Web +- https://github.com/material-components/material-web +- https://material-web.dev/theming/material-theming/ +- https://m3.material.io/develop/web + +### Fluent UI +- https://fluent2.microsoft.design/get-started/develop +- https://fluent2.microsoft.design/components/web/react/ +- https://github.com/microsoft/fluentui +- https://learn.microsoft.com/en-us/fluent-ui/web-components/ + +### Carbon +- https://carbondesignsystem.com/ +- https://github.com/carbon-design-system/carbon +- https://carbondesignsystem.com/developing/react-tutorial/overview/ +- https://carbondesignsystem.com/developing/web-components-tutorial/overview/ + +### Shopify Polaris +- https://shopify.dev/docs/api/app-home/web-components +- https://github.com/Shopify/polaris-react +- https://polaris-react.shopify.com/components + +### Atlassian +- https://atlassian.design/get-started/develop +- https://atlassian.design/components/button/examples +- https://atlaskit.atlassian.com/packages/design-system/button/example/disabled +- https://atlassian.design/tokens/design-tokens + +### Primer +- https://primer.style/ +- https://github.com/primer/css +- https://github.com/primer/brand + +### GOV.UK +- https://design-system.service.gov.uk/components/button/ +- https://design-system.service.gov.uk/styles/layout/ +- https://github.com/alphagov/govuk-frontend + +### USWDS +- https://designsystem.digital.gov/documentation/developers/ +- https://designsystem.digital.gov/components/button/ +- https://designsystem.digital.gov/components/card/ +- https://github.com/uswds/uswds + +### Bootstrap +- https://getbootstrap.com/docs/5.3/layout/grid/ +- https://getbootstrap.com/docs/5.3/components/card/ + +### Tailwind +- https://tailwindcss.com/docs/dark-mode +- https://tailwindcss.com/blog/tailwindcss-v4 + +### Radix +- https://www.radix-ui.com/themes/docs/components/theme +- https://www.radix-ui.com/themes/docs/components/card +- https://github.com/radix-ui/themes + +### shadcn/ui +- https://ui.shadcn.com/docs +- https://ui.shadcn.com/docs/components/card +- https://github.com/shadcn-ui/ui + +### Native CSS / W3C standards +- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/backdrop-filter +- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-color-scheme +- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-reduced-motion +- https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Grid_layout +- https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Scroll-driven_animations +- https://drafts.csswg.org/scroll-animations-1/ + +### Apple Liquid Glass (Apple platforms only) +- https://developer.apple.com/design/human-interface-guidelines/materials +- https://developer.apple.com/documentation/TechnologyOverviews/liquid-glass +- https://developer.apple.com/documentation/TechnologyOverviews/adopting-liquid-glass +- https://developer.apple.com/documentation/SwiftUI/Material + +--- + +## Appendix C - Apple Liquid Glass: Honest Web Approximation + +Do **not** treat random CSS snippets as official Apple Liquid Glass. + +### What is official +Apple documents Liquid Glass inside Apple's Human Interface Guidelines and Developer Documentation for **Apple platforms**. It is a dynamic material used across Apple platform UI. Apple's native implementation belongs to Apple platform APIs and system components, **not a public web CSS package**. + +Relevant official docs: +- Apple Human Interface Guidelines → Materials +- Apple Developer Documentation → Liquid Glass +- Apple Developer Documentation → Adopting Liquid Glass +- SwiftUI → Material + +### What is NOT official +There is no `liquid-glass.css` from Apple for normal websites. + +A web approximation can use: +- `backdrop-filter` +- transparent backgrounds +- layered borders +- highlight overlays +- gradients +- motion +- strong contrast fallbacks + +But that is **web glassmorphism / frosted-glass approximation**, not official Apple Liquid Glass. Label it as such in comments. + +### Safer web approximation skeleton + +```css +.liquid-glass-web-approx { + position: relative; + isolation: isolate; + overflow: hidden; + border-radius: 999px; + border: 1px solid rgb(255 255 255 / .32); + background: + linear-gradient(135deg, rgb(255 255 255 / .30), rgb(255 255 255 / .08)), + rgb(255 255 255 / .12); + backdrop-filter: blur(24px) saturate(180%) contrast(1.05); + -webkit-backdrop-filter: blur(24px) saturate(180%) contrast(1.05); + box-shadow: + inset 0 1px 0 rgb(255 255 255 / .48), + inset 0 -1px 0 rgb(255 255 255 / .12), + 0 18px 60px rgb(0 0 0 / .18); +} + +.liquid-glass-web-approx::before { + content: ""; + position: absolute; + inset: 0; + z-index: -1; + border-radius: inherit; + background: + radial-gradient(circle at 20% 0%, rgb(255 255 255 / .55), transparent 34%), + linear-gradient(90deg, rgb(255 255 255 / .18), transparent 42%, rgb(255 255 255 / .14)); + pointer-events: none; +} + +.liquid-glass-web-approx::after { + content: ""; + position: absolute; + inset: 1px; + border-radius: inherit; + border: 1px solid rgb(255 255 255 / .14); + pointer-events: none; +} + +@media (prefers-color-scheme: dark) { + .liquid-glass-web-approx { + border-color: rgb(255 255 255 / .18); + background: + linear-gradient(135deg, rgb(255 255 255 / .16), rgb(255 255 255 / .04)), + rgb(15 23 42 / .42); + box-shadow: + inset 0 1px 0 rgb(255 255 255 / .22), + 0 18px 60px rgb(0 0 0 / .42); + } +} + +@media (prefers-reduced-transparency: reduce) { + .liquid-glass-web-approx { + background: rgb(255 255 255 / .96); + backdrop-filter: none; + -webkit-backdrop-filter: none; + } +} +``` + +**Important:** `prefers-reduced-transparency` has uneven browser support; test it. Always provide enough contrast even without blur. + +--- + +**End of appendices.** Install commands above are reality anchors. The Apple Liquid Glass skeleton is a labeled approximation, not an Apple-issued package. For canonical docs per design system, consult the system's official docs (links in Section 2 plus Appendix B). diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md new file mode 100644 index 0000000..b20ba5b --- /dev/null +++ b/.claude/CLAUDE.md @@ -0,0 +1,3 @@ +# graphify +- **graphify** (`.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify` +When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else. diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..2ad0881 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,34 @@ +{ + "permissions": { + "allow": [ + "Bash(git add:*)", + "Bash(git commit:*)", + "Bash(git push origin:*)", + "Bash(tea pr create:*)" + ] + }, + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash|Grep", + "hooks": [ + { + "type": "command", + "command": "graphify hook-guard search", + "timeout": 10 + } + ] + }, + { + "matcher": "Read|Glob", + "hooks": [ + { + "type": "command", + "command": "graphify hook-guard read", + "timeout": 10 + } + ] + } + ] + } +} \ No newline at end of file diff --git a/.claude/skills/graphify/.graphify_version b/.claude/skills/graphify/.graphify_version new file mode 100644 index 0000000..56acc9f --- /dev/null +++ b/.claude/skills/graphify/.graphify_version @@ -0,0 +1 @@ +0.9.71 \ No newline at end of file diff --git a/.claude/skills/graphify/SKILL.md b/.claude/skills/graphify/SKILL.md new file mode 100644 index 0000000..456244a --- /dev/null +++ b/.claude/skills/graphify/SKILL.md @@ -0,0 +1,762 @@ +--- +name: graphify +description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools." +--- + +# /graphify + +Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md. + +## Usage + +``` +/graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault) +/graphify # full pipeline on specific path +/graphify https://github.com// # clone repo then run full pipeline on it +/graphify https://github.com// --branch # clone a specific branch +/graphify ... # clone multiple repos, build each, merge into one cross-repo graph +/graphify --mode deep # thorough extraction, richer INFERRED edges +/graphify --update # incremental - re-extract only new/changed files +/graphify --directed # build directed graph (preserves edge direction: source→target) +/graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy +/graphify --cluster-only # rerun clustering on existing graph +/graphify --no-viz # skip visualization, just report + JSON +/graphify --html # (HTML is generated by default - this flag is a no-op) +/graphify --svg # also export graph.svg (embeds in Notion, GitHub) +/graphify --graphml # export graph.graphml (Gephi, yEd) +/graphify --neo4j # generate graphify-out/cypher.txt for Neo4j +/graphify --neo4j-push bolt://localhost:7687 # push directly to Neo4j +/graphify --falkordb # generate graphify-out/cypher.txt for FalkorDB +/graphify --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB +/graphify --mcp # start MCP stdio server for agent access +/graphify --watch # watch folder, auto-rebuild on code changes (no LLM needed) +/graphify --wiki # build agent-crawlable wiki (index.md + one article per community) +/graphify --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault) +/graphify add # fetch URL, save to ./raw, update graph +/graphify add --author "Name" # tag who wrote it +/graphify add --contributor "Name" # tag who added it to the corpus +/graphify query "" # BFS traversal - broad context +/graphify query "" --dfs # DFS - trace a specific path +/graphify query "" --budget 1500 # cap answer at N tokens +/graphify path "AuthModule" "Database" # shortest path between two concepts +/graphify explain "SwinTransformer" # plain-language explanation of a node +``` + +## What graphify is for + +Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about. + +## What You Must Do When Invoked + +If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return. + +**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query ""` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it. + +If no path was given, use `.` (current directory). Do not ask the user for a path. + +If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path. + +Follow these steps in order. Do not skip steps. + +### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths) + +Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step. + +### Step 1 - Ensure graphify is installed + +```powershell +# Detect Python with graphify — uv/pipx-aware (fixes #831) +New-Item -ItemType Directory -Force -Path graphify-out | Out-Null +$GRAPHIFY_PYTHON = $null + +function Find-GraphifyPython { + # 1. uv tool install — 'uv tool dir' is authoritative, respects UV_TOOL_DIR automatically + if (Get-Command uv -ErrorAction SilentlyContinue) { + $uvDir = (uv tool dir 2>$null).Trim() + if ($uvDir) { + $py = Join-Path $uvDir "graphifyy\Scripts\python.exe" + if (Test-Path $py) { + & $py -c "import graphify" 2>$null + if ($LASTEXITCODE -eq 0) { return $py } + } + } + } + # 2. pipx install — 'pipx environment' respects PIPX_HOME automatically + if (Get-Command pipx -ErrorAction SilentlyContinue) { + $venvs = (pipx environment --value PIPX_LOCAL_VENVS 2>$null).Trim() + if ($venvs) { + $py = Join-Path $venvs "graphifyy\Scripts\python.exe" + if (Test-Path $py) { + & $py -c "import graphify" 2>$null + if ($LASTEXITCODE -eq 0) { return $py } + } + } + } + # 3. Active venv / conda / pip-into-current-env + $pyCmd = Get-Command python -ErrorAction SilentlyContinue + if ($pyCmd) { + & $pyCmd.Source -c "import graphify" 2>$null + if ($LASTEXITCODE -eq 0) { + return (& $pyCmd.Source -c "import sys; print(sys.executable)").Trim() + } + } + return $null +} + +# Try to find the right Python (uv → pipx → active env) +$GRAPHIFY_PYTHON = Find-GraphifyPython + +# Not found — install then re-detect +if (-not $GRAPHIFY_PYTHON) { + if (Get-Command uv -ErrorAction SilentlyContinue) { + uv tool install --upgrade graphifyy -q 2>&1 | Select-Object -Last 3 + } else { + pip install graphifyy -q 2>&1 | Select-Object -Last 3 + } + $GRAPHIFY_PYTHON = Find-GraphifyPython +} + +# Save interpreter path — all subsequent steps read this. +# `Out-File -Encoding utf8` always writes a BOM on Windows PowerShell 5.1 (utf8NoBOM +# only exists from PowerShell 6), and that BOM rides into the saved path, so the hook +# rebuild fails with WinError 123 (#3028). WriteAllText with an explicit BOM-less +# encoding writes the bytes POSIX writes, and adds no trailing newline. +$Utf8NoBom = New-Object System.Text.UTF8Encoding $false +[System.IO.File]::WriteAllText((Join-Path $PWD 'graphify-out\.graphify_python'), [string]$GRAPHIFY_PYTHON, $Utf8NoBom) +# Save scan root so `graphify update` (no args) knows where to look next time. +# INPUT_PATH is captured through a single-quoted (literal) here-string, never +# substituted directly into the command line: an unquoted bareword argument +# substituted here would let a malicious path (a stray `;`, `|`, or `$(...)`) +# execute as script code the moment this line runs. +$InputPathRaw = @' +INPUT_PATH +'@ +[System.IO.File]::WriteAllText((Join-Path $PWD 'graphify-out\.graphify_root'), (Resolve-Path $InputPathRaw.Trim()).Path, $Utf8NoBom) +``` + +If the import succeeds, print nothing and move straight to Step 2. + +**In every subsequent block, run Python through the saved interpreter — `& (Get-Content graphify-out\.graphify_python)` in place of a bare `python3` — so every step uses the interpreter that actually has graphify.** + +### Step 2 - Detect files + +```powershell +@' +import json +from graphify.detect import detect +from pathlib import Path +result = detect(Path('INPUT_PATH')) +# Write the sidecar from Python, not a shell redirect, so the same block renders +# on PowerShell hosts without console-encoding drift (#2528). +Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8") +print(f'Detected {result["total_files"]} files') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` + +Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead: + +``` +Corpus: X files · ~Y words + code: N files (.py .ts .go ...) + docs: N files (.md .txt ...) + papers: N files (.pdf ...) + images: N files + video: N files (.mp4 .mp3 ...) +``` + +Omit any category with 0 files from the summary. + +Then act on it: +- If `total_files` is 0: stop with "No supported files found in [path]." +- If `skipped_sensitive` is non-empty: report the count and list the skipped file names, so a wrongly-flagged source or doc is visible and can be renamed or moved (#2106). +- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count: + - Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH). + - Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`). + - Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars. + - For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`. + - If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed. + - Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding. +- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not. + +### Step 2.5 - Video and audio (only if video files detected) + +Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3. + +### Step 3 - Extract entities and relationships + +**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it. + +This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens). + +> **graphify needs no API key. Never ask the user for one, and never block on one.** Code is extracted structurally (AST) with no LLM and no key at all — a code-only corpus (the common `/graphify .` on a repo) skips semantic extraction entirely, so it needs nothing here: go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) uses Gemini **only if** `GEMINI_API_KEY`/`GOOGLE_API_KEY` is already set; otherwise the host agent itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you catch yourself about to prompt for, wait on, or stop because of a missing API key, that is a misread of this skill — proceed without one. + +**Before semantic extraction:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user: +> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`). + +Print it once, then continue — do not wait for the user to supply a key. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it. + +> **No other API keys are read.** When `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, semantic extraction falls to the host agent itself — the running session is the LLM. On a host that dispatches subagents (e.g. Claude Code), dispatch them as written in Part B. On a host that runs the CLI directly in a terminal and cannot dispatch subagents, do not stall: a code-only corpus has no semantic work, so write the empty semantic file (Part B "Fast path") and continue to Part C; for a corpus with docs/papers/images, either set a Gemini key or extract those inline yourself, but in no case prompt for `ANTHROPIC_API_KEY` — that prompt is a misread of this skill. + +**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.** + +Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers. + +#### Part A - Structural extraction for code files + +For any code files detected, run AST extraction in parallel with Part B subagents: + +```powershell +@' +import sys, json +from graphify.extract import collect_files, extract +from pathlib import Path +import json + +code_files = [] +detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8")) +for f in detect.get('files', {}).get('code', []): + code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)]) + +if code_files: + result = extract(code_files, cache_root=Path('INPUT_PATH')) + Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8") + print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges') +else: + Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding="utf-8") + print('No code files - skipping AST extraction') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` + +#### Part B - Semantic extraction (parallel subagents) + +**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do. **First write an empty semantic file** so Part C's merge has its input (it reads `.graphify_semantic.json` unconditionally; without this a code-only run hits `FileNotFoundError`): + +```powershell +@' +import json +from pathlib import Path +Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` + +**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.** + +Before dispatching subagents, print a timing estimate: +- Load `total_words` and file counts from `graphify-out/.graphify_detect.json` +- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25) +- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit)) +- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys" + +**Step B0 - Check extraction cache first** + +Before dispatching any subagents, check which files already have cached extraction results: + +SPEC_PATH below is the **absolute** path of the `references/extraction-spec.md` that ships beside this SKILL.md — the same file Step B2 loads and hands to every subagent. It is the extraction prompt, so cache entries are attributed to it: when a graphify upgrade changes the prompt, entries produced by the old one are re-extracted instead of replayed, and unchanged prompts keep their entries (#1939). Substitute the real path in both Step B0 and Step B3 — pass the same one to each, and do not drop the argument. + +```powershell +@' +import json +from graphify.cache import check_semantic_cache +from pathlib import Path + +detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8")) +# Only content files go to semantic extraction. Code is already covered structurally +# by the AST pass (Part A); flattening every category here makes subagents re-read +# every source file (#1392). Video is transcribed to a document in Step 2.5 first. +all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])] + +cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH') + +# Always (re)write the cache file: write hits, else DELETE any leftover from a prior +# run so Part C never merges a stale .graphify_cached.json (#1392). +if cached_nodes or cached_edges or cached_hyperedges: + Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8") +else: + Path('graphify-out/.graphify_cached.json').unlink(missing_ok=True) +Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8") +print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` + +Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly. + +**Step B1 - Split into chunks** + +Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted. + +**Step B2 - Dispatch ALL subagents in a single message** + +Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose. + +**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs. + +Concrete example for 3 chunks: +``` +[Agent tool call 1: files 1-15, subagent_type="general-purpose"] +[Agent tool call 2: files 16-30, subagent_type="general-purpose"] +[Agent tool call 3: files 31-45, subagent_type="general-purpose"] +``` +All three in one message. Not three separate messages. + +Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH). + +CHUNK_PATH must be an **absolute** path — derive it before dispatching: +```powershell +$PROJECT_ROOT = (Get-Location).Path # cwd — where Part C globs graphify-out\ (NOT .graphify_root/scan dir, #1392) +# Then for chunk N: $CHUNK_PATH = Join-Path $PROJECT_ROOT "graphify-out\.graphify_chunk_0N.json" +``` + +Subagent prompt template: + +See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, frontmatter, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH. + +**Step B3 - Collect, cache, and merge** + +Wait for all subagents. For each result: +- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal +- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache +- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip. +- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort + +If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used. + +Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run: +```powershell +@' +import json, glob +from pathlib import Path + +chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json')) +all_nodes, all_edges, all_hyperedges = [], [], [] +total_in, total_out = 0, 0 +for c in chunks: + d = json.loads(Path(c).read_text(encoding="utf-8")) + all_nodes += d.get('nodes', []) + all_edges += d.get('edges', []) + all_hyperedges += d.get('hyperedges', []) + total_in += d.get('input_tokens', 0) + total_out += d.get('output_tokens', 0) +Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({ + 'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges, + 'input_tokens': total_in, 'output_tokens': total_out, +}, indent=2, ensure_ascii=False), encoding="utf-8") +print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` + +Save new results to cache. Pass the same SPEC_PATH as Step B0 — it stamps each entry with the prompt that produced it, and a write under a different prompt than the read lands where the next run won't look (#1939): +```powershell +@' +import json +from graphify.cache import save_semantic_cache +from pathlib import Path + +new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]} +uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_text(encoding="utf-8").splitlines() if line] +saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH') +print(f'Cached {saved} files') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` + +Merge cached + new results into `graphify-out/.graphify_semantic.json`: +```powershell +@' +import json +from pathlib import Path + +cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]} +new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]} + +all_nodes = cached['nodes'] + new.get('nodes', []) +all_edges = cached['edges'] + new.get('edges', []) +all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', []) +seen = set() +deduped = [] +for n in all_nodes: + if n['id'] not in seen: + seen.add(n['id']) + deduped.append(n) + +merged = { + 'nodes': deduped, + 'edges': all_edges, + 'hyperedges': all_hyperedges, + 'input_tokens': new.get('input_tokens', 0), + 'output_tokens': new.get('output_tokens', 0), +} +Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8") +print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached["nodes"])} from cache, {len(new.get("nodes",[]))} new)') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` +Clean up temp files: `Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_cached.json, graphify-out\.graphify_uncached.txt, graphify-out\.graphify_semantic_new.json` + +#### Part C - Merge AST + semantic into final extraction + +```powershell +@' +import sys, json +from pathlib import Path + +ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding="utf-8")) +sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding="utf-8")) + +# Merge: AST nodes first, semantic nodes deduplicated by id +seen = {n['id'] for n in ast['nodes']} +merged_nodes = list(ast['nodes']) +for n in sem['nodes']: + if n['id'] not in seen: + merged_nodes.append(n) + seen.add(n['id']) + +merged_edges = ast['edges'] + sem['edges'] +merged_hyperedges = sem.get('hyperedges', []) +merged = { + 'nodes': merged_nodes, + 'edges': merged_edges, + 'hyperedges': merged_hyperedges, + 'input_tokens': sem.get('input_tokens', 0), + 'output_tokens': sem.get('output_tokens', 0), +} +Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8") +total = len(merged_nodes) +edges = len(merged_edges) +print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem["nodes"])} semantic)') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` + +### Step 4 - Build graph, cluster, analyze, generate outputs + +**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code. + +```powershell +New-Item -ItemType Directory -Force -Path graphify-out | Out-Null +@' +import sys, json +from graphify.build import build_from_json +from graphify.cluster import cluster, score_all +from graphify.analyze import god_nodes, surprising_connections, suggest_questions +from graphify.report import generate +from graphify.export import to_json +from pathlib import Path + +extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8")) +detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8")) + +# root= mirrors the --update runbook (#1361): relativize source_file to the same +# base so the full build and incremental --update never drift apart on re-extract. +G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED) +# Guard BEFORE any write: an empty extraction must not clobber a good graph.json / +# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392). +if G.number_of_nodes() == 0: + print('ERROR: Graph is empty - extraction produced no nodes.') + print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.') + raise SystemExit(1) +communities = cluster(G) +cohesion = score_all(G, communities) +tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)} +gods = god_nodes(G) +surprises = surprising_connections(G, communities) +labels = {cid: 'Community ' + str(cid) for cid in communities} +# Placeholder questions - regenerated with real labels in Step 5 +questions = suggest_questions(G, communities, labels) + +# Export FIRST and honor the #479 shrink-guard: to_json returns False (writing +# nothing) when the new graph is smaller than the existing graph.json. Only write +# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so +# they never describe a graph that graph.json doesn't contain (#1392). +wrote = to_json(G, communities, 'graphify-out/graph.json') +if not wrote: + print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).') + print('If this shrink is intentional (you deleted files), re-run a full build with --force.') + raise SystemExit(1) +report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions) +Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8") +analysis = { + 'communities': {str(k): v for k, v in communities.items()}, + 'cohesion': {str(k): v for k, v in cohesion.items()}, + 'gods': gods, + 'surprises': surprises, + 'questions': questions, +} +Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8") +print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` + +If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization. + +Replace INPUT_PATH with the actual path. + +### Step 4.5 - Graph health check (read-only integrity gate) + +A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts. + +```powershell +@' +import json +from pathlib import Path +from graphify.diagnostics import diagnose_extraction, format_diagnostic_report + +extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8")) +summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH') +print(format_diagnostic_report(summary)) +flags = [f'{summary[k]} {label}' for k, label in ( + ('dangling_endpoint_edges', 'dangling-endpoint edges'), + ('missing_endpoint_edges', 'missing-endpoint edges'), + ('self_loop_edges', 'self-loop edges'), + ('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'), + ('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'), +) if summary.get(k, 0)] +print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` + +Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules). + +### Step 5 - Label communities + +Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading"). + +Then regenerate the report and save the labels for the visualizer: + +```powershell +@' +import sys, json +from graphify.build import build_from_json +from graphify.cluster import score_all +from graphify.analyze import god_nodes, surprising_connections, suggest_questions +from graphify.report import generate +from graphify.export import to_json +from pathlib import Path + +extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8")) +detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8")) +analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8")) + +# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity. +G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED) +communities = {int(k): v for k, v in analysis['communities'].items()} +cohesion = {int(k): v for k, v in analysis['cohesion'].items()} +tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)} + +# LABELS - replace these with the names you chose above +labels = LABELS_DICT + +# Regenerate questions with real community labels (labels affect question phrasing) +questions = suggest_questions(G, communities, labels) + +report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions) +Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8") +Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8") +# Re-export so graph.json nodes carry the curated community_name (#2490). +# Same extraction as Step 4, so the #479 shrink-guard passes on node count; +# if it still refuses, surface the guard message - do not force past it. +wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels) +if not wrote: + print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).') + print('If this shrink is intentional (you deleted files), re-run a full build with --force.') +print('Report updated with community labels') +'@ | & (Get-Content graphify-out\.graphify_python) - +``` + +Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`). +Replace INPUT_PATH with the actual path. + +### Step 6 - Generate Obsidian vault (opt-in) + HTML + +**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node. + +If `--obsidian` was given: + +- If `--obsidian-dir ` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`. + +```powershell +graphify export obsidian +# or with custom dir: graphify export obsidian --dir ~/vaults/my-project +``` + +Generate the HTML graph (always, unless `--no-viz`): + +```powershell +graphify export html # auto-aggregates to community view if graph > 5000 nodes +# or: graphify export html --no-viz +``` + +### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) + +These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available. + +--- + +### Step 9 - Save manifest, update cost tracker, clean up, and report + +```powershell +@' +import json +from pathlib import Path +from datetime import datetime, timezone +from graphify.detect import save_manifest + +# Save manifest for --update +detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8")) +extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8")) +# In --update mode, 'all_files' carries the full corpus; 'files' is the changed +# subset. Full-rebuild mode populates only 'files', so the fallback handles that. +# root= relativizes the manifest keys to the scan root (same base as the build), +# so the on-disk manifest is portable across clones/machines and a later --update +# matches cached files instead of missing every one (#1417). +# +# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output: +# a detected file whose chunk failed or was omitted must stay unstamped so the +# next --update re-queues it, otherwise it is marked done and its content is lost +# forever (#2015). This mirrors the library extract path exactly +# (cli._stamped_manifest_files + clear_semantic + scan_corpus); do not stamp the +# raw corpus. Code files are always stamped (AST is deterministic); only semantic +# types are gated on output. +from graphify.cli import _stamped_manifest_files +_corpus = detect.get('all_files') or detect['files'] +_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH')) +# Files dispatched this run (the changed subset) but NOT stamped above still carry +# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues +# them instead of reading them as unchanged (#1948). +_sem_types = ('document', 'paper', 'image') +_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl} +_stamped = {f for fl in _manifest_files.values() for f in fl} +_cleared = _dispatched - _stamped +# scan_corpus = the RAW full corpus (not the stamp-filtered subset) so in-root +# files newly excluded since last run are dropped rather than masquerading as +# deletions; untouched files' prior rows are still preserved (#1908). +_scan = {f for fl in _corpus.values() for f in fl} +save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None) + +# Update cumulative cost tracker +input_tok = extract.get('input_tokens', 0) +output_tok = extract.get('output_tokens', 0) + +cost_path = Path('graphify-out/cost.json') +if cost_path.exists(): + cost = json.loads(cost_path.read_text(encoding="utf-8")) +else: + cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0} + +cost['runs'].append({ + 'date': datetime.now(timezone.utc).isoformat(), + 'input_tokens': input_tok, + 'output_tokens': output_tok, + 'files': detect.get('total_files', 0), +}) +cost['total_input_tokens'] += input_tok +cost['total_output_tokens'] += output_tok +cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding="utf-8") + +print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens') +print(f'All time: {cost["total_input_tokens"]:,} input, {cost["total_output_tokens"]:,} output ({len(cost["runs"])} runs)') +'@ | & (Get-Content graphify-out\.graphify_python) - +Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_detect.json, graphify-out\.graphify_extract.json, graphify-out\.graphify_ast.json, graphify-out\.graphify_semantic.json, graphify-out\.graphify_analysis.json +Get-ChildItem graphify-out -Filter '.graphify_chunk_*.json' -File -ErrorAction SilentlyContinue | Remove-Item -Force +Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.needs_update +``` + +Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root. + +Tell the user (omit the obsidian line unless --obsidian was given): +``` +Graph complete. Outputs in PATH_TO_DIR/graphify-out/ + + graph.html - interactive graph, open in browser + GRAPH_REPORT.md - audit report + graph.json - raw graph data + obsidian/ - Obsidian vault (only if --obsidian was given) +``` + +If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi + +Replace PATH_TO_DIR with the actual absolute path of the directory that was processed. + +Then paste these sections from GRAPH_REPORT.md directly into the chat: +- God Nodes +- Surprising Connections +- Suggested Questions + +Do NOT paste the full report - just those three sections. Keep it concise. + +Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask: + +> "The most interesting question this graph can answer: **[question]**. Want me to trace it?" + +If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report. + +The graph is the map. Your job after the pipeline is to be the guide. + +--- + +## Interpreter guard for subcommands + +Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first: + +```powershell +if (-not (Test-Path graphify-out\.graphify_python)) { + $GRAPHIFY_PYTHON = $null + $graphifyCmd = Get-Command graphify -ErrorAction SilentlyContinue + if ($graphifyCmd) { + # The interpreter that owns the graphify entry point sits next to it + # (\Scripts\python.exe for uv tool, pipx, and venv installs). + $py = Join-Path (Split-Path $graphifyCmd.Source) "python.exe" + if (Test-Path $py) { $GRAPHIFY_PYTHON = $py } + } + if (-not $GRAPHIFY_PYTHON) { $GRAPHIFY_PYTHON = "python" } + New-Item -ItemType Directory -Force -Path graphify-out | Out-Null + & $GRAPHIFY_PYTHON -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)" +} +``` + +## For --update and --cluster-only + +Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows. + +--- + +## For /graphify query + +When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it: + +```powershell +graphify query "" +``` + +Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`. + +--- + +## For /graphify add and --watch + +Neither is part of the default build. When the user runs `/graphify add ` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`. + +--- + +## For the commit hook and native CLAUDE.md integration + +When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see `references/hooks.md`. + +--- + +## Troubleshooting + +### PowerShell 5.1: Vertical scrolling stops working + +If vertical scrolling breaks in PowerShell after running graphify, this is caused by ANSI escape sequences from the `graspologic` library. Graphify v0.3.10+ suppresses this output, but if you still see the issue: + +1. **Upgrade graphify**: `pip install --upgrade graphifyy` +2. **Use Windows Terminal** instead of the legacy PowerShell console — Windows Terminal handles ANSI codes correctly +3. **Reset your terminal**: close and reopen PowerShell +4. **Skip Leiden**: uninstall its backend (`pip uninstall graspologic` on Python < 3.13, `pip uninstall graspologic-native` on Python 3.13+) and graphify will fall back to NetworkX's built-in Louvain algorithm, which produces no ANSI output + +--- + +## Honesty Rules + +- Never invent an edge. If unsure, use AMBIGUOUS. +- Never skip the corpus check warning. +- Always show token cost in the report. +- Never hide cohesion scores behind symbols - show the raw number. +- Never run HTML viz on a graph with more than 5,000 nodes without warning the user. diff --git a/.claude/skills/graphify/references/add-watch.md b/.claude/skills/graphify/references/add-watch.md new file mode 100644 index 0000000..349f8b4 --- /dev/null +++ b/.claude/skills/graphify/references/add-watch.md @@ -0,0 +1,56 @@ +# graphify reference: add a URL and watch a folder + +Load this when the user ran `/graphify add ` or passed `--watch`. Neither is part of the default build. + +## For /graphify add + +Fetch a URL and add it to the corpus, then update the graph. + +```bash +$(cat graphify-out/.graphify_python) -c " +import sys +from graphify.ingest import ingest +from pathlib import Path + +try: + out = ingest('URL', Path('./raw'), author='AUTHOR', contributor='CONTRIBUTOR') + print(f'Saved to {out}') +except ValueError as e: + print(f'error: {e}', file=sys.stderr) + sys.exit(1) +except RuntimeError as e: + print(f'error: {e}', file=sys.stderr) + sys.exit(1) +" +``` + +Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph. + +Supported URL types (auto-detected): +- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`) +- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author +- arXiv → abstract + metadata saved as `.md` +- PDF → downloaded as `.pdf` +- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run +- Any webpage → converted to markdown via html2text + +--- + +## For --watch + +Start a background watcher that monitors a folder and auto-updates the graph when files change. + +```bash +$(cat graphify-out/.graphify_python) -m graphify.watch "$(cat graphify-out/.graphify_root)" --debounce 3 +``` + +This watches the same folder graphify extracted, read from the trusted `graphify-out/.graphify_root` that Step 1 resolved - there is no path to substitute, so a scan root containing shell metacharacters can never be re-interpreted here. Behavior depends on what changed: + +- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically. +- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required). + +Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file. + +Press Ctrl+C to stop. + +For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves. diff --git a/.claude/skills/graphify/references/exports.md b/.claude/skills/graphify/references/exports.md new file mode 100644 index 0000000..242ff86 --- /dev/null +++ b/.claude/skills/graphify/references/exports.md @@ -0,0 +1,87 @@ +# graphify reference: extra exports and benchmark + +Load this when the user passed one of the export flags (`--wiki`, `--neo4j`, `--neo4j-push`, `--falkordb`, `--falkordb-push`, `--svg`, `--graphml`, `--mcp`), or when the corpus is large enough for the token-reduction benchmark. Each step runs only for its own flag. + +### Step 6b - Wiki (only if --wiki flag) + +**Only run this step if `--wiki` was explicitly given in the original command.** + +Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available. + +```bash +graphify export wiki +``` + +### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag) + +**If `--neo4j`** - generate a Cypher file for manual import: + +```bash +graphify export neo4j +``` + +**If `--neo4j-push `** - push directly to a running Neo4j instance. Ask the user for credentials if not provided: + +```bash +graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD +``` + +Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates. + +### Step 7a - FalkorDB export (only if --falkordb or --falkordb-push flag) + +**If `--falkordb`** - generate a Cypher file. The statements are OpenCypher, but FalkorDB's `GRAPH.QUERY` runs one statement at a time (no bulk script import like Neo4j's `cypher-shell`), so prefer `--falkordb-push` to load a graph. Use this only when you want the portable `cypher.txt` artifact: + +```bash +graphify export falkordb +``` + +**If `--falkordb-push `** - push directly to a running FalkorDB instance. Credentials are optional; ask the user only if the instance requires auth: + +```bash +graphify export falkordb --push falkordb://localhost:6379 +``` + +Default URI is `falkordb://localhost:6379` (the scheme is informational - `redis://` or a bare `host:port` work too), auth is optional, and the target graph defaults to `graphify`. Uses MERGE - safe to re-run without creating duplicates. + +### Step 7b - SVG export (only if --svg flag) + +```bash +graphify export svg +``` + +### Step 7c - GraphML export (only if --graphml flag) + +```bash +graphify export graphml +``` + +### Step 7d - MCP server (only if --mcp flag) + +```bash +$(cat graphify-out/.graphify_python) -m graphify.serve graphify-out/graph.json +``` + +This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live. + +To configure in Claude Desktop, add to `claude_desktop_config.json`. Claude Desktop can't run `$(...)`, and under `uv tool install` the system `python3` can't import graphify — so set `command` to the **absolute interpreter path** printed by `cat graphify-out/.graphify_python`: +```json +{ + "mcpServers": { + "graphify": { + "command": "", + "args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"] + } + } +} +``` + +### Step 8 - Token reduction benchmark (only if total_words > 5000) + +If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run: + +```bash +graphify benchmark +``` + +Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora. diff --git a/.claude/skills/graphify/references/extraction-spec.md b/.claude/skills/graphify/references/extraction-spec.md new file mode 100644 index 0000000..388df76 --- /dev/null +++ b/.claude/skills/graphify/references/extraction-spec.md @@ -0,0 +1,70 @@ +# graphify reference: extraction subagent prompt + +Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH). + +``` +You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment. +Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble. + +Files (chunk CHUNK_NUM of TOTAL_CHUNKS): +FILE_LIST + +Rules: +- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2") +- INFERRED: reasonable inference (shared data structure, implied dependency) +- AMBIGUOUS: uncertain - flag for review, do not omit + +Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns). + Do not re-extract imports - AST already has those. +Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected. +Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction. `calls` edges MUST stay within one language: a Python function cannot `calls` a JS/TS/Go/Rust/Java symbol and vice versa — cross-language call edges are phantom artifacts, never emit them. +Image files: use vision to understand what the image IS - do not just OCR. + UI screenshot: layout patterns, design decisions, key elements, purpose. + Chart: metric, trend/insight, data source. + Tweet/post: claim as node, author, concepts mentioned. + Diagram: components and connections. + Research figure: what it demonstrates, method, result. + Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS. + +DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps, + shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting. + +Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples: +- Two functions that both validate user input but never call each other +- A class in code and a concept in a paper that describe the same algorithm +- Two error types that handle the same failure mode differently +Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things. + +Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples: +- All classes that implement a common protocol or interface +- All functions in an authentication flow (even if they don't all call each other) +- All concepts from a paper section that form one coherent idea +Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk. + +If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, + contributor onto every node from that file. + +confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default: +- EXTRACTED edges: confidence_score = 1.0 always +- INFERRED edges: pick exactly ONE value from this set — never 0.5: + 0.95 direct structural evidence (shared data structure, named cross-file reference). + 0.85 strong inference (clear functional alignment, no direct symbol link). + 0.75 reasonable inference (shared problem domain + similar shape, requires interpretation). + 0.65 weak inference (thematically related, no shape evidence). + 0.55 speculative but plausible (surface-level co-occurrence only). + Models follow discrete rubrics better than continuous ranges; the bimodal + distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the + range guidance is being collapsed to a binary. If no value above fits, mark + the edge AMBIGUOUS rather than picking 0.4 or below. +- AMBIGUOUS edges: 0.1-0.3 + +Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it. + +Generate the extraction JSON matching this schema exactly: +{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":""}],"input_tokens":0,"output_tokens":0} + +source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate. + +Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost): +CHUNK_PATH +``` diff --git a/.claude/skills/graphify/references/github-and-merge.md b/.claude/skills/graphify/references/github-and-merge.md new file mode 100644 index 0000000..a41ea06 --- /dev/null +++ b/.claude/skills/graphify/references/github-and-merge.md @@ -0,0 +1,46 @@ +# graphify reference: GitHub clone and cross-repo merge + +Load this when the user passed one or more `https://github.com/...` URLs, or named several local subfolders to merge into one graph. + +### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given) + +**Single repo:** +```bash +LOCAL_PATH=$(graphify clone [--branch ]) +# Use LOCAL_PATH as the target for all subsequent steps +``` + +**Multiple repos (cross-repo graph):** +```bash +# Clone each repo, run the full pipeline on each, then merge +graphify clone # → ~/.graphify/repos// +graphify clone # → ~/.graphify/repos// +# Run /graphify on each local path to produce their graph.json files +# Then merge: +graphify merge-graphs \ + ~/.graphify/repos///graphify-out/graph.json \ + ~/.graphify/repos///graphify-out/graph.json \ + --out graphify-out/cross-repo-graph.json +``` + +Graphify clones into `~/.graphify/repos//` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin. + +**Multiple local subfolders (monorepo or multi-service layout):** + +The skill pipeline writes all intermediate and final outputs to `graphify-out/` in the current working directory. Running the skill on each subfolder separately will clobber the same output dir. Instead, use the CLI directly for each subfolder — it places `graphify-out/` *inside* the scanned path: + +```bash +graphify extract ./core/ # → ./core/graphify-out/graph.json +graphify extract ./service/ # → ./service/graphify-out/graph.json +graphify extract ./platform/ # → ./platform/graphify-out/graph.json +# Add --backend gemini|kimi|openai|deepseek|claude-cli depending on which API key you have set + +# Then merge at the project root: +graphify merge-graphs \ + ./core/graphify-out/graph.json \ + ./service/graphify-out/graph.json \ + ./platform/graphify-out/graph.json \ + --out graphify-out/graph.json +``` + +Once `graphify-out/graph.json` exists, the fast path above takes over: any codebase question runs `graphify query` directly on the merged graph — no re-extraction, no size gate. diff --git a/.claude/skills/graphify/references/hooks.md b/.claude/skills/graphify/references/hooks.md new file mode 100644 index 0000000..438b8b1 --- /dev/null +++ b/.claude/skills/graphify/references/hooks.md @@ -0,0 +1,33 @@ +# graphify reference: commit hook and native CLAUDE.md integration + +Load this when the user asked to install the post-commit hook or wire graphify into a project's CLAUDE.md. + +## For git commit hook + +Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor. + +```bash +graphify hook install # install +graphify hook uninstall # remove +graphify hook status # check +``` + +After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those. + +If a post-commit hook already exists, graphify appends to it rather than replacing it. + +--- + +## For native CLAUDE.md integration + +Run once per project to make graphify always-on in Claude Code sessions: + +```bash +graphify claude install +``` + +This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions. + +```bash +graphify claude uninstall # remove the section +``` diff --git a/.claude/skills/graphify/references/query.md b/.claude/skills/graphify/references/query.md new file mode 100644 index 0000000..56565eb --- /dev/null +++ b/.claude/skills/graphify/references/query.md @@ -0,0 +1,311 @@ +# graphify reference: query, path, explain + +Load this when the user asks a question against an existing graph, or runs `/graphify path` or `/graphify explain`. The core's query stub points here for the full traversal flow. These flows use the `graphify query` CLI when it is available and fall back to an inline NetworkX traversal otherwise. + +Two traversal modes - choose based on the question: + +| Mode | Flag | Best for | +|------|------|----------| +| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first | +| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path | + +First check the graph exists: +```bash +$(cat graphify-out/.graphify_python) -c " +from pathlib import Path +if not Path('graphify-out/graph.json').exists(): + print('ERROR: No graph found. Run /graphify first to build the graph.') + raise SystemExit(1) +" +``` +If it fails, stop and tell the user to run `/graphify ` first. + +### Step 0 — Constrained query expansion (REQUIRED before traversal) + +graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise. + +Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first: + +1. Extract the token vocabulary from node labels: +```bash +$(cat graphify-out/.graphify_python) -c " +import json, re +from pathlib import Path +data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8')) +vocab = set() +for n in data['nodes']: + for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE): + parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c] + for p in parts: + t = p.lower() + if 3 <= len(t) <= 30: + vocab.add(t) +Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)), encoding='utf-8') +print(f'vocab: {len(vocab)} tokens') +" +``` + +2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints: + - You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens. + - If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory. + - If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search. + - Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab. + - Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present. + +3. Print the selection explicitly to the user before running the query, so the expansion is auditable: +``` +Query expanded to (from graph vocab, N tokens): [token1, token2, ...] +``` +If the list is empty, say so plainly and stop — do not proceed to traversal. + +### Step 1 — Traversal + +Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.) + +Prefer the CLI when it is installed: +```bash +graphify query "QUESTION" +# or: graphify query "QUESTION" --dfs --budget 3000 +``` + +If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline: + +1. Find the 1-3 nodes whose label best matches the expanded tokens. +2. Run the appropriate traversal from each starting node. +3. Read the subgraph - node labels, edge relations, confidence tags, source locations. +4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact. +5. If the graph lacks enough information, say so - do not hallucinate edges. + +```bash +$(cat graphify-out/.graphify_python) -c " +import sys, json +from networkx.readwrite import json_graph +import networkx as nx +from pathlib import Path + +data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8')) +G = json_graph.node_link_graph(data, edges='links') + +question = 'QUESTION' +mode = 'MODE' # 'bfs' or 'dfs' +terms = [t.lower() for t in question.split() if len(t) >= 3] # match the vocab threshold; keeps api/jwt/ios (#1392) + +# Find best-matching start nodes +scored = [] +for nid, ndata in G.nodes(data=True): + label = ndata.get('label', '').lower() + score = sum(1 for t in terms if t in label) + if score > 0: + scored.append((score, nid)) +scored.sort(reverse=True) +start_nodes = [nid for _, nid in scored[:3]] + +if not start_nodes: + print('No matching nodes found for query terms:', terms) + sys.exit(0) + +subgraph_nodes = set() +subgraph_edges = [] + +if mode == 'dfs': + # DFS: follow one path as deep as possible before backtracking. + # Depth-limited to 6 to avoid traversing the whole graph. + visited = set() + stack = [(n, 0) for n in reversed(start_nodes)] + while stack: + node, depth = stack.pop() + if node in visited or depth > 6: + continue + visited.add(node) + subgraph_nodes.add(node) + for neighbor in G.neighbors(node): + if neighbor not in visited: + stack.append((neighbor, depth + 1)) + subgraph_edges.append((node, neighbor)) +else: + # BFS: explore all neighbors layer by layer up to depth 3. + frontier = set(start_nodes) + subgraph_nodes = set(start_nodes) + for _ in range(3): + next_frontier = set() + for n in frontier: + for neighbor in G.neighbors(n): + if neighbor not in subgraph_nodes: + next_frontier.add(neighbor) + subgraph_edges.append((n, neighbor)) + subgraph_nodes.update(next_frontier) + frontier = next_frontier + +# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token) +token_budget = BUDGET # default 2000 +char_budget = token_budget * 4 + +# Score each node by term overlap for ranked output +def relevance(nid): + label = G.nodes[nid].get('label', '').lower() + return sum(1 for t in terms if t in label) + +ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True) + +lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes'] +for nid in ranked_nodes: + d = G.nodes[nid] + lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]') +for u, v in subgraph_edges: + if u in subgraph_nodes and v in subgraph_nodes: + _raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw + lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}') + +output = '\n'.join(lines) +if len(output) > char_budget: + output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)' +print(output) +" +``` + +Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains. + +After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node: + +```bash +$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2 +``` + +Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph. + +**Work memory (self-improving loop).** Add an `--outcome` so future sessions learn from this one — append `--outcome useful|dead_end|corrected` to the `save-result` command (and `--correction "the right answer"` when correcting): + +- `useful` — the cited nodes answered the question well (they become *preferred sources*). +- `dead_end` — the question/path led nowhere; don't re-derive it next time. +- `corrected` — the saved answer was wrong; `--correction` records what was right. + +At the **start** of graph work, refresh and read the lessons: run `graphify reflect --if-stale` (cheap, deterministic, no LLM; `--if-stale` makes it a no-op when `LESSONS.md` is already newer than every input, e.g. when the git hook just refreshed it), then read `graphify-out/reflections/LESSONS.md`. It lists **preferred sources** (start there), **known dead ends** (skip them), and prior **corrections**. Running `reflect` yourself keeps the lessons current even without the git hook installed; if the post-commit hook *is* installed, `--if-stale` means your session-start run costs almost nothing. + +--- + +## For /graphify path + +Find the shortest path between two named concepts in the graph. Prefer the CLI when installed: + +```bash +graphify path "NODE_A" "NODE_B" +``` + +If the CLI is unavailable, run it inline: + +```bash +$(cat graphify-out/.graphify_python) -c " +import json, sys +import networkx as nx +from networkx.readwrite import json_graph +from pathlib import Path + +data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8')) +G = json_graph.node_link_graph(data, edges='links') + +a_term = 'NODE_A' +b_term = 'NODE_B' + +def find_node(term): + term = term.lower() + scored = sorted( + [(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n) + for n in G.nodes()], + reverse=True + ) + return scored[0][1] if scored and scored[0][0] > 0 else None + +src = find_node(a_term) +tgt = find_node(b_term) + +if not src or not tgt: + print(f'Could not find nodes matching: {a_term!r} or {b_term!r}') + sys.exit(0) + +try: + path = nx.shortest_path(G, src, tgt) + print(f'Shortest path ({len(path)-1} hops):') + for i, nid in enumerate(path): + label = G.nodes[nid].get('label', nid) + if i < len(path) - 1: + _raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw + rel = edge.get('relation', '') + conf = edge.get('confidence', '') + print(f' {label} --{rel}--> [{conf}]') + else: + print(f' {label}') +except nx.NetworkXNoPath: + print(f'No path found between {a_term!r} and {b_term!r}') +except nx.NodeNotFound as e: + print(f'Node not found: {e}') +" +``` + +Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant. + +After writing the explanation, save it back: + +```bash +$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B +``` + +--- + +## For /graphify explain + +Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed: + +```bash +graphify explain "NODE_NAME" +``` + +If the CLI is unavailable, run it inline: + +```bash +$(cat graphify-out/.graphify_python) -c " +import json, sys +import networkx as nx +from networkx.readwrite import json_graph +from pathlib import Path + +data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8')) +G = json_graph.node_link_graph(data, edges='links') + +term = 'NODE_NAME' +term_lower = term.lower() + +# Find best matching node +scored = sorted( + [(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n) + for n in G.nodes()], + reverse=True +) +if not scored or scored[0][0] == 0: + print(f'No node matching {term!r}') + sys.exit(0) + +nid = scored[0][1] +data_n = G.nodes[nid] +print(f'NODE: {data_n.get(\"label\", nid)}') +print(f' source: {data_n.get(\"source_file\",\"unknown\")}') +print(f' type: {data_n.get(\"file_type\",\"unknown\")}') +print(f' degree: {G.degree(nid)}') +print() +print('CONNECTIONS:') +for neighbor in G.neighbors(nid): + _raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw + nlabel = G.nodes[neighbor].get('label', neighbor) + rel = edge.get('relation', '') + conf = edge.get('confidence', '') + src_file = G.nodes[neighbor].get('source_file', '') + print(f' --{rel}--> {nlabel} [{conf}] ({src_file})') +" +``` + +Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations. + +After writing the explanation, save it back: + +```bash +$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME +``` diff --git a/.claude/skills/graphify/references/transcribe.md b/.claude/skills/graphify/references/transcribe.md new file mode 100644 index 0000000..b967f83 --- /dev/null +++ b/.claude/skills/graphify/references/transcribe.md @@ -0,0 +1,52 @@ +# graphify reference: transcribe video and audio + +Load this only when `detect` reported one or more `video` files. A corpus with no video never reads this. + +### Step 2.5 - Transcribe video / audio files (only if video files detected) + +Skip this step entirely if `detect` returned zero `video` files. + +Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3. + +**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed. + +**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."` + +**Step 1 - Write the Whisper prompt yourself.** + +Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example: + +- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."` +- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."` + +**Export** it as `GRAPHIFY_WHISPER_PROMPT` (the exact name the transcriber reads — and it must be `export`ed so the child Python process sees it) for the next command. + +**Step 2 - Transcribe:** + +```bash +export GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed (must be exported) +export GRAPHIFY_WHISPER_PROMPT="" +$(cat graphify-out/.graphify_python) -c " +import json, os, sys +from pathlib import Path +from graphify.transcribe import transcribe_all + +detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\")) +video_files = detect.get('files', {}).get('video', []) +prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.') + +transcript_paths = transcribe_all(video_files, initial_prompt=prompt) +# Write the JSON from Python (NOT a shell '>' redirect): transcribe_all/Whisper +# print progress to stdout, which would otherwise corrupt the JSON file (#1392). +Path('graphify-out/.graphify_transcripts.json').write_text(json.dumps(transcript_paths, ensure_ascii=False), encoding=\"utf-8\") +print(f'Transcribed {len(transcript_paths)} file(s)', file=sys.stderr) +" +``` + +After transcription: +- Read the transcript paths from `graphify-out/.graphify_transcripts.json` +- Add them to the docs list before dispatching semantic subagents in Step 3B +- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs` +- If transcription fails for a file, print a warning and continue with the rest + +**Whisper model:** Default is `base`. If the user passed `--whisper-model `, `export GRAPHIFY_WHISPER_MODEL=` (it must be exported, not just assigned) before running the command above. diff --git a/.claude/skills/graphify/references/update.md b/.claude/skills/graphify/references/update.md new file mode 100644 index 0000000..3632fd4 --- /dev/null +++ b/.claude/skills/graphify/references/update.md @@ -0,0 +1,210 @@ +# graphify reference: incremental update and cluster-only + +Load this only when the user passed `--update` or `--cluster-only`. A first-time full build never reads this file. + +## For --update (incremental re-extraction) + +Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time. + +```bash +$(cat graphify-out/.graphify_python) -c " +import sys, json +from graphify.detect import detect_incremental, save_manifest +from pathlib import Path + +result = detect_incremental(Path('INPUT_PATH')) +new_total = result.get('new_total', 0) +print(json.dumps(result, indent=2, ensure_ascii=False)) +Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\") +deleted = list(result.get('deleted_files', [])) +if new_total == 0 and not deleted: + print('No files changed since last run. Nothing to update.') + raise SystemExit(0) +if deleted: + print(f'{len(deleted)} deleted file(s) to prune.') +if new_total > 0: + print(f'{new_total} new/changed file(s) to re-extract.') +" +``` + +Then populate `.graphify_detect.json` so Steps 3A–6 (which read it unconditionally) see the right state for an incremental run. `files` carries the changed subset (drives Step 3A AST + Step 3B0 cache check on only what changed); `all_files` carries the full corpus for any step that needs corpus-wide context: + +```bash +$(cat graphify-out/.graphify_python) -c " +import json +from pathlib import Path +r = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\")) +Path('graphify-out/.graphify_detect.json').write_text(json.dumps({ + 'files': r.get('new_files', {}), + 'all_files': r.get('files', {}), + 'total_files': r.get('new_total', 0), + 'total_words': r.get('total_words', 0), + 'skipped_sensitive': r.get('skipped_sensitive', []), + 'needs_graph': True, +}, ensure_ascii=False), encoding=\"utf-8\") +" +``` + +If new files exist, first check whether all changed files are code files: + +```bash +$(cat graphify-out/.graphify_python) -c " +import json +from pathlib import Path + +result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {} +code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'} +new_files = result.get('new_files', {}) +all_changed = [f for files in new_files.values() for f in files] +code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed) +print('code_only:', code_only) +" +``` + +If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8. + +If `code_only` is False (any changed file is a doc/paper/image/video): **first, if any changed file is in `new_files['video']`, run `references/transcribe.md` (Step 2.5) on those files, then rewrite `.graphify_detect.json` to move the resulting transcript paths into `files['document']` and drop `files['video']`** — otherwise raw `.mp4/.mp3` paths are fed to semantic subagents as unreadable media (#1392). Then run the full Steps 3A–3C pipeline as normal. + + +If no new files exist (only deletions), create an empty extraction so the merge step can prune: + +```bash +if [ ! -f graphify-out/.graphify_extract.json ]; then + echo '[graphify update] Only deletions -- creating empty extraction for merge.' + $(cat graphify-out/.graphify_python) -c " +import json +from pathlib import Path +Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8') +" +fi +``` + + +Then: + +```bash +$(cat graphify-out/.graphify_python) -c " +import json +from pathlib import Path +from graphify.build import build_merge +from graphify.detect import save_manifest + +# Load new extraction and incremental state +new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\")) +incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\")) +deleted = list(incremental.get('deleted_files', [])) +# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are +# handled by build_merge's replace-on-re-extract (#1344): every source_file in +# new_chunks is dropped from the base before merge, so old/stale nodes don't survive. +# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base +# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot +# now that replace — not the dedup pass — reconciles changed files). +prune = list(deleted) or None + +# Use build_merge() — reads graph.json directly without NetworkX round-trip +# so edge direction (calls, implements, imports) is always preserved (#801). +# Pass root= so prune_sources (absolute paths from detect_incremental) are +# relativized to match the graph's relative source_file values; without it +# nothing is pruned and stale nodes accumulate on every update (#1361). +# directed=IS_DIRECTED: replace IS_DIRECTED with True if --directed was given, else +# False. Without it a --directed --update silently rebuilds undirected and collapses +# reciprocal A<->B edges (#1392). +G = build_merge( + [new_extraction], + graph_path='graphify-out/graph.json', + prune_sources=prune, + root='INPUT_PATH', + directed=IS_DIRECTED, +) +print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges') + +# Write merged result back to .graphify_extract.json so Step 4 sees the full graph +merged_out = { + 'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)], + 'edges': [ + # Explicit source/target last so they win over any stale attrs in d. + {**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')}, + 'source': d.get('_src', u), 'target': d.get('_tgt', v)} + for u, v, d in G.edges(data=True) + ], + # G.graph["hyperedges"] holds hyperedges from both existing graph.json + # and new_extraction (build_merge combines them). Falling back to + # new_extraction only would silently drop prior-run hyperedges (#801). + 'hyperedges': list(G.graph.get('hyperedges', [])), + 'input_tokens': new_extraction.get('input_tokens', 0), + 'output_tokens': new_extraction.get('output_tokens', 0), +} +Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out, ensure_ascii=False), encoding=\"utf-8\") +print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)') + +# Save manifest so next --update diffs against today's state, not the +# prior run's baseline (prevents ghost-node reports on subsequent updates). +# root= matches the build_merge call above so the manifest keys stay relative to +# the scan root — portable across clones/machines, so --update keeps matching +# cached files instead of missing every one after a move (#1417). +# +# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output +# THIS run (new_extraction is this run's fresh extraction, read above before the +# merge overwrote the file): a changed doc whose chunk failed must stay unstamped +# so the next --update re-queues it, otherwise it is marked done and its content +# is lost forever (#2015). Mirrors the library extract path +# (cli._stamped_manifest_files + clear_semantic + scan_corpus). +from graphify.cli import _stamped_manifest_files +_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH')) +# Changed semantic files dispatched this run but NOT stamped had their chunk fail +# or be omitted; clear any stale semantic_hash so they are re-queued (#1948). +_sem_types = ('document', 'paper', 'image') +_dispatched = {f for t, fl in incremental.get('new_files', {}).items() if t in _sem_types for f in fl} +_stamped = {f for fl in _manifest_files.values() for f in fl} +_cleared = _dispatched - _stamped +# scan_corpus = the RAW full corpus so in-root files newly excluded since last run +# are dropped rather than masquerading as deletions; untouched rows preserved (#1908). +_scan = {f for fl in incremental['files'].values() for f in fl} +save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None) +print('[graphify update] Manifest saved.') +" +``` + +Then run Steps 4–8 on the merged graph as normal. + +After Step 4, show the graph diff: + +```bash +$(cat graphify-out/.graphify_python) -c " +import json +from graphify.analyze import graph_diff +from graphify.build import build_from_json +from networkx.readwrite import json_graph +import networkx as nx +from pathlib import Path + +# Load old graph (before update) from backup written before merge +old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_old.json').exists() else None +new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\")) +G_new = build_from_json(new_extract, directed=IS_DIRECTED) + +if old_data: + G_old = json_graph.node_link_graph(old_data, edges='links') + diff = graph_diff(G_old, G_new) + print(diff['summary']) + if diff['new_nodes']: + print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5])) + if diff['new_edges']: + print('New edges:', len(diff['new_edges'])) +" +``` + +Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json` +Clean up after: `rm -f graphify-out/.graphify_old.json` + +--- + +## For --cluster-only + +Skip Steps 1–3. Re-run clustering on the existing graph: + +```bash +graphify cluster-only . +``` + +`graphify cluster-only .` is **self-contained**: it re-clusters, names communities, and regenerates `GRAPH_REPORT.md`, `graph.json`, and `graph.html` from the existing graph. **Do not re-run Steps 5–9** — they read intermediate files (`.graphify_extract.json`, `.graphify_detect.json`, `.graphify_analysis.json`) that a prior build's cleanup (Step 9) already deleted, so they raise `FileNotFoundError` (#1392). When it finishes, present the refreshed `GRAPH_REPORT.md` summary as usual. diff --git a/.gitignore b/.gitignore index a8ec6a0..bcaa702 100644 --- a/.gitignore +++ b/.gitignore @@ -31,4 +31,6 @@ server/uploads/ server/clips/ # skills -graphify-out/ \ No newline at end of file +graphify-out/ +# skill links into .agents/skills (installed from skills-lock.json) +.claude/skills/design-taste-frontend diff --git a/CLAUDE.md b/CLAUDE.md index 24281e0..4f51c98 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,12 +32,17 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Never run commands against the production server or database unless explicitly asked. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. +- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`): `docs/analytics-reports.md`. Short links `/go/` (Data → Links/redirects, `server/src/routes/redirects.js`) count clicks, report each to Plausible as a pageview and add the link's UTM tags: `docs/redirects.md`. - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`. +- Present remote: a presenting screen (`/events/:id/present`) shows a code; a phone at `/remote/` steps, pauses, jumps and changes its setup, anyone with the code (`server/src/routes/present.js`, `src/pages/PresentRemote.tsx`). Server-sent events held in memory (one process); the API sends `X-Accel-Buffering: no`, so nginx needs no block of its own. +- Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`. - Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for `/api/admin/import/docx` with an 11m body limit: `docs/importing.md`. - Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`. - Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`. - Request form (`/request`): files go to the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`). `driveUpload(folder, ...)` finds or makes the named folder in the shared drive, so other uses get their own folder. Tools → Media → Files uploads to "Media" and shares each file as anyone-with-the-link (`server/src/routes/files.js`, migration 048); link fields with `files: true` pick from it ("Choose a file"), and link cards take its first-page preview. Needs a `/api/admin/files` nginx block (51m). Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.md`. +- Profile accounts (migration 076): admins invite an email (Data → Profile accounts), the person sets a password from the link or signs in with any Google account under that email, claims their People record (an admin approves), then edits it and hides parts at `/account`. Public reads of people go through the `v_people_public` view, never `people`. Discord linking is off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set: `docs/profile-accounts.md`. +- Planning Center (migration 085): Data → Planning Center compares a Planning Center People list (Site settings → Planning Center) with the site's people and applies what an admin picks: link (`people.pco_id`), update the name and private email and phone, or add unpublished. Off until `PCO_APP_ID` and `PCO_SECRET` are set: `docs/planning-center.md`. - Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plus `GOOGLE_DIRECTORY_AS`), anyone in one gets a Google-only account whose role follows the group, rechecked at sign-in, hourly and by Panel → Re-sync now (`server/src/accessGroups.js`); superadmins and admin-cli accounts are never changed by groups. Passwords still work. Setup: `docs/google-sign-in.md`. ## Git workflow @@ -59,17 +64,17 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - All pages use `PageShell.tsx` as the wrapper unless explicitly noted otherwise. - Pages live in `src/pages/`; section-level components go in `src/pages/sections/`. - `src/data/` holds only hardcoded data shared across multiple section files (e.g. `historyDecades.ts`, map grid). Everything else comes from SQLite, through hooks in `src/lib/`. -- `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages). +- Pages are rows of `site_pages` (migration 080), edited in Pages → Page management: address, title, intro, Hidden (Not found below viewer) and Disabled (out of the menus, sitemap and search). Every page is a page of sections, the front page included (its hero and bands are section types: `src/pages/sections/Bands.tsx`, their settings in `section_*` tables read by `server/src/sectionData.js`; forms and embeds are section types too, `src/pages/sections/FormSections.tsx`), and new ones are made there; `PageAtPath.tsx` (the `*` route) draws whatever page is at an address. The pages the code links to (`CORE_PAGES` in `server/src/admin-schema/sitePages.js`: /give, /feedback, /request, /qr, /privacy, /terms) keep their address and can't be deleted. Record routes (`/events/:id`...) stay in `App.tsx`, and their first path segments are reserved. Menu links are Pages → Navigation (`site_nav_links`, `server/src/siteNav.js`, read through `src/lib/useSiteNav.ts`); `navConfig.ts` only holds the defaults the app starts from before that loads. - `api.ts` is the shared caching client used by frontend data hooks. - `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content. -- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`). +- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews), `/uploads/captions/` (videos' .vtt files); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`). ## Rules and gotchas -- **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs. +- **Role checks must use ladder comparisons, never equality.** Roles rank member → viewer → editor → admin → superadmin (member is a profile account: the site and its own profile, never the admin; `/api/admin` needs viewer, `requireStaff`). Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `isStaff`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs. - **Imports need explicit extensions** (`.ts`, `.tsx`, `.js`) everywhere. - **Vite resolves `.js` before `.ts`**, so a `.js` and `.ts` file with the same base name will import the wrong one. Give new hooks distinct names. - **Don't use `fallback: EMPTY` in api.ts hooks.** It silently returns empty arrays and hides server errors; let the error state surface. -- **Colors are tokens, not hex.** Admins can override any token (Panel → Site settings → Colors). The defaults are `server/src/themeDefaults.js` plus the same values as CSS in `src/index.css`; the build fails if they differ (`themeDefaultsCheck` in `vite.config.ts`), and migration 041's CHECK lists the token names. Use the utilities from `src/index.css` (`text-ink`, `text-body`, `text-muted`, `text-link`, `bg-surface`, `bg-tint`, `bg-action`, `border-brand/20`...) so dark mode works; a literal only for something that must look the same in both modes (white on a dark band, a platform's color). Data colors (accents, event and region colors) go through `withAlpha`, `accentText` and `readableOn` in `src/lib/color.ts`, never `${color}55`. +- **Colors are tokens, not hex.** Admins can override any token (Panel → Site settings → Colors). The defaults are `server/src/themeDefaults.js` plus the same values as CSS in `src/index.css`; the build fails if they differ (`themeDefaultsCheck` in `vite.config.ts`), and migration 041's CHECK lists the token names. Use the utilities from `src/index.css` (`text-ink`, `text-body`, `text-muted`, `text-link`, `bg-surface`, `bg-tint`, `bg-action`, `border-brand/20`...) so dark mode works; a literal only for something that must look the same in both modes (white on a dark band, a platform's color). Data colors (accents, event and region colors) go through `withAlpha`, `accentText` and `readableOn` in `src/lib/color.ts`, never `${color}55`. A palette color in a component or CSS file is `var(--pal--)`, not its hex, so the color blind modes reach it. - **Icons are Phosphor** (`@phosphor-icons/react`), weight `bold` (or `fill` for play/star). No hand-drawn `` icons and no Unicode glyphs as icons (× › ▶ →). Brand marks are the exception: `DoveMark`, `PlatformIcon`, the Google logo, the group map. - **Accents come from `src/lib/color.ts`:** `BRAND` (the teal, via the button token so the admin palette reaches it) and `ACCENTS` (deep, green, olive), all from `PALETTE` (the site's 16-color grid). Not a new hex in a page. - **Corners: square.** Everything is square except buttons, which use the `btn` utility (Poppins Bold, a small `var(--btn-radius)` corner, also for plain CSS), video players (small rounded) and things round by nature (dots, radio marks, the play button). A note in place of content (empty section, "coming soon") uses the `notice` utility (corner brackets), not a dashed border. Cards sit on `bg-raised` with a shadow so they stand off the page. Nothing glows: no blur blobs, no glow shadows. @@ -81,14 +86,16 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu Descriptor-driven: `server/src/admin-crud.js` and `server/src/admin-schema/` (server, one file per entity, registered in `admin-schema.js`) and `src/lib/adminSchema/` (client, one file per entity, registered in `adminSchema.ts`) generate SQL and form fields from declarative entity configs. Adding an entity should mean adding a descriptor, not new CRUD code. - Child collections are deleted and reinserted wholesale. Unsafe for entities referenced by foreign keys elsewhere. - `reindex: false` prevents cross-entity sort order collisions. +- A child collection can have `extensions` of its own (1:1 side tables keyed by the child row's id, eg. a page section's `section_hero`), and both those and its nested collections take a `when` on the row's values (a section's preset). A `when` value can be a list. - `check: (db, id) => void` runs after a save has written everything, inside its transaction; throwing an `HttpError` refuses the save (Site settings uses it for the color contrast check, `server/src/theme.js`). - The `OMIT` sentinel distinguishes unsent fields from deliberate clears. - `admin-schema-sync.js` runs at boot and throws if descriptors don't match live `PRAGMA table_info`. If boot fails after a schema change, update the descriptor or migration so they agree. - `admin-cli.js` imports `ROLES` and `destroyAllSessionsFor` from `auth.js`. Keep it that way to prevent drift. +- Drafts (migration 077, `server/src/drafts.js`, `docs/drafts.md`): any existing record can be saved as a draft (one per record), previewed on the real page and published (the ordinary PATCH, which drops the draft). Checking and previewing apply the draft in a transaction that is rolled back; `tx()` nests as a savepoint for that, so never call `BEGIN` by hand. A new entity with a public page adds its path to `PREVIEW_PATHS` in `src/lib/adminSchema.ts`. ## Migrations -- `server/src/migrations/023_schema.sql` is the baseline: the whole schema, consolidated from the old 001–023. It only runs on an empty database; the runner refuses a database between v1 and v22. It's the place to read the schema, not to change it: a database that already exists never re-runs it. -- Changes go in new sequential files after it: `024_`, `025_`, ... +- `server/src/migrations/066_schema.sql` is the baseline: the whole schema, consolidated on 2026-10-04 from the old 023–066 (generated from the live schema, so the comments are the ones inside each table). `066_seed.sql` runs right after it with the least a new database needs (single rows, event scopes, the site pages' sections, the Musicians tag); content is typed in through the admin. Both only run on an empty database; the runner refuses a database between v1 and v65 (bring it to v66 with a release from before the consolidation first). It's the place to read the schema, not to change it: a database that already exists never re-runs it. +- Changes go in new sequential files after it: `067_`, `068_`, ... - The runner may drop statements after a `BEGIN...END` trigger body. Keep triggers last in a file, and put each `CREATE VIEW` before any trigger or in its own file. - The runner turns foreign keys off around every migration (it can't be done inside the file's transaction) and runs `PRAGMA foreign_key_check` before committing, so a table rebuild needs no `PRAGMA foreign_keys` of its own. When views or triggers name the table being rebuilt, wrap the drop-and-rename in `PRAGMA legacy_alter_table = ON` ... `OFF`, then recreate the rebuilt table's own indexes and triggers. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..747cf1a --- /dev/null +++ b/TODO.md @@ -0,0 +1,380 @@ +# TODO +- Instructions for this document: update it as things are completed, moving items from TODO to Done under the same category. Develop content here based on conversations. Leave the categories blank in Part 1: TODO when you are moving items out of them to Done. +- Status: everything up to v1.8.3-video-mgmt is tested and deployed. PR #14 (branch `audit`, v1.9.0 to v1.9.4-audit) was merged into main on 2026-09-29 (adc88e5). Branch `content-display` was merged as PR #15 (v1.9.5 to v1.9.11, 2026-09-29) and PR #16 (v1.9.12 to v1.9.14, 2026-09-30, c76df02). All of it is deployed and checked in a browser (2026-09-30). The design overhaul (PR #18, v1.10.0 to v1.10.2) and the revised palette (PR #19, branch `palette-test`) were merged into main on 2026-09-30 (6f86a11); not deployed yet. Branch `page-updates` (v1.10.3 to v1.10.6) was merged into main as PR #20 on 2026-10-01 (3e4a725); not deployed yet. Branch `page-fixes` (v1.10.7 to v1.10.10) was merged as PR #21 on 2026-10-01 (0bb4b86); not deployed yet. Back up the database before deploying (migrations 056 to 059: 056 and 057 rebuild content_blocks, 058 page_sections, 059 recreates v_events). Branch `audit-3` (v1.11.0-audit) is open as PR #22; branch `audit-ui` (v1.11.1-audit, on top of it) as PR #23; branch `newsletter-layout` (v1.11.2-newsletter, on top of that, migration 060) as PR #24. + +--- + + +# Part 1: TODO +- Items from notes.txt (2026-10-16). Each has questions under it: tick one when it's settled, or write the answer after "Answer:". + +## Pages +- [ ] **Resources page by audience**: frame the page as For Young Adults, For Ministries, For All. + - [ ] Are these three tabs, three sections (each in the side nav), or a filter over one list? Answer: + - [ ] Does each resource belong to exactly one audience, or can it be in several (eg. a tag per audience)? Answer: + - [ ] What happens to the page's current sections: move under an audience, or replaced? Answer: +- [ ] **Library**: a library for NGUers. + - [ ] What goes in it: links out, uploaded files (Drive "Media"), books, videos, our own articles? Answer: + - [ ] Public, or only for NGUers? If only NGUers, how do they sign in (there are only admin accounts today)? Answer: + - [ ] Is the metaphysics dictionary / Metaphysical Bible Dictionary part of it (see Future: Poetry Builder needs the same import)? Answer: + - [ ] Is the Metaphysical Bible Dictionary free to republish (public domain edition), or only linked? Answer: +- [ ] **The Acronym Dictionary**: a page of acronyms (Unity, New Thought, NGU). + - [ ] A page of its own, or a part of the Library? Answer: + - [ ] Each entry: acronym, meaning, a short description, a link? Anything else (category, related org)? Answer: + - [ ] Who adds entries: admins in Data, or anyone through the request form? Answer: + - [ ] Do you have a starting list to import? Answer: +- [ ] **Retreat content index**: ideas and content from retreats, which event each was featured at, tabs for the major pillars, a table of contents to fill out (borrowed from YOU history). Also retreat templates. + - [ ] What are the major pillars (the tab names)? Answer: + - [ ] What is one entry: a talk, an activity, a theme, a workshop? Its fields (title, description, files, presenter, event)? Answer: + - [ ] Where does the YOU history version live, so I can see what to borrow? Answer: + - [ ] Public, or for retreat teams only? Answer: + - [ ] How does the feedback form fit: a form per retreat linked to its entries, or feedback shown on entries? Answer: + - [ ] Retreat templates: documents to download (Drive files), or a "start a new retreat from this one" copy in the admin? Answer: +- [ ] **Centralized scholarship and donor giving page**: one page for scholarships and giving. + - [ ] Does giving stay on Church Center (embeds), with this page gathering them, or something else? Answer: + - [ ] What is "etc.": scholarships, the Catalyst Fund, general giving, per-event giving? Answer: + - [ ] Do scholarships need an application (a form like /request), or only a description and a link? Answer: + - [ ] Show donors or totals (eg. a goal bar), or none? Answer: +- [ ] **Website changelog**: the site's construction as an evolving blog post, tabs marking each update. + - [ ] One blog post with a tab per version, or a blog post per version under a "Website updates" tag? Answer: + - [ ] Written by hand, or started from the tags and TODO.md Done list (then edited)? Answer: + - [ ] Does it go back to v1.0, or start from now? Answer: + - [ ] Linked from the footer next to the version, or only in the blog? Answer: + +## Sections + +## Page Features +- [ ] **Full profiles**: people get full profile pages. Profile accounts, claiming and visibility are done (Part 2, Accounts); what's left is the page itself. + - [ ] What is missing from a person's page today that makes it "full": bio, more photos, links, events they spoke at, groups, blog posts they wrote? Answer: + - [ ] Ties to Planning Center sync (Data) and the gamification below? Answer: +- [ ] **Page preview images per page**: the event's banner on event pages, the person's photo on theirs, the org's logo on org pages. + - Already done in `server/src/pageMeta.js`: events use the event photo, then the event logo, then its org's logo; people their photo; orgs, teams and awards their logo; blog posts their cover. SVG logos are skipped (social sites don't show them). + - [ ] Which page showed the wrong picture, and where (Discord, iMessage, Facebook)? Answer: + - [ ] Is it production (not deployed yet?) or the SVG skip? Should an SVG logo get a PNG copy made at upload for previews? Answer: + - [ ] Should event pages prefer the card background ("banner") over the event photo? Answer: + +- [ ] **Gamification synced to Discord**: points, badges or levels on the site, synced to Discord. Linking a profile to Discord is done (Part 2, Accounts); the bot, points and badges are next. + - [ ] What earns points: going to events, writing for the blog, volunteering, Discord activity? Answer: all of the above, we could create badges on profiles. + - [ ] Where are they shown: on full profiles, a leaderboard, only in Discord? Answer: shown on profiles when logged in, no leaderboard for now, and when using a command in discord. this content would not show on the public bio section of a user when viewing from a people tile. + - [ ] Which way does it sync: site → Discord roles, Discord → site, or both? Is there a Discord bot already (or only the reports webhook)? Answer: would like a bot built, for if things in discord update or affect gamification shown on the website. most things will be assigned to users by moderators. + - [ ] How do we match a person to their Discord account (they link it themselves)? Answer: they can link it, admins can overwrite and update/set +- [ ] **Site version names**: in the footers now (Part 2, Page features); still to show them in the changelog once it's built (Pages: Website changelog). + +## Accessibility Features +- [ ] Check the mobile fixes on a real phone (or the browser's phone view at 320, 375 and 430px), light and dark: every page, the menu, the hero, the retreat carousel, people tiles and their details, the community map, schedule blocks, the banner. +- [ ] **Listen to a page**: a screen reader or compiled audio for certain pages. + - [ ] The browser's own voice (free, reads the Reading mode text, sounds robotic), or recorded/generated audio files (better voice, has to be made for each page and kept current)? Answer: + - [ ] Which pages: blog posts, History, Organization, all? Answer: + - [ ] A Listen button in the Accessibility panel, or on each page by its title? Answer: + +## Mobile + +## Page Editing +- [ ] **Page management revamp**, in steps (answers from 2026-10-16: disabled means out of the menus, sitemap and search with the address still working; admins can make new pages; the front page, the Community blog's settings, the form and embed pages and Privacy/Terms all become pages of sections; section types like the hero, stats, featured cards, calendar and countdown can go on any page, each with its own content). + - [x] Step 1, the page registry (Done, below). + - [x] Step 2, the core pages as sections (Done, below). + - [x] Step 3, section types with their own settings and the front page as sections (Done, below). + +## Admin + +## Data +- [ ] **New Thought young adult directory**: the tabs are built (Part 2, Page features). Content: make the People tags (eg. Authors, Creators), tag people, and set Community's Directories section to them. + +## Navigation + +## Tools + +## Content +- [ ] **Newsletter: featured partners and new partnerships**, maybe as a blog post. + - [ ] A newsletter part of its own (picks organizations, shows logos), or a blog post the newsletter links to? Answer: +- [ ] **Blog posts to write** (content, not code): + - [ ] The Catalyst Fund. + - [ ] How churches can engage with young people, through social media: what tools they use. + - [ ] Aidan's ultimate guide: church management systems, donor engagement platforms, free tools for nonprofits, nonprofit technology, AI (its benefits, and using tools ethically). + - [ ] Should any of these come out as a series (a tag), or one at a time? Answer: + +## Production cleanup + +## Audits + +## Future +- Timeline vine/tree SVG (you'll provide it); until then the timeline is solid teal dots on a teal rail, one color throughout. +- Legal check of the Privacy Policy and Terms for NGU's state and nonprofit status (wording read 2026-09-28, fine for now). +- Enforce the Content-Security-Policy after watching its reports on the server (`journalctl -u ngu-api | grep csp`, `docs/security-headers.md`). +- Potentially make new vertical nav circle a sun svg later on. +- Poetry Builder, need to import the metaphysical bible dictionary and virtue list. + +--- + + + + + +# Part 2: Done +## v1.14.0-profiles: page management (branch `page-management`, on top of `page-features`, no PR yet; migrations 080 to 085, back up the database before deploying) +- [x] **Planning Center sync** (Data, migration 085, `docs/planning-center.md`): Data → Planning Center (admins and up) fetches one Planning Center People list (Site settings → Planning Center) and compares each member with the site: linked, or suggested by the same email, else the same name, with the fields that would change (name, sort name, private email and phone) side by side. For each: link (and update; Planning Center wins), link to someone else, make a new unpublished person, or skip; Apply writes it all at once. One way, by hand. Off until `PCO_APP_ID` and `PCO_SECRET` are on the service. Tested against a stand-in for Planning Center's API only. + - [ ] Check with the real list: the token, a list number, a compare, an apply. +- [x] **Rotating words** (Sections, migration 084): text typed as `{Next|Now|Rising}` cycles through its choices, in the hero's headline, section titles (bands' too), headings, paragraphs, callouts and quotes, eg. `{Next|Now} Generation of {Unity|New Thought}`. Five motions (slide, flip like a card, fade, type letter by letter, mirror turning round), from the top or the bottom, a number of seconds per word: defaults in Site settings → Animated words, and a hero or a block can set its own. Each word's space is the longest's, so the line doesn't jump. Less motion (the system's setting, or reading mode) shows the first word, still, and screen readers always get the first; menus, tab titles, search descriptions and newsletters use the first word too (`src/components/RotatingWords.tsx`, `src/lib/words.ts`). + - [ ] Check in a browser: each motion and direction, a group in a section title and a paragraph, the space it keeps on a phone, reduced motion. +- [x] **Section types with their own settings, and the front page as sections** (migration 083): the front page is Home in Page management, a page of sections like the others: its hero first, then its bands in their old order (hidden ones stay hidden), each a section type that can go on any page with content of its own: Hero (words, buttons, photos, video, livestream or event), Event countdown, Event calendar, Numbers, Featured cards, Connect nav, and a Timeline shown as the rail of featured moments. The Community blog's slots, pinned posts and feeds moved into its section, so it can go on any page too. Any section can be Hidden. The Front page editor is gone (its fields are each section's), and so are its tables and the Community page's. On the front page the bands look as they did and any other section is a band in the same style; on other pages a band brings its own heading. The National Retreats band became an Events section with an All retreats button. The newsletter's "featured cards" come from the front page's featured card sections. Admin engine: a child collection can have its own side tables and gated nested collections. + - [ ] Check in a browser: the front page (every band, the countdown overlapping the hero, reading mode, the menu's Home dropdown), editing the hero and a band in Page management, a Hero and a Numbers section put on another page, hiding a section, the Community blog (pinned posts, feeds), a draft preview of the front page, the newsletter's featured cards. +- [x] **Core pages as sections** (migrations 081, 082): Feedback, Request, QR codes, Give, Privacy and Terms are pages of sections now, edited in Page management like any other. Their forms and embeds are section types any page can use (Website feedback form, Request form, Data request form, Giving button, QR code maker); Give's words, and all of Privacy and Terms, are blocks (headings, paragraphs, lists), with "Last updated" in the section's blurb. The privacy contact email was written into the policy's text and its Site settings field is gone. These pages keep their address (the site's code links to them) and can't be deleted. The privacy notice's link now goes to #cookies-and-browser-storage. + - [ ] Check in a browser: each of the six pages (reading width of Privacy and Terms, the giving modal opening), editing a Privacy paragraph, a Request form section put on another page. +- [x] **Page registry** (migration 080): every page of the site is a row in Pages → Page management (admins and up): its address, title, intro, Hidden (Not found below viewer) and Disabled (out of the menus, the sitemap and search; the address still works), and the order of its admin card. New pages are made there, as pages of sections at the address given (any address but the admin's, the API's, the records' and the account pages'). The admin home's Pages group opens with a Page management banner (New page, Menus), then a card per page. The six page editors (Retreats, Community...) are one editor now; site.json's `pages` and Navigation's page list moved into the registry and are gone. The fixed pages (Feedback, Request, Give, QR codes, Privacy, Terms, the front page) take their words from it too and can't be deleted. + - [ ] Check in a browser: the admin home's banner and page cards, making a page (address, sections) and opening it, hiding and disabling one (menus, the page signed out), renaming Feedback, the Under page select in Navigation. + +## v1.14.0-profiles: page features (branch `page-features`, with `nav-access` under it, no PR yet; migrations 078 and 079, back up the database before deploying) +- [x] **Featured event label** (Mobile): the "Featured event" badge left the headline; from lg up it sits above the event's card it names, and on a phone (the card under the words) it's left out. +- [x] **Site version names**: the tag's words after the number are the version's name, `v1.13.2-region-cards` → "The Region Cards Update" (`src/lib/version.ts`), shown with the number in the site's footer and beside the version in the admin's footer and home. +- [x] **Image converter** (Tools → Image converter): pictures to JPG, PNG or WebP in the browser (nothing uploaded): pick or drop several, a quality slider for JPG and WebP, download each or all. JPG fills transparency white. Media's images each have a Download as… (JPG, PNG, WebP) doing the same (`src/lib/convertImage.ts`). +- [x] **Directory tabs** (migration 078): the People directory preset takes several People tags, a tab each in the order picked (Directory: tags under the section); one tag shows without tabs, reading mode lists every tag. Each section's old single tag became its first. +- [x] **Blog post tabs** (migration 079): a Tab block in a post (its text the tab's title) starts a tab holding the blocks after it; blocks before the first Tab are the intro above the tabs. The contents list follows the open tab, a link to a heading in another tab opens it, and Download PDF and reading mode show every tab under its title. Outside a post a Tab block reads as a heading. +- [x] **Featured event card height** (Sections): from lg up the event's photo sits beside its words instead of above them, with tighter type and buttons, so the card is about as tall as the hero's text beside it; stacked as before on a phone. The photo stays whole (16:9). +- [x] **Word import, more of it** (Page Features): a line starting `Tab:` (any style) starts a tab; the Quote style becomes a Quote (a dash and a name at the end is who said it), Intense Quote a Callout, a line of `---` a Divider, a YouTube, Vimeo or Facebook link alone on its line a Video, and `Button: Register` with Register linked a Button. Blog posts → What becomes what (beside Import from Word) shows the whole mapping; `docs/importing.md` too. The note after an import counts tabs and the rest. +- [x] **Side nav sun into the footer** (Navigation): the sun is far bigger than the sticky layer that carries it, so once the last section went up past the list it hung over the footer. It now fades out as the list leaves with the last section, and back in on the way up. + - [ ] Check in a browser: the featured event card beside a two-line headline at 1024, 1280 and 1536px; What becomes what and a real Word document with Tab: lines, a quote and a video link; the side nav sun fading at the end of a long page (2xl screen) and with a tall footer; the featured event hero at phone and desktop width, the footers' version line, converting a PNG with transparency to JPG and a JPG to WebP (and Download as in Media), a Directories section with two tags and with one, a post with an intro and three tabs (contents, keyboard arrows, PDF, reading mode). + +## Page Editing (branch `nav-access`, no PR yet; migration 077) +- [x] **Drafts of every record** (migration 077, `docs/drafts.md`): an existing record of any kind (events, people, organizations, blog posts, the front page, the site pages, Navigation, Site settings...) can be saved as a draft instead of going live. One draft per record; anyone who can edit it can save, preview, publish or discard it. Opening a record with a draft opens the draft, saying who saved it and when, and warning when the live record was saved since. Lists mark records with a draft. +- [x] **Preview on the real page**: Preview saves the draft and opens the record's page in a new tab with it applied, under an amber "Previewing a draft" bar, for signed-in admin accounts only; anyone else sees the live page. The server answers that tab's reads from a second connection holding the draft in a transaction it rolls back, so no page needed code of its own. + - [ ] Check in a browser: save a draft of an event, a site page (a section's title) and Navigation (a link), preview each, publish one, discard one; open the same address signed out. + +## Accounts (branch `nav-access`, no PR yet; migration 076, back up the database before deploying) +- [x] **Profile accounts** (migration 076, `docs/profile-accounts.md`): a member role below viewer, signed in to the site and their own profile, never the admin (`/api/admin` now refuses anything under viewer). By invite only: Data → Profile accounts (admins and up) adds an email and shows its link once; Email invite sends a fresh one through Gmail. The link (`/account/welcome`) sets a password, or they sign in with Google under that email, any Google account. A New sign-in link on the account doubles as a password reset. +- [x] **Claiming a People record**: on `/account` (Your profile; the footer's Sign in link) they ask to be a record; admins approve or decline it under Claims, or set it directly on the account. +- [x] **Editing it and choosing what shows**: with a record, they edit its pronouns, tagline, location, public email and phone, bio and photo, and hide any of photo, pronouns, tagline, bio, email, phone, location, links. Hidden parts stay in the record (the People editor shows the same switches) and are left out everywhere on the site: every public read of people goes through the new `v_people_public` view, and the views that read people were rebuilt over it. +- [x] **Discord linking**: a profile links its Discord account (identify scope: id and name) from `/account`; an admin can set or clear it on the account. Off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set on the service. + - [ ] Check in a browser: invite (copy link and Email invite), the welcome page with a password and with a non-org Google account, a claim and its approval, editing and hiding (then the person's page, a team page and a people tile signed out), Discord linking once it's set up, a member opening /admin. + +## Navigation (branch `nav-access`, no PR yet; migration 075, back up the database before deploying) +- [x] **Pages → Navigation** (migration 075): the header's pages and buttons, the footer's Get in Touch and bottom row, edited in the admin (admins and up): place, order, label, link (a page, a #section or an address elsewhere), a header page set under another page's menu (after its sections), a filled button (Give's style, also beside the footer's logo), new tab. `navConfig.ts` is now only the defaults the app starts from before the nav loads. Page titles and intros moved here from Site settings (the old rows came along). +- [x] **Hidden pages**: a page ticked Hidden in Navigation answers Not found (404, noindex) to everyone below viewer, server and app both, and is out of the menus, the sitemap and the not-found page's suggestions; links to it are only sent to viewers and up. Signed in, it shows with a bar saying it's hidden. Its sections aren't cached (`server/src/siteNav.js`, `GET /api/nav`). +- [x] **Shop**: a Shop page of sections at `/shop` (Pages → Shop, empty for now), starting hidden, with a Shop button in the header (beside Contact Us and Give, and in the phone menu's list with them). Unhide it in Navigation once it has content; its sections can link out to the Bonfire store. + - [ ] Check in a browser: the header and phone menu, a page set under another's menu, the footer, signed out and signed in (the hidden bar, Shop showing), light and dark. +## Feature updates (branch `feature-updates`, v1.13.x, no PR yet; migrations 069 to 071, back up the database before deploying) +- [x] **Partner cards, logo first**: the organization cards (Partners, Ministries) lead with the logo, large and centered, the name under it as a small line (still the heading); with no logo, its initials. Cards sit raised with a shadow and an accent top edge. +- [x] **Frame a photo on upload**: photo fields (people, event photo and card background, blog cover and guest photo, hero photos, link card pictures, block images, schedule graphics and map images; not logos) open Frame the photo for a JPEG, PNG or WebP: drag (or arrow keys) to place, zoom slider, a shape menu (the field's own first; As uploaded keeps the photo's). The framed part is what uploads; Upload as is skips. Nothing stored beside the picture, so re-framing is uploading again. + - [ ] Check in a browser: the partner cards with and without logos (light, dark); framing a portrait into a square and a wide photo into 16:9, Upload as is, Cancel, and a PNG keeping its transparency. +- [x] **Content blocks: Shown in** (migration 071): The page, The card only, or The card and the page. A card block used to show on the page too without saying so; every existing card block became "both", so nothing moved. Pages no longer print card paragraphs separately; a "both" block comes with the page's blocks, in its place in the list. + - [ ] Check in a browser: an event with a "both" paragraph (on its card and page) and one with "card only" (card, not page); an organization, team and person page still show their text. +- [x] **Group pages**: the facts at the top sit in a framed card (City, Part of Region, Ministry, Meets, Since, tags); email buttons go to the link's URL, not its label (`splitLinks` took the label); every website and email row is listed with its own label, not only the first. +- [x] **Tags** (migration 070): Data → Tags (Online and In-Person to start) replace the Online checkbox on organizations and events. Records ticked Online got the Online tag (nothing got In-Person). The tag with URL ID `online` still makes an event online (calendar filter, place line, search data) through `v_events`. Tags show on the record's page and on group entries in the Community map list and grid; the map no longer keeps online groups off their state's tile. + - [ ] Check in a browser: a group page's facts card (light, dark, reading mode), two emails and two websites, tags on a group and an event, the Tags list in Data, and the calendar's Online filter still working. +- [x] **Schedule presentation** (digital signage): an event page's schedule block has a Present button (everyone) opening `/events//present` in a new tab. A setup screen picks the days and entries and the seconds for each kind of slide (day overview, entry spotlight with the person's photo and name beside the entry, graphics, map images; 0 leaves one out); Play goes full screen and loops, the parts of each slide animating in, a bar showing the time left. The settings are in the address (bookmark it on a signage screen; `play=1` skips setup). Arrows step, Space pauses, S returns to setup; the screen is kept awake where the browser allows. Not by the clock: it loops what was picked. +- [x] **Map image on schedule entries** (migration 069): an entry's own map picture, shown in its fold-out in place of the Google map (the "Open in Google Maps" link stays when a place is set) and as a slide in the presentation. + - [ ] Check in a browser: the Present button, setup, each slide kind (light and dark, a long day of 9+ entries in two columns), full screen on the signage device, and a map image in the fold-out. +- [x] **Group map** (Community): hovering a state outlines it in ink while its region stays lit; the list puts each region's groups under their state's subheading, each entry a raised card; the region's list of states is gone from the list (its map note stays); the list no longer scrolls on hover, only on click (a state goes to its subheading, or its region when it has no groups; a legend region to that region). +- [x] **Side nav pill** too tall when the window narrows (Community): the pill (straight sides, round ends) was sized as an ellipse, about three times the list's height; it's sized as the pill now. +- [x] The "Hide past events" button was clipped at the bottom when it grew on hover: the event cards' root wrapper was `overflow-hidden`; it is `overflow-x-clip` now (the carousel still can't spill sideways). + +## v1.13.1-data (branch `data`, merged as PR #28, 2026-10-06, 970730d; migrations 065 and 066, the consolidated baseline, then 067 and 068, back up the database before deploying; not checked in a browser yet) +- [x] Newsletter: a new draft's Coming Up "Pick from" showed "events no longer exists". Events is that select's blank choice, so new drafts now leave the source blank and older drafts' `events` loads as blank. +- [x] **Frame from a video**: a video featured card's Image field has "Frame at" (a typed time, prefilled from the link's `t=`); the server takes that one frame with yt-dlp and ffmpeg and saves it to `/uploads/thumbnails/` as the card's picture (`POST /api/admin/video-frame`, editors and up). Choosing any other picture already worked through the same field. Not tested end to end yet: needs yt-dlp, which is on the VPS but not the dev machine. +- [x] **Plausible reports to Discord** (migration 065): daily (yesterday) and weekly (Mondays, last 7 days with the change from the week before), each switched on in Panel → Site settings → Reports; sent at 8:00 America/Chicago. Needs `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` on the ngu-api service (`PLAUSIBLE_URL` if Plausible isn't on 127.0.0.1:8000). Try it with `node src/analyticsReport.js daily`. Tested with a stubbed Plausible only. +- [x] **Captions for uploaded videos** (migration 066): video blocks have a Captions field and the hero a Video captions field, each taking a WebVTT (.vtt) upload (kept as is, in `/uploads/captions/`), drawn as `` on a video file (WCAG 1.2.2). Embeds bring their own. Needs `text/vtt vtt;` in nginx's mime.types if it isn't there (`docs/media-uploads.md`, step 5). +- [x] **Migrations consolidated** into `066_schema.sql` (generated from the live v66 schema, checked identical: 136 objects, every table's columns) and `066_seed.sql` (single rows, event scopes, home sections, the five site pages and their sections, the Musicians tag; the hero words, paths, stats and the Organization address and tax ID are no longer seeded). A database at v66 skips both; one below v66 is refused. **Deploy order:** production is below v66, so deploy 33be618 (the last commit with the old files) first, let it migrate to v66, then deploy this. +- [x] **Partners section picks its organizations** (migration 067): the organization cards preset (Community → Partners) has "Cards: list" (Partners by default, Ministries, or both, every published, listed one by name) and an optional hand-picked "Cards: organizations" list (partners or ministries, in order, published ones, listed or not) that replaces it. Ministry cards link to their website only (no page). `/organizations` now takes `kind=ministry` and `ids=`. +- [x] **Links/redirects** (migration 068): Data → Links/redirects makes short links, `/go/`, for the newsletter. Each click is counted (Clicks, Last click on the list), sent to Plausible as a pageview of `/go/`, and redirected with the link's optional UTM tags added. Editors and up. `docs/redirects.md`. +- [x] Newsletter: Save as a new draft beside Save draft; a Title color; every part color is a color picker (any hex, or none) instead of the palette dropdown. +- [x] Region pages no longer show the raw domestic/international scope. +- [x] Keywords question (2026-10-04): Google has ignored `` since 2009, so nothing to add. What counts is the words on the page: titles, headings and descriptions, which `pageMeta.js` already fills per page. The Google side is Search Console, which shows the searches the pages appear for. + +## Pages and Data (branch `data`, merged as PR #27, v1.13.0-data, 2026-10-04, 3b45944; migrations 062 to 064, back up the database before deploying; not checked in a browser yet) +- [x] **Musician directory, as people tags** (migration 062): Data → People tags lists what people can be tagged as (Musicians seeded); a person's Directories repeater tags them, and their new Specialty line ("Vocals, piano · Gospel, folk") shows on their tile in a directory, with their links in the details panel. A People directory section preset (Community, Resources, Organization) shows a tag's first 12 and links to its full page, `/directory/` (eg. `/directory/musician`), titled and indexed like any page. Another directory (Speakers) is a new tag, no code. +- [x] **Ministry organizations** (migration 063): a new organization kind for Unity ministries. A group picks its ministry (Group → Ministry), and its page says "Ministry: ", linked to the ministry's website link when it has one. Ministries have no page, list, sitemap entry, timeline entry or 404 suggestion on the public site, and aren't offered where a record links to its organization (event hosts, teams, awards, roles, home organization, featured cards, timeline). +- [x] **Organization contacts and the recipient export** (migration 064): Data → Contact types holds the roles you make (none seeded); each organization has a private Contacts repeater (type, name, email, phone; editors and up only). Tools → Newsletter → Recipients filters them by contact type, organization kind, region (the region and its groups) and published, previews the matches and downloads a CSV for Mailchimp (Email, First Name, Last Name, Phone, Organization, Kind, Region, Contact type). A type still in use can't be deleted. + - [ ] Check in a browser: tag a person, the directory section and page (light, dark, reading mode), a group's ministry line, contacts on an organization (as a viewer too), the export and its CSV. + +## Accessibility, second round (branch `accessibility`, merged as PR #26, v1.12.1-accessibility, 2026-10-03, 07e56bf; not checked in a browser yet) +- [x] **Reading mode rebuilt** (`src/components/ReaderView.tsx`): the page as text only, headings, paragraphs, links and pictures with a description, in one column, with a line of links to the site's pages at the top. No header, footer, backdrop, buttons, cards or forms; the accessibility button stays, to turn it off. The real page still renders, hidden, and the reader writes out what it drew, again whenever it changes, so every page works without a version of its own. A card that is one link gives its heading the link; a button that opens something (a person's tile, a schedule row) keeps its words as a line; carousel copies and decorative pictures (empty alt) are left out. +- [x] **Color blind modes cover the whole site**: each mode now replaces all three color families (teal, green, amber), not just green, with sets picked by simulation (each family's darkness can differ, since a red-green color blind eye sees one blue to yellow line plus light and dark). The closest pair goes from 11.4 to 27.9 (protanopia), 19.5 to 24.7 (deuteranopia) and 6.4 to 21.1 (tritanopia); every theme token still meets 4.5:1 in light and dark mode. The theme tokens, the backdrop circles, the side nav circle, the header and menu, the hero, the stats band and data colors all follow (`--pal-*` variables in index.css, `SWAPS` in color.ts). +- [x] **Reading mode spacing and width**: words from parts the page draws on their own lines (a name above a title, a flex row's items) no longer run together; the column is 60rem (was 42rem) and headings are bold, in the display face. +- [x] **Front page in reading mode**: bands the reader can't read well draw a text version of their own (`useReadingMode()`): the numbers, one line each ("1,200+ Members"), no longer stuck at 0 (the count waited for the band to scroll into view, which the hidden page never does; reduced motion now shows them at once too); the calendar, the next six weeks from today as a list (date, linked title, time, type, place) on any page that has one; the featured cards, each a linked heading with its words, a video card linking to its video. The countdown is left out, since the retreats band shows that event. +- [x] **Reading mode, every page and section** (audited section by section): the reader itself now reads an icon-only link's aria-label, puts a card's link on its first line or picture when it has no heading, gives each item of a row of facts or link buttons its own line, keeps line breaks, skips what CSS hides (a blog post's print-only footer), turns a form into one line saying it can't be used there, shows empty table cells as "-", and keeps section and heading ids so #links land (side nav, a post's contents). What it can't read draws its own text version (`useReadingMode()`): the hero (its words, buttons, every slide's caption, livestream and video links), the pathfinder (every path and its actions), the front page history (linked entries), event lists (every event, past ones too, no carousel), the org lists and groups map (every region and all its groups, linked), the history timeline (every year open, upcoming too), schedules (every day, fold-outs included), people tiles (everyone, with their details) and videos (a link). Heading levels fixed where cards repeated their section's level; org names are linked headings; Team pages lose their doubled "Members"; Giving links the treasurer's email. +- [x] **Local groups map fits a phone**: it scales to the column's width instead of holding 34rem and scrolling sideways. + +## Navigation (branch `accessibility`) +- [x] **No fixed back links on record pages**: a group, region or partner page no longer ends its facts line with "All groups" (and so on), and a team page no longer says "Back to " (its "A team of" link stays); records are reached from many pages, so the browser's back is the right way back. Not-found pages keep their link, having nowhere else to send a visitor. +- [x] **Side nav label on its circle, dark mode**: the lit label was its accent mixed halfway to white, which for the deep teal (Unity Regions) left 4.2:1 on a circle of the same teal. Labels now use `--nav-text-mix` (30% in dark mode): 6.8:1 or better for every accent. + +## Accessibility (branch `accessibility`, merged as PR #25, v1.12.0-accessibility, 2026-10-03; not checked in a browser yet) +- [x] **Plausible analytics**, self-hosted behind nginx at `/pa/`: the API adds its script to every page (`analyticsTag`, `server/src/pageMeta.js`), counting under site.json's url hostname, so dev and live report separately. +- [x] **Accessibility panel:** the switches' knob stays in its track (an absolute child of a ` + + {/* After the button in the page, so Tab goes from it into the + panel; drawn above it. */} {open && (
        - {SETTINGS.map((setting) => { + {SETTINGS.map((setting, i) => { const on = state[setting.key] const labelId = `${panelId}-${setting.attribute}` + const helpId = `${labelId}-help` return (
      • @@ -143,26 +211,35 @@ export default function AccessibilityPanel() { {setting.label} - {setting.help} + + {setting.help} +
      • ) })}
      + +
      )} - -
    ) } diff --git a/src/components/Banner.tsx b/src/components/Banner.tsx index a0be933..e03d1c6 100644 --- a/src/components/Banner.tsx +++ b/src/components/Banner.tsx @@ -25,7 +25,7 @@ export default function Banner() { if (!visible) return null; const linkClass = - "underline underline-offset-4 decoration-[#9cc47c] hover:text-white transition-colors"; + "underline underline-offset-4 decoration-[var(--pal-green-2)] hover:text-white transition-colors"; return (
    !block.present?.hide && block.type !== 'divider') + .map((block) => (block.present?.text ? { ...block, text: block.present.text } : block)) + : blocks.filter((block) => !block.present?.only) + } if (!blocks?.length) return null // Headings get ids so a post's contents (PostContents) and a shared // link (#getting-there) can point at them. - const { idAt } = headingAnchors(blocks) + const { idAt } = headingAnchors(blocks, anchorPrefix) + // The heading level a block's own headings take: under the last + // heading (h3) or subheading (h4) before it, else the section's h2. + let under = 2 + const levels = blocks.map((block) => { + const level = (under + 1) as 3 | 4 | 5 + if (block.type === 'heading') under = 3 + if (block.type === 'subheading') under = 4 + return level + }) + + + // The places mapped here, for a schedule's places to link to: a + // map block's venue's locations (only those its sections show). + const maps = new Set( + blocks.flatMap((block) => + block.type === 'map' && block.venue + ? block.venue.locations.map((location) => mapAnchor(block.venue!.id, location.key)) + : [], + ), + ) return ( +
    {blocks.map((block, index) => ( - + + + ))}
    +
    ) } @@ -109,6 +180,182 @@ function LinkCard({ item }: { item: ContentBlockItem }) { ) } +/* One event card (088): the event's picture, its type and date, + its title (or the item's text) and card text (or the item's + detail); the whole card links to the event. */ +/* An event's type and date, eg. workshop · June 14, 2025 (shown + capitalized), or null with neither. */ +export function eventLine(event: ItemEvent): string | null { + const when = event.date_label || (event.starts_on ? occurrenceLabel(event.starts_on) : null) + const kind = event.event_type && event.event_type !== 'other' ? event.event_type : null + return [kind, when].filter(Boolean).join(' · ') || null +} + +function EventCard({ + item, + accent, + open, + panelId, + onToggle, +}: { + item: ContentBlockItem + accent: string + open: boolean + panelId: string + onToggle: () => void +}) { + const event = item.event! + const img = useSmallImage(mediaUrl(event.image)) + const color = event.color || accent + const line = eventLine(event) + return ( + + ) +} + +/* An event in full (088): its photo, type and date, title, place and + person host, then its own page's blocks (else its card text), and + a link to its page. */ +function EventInFull({ item, accent, level }: { item: ContentBlockItem; accent: string; level: 3 | 4 | 5 }) { + const event = item.event! + const color = event.color || accent + const photo = mediaUrl(event.photo || event.image) + const line = eventLine(event) + const Title = `h${level}` as 'h3' + const blurb = item.detail || event.blurb + return ( +
    + {photo && {event.photo_alt} +
    + {line && ( +

    + {line} +

    + )} + {item.text || event.title} + {(event.location_label || item.person) && ( +

    + {event.location_label && {event.location_label}} + {item.person && ( + + + {item.person.name} + + )} +

    + )} +
    + {event.blocks?.length ? ( + + ) : blurb ? ( +
    + +
    + ) : null} + + {event.title}: the event's page + +
    + ) +} + +/* An events block (088): its events as cards; one opened shows in + full under them, scrolled into view. A featured one (090) is + already open, above the cards, under its own heading and + subheading. Reading mode has them all in full. */ +function EventsBlock({ items, accent, level }: { items: ContentBlockItem[]; accent: string; level: 3 | 4 | 5 }) { + const [open, setOpen] = useState(null) + const panelId = useId() + const panel = useRef(null) + const reading = useReadingMode() + useEffect(() => { + if (open != null) panel.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' }) + }, [open]) + + const featured = reading ? items : items.filter((item) => item.featured) + const cards = reading ? [] : items.filter((item) => !item.featured) + + return ( +
    + {featured.map((item, i) => ( + + ))} + {cards.length > 0 && ( + <> +
      + {cards.map((item, i) => ( +
    • + setOpen(open === i ? null : i)} + /> +
    • + ))} +
    +
    + {open != null && cards[open] && } +
    + + )} +
    + ) +} + +/* A featured event: its heading and subheading, if set, then the + event in full, its title a level under the heading. */ +function FeaturedEvent({ item, accent, level }: { item: ContentBlockItem; accent: string; level: 3 | 4 | 5 }) { + if (!item.heading && !item.subheading) return + const Heading = `h${level}` as 'h3' + const color = item.event?.color || accent + return ( +
    +
    + {item.heading && ( + + {item.heading} + + )} + {item.subheading &&

    {item.subheading}

    } +
    + +
    + ) +} + /* A table block's text as rows of cells: one row per line, cells split by "|" (a literal bar is "\|"), blank lines skipped. A leading and trailing bar, as in Markdown, is allowed. */ @@ -135,28 +382,47 @@ function Caption({ text }: { text?: string | null }) { ) } -// Clear of the fixed header when jumped to. -const ANCHOR_MARGIN = { scrollMarginTop: 'calc(var(--header-h, 5rem) + 1rem)' } - -function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; anchor?: string }) { +function Block({ + block, + accent, + anchor, + level, +}: { + block: ContentBlock + accent: string + anchor?: string + level: 3 | 4 | 5 +}) { const text = block.text ?? '' + const reading = useReadingMode() + // On a screen: links are their text, people and organizations + // just pictures and names (095). + const presenting = usePresenting() + // An image block's dark theme picture (102). + const dark = useDarkTheme() switch (block.type) { + // A blog post's tab marker (BlogPost.tsx splits the post at + // them); anywhere else, it reads as a heading. + case 'tab': case 'heading': return ( -

    - {text} +

    +

    ) case 'subheading': return ( -

    - {text} +

    +

    ) - case 'list': + case 'list': { + // Bold text and a plain detail, unless the block is set Plain + // (092): plain text, gray detail. + const plain = block.list_style === 'plain' return (
      {(block.items ?? []).map((item, index) => ( @@ -164,20 +430,23 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; - - {item.url ? ( - - {item.text} - - ) : ( - - )} - {item.detail && : {item.detail}} + + + {item.url && !presenting ? ( + + {item.text} + + ) : ( + + )} + + {item.detail && : {item.detail}} ))}
    ) + } case 'links': return ( @@ -248,8 +517,9 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; const width = Math.max(...rows.map((row) => row.length)) return ( // Wide tables scroll sideways inside their box on a phone - // rather than squeezing every column to a word. -
    + // rather than squeezing every column to a word. Focusable, so + // the arrow keys scroll it too (Safari won't on its own). +
    @@ -294,8 +564,16 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; ) case 'image': { - const src = mediaUrl(block.media) + const src = mediaUrl((dark && block.media_dark) || block.media) if (!src) return null + // The reader leaves out a picture with no alt, and its link with it. + if (reading && block.href && !block.alt) { + return ( +

    + {text || 'Open link'} +

    + ) + } const img = ( ) return ( -
    +
    {block.href ? {img} : img}
    @@ -320,15 +598,49 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; return (
    - +
    -
    + {!reading && } ) case 'schedule': if (!block.items?.length) return null - return + return ( + + ) + + case 'map': + if (!block.venue) return null + return + + case 'events': { + const events = (block.items ?? []).filter((item) => item.event) + if (events.length === 0) return null + return + } + + case 'organizations': { + // Picked ones in their order, else every listed one of its kind. + const ids = (block.items ?? []).map((item) => item.org_id).filter((id): id is string => Boolean(id)) + if (ids.length === 0 && !block.org_kind) return null + if (presenting) return + return ( + + ) + } case 'people': { const picked = (block.items ?? []) @@ -337,8 +649,8 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; if (!block.team_id && picked.length === 0) return null return (
    - {block.team_id && } - {picked.length > 0 && } + {block.team_id && } + {picked.length > 0 && }
    ) } @@ -349,7 +661,7 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; case 'paragraph': default: if (!text) return null - return block.href ? ( + return block.href && !presenting ? (

    {text} diff --git a/src/components/FeaturedCards.tsx b/src/components/FeaturedCards.tsx index 708052a..23ca4eb 100644 --- a/src/components/FeaturedCards.tsx +++ b/src/components/FeaturedCards.tsx @@ -2,7 +2,8 @@ FEATURED CARDS A grid of cards that point somewhere: the front page's featured - band now, the Community blog's posts next. The data comes from + band, the Community blog's posts, a region's own cards (in the + region list and on its page). The data comes from loadFeaturedCards in server/src/shape.js, already resolved, so this only draws. @@ -23,6 +24,17 @@ fall outside), 4px thick. With three or more cards the first is the large one, two rows tall, and the next two stack beside it, so it no longer stretches its neighbor. + + The front page sets the shape by hand (073): `columns` is how many + across on a wide screen (2, 3 or 4; default 3), and a card's + `size` makes it wide (2 columns), tall (2 rows), large (both) or + normal. A card with no size is automatic, the rule above, so + cards nobody has sized lay out as they always have. Cards stay in + their list order; a shape that leaves a hole leaves it. + + Reading mode (readingMode.ts) gets each card as a linked heading + and its words, a video card linking to its video. `level` is that + heading's level, one under the heading above the cards. ═══════════════════════════════════════════════════════════════ */ @@ -30,12 +42,13 @@ import HomeLink from '../pages/sections/home/HomeLink.tsx' import VideoPlayer from './VideoPlayer.tsx' import { refHref } from '../lib/hrefs.ts' import { mediaUrl } from '../lib/media.ts' -import type { FeaturedCard } from '../lib/useFrontPage.ts' +import type { FeaturedCard, FeaturedColumns, FeaturedSize } from '../lib/sectionTypes.ts' +import { useReadingMode } from '../lib/readingMode.ts' import { useSmallImage } from '../lib/useSmallImage.ts' /* Image kinds that are photographs, drawn edge to edge. Anything else is a logo, drawn whole. */ -const PHOTO_KINDS = new Set(['event-background', 'featured', 'person']) +const PHOTO_KINDS = new Set(['event-photo', 'featured', 'person']) function hrefFor(card: FeaturedCard): string | null { if (card.kind === 'record' && card.ref) { @@ -80,8 +93,32 @@ function VideoPicture({ card }: { card: FeaturedCard }) { const RULE = 'border-brand' -function Card({ card, large }: { card: FeaturedCard; large: boolean }) { +/* Columns across, by setting. Two columns start at sm; three and + four take over at lg. Written out whole so Tailwind sees them. */ +const GRID_COLUMNS: Record = { + 2: 'sm:grid-cols-2', + 3: 'sm:grid-cols-2 lg:grid-cols-3', + 4: 'sm:grid-cols-2 lg:grid-cols-4', +} + +/* A card's spans, from the breakpoint its grid reaches its full + width: sm for a two column grid, lg otherwise. Below that every + card is one cell, so a wide card can't overflow a narrow grid. */ +const SPANS: Record<'sm' | 'lg', Record> = { + sm: { normal: '', wide: 'sm:col-span-2', tall: 'sm:row-span-2', large: 'sm:col-span-2 sm:row-span-2' }, + lg: { normal: '', wide: 'lg:col-span-2', tall: 'lg:row-span-2', large: 'lg:col-span-2 lg:row-span-2' }, +} + +/* A card's size, or for one with none, the automatic rule: the first + of three or more is large. */ +function sizeOf(card: FeaturedCard, index: number, count: number): FeaturedSize { + return card.size ?? (index === 0 && count >= 3 ? 'large' : 'normal') +} + +function Card({ card, size, spans, level }: { card: FeaturedCard; size: FeaturedSize; spans: string; level: 3 | 4 | 5 }) { + const large = size === 'large' const href = hrefFor(card) + const Title = `h${level}` as const const text = (

    @@ -89,7 +126,7 @@ function Card({ card, large }: { card: FeaturedCard; large: boolean }) {

    {card.eyebrow}

    )} {card.title && ( -

    + {href ? ( // Stretched over the whole card, so the picture and the // blurb are part of the click without nesting links. @@ -102,7 +139,7 @@ function Card({ card, large }: { card: FeaturedCard; large: boolean }) { ) : ( card.title )} - </h3> + )} {card.blurb && (

    {card.blurb}

    @@ -112,9 +149,7 @@ function Card({ card, large }: { card: FeaturedCard; large: boolean }) { return (
  • {card.kind === 'video' ? ( // Above the stretched link, which a video card doesn't have @@ -131,18 +166,45 @@ function Card({ card, large }: { card: FeaturedCard; large: boolean }) { ) } -export default function FeaturedCards({ cards }: { cards: FeaturedCard[] }) { - const leadLarge = cards.length >= 3 +type FeaturedCardsProps = { cards: FeaturedCard[]; level?: 3 | 4 | 5; columns?: FeaturedColumns } + +function ReadingCards({ cards, level = 3 }: FeaturedCardsProps) { + const Title = `h${level}` as const + return ( + <> + {cards.map((card, index) => { + const href = card.kind === 'video' ? card.url : hrefFor(card) + return ( +
    + {card.eyebrow &&

    {card.eyebrow}

    } + {card.title && {href ? <HomeLink url={href}>{card.title}</HomeLink> : card.title}} + {card.blurb &&

    {card.blurb}

    } +
    + ) + })} + + ) +} + +export default function FeaturedCards({ cards, level = 3, columns = 3 }: FeaturedCardsProps) { + const reading = useReadingMode() + if (reading) return + const spans = SPANS[columns === 2 ? 'sm' : 'lg'] return (
    -
      - {cards.map((card, index) => ( - - ))} +
        + {cards.map((card, index) => { + const size = sizeOf(card, index, cards.length) + return ( + + ) + })}
    ) diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx index c252e21..f3dda88 100644 --- a/src/components/Footer.tsx +++ b/src/components/Footer.tsx @@ -1,74 +1,60 @@ import { Link } from "react-router-dom"; -import { PAGE_LINKS, NAV_ACTIONS } from "../navConfig.ts"; import { useNavSections } from "../lib/navSections.ts"; +import { useSiteNav } from "../lib/useSiteNav.ts"; +import { useAuth } from "../lib/auth.tsx"; +import { VERSION_NAME, VERSION_NUMBER } from "../lib/version.ts"; +import SiteLink from "./SiteLink.tsx"; import siteLogo from "../assets/logos/NGU_Logo.svg"; import PlatformIcon from "./PlatformIcon.tsx"; import { ORGANIZATION_DETAILS as Organization_Details } from "../data/organizationDetails.ts"; +import { SOCIAL_LINKS } from "../data/socialLinks.ts"; -const Social_Links = [ - { label: "Instagram", href: "https://www.instagram.com/nextgenerationunity/", platform: "instagram" }, - { label: "Facebook", href: "https://www.facebook.com/NextGenerationofUnity", platform: "facebook" }, - { label: "Discord", href: "https://discord.com/invite/AtngzpqaX5", platform: "discord" }, -]; - -// Give's destination lives in navConfig so the footer and the nav can't drift. -// Only the label differs down here. -const giveAction = NAV_ACTIONS.find((a) => a.variant === "fancy"); - -/* An internal route, or an off-site address opened in a new tab. */ -type TouchLink = { label: string } & ( - | { external?: false; to: string } - | { external: true; href: string } -); - -const Get_In_Touch: TouchLink[] = [ - { label: "Feedback", to: "/feedback"}, - { label: "Request", to: "/request" }, - { label: "Contact Us", to: "/organization#contact" }, -]; - -const Footer_Links = [ - { label: "Privacy Policy", to: "/privacy" }, - { label: "Terms of Service", to: "/terms" }, -]; +/* Every link here is Pages → Navigation's (useSiteNav): the filled + header buttons (Give) beside the logo, Get in Touch, the site map + (the header's pages, their sections and the pages set under them) + and the bottom row. The bottom row ends with the profile account's + way in (076): Sign in, or Your profile once signed in. */ const footerLinkClass = - "text-white/65 hover:text-[#9cc47c] text-sm transition-colors"; + "text-white/65 hover:text-[var(--pal-green-2)] text-sm transition-colors"; // inline-block with a little height of its own, so a finger can hit it. const pageLinkClass = - "inline-block py-1 text-white/80 hover:text-[#9cc47c] text-sm font-semibold transition-colors"; + "inline-block py-1 text-white/80 hover:text-[var(--pal-green-2)] text-sm font-semibold transition-colors"; const sectionLinkClass = - "inline-block py-1 text-white/65 hover:text-[#9cc47c] text-sm transition-colors"; + "inline-block py-1 text-white/65 hover:text-[var(--pal-green-2)] text-sm transition-colors"; const headingClass = "text-white/90 text-sm font-semibold mb-4"; export default function Footer() { const sectionsOf = useNavSections(); + const nav = useSiteNav(); + const { user } = useAuth(); return (
    - {/* Brand and details on top, the site map across the full - width below them. */} + {/* Brand and details, beside the socials and contact links; + the site map spans the full width below them all. */}
    {/* The logo, and Give beside it. */}
    Next Generation of Unity - {giveAction && ( - - {giveAction.label} - - )} + {nav.actions + .filter((action) => action.filled) + .map((action) => ( + + {action.label} + + ))}
    @@ -82,44 +68,13 @@ export default function Footer() { {Organization_Details.nonprofit} Tax ID: {Organization_Details.taxId}.

    - {/* Site map: mirrors both nav tiers */} -
    {/* Socials + get in touch */}
    - {Social_Links.map(({ label, href, platform }) => ( + {SOCIAL_LINKS.map(({ label, href, platform }) => ( Get in Touch
  • + {/* Site map: every page and its sections, across the full width. */} + +
    -

    © 2026 Next Generation of Unity. All rights reserved.

    -
    - {Footer_Links.map((link) => ( - +
    +

    © 2026 Next Generation of Unity. All rights reserved.

    +

    + {VERSION_NUMBER} + {VERSION_NAME && <> · {VERSION_NAME}} +

    +
    +
    + {nav.legal.map((link) => ( + {link.label} - + ))} + + {user ? "Your profile" : "Sign in"} +
    diff --git a/src/components/GoogleLogo.tsx b/src/components/GoogleLogo.tsx new file mode 100644 index 0000000..5d59139 --- /dev/null +++ b/src/components/GoogleLogo.tsx @@ -0,0 +1,12 @@ +/* Google's "G", for the Sign in with Google buttons: a brand mark, + so drawn as Google gives it rather than as a Phosphor icon. */ +export default function GoogleLogo({ className = 'h-5 w-5' }: { className?: string }) { + return ( + + ) +} diff --git a/src/components/InlineText.tsx b/src/components/InlineText.tsx index 381abf7..0c7f4f7 100644 --- a/src/components/InlineText.tsx +++ b/src/components/InlineText.tsx @@ -4,7 +4,7 @@ The little formatting a content block's text may carry, typed in the admin as plain characters: - **bold** *italic* [link text](url) + **bold** *italic* [link text](url) {Next|Now} (rotating words) a line break keeps its place a blank line starts a new paragraph @@ -21,8 +21,10 @@ import { Fragment, type CSSProperties, type ReactNode } from 'react' import { Link } from 'react-router-dom' import { accentText } from '../lib/color.ts' +import { RotatingWords } from './RotatingWords.tsx' +import { usePresenting } from '../lib/presenting.ts' -const TOKEN = /\*\*(.+?)\*\*|\*(.+?)\*|\[([^\]]+)\]\(([^)\s]+)\)/g +const TOKEN = /\*\*(.+?)\*\*|\*(.+?)\*|\[([^\]]+)\]\(([^)\s]+)\)|\{([^{}|\n]+(?:\|[^{}|\n]+)+)\}/g const SAFE_URL = /^(\/(?!\/)|#|https?:\/\/|mailto:|tel:)/i /** External if it has a scheme or starts with //; otherwise it's @@ -76,17 +78,20 @@ export function Anchor({ ) } -function line(text: string, accent: string, key: string): ReactNode[] { +/* `plain`: a link's text alone, presented (095). */ +function line(text: string, accent: string, key: string, plain = false): ReactNode[] { const out: ReactNode[] = [] let last = 0 let n = 0 for (const match of text.matchAll(TOKEN)) { const at = match.index ?? 0 if (at > last) out.push(text.slice(last, at)) - const [whole, bold, italic, label, url] = match + const [whole, bold, italic, label, url, words] = match const k = `${key}-${n++}` - if (bold != null) out.push({bold}) + if (words != null) out.push( word.trim())} />) + else if (bold != null) out.push({bold}) else if (italic != null) out.push({italic}) + else if (label != null && plain) out.push(label) else if (label != null && SAFE_URL.test(url)) { out.push( @@ -102,13 +107,14 @@ function line(text: string, accent: string, key: string): ReactNode[] { /** Text inside another element: formatting and line breaks. */ export function Inline({ text, accent }: { text?: string | null; accent: string }) { + const plain = usePresenting() const lines = (text ?? '').split('\n') return ( <> {lines.map((part, i) => ( {i > 0 &&
    } - {line(part, accent, `l${i}`)} + {line(part, accent, `l${i}`, plain)}
    ))} diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx index e5b42a6..0bf5727 100644 --- a/src/components/Layout.tsx +++ b/src/components/Layout.tsx @@ -1,36 +1,36 @@ -import { X, List } from "@phosphor-icons/react"; -import { Suspense, useState, useEffect, useRef } from "react"; +import { X, List, EyeSlash, PencilSimple } from "@phosphor-icons/react"; +import { lazy, Suspense, useState, useEffect, useRef } from "react"; import { NavLink, Link, Outlet, useLocation } from "react-router-dom"; -import { PAGE_LINKS, NAV_ACTIONS } from "../navConfig.ts"; +import type { NavLink as NavLinkItem } from "../navConfig.ts"; import { useNavSections } from "../lib/navSections.ts"; +import { useSiteNav } from "../lib/useSiteNav.ts"; +import SiteLink from "./SiteLink.tsx"; import Banner from "./Banner.tsx"; import siteLogo from "../assets/logos/NGU_Logo.svg"; import Footer from "./Footer.tsx"; import PrivacyNotice from "./PrivacyNotice.tsx"; import PageBackdrop from "./PageBackdrop.tsx"; import AccessibilityPanel from "./AccessibilityPanel.tsx"; +import ReaderView from "./ReaderView.tsx"; import ThemeToggle from "./ThemeToggle.tsx"; -import { scrollBehavior } from "../lib/motion.ts"; +import { jumpTo } from "../lib/focus.ts"; +import { useReadingMode } from "../lib/readingMode.ts"; +import { draftPreview, stopPreview } from "../lib/api.ts"; + +const NotFound = lazy(() => import("../pages/NotFound.tsx")); /* ── Right-side nav actions ──────────────────────────────── */ -type NavActionItem = { - label: string; - to: string; - variant: string; - external?: boolean; -}; - const ACTION_VARIANTS: Record< string, { className: string; style: React.CSSProperties } > = { - ghost: { + outline: { className: "font-semibold border border-white/30 text-white/85 hover:border-white/60 hover:text-white hover:bg-white/10", style: {}, }, - fancy: { + filled: { className: "font-bold text-white hover:scale-105", style: { background: "var(--color-action)" }, }, @@ -46,33 +46,20 @@ function NavAction({ size = "desktop", onClick, }: { - item: NavActionItem; + item: NavLinkItem; size?: keyof typeof ACTION_SIZES; onClick?: () => void; }) { - const v = ACTION_VARIANTS[item.variant] ?? ACTION_VARIANTS.ghost; + const v = ACTION_VARIANTS[item.filled ? "filled" : "outline"]; const className = `inline-block whitespace-nowrap btn transition-all duration-200 active:scale-[0.98] ${ACTION_SIZES[size]} ${v.className}`; - return item.external ? ( - + return ( + {item.label} - - ) : ( - - {item.label} - + ); } -const navActions = NAV_ACTIONS as NavActionItem[]; - /* ── Layout ──────────────────────────────────────────────── */ export default function Layout() { @@ -82,9 +69,42 @@ export default function Layout() { const [headerHeight, setHeaderHeight] = useState(72); const headerRef = useRef(null); const closeMenuRef = useRef(null); + const openMenuRef = useRef(null); + // The desktop dropdown Escape has shut, until the pointer or focus + // leaves it (hover and focus would otherwise hold it open). + const [dismissed, setDismissed] = useState(null); const location = useLocation(); + const lastPath = useRef(location.pathname); + const reading = useReadingMode(); + // The page itself, drawn hidden for the reader view to read. + const pageRef = useRef(null); const sectionsOf = useNavSections(); + const nav = useSiteNav(); + // A hidden page (Pages → Navigation) is Not found below viewer; a + // viewer and up sees it, under a bar saying so. The server answers + // the same (server/src/siteNav.js); this covers the app's own moves. + const hiddenHere = nav.isHidden(location.pathname); + const page = ( + {hiddenHere && !nav.seesHidden ? : } + ); + // A draft's preview tab (api.ts): the page as it would be with the + // draft published, for signed-in admin accounts. + const previewBar = draftPreview && ( +

    +

    + ); + const hiddenBar = hiddenHere && nav.seesHidden && ( +

    +

    + ); // Close the mobile menu whenever the route changes useEffect(() => { @@ -98,7 +118,13 @@ export default function Layout() { closeMenuRef.current?.focus(); const onKey = (e: KeyboardEvent) => e.key === "Escape" && setMobileMenuOpen(false); window.addEventListener("keydown", onKey); - return () => window.removeEventListener("keydown", onKey); + return () => { + window.removeEventListener("keydown", onKey); + // Closed with Escape or Close, focus fell to the page with the + // menu: give it back to the menu button. A link that changed + // the page has already sent it to the new page (below). + if (document.activeElement === document.body) openMenuRef.current?.focus(); + }; }, [mobileMenuOpen]); // The header grows and shrinks: the banner can be dismissed, and @@ -113,35 +139,68 @@ export default function Layout() { ); ro.observe(el); return () => ro.disconnect(); - }, []); + }, [reading]); + + // On the root, so anything can read it: index.css keeps focused + // and jumped-to things clear of the header with it + // (scroll-padding-top), and PostContents offsets by it. + useEffect(() => { + const root = document.documentElement; + // Reading mode has no header to stay clear of. + root.style.setProperty("--header-h", `${reading ? 0 : headerHeight}px`); + // The admin has no fixed header: nothing to stay clear of there. + return () => { + root.style.removeProperty("--header-h"); + }; + }, [headerHeight, reading]); // Router does not scroll on navigation. Go to top on a new page, // or to the anchor if the URL carries one (handles deep links too). + // A new page also takes focus to its content, as a page load would, + // so a screen reader starts there and Tab doesn't begin from a + // link that may be gone. useEffect(() => { - if (location.hash) { - const el = document.querySelector(location.hash); - if (el) { - el.scrollIntoView({ behavior: scrollBehavior() }); - return; - } - } + const newPage = lastPath.current !== location.pathname; + lastPath.current = location.pathname; + if (location.hash && jumpTo(decodeURIComponent(location.hash.slice(1)))) return; window.scrollTo({ top: 0 }); + if (newPage) document.getElementById("main")?.focus({ preventScroll: true }); }, [location.pathname, location.hash, location.key]); + const skipLink = ( + + Skip to content + + ); + + // Reading mode: the page as plain text (ReaderView.tsx), with no + // header, backdrop, footer or notices; the panel stays, to turn it + // off. The page itself still renders, hidden, for the reader to + // read, so every page works without a version of its own. + if (reading) { + return ( +
    + {skipLink} +
    + + +
    + +
    + ); + } + return ( // overflow-x-clip, not -hidden: hidden makes this div a scroll // container, and then nothing inside it can be position: sticky // (a blog post's contents column scrolled away with the page). -
    - - Skip to content - +
    + {skipLink} {/* ── NAV ─────────────────────────────────────────────── */}
    @@ -166,43 +225,77 @@ export default function Layout() { {/* Each page, and under it on hover or keyboard focus its sections (navSections.ts): the sections live in these - dropdowns rather than a strip of their own. */} + dropdowns rather than a strip of their own. Home has + none: it's the logo's link too, and its bands are one + scroll away. */}
    - {PAGE_LINKS.map((page) => { - const pageSections = sectionsOf(page.path); + {nav.main.map((page) => { + const pageSections = page.path === "/" ? [] : sectionsOf(page.path); + const hasMenu = pageSections.length > 0 || page.children.length > 0; return ( -
    +
    { + if (e.key !== "Escape" || !hasMenu) return; + setDismissed(page.path); + e.currentTarget.querySelector("a")?.focus(); + }} + onMouseLeave={() => setDismissed(null)} + onBlur={(e) => { + if (!e.currentTarget.contains(e.relatedTarget as Node)) setDismissed(null); + }} + > `block text-base font-bold pb-1 border-b-2 transition-colors duration-200 ${ isActive - ? "text-white border-[#9cc47c]" + ? "text-white border-[var(--pal-green-2)]" : "text-white/75 hover:text-white border-transparent" }` } > {page.label} - {pageSections.length > 0 && ( + {hasMenu && ( // pt-3 is the bridge the pointer crosses from the - // link into the menu without it closing. -
    + // link into the menu without it closing. Keyboard + // focus opens it too, but only keyboard focus + // (:focus-visible): a click leaves focus on the + // link, which held the menu open after the + // pointer had gone. +
      {pageSections.map((section) => (
    • {section.label}
    • ))} + {/* Pages set under this one (Pages → Navigation), after its sections. */} + {page.children.map((child) => ( +
    • + + {child.label} + +
    • + ))}
    )} @@ -214,14 +307,15 @@ export default function Layout() {
    - {navActions.map((item) => ( - + {nav.actions.map((item) => ( + ))}
    + ) + })} +
    + )} + {groups.map((group, g) => ( +
    + {group.name &&

    {group.name}

    } +
      + {group.locations.map((location) => { + const on = active === location.key + const row = ( + <> + + + + {location.name} + + {location.detail && {location.detail}} + + + ) + const rowClass = 'flex items-start gap-3 px-2 py-1.5 text-body' + const rowStyle = on ? { background: withAlpha(accent, 12) } : undefined + return ( +
    1. + {isMarked(location) ? ( + + {row} + + ) : ( +
      {row}
      + )} + +
    2. + ) + })} +
    +
    + ))} + + + ) +} + +/* A zoom button over the map picture. */ +function ZoomButton({ + label, + disabled, + onClick, + children, +}: { + label: string + disabled?: boolean + onClick: () => void + children: ReactNode +}) { + return ( + + ) +} + +/* A location's Google and Apple Maps links (091), as buttons that + open them in a new tab. */ +function MapLinks({ location, accent }: { location: VenueLocation; accent: string }) { + const links = [ + { href: location.google_maps_url, label: 'Google Maps', Icon: GoogleLogo }, + { href: location.apple_maps_url, label: 'Apple Maps', Icon: AppleLogo }, + ].filter((link) => link.href) + if (links.length === 0) return null + return ( + + {links.map(({ href, label, Icon }) => ( +
    + + ))} + + ) +} diff --git a/src/components/OptionFilter.tsx b/src/components/OptionFilter.tsx new file mode 100644 index 0000000..d052182 --- /dev/null +++ b/src/components/OptionFilter.tsx @@ -0,0 +1,53 @@ +/* ═══════════════════════════════════════════════════════════════ + OPTION FILTER + + A select over hundreds of records (every person, every event) + only matches first letters as you type, so finding one means + scrolling. Past FILTER_FROM options, a small box above it narrows + the list to the options whose label holds what's typed: + + const [needle, setNeedle] = useState('') + const shown = narrow(list, needle, ([, label]) => label, ([id]) => id === value) + {list.length > FILTER_FROM && } + + `keep` holds an option in whatever the box says (the one chosen), + so narrowing never blanks the select's value. + ═══════════════════════════════════════════════════════════════ */ + +import { MagnifyingGlass } from '@phosphor-icons/react' + +export const FILTER_FROM = 50 + +export function narrow(items: T[], needle: string, text: (item: T) => string, keep?: (item: T) => boolean): T[] { + const term = needle.trim().toLowerCase() + if (!term) return items + return items.filter((item) => keep?.(item) || String(text(item) ?? '').toLowerCase().includes(term)) +} + +type OptionFilterProps = { + value: string + onChange: (value: string) => void + label: string + className?: string +} + +export function OptionFilter({ value, onChange, label, className = 'mb-1.5' }: OptionFilterProps) { + return ( +
    +
    + ) +} diff --git a/src/components/OrgContact.tsx b/src/components/OrgContact.tsx index 3df7ebb..54f9189 100644 --- a/src/components/OrgContact.tsx +++ b/src/components/OrgContact.tsx @@ -5,15 +5,24 @@ filled in its accent, then its website, email and socials outlined. Nothing at all when it has none. Used on an organization's page and on the Organization page (NGU's own). + A platform's icon has its name beside it for screen readers and + reading mode, unless the label already says it (PlatformName). ═══════════════════════════════════════════════════════════════ */ import PlatformIcon from './PlatformIcon.tsx' import type { OrganizationRecord } from '../lib/useContent.ts' import { accentText } from '../lib/color.ts' +import { PLATFORMS } from '../lib/platforms.ts' + +function PlatformName({ platform, label }: { platform?: string | null; label?: string | null }) { + const name = PLATFORMS.find((p) => p.id === platform)?.label + if (!name || label?.toLowerCase().includes(name.toLowerCase())) return null + return {label ? `${name}: ` : name} +} export default function OrgContact({ org, accent }: { org: OrganizationRecord; accent: string }) { const hasAny = - org.links.length > 0 || org.socials.length > 0 || org.website || org.email + org.links.length > 0 || org.socials.length > 0 || org.websites.length > 0 || org.emails.length > 0 if (!hasAny) return null @@ -29,31 +38,32 @@ export default function OrgContact({ org, accent }: { org: OrganizationRecord; a style={{ background: accent }} > + {link.label} ))} - {/* website and email arrive as bare strings (splitLinks in - shape.js); socials are whole link rows. */} + {/* Every website and email row, each its own button with its + own label; an email's url is the bare address (splitLinks + in shape.js). */} {[ - org.website ? { url: org.website, label: 'Website', platform: null } : null, - org.email ? { url: `mailto:${org.email}`, label: org.email, platform: null } : null, + ...org.websites, + ...org.emails.map((link) => ({ ...link, url: `mailto:${link.url}` })), ...org.socials, - ] - .filter((link): link is NonNullable => Boolean(link)) - .map((link) => ( - - - {link.label} - - ))} + ].map((link) => ( + + + + {link.label} + + ))}
    ) } diff --git a/src/components/OrgLogo.tsx b/src/components/OrgLogo.tsx index 714dd2e..1632662 100644 --- a/src/components/OrgLogo.tsx +++ b/src/components/OrgLogo.tsx @@ -16,10 +16,13 @@ export default function OrgLogo({ org, color, size = 'h-14 w-14', + fallbackSize = size, }: { org: { logo?: string | null; name: string } color: string size?: string + /** The initials square's size, when the logo's box isn't square. */ + fallbackSize?: string }) { return (