From a797e1a87baf493661724ee473df925a0bbba844 Mon Sep 17 00:00:00 2001 From: Dara Adedeji <76637177+SunkenInTime@users.noreply.github.com> Date: Tue, 25 Aug 2026 00:33:08 -0400 Subject: [PATCH] Remove obsolete bundled agent skills - Delete redundant Convex and UI skill packages from the repository --- .../skills/convex-create-component/SKILL.md | 411 -- .../agents/openai.yaml | 10 - .../convex-create-component/assets/icon.svg | 3 - .../references/hybrid-components.md | 37 - .../references/local-components.md | 38 - .../references/packaged-components.md | 51 - .../skills/convex-migration-helper/SKILL.md | 524 -- .../agents/openai.yaml | 10 - .../convex-migration-helper/assets/icon.svg | 3 - .../skills/convex-performance-audit/SKILL.md | 143 - .../agents/openai.yaml | 10 - .../convex-performance-audit/assets/icon.svg | 3 - .../references/function-budget.md | 232 - .../references/hot-path-rules.md | 359 -- .../references/occ-conflicts.md | 126 - .../references/subscription-cost.md | 252 - .agent/skills/convex-quickstart/SKILL.md | 337 -- .../convex-quickstart/agents/openai.yaml | 10 - .../skills/convex-quickstart/assets/icon.svg | 4 - .agent/skills/convex-setup-auth/SKILL.md | 113 - .../convex-setup-auth/agents/openai.yaml | 10 - .../skills/convex-setup-auth/assets/icon.svg | 3 - .../convex-setup-auth/references/auth0.md | 116 - .../convex-setup-auth/references/clerk.md | 113 - .../references/convex-auth.md | 143 - .../references/workos-authkit.md | 114 - .../skills/convex-create-component/SKILL.md | 322 -- .../agents/openai.yaml | 14 - .../references/advanced-patterns.md | 140 - .../references/hybrid-components.md | 38 - .../references/local-components.md | 39 - .../references/packaged-components.md | 54 - .../skills/convex-migration-helper/SKILL.md | 178 - .../agents/openai.yaml | 13 - .../references/migration-patterns.md | 243 - .../references/migrations-component.md | 219 - .../skills/convex-performance-audit/SKILL.md | 185 - .../agents/openai.yaml | 14 - .../references/function-budget.md | 254 - .../references/hot-path-rules.md | 411 -- .../references/occ-conflicts.md | 137 - .../references/subscription-cost.md | 300 - .agents/skills/convex-quickstart/SKILL.md | 451 -- .../convex-quickstart/agents/openai.yaml | 14 - .agents/skills/convex-setup-auth/SKILL.md | 187 - .../convex-setup-auth/agents/openai.yaml | 14 - .../convex-setup-auth/references/auth0.md | 156 - .../convex-setup-auth/references/clerk.md | 141 - .../references/convex-auth.md | 188 - .../references/workos-authkit.md | 147 - .agents/skills/convex/SKILL.md | 53 - .agents/skills/impeccable/SKILL.md | 176 - .agents/skills/impeccable/agents/openai.yaml | 4 - .agents/skills/impeccable/reference/adapt.md | 190 - .../skills/impeccable/reference/animate.md | 175 - .agents/skills/impeccable/reference/audit.md | 133 - .agents/skills/impeccable/reference/bolder.md | 113 - .agents/skills/impeccable/reference/brand.md | 114 - .../skills/impeccable/reference/clarify.md | 174 - .../impeccable/reference/cognitive-load.md | 106 - .../reference/color-and-contrast.md | 105 - .../skills/impeccable/reference/colorize.md | 154 - .agents/skills/impeccable/reference/craft.md | 193 - .../skills/impeccable/reference/critique.md | 213 - .../skills/impeccable/reference/delight.md | 302 - .../skills/impeccable/reference/distill.md | 111 - .../skills/impeccable/reference/document.md | 427 -- .../skills/impeccable/reference/extract.md | 69 - .agents/skills/impeccable/reference/harden.md | 347 -- .../reference/heuristics-scoring.md | 234 - .../reference/interaction-design.md | 195 - .agents/skills/impeccable/reference/layout.md | 141 - .agents/skills/impeccable/reference/live.md | 622 --- .../impeccable/reference/motion-design.md | 109 - .../skills/impeccable/reference/onboard.md | 234 - .../skills/impeccable/reference/optimize.md | 258 - .../skills/impeccable/reference/overdrive.md | 130 - .../skills/impeccable/reference/personas.md | 179 - .agents/skills/impeccable/reference/polish.md | 233 - .../skills/impeccable/reference/product.md | 62 - .../skills/impeccable/reference/quieter.md | 99 - .../impeccable/reference/responsive-design.md | 114 - .agents/skills/impeccable/reference/shape.md | 151 - .../impeccable/reference/spatial-design.md | 100 - .agents/skills/impeccable/reference/teach.md | 156 - .../skills/impeccable/reference/typeset.md | 124 - .../skills/impeccable/reference/typography.md | 159 - .../skills/impeccable/reference/ux-writing.md | 107 - .../impeccable/scripts/cleanup-deprecated.mjs | 284 - .../impeccable/scripts/command-metadata.json | 94 - .../impeccable/scripts/design-parser.mjs | 820 --- .../skills/impeccable/scripts/detect-csp.mjs | 198 - .../impeccable/scripts/impeccable-paths.mjs | 105 - .../impeccable/scripts/is-generated.mjs | 69 - .../skills/impeccable/scripts/live-accept.mjs | 595 -- .../scripts/live-browser-session.js | 123 - .../skills/impeccable/scripts/live-browser.js | 4860 ----------------- .../impeccable/scripts/live-complete.mjs | 75 - .../impeccable/scripts/live-completion.mjs | 18 - .../skills/impeccable/scripts/live-inject.mjs | 446 -- .../skills/impeccable/scripts/live-poll.mjs | 200 - .../skills/impeccable/scripts/live-resume.mjs | 48 - .../skills/impeccable/scripts/live-server.mjs | 836 --- .../impeccable/scripts/live-session-store.mjs | 254 - .../skills/impeccable/scripts/live-status.mjs | 47 - .../skills/impeccable/scripts/live-wrap.mjs | 632 --- .agents/skills/impeccable/scripts/live.mjs | 247 - .../impeccable/scripts/load-context.mjs | 141 - .../scripts/modern-screenshot.umd.js | 14 - .agents/skills/impeccable/scripts/pin.mjs | 214 - .claude/skills/convex | 1 - .claude/skills/convex-create-component | 1 - .claude/skills/convex-migration-helper | 1 - .claude/skills/convex-performance-audit | 1 - .claude/skills/convex-quickstart | 1 - .claude/skills/convex-setup-auth | 1 - .cursor/rules/code-gen-rules.mdc | 13 - .../use-bun-instead-of-node-vite-npm-pnpm.mdc | 111 - .cursor/skills/frontend-design/LICENSE.txt | 177 - .cursor/skills/frontend-design/SKILL.md | 42 - .windsurf/skills/convex | 1 - .windsurf/skills/convex-create-component | 1 - .windsurf/skills/convex-migration-helper | 1 - .windsurf/skills/convex-performance-audit | 1 - .windsurf/skills/convex-quickstart | 1 - .windsurf/skills/convex-setup-auth | 1 - AGENTS.md | 11 +- CLAUDE.md | 7 - CONTEXT.md | 69 + convex/_generated/ai/ai-files.state.json | 14 - convex/_generated/ai/guidelines.md | 365 -- .../convex_sync_refactor_plan.md | 16 +- ...server_side_sync_boundaries_blueprint.html | 929 ++++ .../server_side_sync_boundaries_delivery.md | 115 + .../server_side_sync_boundaries_handoff.md | 431 ++ skills-lock.json | 47 - skills/convex-create-component/SKILL.md | 322 -- .../agents/openai.yaml | 14 - .../references/advanced-patterns.md | 140 - .../references/hybrid-components.md | 38 - .../references/local-components.md | 39 - .../references/packaged-components.md | 54 - skills/convex-migration-helper/SKILL.md | 178 - .../agents/openai.yaml | 13 - .../references/migration-patterns.md | 243 - .../references/migrations-component.md | 219 - skills/convex-performance-audit/SKILL.md | 185 - .../agents/openai.yaml | 14 - .../references/function-budget.md | 254 - .../references/hot-path-rules.md | 411 -- .../references/occ-conflicts.md | 137 - .../references/subscription-cost.md | 300 - skills/convex-quickstart/SKILL.md | 451 -- skills/convex-quickstart/agents/openai.yaml | 14 - skills/convex-setup-auth/SKILL.md | 187 - skills/convex-setup-auth/agents/openai.yaml | 14 - skills/convex-setup-auth/references/auth0.md | 156 - skills/convex-setup-auth/references/clerk.md | 141 - .../references/convex-auth.md | 188 - .../references/workos-authkit.md | 147 - skills/convex/SKILL.md | 53 - 161 files changed, 1557 insertions(+), 28634 deletions(-) delete mode 100644 .agent/skills/convex-create-component/SKILL.md delete mode 100644 .agent/skills/convex-create-component/agents/openai.yaml delete mode 100644 .agent/skills/convex-create-component/assets/icon.svg delete mode 100644 .agent/skills/convex-create-component/references/hybrid-components.md delete mode 100644 .agent/skills/convex-create-component/references/local-components.md delete mode 100644 .agent/skills/convex-create-component/references/packaged-components.md delete mode 100644 .agent/skills/convex-migration-helper/SKILL.md delete mode 100644 .agent/skills/convex-migration-helper/agents/openai.yaml delete mode 100644 .agent/skills/convex-migration-helper/assets/icon.svg delete mode 100644 .agent/skills/convex-performance-audit/SKILL.md delete mode 100644 .agent/skills/convex-performance-audit/agents/openai.yaml delete mode 100644 .agent/skills/convex-performance-audit/assets/icon.svg delete mode 100644 .agent/skills/convex-performance-audit/references/function-budget.md delete mode 100644 .agent/skills/convex-performance-audit/references/hot-path-rules.md delete mode 100644 .agent/skills/convex-performance-audit/references/occ-conflicts.md delete mode 100644 .agent/skills/convex-performance-audit/references/subscription-cost.md delete mode 100644 .agent/skills/convex-quickstart/SKILL.md delete mode 100644 .agent/skills/convex-quickstart/agents/openai.yaml delete mode 100644 .agent/skills/convex-quickstart/assets/icon.svg delete mode 100644 .agent/skills/convex-setup-auth/SKILL.md delete mode 100644 .agent/skills/convex-setup-auth/agents/openai.yaml delete mode 100644 .agent/skills/convex-setup-auth/assets/icon.svg delete mode 100644 .agent/skills/convex-setup-auth/references/auth0.md delete mode 100644 .agent/skills/convex-setup-auth/references/clerk.md delete mode 100644 .agent/skills/convex-setup-auth/references/convex-auth.md delete mode 100644 .agent/skills/convex-setup-auth/references/workos-authkit.md delete mode 100644 .agents/skills/convex-create-component/SKILL.md delete mode 100644 .agents/skills/convex-create-component/agents/openai.yaml delete mode 100644 .agents/skills/convex-create-component/references/advanced-patterns.md delete mode 100644 .agents/skills/convex-create-component/references/hybrid-components.md delete mode 100644 .agents/skills/convex-create-component/references/local-components.md delete mode 100644 .agents/skills/convex-create-component/references/packaged-components.md delete mode 100644 .agents/skills/convex-migration-helper/SKILL.md delete mode 100644 .agents/skills/convex-migration-helper/agents/openai.yaml delete mode 100644 .agents/skills/convex-migration-helper/references/migration-patterns.md delete mode 100644 .agents/skills/convex-migration-helper/references/migrations-component.md delete mode 100644 .agents/skills/convex-performance-audit/SKILL.md delete mode 100644 .agents/skills/convex-performance-audit/agents/openai.yaml delete mode 100644 .agents/skills/convex-performance-audit/references/function-budget.md delete mode 100644 .agents/skills/convex-performance-audit/references/hot-path-rules.md delete mode 100644 .agents/skills/convex-performance-audit/references/occ-conflicts.md delete mode 100644 .agents/skills/convex-performance-audit/references/subscription-cost.md delete mode 100644 .agents/skills/convex-quickstart/SKILL.md delete mode 100644 .agents/skills/convex-quickstart/agents/openai.yaml delete mode 100644 .agents/skills/convex-setup-auth/SKILL.md delete mode 100644 .agents/skills/convex-setup-auth/agents/openai.yaml delete mode 100644 .agents/skills/convex-setup-auth/references/auth0.md delete mode 100644 .agents/skills/convex-setup-auth/references/clerk.md delete mode 100644 .agents/skills/convex-setup-auth/references/convex-auth.md delete mode 100644 .agents/skills/convex-setup-auth/references/workos-authkit.md delete mode 100644 .agents/skills/convex/SKILL.md delete mode 100644 .agents/skills/impeccable/SKILL.md delete mode 100644 .agents/skills/impeccable/agents/openai.yaml delete mode 100644 .agents/skills/impeccable/reference/adapt.md delete mode 100644 .agents/skills/impeccable/reference/animate.md delete mode 100644 .agents/skills/impeccable/reference/audit.md delete mode 100644 .agents/skills/impeccable/reference/bolder.md delete mode 100644 .agents/skills/impeccable/reference/brand.md delete mode 100644 .agents/skills/impeccable/reference/clarify.md delete mode 100644 .agents/skills/impeccable/reference/cognitive-load.md delete mode 100644 .agents/skills/impeccable/reference/color-and-contrast.md delete mode 100644 .agents/skills/impeccable/reference/colorize.md delete mode 100644 .agents/skills/impeccable/reference/craft.md delete mode 100644 .agents/skills/impeccable/reference/critique.md delete mode 100644 .agents/skills/impeccable/reference/delight.md delete mode 100644 .agents/skills/impeccable/reference/distill.md delete mode 100644 .agents/skills/impeccable/reference/document.md delete mode 100644 .agents/skills/impeccable/reference/extract.md delete mode 100644 .agents/skills/impeccable/reference/harden.md delete mode 100644 .agents/skills/impeccable/reference/heuristics-scoring.md delete mode 100644 .agents/skills/impeccable/reference/interaction-design.md delete mode 100644 .agents/skills/impeccable/reference/layout.md delete mode 100644 .agents/skills/impeccable/reference/live.md delete mode 100644 .agents/skills/impeccable/reference/motion-design.md delete mode 100644 .agents/skills/impeccable/reference/onboard.md delete mode 100644 .agents/skills/impeccable/reference/optimize.md delete mode 100644 .agents/skills/impeccable/reference/overdrive.md delete mode 100644 .agents/skills/impeccable/reference/personas.md delete mode 100644 .agents/skills/impeccable/reference/polish.md delete mode 100644 .agents/skills/impeccable/reference/product.md delete mode 100644 .agents/skills/impeccable/reference/quieter.md delete mode 100644 .agents/skills/impeccable/reference/responsive-design.md delete mode 100644 .agents/skills/impeccable/reference/shape.md delete mode 100644 .agents/skills/impeccable/reference/spatial-design.md delete mode 100644 .agents/skills/impeccable/reference/teach.md delete mode 100644 .agents/skills/impeccable/reference/typeset.md delete mode 100644 .agents/skills/impeccable/reference/typography.md delete mode 100644 .agents/skills/impeccable/reference/ux-writing.md delete mode 100644 .agents/skills/impeccable/scripts/cleanup-deprecated.mjs delete mode 100644 .agents/skills/impeccable/scripts/command-metadata.json delete mode 100644 .agents/skills/impeccable/scripts/design-parser.mjs delete mode 100644 .agents/skills/impeccable/scripts/detect-csp.mjs delete mode 100644 .agents/skills/impeccable/scripts/impeccable-paths.mjs delete mode 100644 .agents/skills/impeccable/scripts/is-generated.mjs delete mode 100644 .agents/skills/impeccable/scripts/live-accept.mjs delete mode 100644 .agents/skills/impeccable/scripts/live-browser-session.js delete mode 100644 .agents/skills/impeccable/scripts/live-browser.js delete mode 100644 .agents/skills/impeccable/scripts/live-complete.mjs delete mode 100644 .agents/skills/impeccable/scripts/live-completion.mjs delete mode 100644 .agents/skills/impeccable/scripts/live-inject.mjs delete mode 100644 .agents/skills/impeccable/scripts/live-poll.mjs delete mode 100644 .agents/skills/impeccable/scripts/live-resume.mjs delete mode 100644 .agents/skills/impeccable/scripts/live-server.mjs delete mode 100644 .agents/skills/impeccable/scripts/live-session-store.mjs delete mode 100644 .agents/skills/impeccable/scripts/live-status.mjs delete mode 100644 .agents/skills/impeccable/scripts/live-wrap.mjs delete mode 100644 .agents/skills/impeccable/scripts/live.mjs delete mode 100644 .agents/skills/impeccable/scripts/load-context.mjs delete mode 100644 .agents/skills/impeccable/scripts/modern-screenshot.umd.js delete mode 100644 .agents/skills/impeccable/scripts/pin.mjs delete mode 120000 .claude/skills/convex delete mode 120000 .claude/skills/convex-create-component delete mode 120000 .claude/skills/convex-migration-helper delete mode 120000 .claude/skills/convex-performance-audit delete mode 120000 .claude/skills/convex-quickstart delete mode 120000 .claude/skills/convex-setup-auth delete mode 100644 .cursor/rules/code-gen-rules.mdc delete mode 100644 .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc delete mode 100644 .cursor/skills/frontend-design/LICENSE.txt delete mode 100644 .cursor/skills/frontend-design/SKILL.md delete mode 120000 .windsurf/skills/convex delete mode 120000 .windsurf/skills/convex-create-component delete mode 120000 .windsurf/skills/convex-migration-helper delete mode 120000 .windsurf/skills/convex-performance-audit delete mode 120000 .windsurf/skills/convex-quickstart delete mode 120000 .windsurf/skills/convex-setup-auth delete mode 100644 CLAUDE.md create mode 100644 CONTEXT.md delete mode 100644 convex/_generated/ai/ai-files.state.json delete mode 100644 convex/_generated/ai/guidelines.md create mode 100644 docs/cloud_sync_refactor/server_side_sync_boundaries_blueprint.html create mode 100644 docs/cloud_sync_refactor/server_side_sync_boundaries_delivery.md create mode 100644 docs/cloud_sync_refactor/server_side_sync_boundaries_handoff.md delete mode 100644 skills-lock.json delete mode 100644 skills/convex-create-component/SKILL.md delete mode 100644 skills/convex-create-component/agents/openai.yaml delete mode 100644 skills/convex-create-component/references/advanced-patterns.md delete mode 100644 skills/convex-create-component/references/hybrid-components.md delete mode 100644 skills/convex-create-component/references/local-components.md delete mode 100644 skills/convex-create-component/references/packaged-components.md delete mode 100644 skills/convex-migration-helper/SKILL.md delete mode 100644 skills/convex-migration-helper/agents/openai.yaml delete mode 100644 skills/convex-migration-helper/references/migration-patterns.md delete mode 100644 skills/convex-migration-helper/references/migrations-component.md delete mode 100644 skills/convex-performance-audit/SKILL.md delete mode 100644 skills/convex-performance-audit/agents/openai.yaml delete mode 100644 skills/convex-performance-audit/references/function-budget.md delete mode 100644 skills/convex-performance-audit/references/hot-path-rules.md delete mode 100644 skills/convex-performance-audit/references/occ-conflicts.md delete mode 100644 skills/convex-performance-audit/references/subscription-cost.md delete mode 100644 skills/convex-quickstart/SKILL.md delete mode 100644 skills/convex-quickstart/agents/openai.yaml delete mode 100644 skills/convex-setup-auth/SKILL.md delete mode 100644 skills/convex-setup-auth/agents/openai.yaml delete mode 100644 skills/convex-setup-auth/references/auth0.md delete mode 100644 skills/convex-setup-auth/references/clerk.md delete mode 100644 skills/convex-setup-auth/references/convex-auth.md delete mode 100644 skills/convex-setup-auth/references/workos-authkit.md delete mode 100644 skills/convex/SKILL.md diff --git a/.agent/skills/convex-create-component/SKILL.md b/.agent/skills/convex-create-component/SKILL.md deleted file mode 100644 index effe01fa..00000000 --- a/.agent/skills/convex-create-component/SKILL.md +++ /dev/null @@ -1,411 +0,0 @@ ---- -name: convex-create-component -description: Design and build Convex components with clear boundaries, isolated state, and app-facing wrappers. Use when creating a new Convex component, extracting reusable backend logic into one, or packaging Convex functionality for reuse across apps. ---- - -# Convex Create Component - -Create reusable Convex components with clear boundaries and a small app-facing API. - -## When to Use - -- Creating a new Convex component in an existing app -- Extracting reusable backend logic into a component -- Building a third-party integration that should own its own tables and workflows -- Packaging Convex functionality for reuse across multiple apps - -## When Not to Use - -- One-off business logic that belongs in the main app -- Thin utilities that do not need Convex tables or functions -- App-level orchestration that should stay in `convex/` -- Cases where a normal TypeScript library is enough - -## Workflow - -1. Ask the user what they are building and what the end goal is. If the repo already makes the answer obvious, say so and confirm before proceeding. -2. Choose the shape using the decision tree below and read the matching reference file. -3. Decide whether a component is justified. Prefer normal app code or a regular library if the feature does not need isolated tables, backend functions, or reusable persistent state. -4. Make a short plan for: - - what tables the component owns - - what public functions it exposes - - what data must be passed in from the app (auth, env vars, parent IDs) - - what stays in the app as wrappers or HTTP mounts -5. Create the component structure with `convex.config.ts`, `schema.ts`, and function files. -6. Implement functions using the component's own `./_generated/server` imports, not the app's generated files. -7. Wire the component into the app with `app.use(...)`. If the app does not already have `convex/convex.config.ts`, create it. -8. Call the component from the app through `components.` using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction`. -9. If React clients, HTTP callers, or public APIs need access, create wrapper functions in the app instead of exposing component functions directly. -10. Run `npx convex dev` and fix codegen, type, or boundary issues before finishing. - -## Choose the Shape - -Ask the user, then pick one path: - -| Goal | Shape | Reference | -|------|-------|-----------| -| Component for this app only | Local | `references/local-components.md` | -| Publish or share across apps | Packaged | `references/packaged-components.md` | -| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | -| Not sure | Default to local | `references/local-components.md` | - -Read exactly one reference file before proceeding. - -## Default Approach - -Unless the user explicitly wants an npm package, default to a local component: - -- Put it under `convex/components//` -- Define it with `defineComponent(...)` in its own `convex.config.ts` -- Install it from the app's `convex/convex.config.ts` with `app.use(...)` -- Let `npx convex dev` generate the component's own `_generated/` files - -## Component Skeleton - -A minimal local component with a table and two functions, plus the app wiring. - -```ts -// convex/components/notifications/convex.config.ts -import { defineComponent } from "convex/server"; - -export default defineComponent("notifications"); -``` - -```ts -// convex/components/notifications/schema.ts -import { defineSchema, defineTable } from "convex/server"; -import { v } from "convex/values"; - -export default defineSchema({ - notifications: defineTable({ - userId: v.string(), - message: v.string(), - read: v.boolean(), - }).index("by_user", ["userId"]), -}); -``` - -```ts -// convex/components/notifications/lib.ts -import { v } from "convex/values"; -import { mutation, query } from "./_generated/server.js"; - -export const send = mutation({ - args: { userId: v.string(), message: v.string() }, - returns: v.id("notifications"), - handler: async (ctx, args) => { - return await ctx.db.insert("notifications", { - userId: args.userId, - message: args.message, - read: false, - }); - }, -}); - -export const listUnread = query({ - args: { userId: v.string() }, - returns: v.array( - v.object({ - _id: v.id("notifications"), - _creationTime: v.number(), - userId: v.string(), - message: v.string(), - read: v.boolean(), - }) - ), - handler: async (ctx, args) => { - return await ctx.db - .query("notifications") - .withIndex("by_user", (q) => q.eq("userId", args.userId)) - .filter((q) => q.eq(q.field("read"), false)) - .collect(); - }, -}); -``` - -```ts -// convex/convex.config.ts -import { defineApp } from "convex/server"; -import notifications from "./components/notifications/convex.config.js"; - -const app = defineApp(); -app.use(notifications); - -export default app; -``` - -```ts -// convex/notifications.ts (app-side wrapper) -import { v } from "convex/values"; -import { mutation, query } from "./_generated/server"; -import { components } from "./_generated/api"; -import { getAuthUserId } from "@convex-dev/auth/server"; - -export const sendNotification = mutation({ - args: { message: v.string() }, - returns: v.null(), - handler: async (ctx, args) => { - const userId = await getAuthUserId(ctx); - if (!userId) throw new Error("Not authenticated"); - - await ctx.runMutation(components.notifications.lib.send, { - userId, - message: args.message, - }); - return null; - }, -}); - -export const myUnread = query({ - args: {}, - handler: async (ctx) => { - const userId = await getAuthUserId(ctx); - if (!userId) throw new Error("Not authenticated"); - - return await ctx.runQuery(components.notifications.lib.listUnread, { - userId, - }); - }, -}); -``` - -Note the reference path shape: a function in `convex/components/notifications/lib.ts` is called as `components.notifications.lib.send` from the app. - -## Critical Rules - -- Keep authentication in the app. `ctx.auth` is not available inside components. -- Keep environment access in the app. Component functions cannot read `process.env`. -- Pass parent app IDs across the boundary as strings. `Id` types become plain strings in the app-facing `ComponentApi`. -- Do not use `v.id("parentTable")` for app-owned tables inside component args or schema. -- Import `query`, `mutation`, and `action` from the component's own `./_generated/server`. -- Do not expose component functions directly to clients. Create app wrappers when client access is needed. -- If the component defines HTTP handlers, mount the routes in the app's `convex/http.ts`. -- If the component needs pagination, use `paginator` from `convex-helpers` instead of built-in `.paginate()`. -- Add `args` and `returns` validators to all public component functions. - -## Patterns - -### Authentication and environment access - -```ts -// Bad: component code cannot rely on app auth or env -const identity = await ctx.auth.getUserIdentity(); -const apiKey = process.env.OPENAI_API_KEY; -``` - -```ts -// Good: the app resolves auth and env, then passes explicit values -const userId = await getAuthUserId(ctx); -if (!userId) throw new Error("Not authenticated"); - -await ctx.runAction(components.translator.translate, { - userId, - apiKey: process.env.OPENAI_API_KEY, - text: args.text, -}); -``` - -### Client-facing API - -```ts -// Bad: assuming a component function is directly callable by clients -export const send = components.notifications.send; -``` - -```ts -// Good: re-export through an app mutation or query -export const sendNotification = mutation({ - args: { message: v.string() }, - returns: v.null(), - handler: async (ctx, args) => { - const userId = await getAuthUserId(ctx); - if (!userId) throw new Error("Not authenticated"); - - await ctx.runMutation(components.notifications.lib.send, { - userId, - message: args.message, - }); - return null; - }, -}); -``` - -### IDs across the boundary - -```ts -// Bad: parent app table IDs are not valid component validators -args: { userId: v.id("users") } -``` - -```ts -// Good: treat parent-owned IDs as strings at the boundary -args: { userId: v.string() } -``` - -### Function Handles for callbacks - -When the app needs to pass a callback function to the component, use function handles. This is common for components that run app-defined logic on a schedule or in a workflow. - -```ts -// App side: create a handle and pass it to the component -import { createFunctionHandle } from "convex/server"; - -export const startJob = mutation({ - handler: async (ctx) => { - const handle = await createFunctionHandle(internal.myModule.processItem); - await ctx.runMutation(components.workpool.enqueue, { - callback: handle, - }); - }, -}); -``` - -```ts -// Component side: accept and invoke the handle -import { v } from "convex/values"; -import type { FunctionHandle } from "convex/server"; -import { mutation } from "./_generated/server.js"; - -export const enqueue = mutation({ - args: { callback: v.string() }, - handler: async (ctx, args) => { - const handle = args.callback as FunctionHandle<"mutation">; - await ctx.scheduler.runAfter(0, handle, {}); - }, -}); -``` - -### Deriving validators from schema - -Instead of manually repeating field types in return validators, extend the schema validator: - -```ts -import { v } from "convex/values"; -import schema from "./schema.js"; - -const notificationDoc = schema.tables.notifications.validator.extend({ - _id: v.id("notifications"), - _creationTime: v.number(), -}); - -export const getLatest = query({ - args: {}, - returns: v.nullable(notificationDoc), - handler: async (ctx) => { - return await ctx.db.query("notifications").order("desc").first(); - }, -}); -``` - -### Static configuration with a globals table - -A common pattern for component configuration is a single-document "globals" table: - -```ts -// schema.ts -export default defineSchema({ - globals: defineTable({ - maxRetries: v.number(), - webhookUrl: v.optional(v.string()), - }), - // ... other tables -}); -``` - -```ts -// lib.ts -export const configure = mutation({ - args: { maxRetries: v.number(), webhookUrl: v.optional(v.string()) }, - returns: v.null(), - handler: async (ctx, args) => { - const existing = await ctx.db.query("globals").first(); - if (existing) { - await ctx.db.patch(existing._id, args); - } else { - await ctx.db.insert("globals", args); - } - return null; - }, -}); -``` - -### Class-based client wrappers - -For components with many functions or configuration options, a class-based client provides a cleaner API. This pattern is common in published components. - -```ts -// src/client/index.ts -import type { GenericMutationCtx, GenericDataModel } from "convex/server"; -import type { ComponentApi } from "../component/_generated/component.js"; - -type MutationCtx = Pick, "runMutation">; - -export class Notifications { - constructor( - private component: ComponentApi, - private options?: { defaultChannel?: string }, - ) {} - - async send(ctx: MutationCtx, args: { userId: string; message: string }) { - return await ctx.runMutation(this.component.lib.send, { - ...args, - channel: this.options?.defaultChannel ?? "default", - }); - } -} -``` - -```ts -// App usage -import { Notifications } from "@convex-dev/notifications"; -import { components } from "./_generated/api"; - -const notifications = new Notifications(components.notifications, { - defaultChannel: "alerts", -}); - -export const send = mutation({ - args: { message: v.string() }, - handler: async (ctx, args) => { - const userId = await getAuthUserId(ctx); - await notifications.send(ctx, { userId, message: args.message }); - }, -}); -``` - -## Validation - -Try validation in this order: - -1. `npx convex codegen --component-dir convex/components/` -2. `npx convex codegen` -3. `npx convex dev` - -Important: - -- Fresh repos may fail these commands until `CONVEX_DEPLOYMENT` is configured. -- Until codegen runs, component-local `./_generated/*` imports and app-side `components....` references will not typecheck. -- If validation blocks on Convex login or deployment setup, stop and ask the user for that exact step instead of guessing. - -## Reference Files - -Read exactly one of these after the user confirms the goal: - -- `references/local-components.md` -- `references/packaged-components.md` -- `references/hybrid-components.md` - -Official docs: [Authoring Components](https://docs.convex.dev/components/authoring) - -## Checklist - -- [ ] Asked the user what they want to build and confirmed the shape -- [ ] Read the matching reference file -- [ ] Confirmed a component is the right abstraction -- [ ] Planned tables, public API, boundaries, and app wrappers -- [ ] Component lives under `convex/components//` (or package layout if publishing) -- [ ] Component imports from its own `./_generated/server` -- [ ] Auth, env access, and HTTP routes stay in the app -- [ ] Parent app IDs cross the boundary as `v.string()` -- [ ] Public functions have `args` and `returns` validators -- [ ] Ran `npx convex dev` and fixed codegen or type issues diff --git a/.agent/skills/convex-create-component/agents/openai.yaml b/.agent/skills/convex-create-component/agents/openai.yaml deleted file mode 100644 index ba9287e4..00000000 --- a/.agent/skills/convex-create-component/agents/openai.yaml +++ /dev/null @@ -1,10 +0,0 @@ -interface: - display_name: "Convex Create Component" - short_description: "Design and build reusable Convex components with clear boundaries." - icon_small: "./assets/icon.svg" - icon_large: "./assets/icon.svg" - brand_color: "#14B8A6" - default_prompt: "Help me create a Convex component for this feature. First check that a component is actually justified, then design the tables, API surface, and app-facing wrappers before implementing it." - -policy: - allow_implicit_invocation: true diff --git a/.agent/skills/convex-create-component/assets/icon.svg b/.agent/skills/convex-create-component/assets/icon.svg deleted file mode 100644 index 10f4c2c4..00000000 --- a/.agent/skills/convex-create-component/assets/icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - diff --git a/.agent/skills/convex-create-component/references/hybrid-components.md b/.agent/skills/convex-create-component/references/hybrid-components.md deleted file mode 100644 index d2bb3514..00000000 --- a/.agent/skills/convex-create-component/references/hybrid-components.md +++ /dev/null @@ -1,37 +0,0 @@ -# Hybrid Convex Components - -Read this file only when the user explicitly wants a hybrid setup. - -## What This Means - -A hybrid component combines a local Convex component with shared library code. - -This can help when: - -- the user wants a local install but also shared package logic -- the component needs extension points or override hooks -- some logic should live in normal TypeScript code outside the component boundary - -## Default Advice - -Treat hybrid as an advanced option, not the default. - -Before choosing it, ask: - -- Why is a plain local component not enough? -- Why is a packaged component not enough? -- What exactly needs to stay overridable or shared? - -If the answer is vague, fall back to local or packaged. - -## Risks - -- More moving parts -- Harder upgrades and backwards compatibility -- Easier to blur the component boundary - -## Checklist - -- [ ] User explicitly needs hybrid behavior -- [ ] Local-only and packaged-only options were considered first -- [ ] The extension points are clearly defined before coding diff --git a/.agent/skills/convex-create-component/references/local-components.md b/.agent/skills/convex-create-component/references/local-components.md deleted file mode 100644 index 7fbfe21a..00000000 --- a/.agent/skills/convex-create-component/references/local-components.md +++ /dev/null @@ -1,38 +0,0 @@ -# Local Convex Components - -Read this file when the component should live inside the current app and does not need to be published as an npm package. - -## When to Choose This - -- The user wants the simplest path -- The component only needs to work in this repo -- The goal is extracting app logic into a cleaner boundary - -## Default Layout - -Use this structure unless the repo already has a clear alternative pattern: - -```text -convex/ - convex.config.ts - components/ - / - convex.config.ts - schema.ts - .ts -``` - -## Workflow Notes - -- Define the component with `defineComponent("")` -- Install it from the app with `defineApp()` and `app.use(...)` -- Keep auth, env access, public API wrappers, and HTTP route mounting in the app -- Let the component own isolated tables and reusable backend workflows -- Add app wrappers if clients need to call into the component - -## Checklist - -- [ ] Component is inside `convex/components//` -- [ ] App installs it with `app.use(...)` -- [ ] Component owns only its own tables -- [ ] App wrappers handle client-facing calls when needed diff --git a/.agent/skills/convex-create-component/references/packaged-components.md b/.agent/skills/convex-create-component/references/packaged-components.md deleted file mode 100644 index 5668e7ed..00000000 --- a/.agent/skills/convex-create-component/references/packaged-components.md +++ /dev/null @@ -1,51 +0,0 @@ -# Packaged Convex Components - -Read this file when the user wants a reusable npm package or a component shared across multiple apps. - -## When to Choose This - -- The user wants to publish the component -- The user wants a stable reusable package boundary -- The component will be shared across multiple apps or teams - -## Default Approach - -- Prefer starting from `npx create-convex@latest --component` when possible -- Keep the official authoring docs as the source of truth for package layout and exports -- Validate the bundled package through an example app, not just the source files - -## Build Flow - -When building a packaged component, make sure the bundled output exists before the example app tries to consume it. - -Recommended order: - -1. `npx convex codegen --component-dir ./path/to/component` -2. Run the package build command -3. Run `npx convex dev --typecheck-components` in the example app - -Do not assume normal app codegen is enough for packaged component workflows. - -## Package Exports - -If publishing to npm, make sure the package exposes the entry points apps need: - -- package root for client helpers, types, or classes -- `./convex.config.js` for installing the component -- `./_generated/component.js` for the app-facing `ComponentApi` type -- `./test` for testing helpers when applicable - -## Testing - -- Use `convex-test` for component logic -- Register the component schema and modules with the test instance -- Test app-side wrapper code from an example app that installs the package -- Export a small helper from `./test` if consumers need easy test registration - -## Checklist - -- [ ] Packaging is actually required -- [ ] Build order avoids bundle and codegen races -- [ ] Package exports include install and typing entry points -- [ ] Example app exercises the packaged component -- [ ] Core behavior is covered by tests diff --git a/.agent/skills/convex-migration-helper/SKILL.md b/.agent/skills/convex-migration-helper/SKILL.md deleted file mode 100644 index f353678f..00000000 --- a/.agent/skills/convex-migration-helper/SKILL.md +++ /dev/null @@ -1,524 +0,0 @@ ---- -name: convex-migration-helper -description: Plan and execute Convex schema migrations safely, including adding fields, creating tables, and data transformations. Use when schema changes affect existing data. ---- - -# Convex Migration Helper - -Safely migrate Convex schemas and data when making breaking changes. - -## When to Use - -- Adding new required fields to existing tables -- Changing field types or structure -- Splitting or merging tables -- Renaming or deleting fields -- Migrating from nested to relational data - -## Key Concepts - -### Schema Validation Drives the Workflow - -Convex will not let you deploy a schema that does not match the data at rest. This is the fundamental constraint that shapes every migration: - -- You cannot add a required field if existing documents don't have it -- You cannot change a field's type if existing documents have the old type -- You cannot remove a field from the schema if existing documents still have it - -This means migrations follow a predictable pattern: **widen the schema, migrate the data, narrow the schema**. - -### Online Migrations - -Convex migrations run online, meaning the app continues serving requests while data is updated asynchronously in batches. During the migration window, your code must handle both old and new data formats. - -### Prefer New Fields Over Changing Types - -When changing the shape of data, create a new field rather than modifying an existing one. This makes the transition safer and easier to roll back. - -### Don't Delete Data - -Unless you are certain, prefer deprecating fields over deleting them. Mark the field as `v.optional` and add a code comment explaining it is deprecated and why it existed. - -## Safe Changes (No Migration Needed) - -### Adding Optional Field - -```typescript -// Before -users: defineTable({ - name: v.string(), -}) - -// After - safe, new field is optional -users: defineTable({ - name: v.string(), - bio: v.optional(v.string()), -}) -``` - -### Adding New Table - -```typescript -posts: defineTable({ - userId: v.id("users"), - title: v.string(), -}).index("by_user", ["userId"]) -``` - -### Adding Index - -```typescript -users: defineTable({ - name: v.string(), - email: v.string(), -}) - .index("by_email", ["email"]) -``` - -## Breaking Changes: The Deployment Workflow - -Every breaking migration follows the same multi-deploy pattern: - -**Deploy 1 - Widen the schema:** - -1. Update schema to allow both old and new formats (e.g., add optional new field) -2. Update code to handle both formats when reading -3. Update code to write the new format for new documents -4. Deploy - -**Between deploys - Migrate data:** - -5. Run migration to backfill existing documents -6. Verify all documents are migrated - -**Deploy 2 - Narrow the schema:** - -7. Update schema to require the new format only -8. Remove code that handles the old format -9. Deploy - -## Using the Migrations Component (Recommended) - -For any non-trivial migration, use the [`@convex-dev/migrations`](https://www.convex.dev/components/migrations) component. It handles batching, cursor-based pagination, state tracking, resume from failure, dry runs, and progress monitoring. - -### Installation - -```bash -npm install @convex-dev/migrations -``` - -### Setup - -```typescript -// convex/convex.config.ts -import { defineApp } from "convex/server"; -import migrations from "@convex-dev/migrations/convex.config.js"; - -const app = defineApp(); -app.use(migrations); -export default app; -``` - -```typescript -// convex/migrations.ts -import { Migrations } from "@convex-dev/migrations"; -import { components } from "./_generated/api.js"; -import { DataModel } from "./_generated/dataModel.js"; - -export const migrations = new Migrations(components.migrations); -export const run = migrations.runner(); -``` - -The `DataModel` type parameter is optional but provides type safety for migration definitions. - -### Define a Migration - -The `migrateOne` function processes a single document. The component handles batching and pagination automatically. - -```typescript -// convex/migrations.ts -export const addDefaultRole = migrations.define({ - table: "users", - migrateOne: async (ctx, user) => { - if (user.role === undefined) { - await ctx.db.patch(user._id, { role: "user" }); - } - }, -}); -``` - -Shorthand: if you return an object, it is applied as a patch automatically. - -```typescript -export const clearDeprecatedField = migrations.define({ - table: "users", - migrateOne: () => ({ legacyField: undefined }), -}); -``` - -### Run a Migration - -From the CLI: - -```bash -# Define a one-off runner in convex/migrations.ts: -# export const runIt = migrations.runner(internal.migrations.addDefaultRole); -npx convex run migrations:runIt - -# Or use the general-purpose runner -npx convex run migrations:run '{"fn": "migrations:addDefaultRole"}' -``` - -Programmatically from another Convex function: - -```typescript -await migrations.runOne(ctx, internal.migrations.addDefaultRole); -``` - -### Run Multiple Migrations in Order - -```typescript -export const runAll = migrations.runner([ - internal.migrations.addDefaultRole, - internal.migrations.clearDeprecatedField, - internal.migrations.normalizeEmails, -]); -``` - -```bash -npx convex run migrations:runAll -``` - -If one fails, it stops and will not continue to the next. Call it again to retry from where it left off. Completed migrations are skipped automatically. - -### Dry Run - -Test a migration before committing changes: - -```bash -npx convex run migrations:runIt '{"dryRun": true}' -``` - -This runs one batch and then rolls back, so you can see what it would do without changing any data. - -### Check Migration Status - -```bash -npx convex run --component migrations lib:getStatus --watch -``` - -### Cancel a Running Migration - -```bash -npx convex run --component migrations lib:cancel '{"name": "migrations:addDefaultRole"}' -``` - -Or programmatically: - -```typescript -await migrations.cancel(ctx, internal.migrations.addDefaultRole); -``` - -### Run Migrations on Deploy - -Chain migration execution after deploying: - -```bash -npx convex deploy --cmd 'npm run build' && npx convex run migrations:runAll --prod -``` - -### Configuration Options - -#### Custom Batch Size - -If documents are large or the table has heavy write traffic, reduce the batch size to avoid transaction limits or OCC conflicts: - -```typescript -export const migrateHeavyTable = migrations.define({ - table: "largeDocuments", - batchSize: 10, - migrateOne: async (ctx, doc) => { - // migration logic - }, -}); -``` - -#### Migrate a Subset Using an Index - -Process only matching documents instead of the full table: - -```typescript -export const fixEmptyNames = migrations.define({ - table: "users", - customRange: (query) => - query.withIndex("by_name", (q) => q.eq("name", "")), - migrateOne: () => ({ name: "" }), -}); -``` - -#### Parallelize Within a Batch - -By default each document in a batch is processed serially. Enable parallel processing if your migration logic does not depend on ordering: - -```typescript -export const clearField = migrations.define({ - table: "myTable", - parallelize: true, - migrateOne: () => ({ optionalField: undefined }), -}); -``` - -## Common Migration Patterns - -### Adding a Required Field - -```typescript -// Deploy 1: Schema allows both states -users: defineTable({ - name: v.string(), - role: v.optional(v.union(v.literal("user"), v.literal("admin"))), -}) - -// Migration: backfill the field -export const addDefaultRole = migrations.define({ - table: "users", - migrateOne: async (ctx, user) => { - if (user.role === undefined) { - await ctx.db.patch(user._id, { role: "user" }); - } - }, -}); - -// Deploy 2: After migration completes, make it required -users: defineTable({ - name: v.string(), - role: v.union(v.literal("user"), v.literal("admin")), -}) -``` - -### Deleting a Field - -Mark the field optional first, migrate data to remove it, then remove from schema: - -```typescript -// Deploy 1: Make optional -// isPro: v.boolean() --> isPro: v.optional(v.boolean()) - -// Migration -export const removeIsPro = migrations.define({ - table: "teams", - migrateOne: async (ctx, team) => { - if (team.isPro !== undefined) { - await ctx.db.patch(team._id, { isPro: undefined }); - } - }, -}); - -// Deploy 2: Remove isPro from schema entirely -``` - -### Changing a Field Type - -Prefer creating a new field. You can combine adding and deleting in one migration: - -```typescript -// Deploy 1: Add new field, keep old field optional -// isPro: v.boolean() --> isPro: v.optional(v.boolean()), plan: v.optional(...) - -// Migration: convert old field to new field -export const convertToEnum = migrations.define({ - table: "teams", - migrateOne: async (ctx, team) => { - if (team.plan === undefined) { - await ctx.db.patch(team._id, { - plan: team.isPro ? "pro" : "basic", - isPro: undefined, - }); - } - }, -}); - -// Deploy 2: Remove isPro from schema, make plan required -``` - -### Splitting Nested Data Into a Separate Table - -```typescript -export const extractPreferences = migrations.define({ - table: "users", - migrateOne: async (ctx, user) => { - if (user.preferences === undefined) return; - - const existing = await ctx.db - .query("userPreferences") - .withIndex("by_user", (q) => q.eq("userId", user._id)) - .first(); - - if (!existing) { - await ctx.db.insert("userPreferences", { - userId: user._id, - ...user.preferences, - }); - } - - await ctx.db.patch(user._id, { preferences: undefined }); - }, -}); -``` - -Make sure your code is already writing to the new `userPreferences` table for new users before running this migration, so you don't miss documents created during the migration window. - -### Cleaning Up Orphaned Documents - -```typescript -export const deleteOrphanedEmbeddings = migrations.define({ - table: "embeddings", - migrateOne: async (ctx, doc) => { - const chunk = await ctx.db - .query("chunks") - .withIndex("by_embedding", (q) => q.eq("embeddingId", doc._id)) - .first(); - - if (!chunk) { - await ctx.db.delete(doc._id); - } - }, -}); -``` - -## Migration Strategies for Zero Downtime - -During the migration window, your app must handle both old and new data formats. There are two main strategies. - -### Dual Write (Preferred) - -Write to both old and new structures. Read from the old structure until migration is complete. - -1. Deploy code that writes both formats, reads old format -2. Run migration on existing data -3. Deploy code that reads new format, still writes both -4. Deploy code that only reads and writes new format - -This is preferred because you can safely roll back at any point, the old format is always up to date. - -```typescript -// Bad: only writing to new structure before migration is done -export const createTeam = mutation({ - args: { name: v.string(), isPro: v.boolean() }, - handler: async (ctx, args) => { - await ctx.db.insert("teams", { - name: args.name, - plan: args.isPro ? "pro" : "basic", - }); - }, -}); - -// Good: writing to both structures during migration -export const createTeam = mutation({ - args: { name: v.string(), isPro: v.boolean() }, - handler: async (ctx, args) => { - const plan = args.isPro ? "pro" : "basic"; - await ctx.db.insert("teams", { - name: args.name, - isPro: args.isPro, - plan, - }); - }, -}); -``` - -### Dual Read - -Read both formats. Write only the new format. - -1. Deploy code that reads both formats (preferring new), writes only new format -2. Run migration on existing data -3. Deploy code that reads and writes only new format - -This avoids duplicating writes, which is useful when having two copies of data could cause inconsistencies. The downside is that rolling back to before step 1 is harder, since new documents only have the new format. - -```typescript -// Good: reading both formats, preferring new -function getTeamPlan(team: Doc<"teams">): "basic" | "pro" { - if (team.plan !== undefined) return team.plan; - return team.isPro ? "pro" : "basic"; -} -``` - -## Small Table Shortcut - -For small tables (a few thousand documents at most), you can migrate in a single `internalMutation` without the component: - -```typescript -import { internalMutation } from "./_generated/server"; - -export const backfillSmallTable = internalMutation({ - handler: async (ctx) => { - const docs = await ctx.db.query("smallConfig").collect(); - for (const doc of docs) { - if (doc.newField === undefined) { - await ctx.db.patch(doc._id, { newField: "default" }); - } - } - }, -}); -``` - -```bash -npx convex run migrations:backfillSmallTable -``` - -Only use `.collect()` when you are certain the table is small. For anything larger, use the migrations component. - -## Verifying a Migration - -Query to check remaining unmigrated documents: - -```typescript -import { query } from "./_generated/server"; - -export const verifyMigration = query({ - handler: async (ctx) => { - const remaining = await ctx.db - .query("users") - .filter((q) => q.eq(q.field("role"), undefined)) - .take(10); - - return { - complete: remaining.length === 0, - sampleRemaining: remaining.map((u) => u._id), - }; - }, -}); -``` - -Or use the component's built-in status monitoring: - -```bash -npx convex run --component migrations lib:getStatus --watch -``` - -## Migration Checklist - -- [ ] Identify the breaking change and plan the multi-deploy workflow -- [ ] Update schema to allow both old and new formats -- [ ] Update code to handle both formats when reading -- [ ] Update code to write the new format for new documents -- [ ] Deploy widened schema and updated code -- [ ] Define migration using the `@convex-dev/migrations` component -- [ ] Test with `dryRun: true` -- [ ] Run migration and monitor status -- [ ] Verify all documents are migrated -- [ ] Update schema to require new format only -- [ ] Clean up code that handled old format -- [ ] Deploy final schema and code -- [ ] Remove migration code once confirmed stable - -## Common Pitfalls - -1. **Don't make a field required before migrating data**: Convex will reject the deploy. Always widen the schema first. -2. **Don't `.collect()` large tables**: Use the migrations component for proper batched pagination. `.collect()` is only safe for tables you know are small. -3. **Don't forget to write the new format before migrating**: If your code doesn't write the new format for new documents, documents created during the migration window will be missed. -4. **Don't skip the dry run**: Use `dryRun: true` to validate your migration logic before committing changes to production data. -5. **Don't delete fields prematurely**: Prefer deprecating with `v.optional` and a comment. Only delete after you are confident the data is no longer needed. -6. **Don't use crons for migration batches**: The migrations component handles batching via recursive scheduling internally. Crons require manual cleanup and an extra deploy to remove. diff --git a/.agent/skills/convex-migration-helper/agents/openai.yaml b/.agent/skills/convex-migration-helper/agents/openai.yaml deleted file mode 100644 index c2a7fcc5..00000000 --- a/.agent/skills/convex-migration-helper/agents/openai.yaml +++ /dev/null @@ -1,10 +0,0 @@ -interface: - display_name: "Convex Migration Helper" - short_description: "Plan and run safe Convex schema and data migrations." - icon_small: "./assets/icon.svg" - icon_large: "./assets/icon.svg" - brand_color: "#8B5CF6" - default_prompt: "Help me plan and execute this Convex migration safely. Start by identifying the schema change, the existing data shape, and the widen-migrate-narrow path before making edits." - -policy: - allow_implicit_invocation: true diff --git a/.agent/skills/convex-migration-helper/assets/icon.svg b/.agent/skills/convex-migration-helper/assets/icon.svg deleted file mode 100644 index fba7241a..00000000 --- a/.agent/skills/convex-migration-helper/assets/icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - diff --git a/.agent/skills/convex-performance-audit/SKILL.md b/.agent/skills/convex-performance-audit/SKILL.md deleted file mode 100644 index 6ee0417f..00000000 --- a/.agent/skills/convex-performance-audit/SKILL.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -name: convex-performance-audit -description: Audit and optimize Convex application performance, covering hot path reads, write contention, subscription cost, and function limits. Use when a Convex feature is slow, reads too much data, writes too often, has OCC conflicts, or needs performance investigation. ---- - -# Convex Performance Audit - -Diagnose and fix performance problems in Convex applications, one problem class at a time. - -## When to Use - -- A Convex page or feature feels slow or expensive -- `npx convex insights --details` reports high bytes read, documents read, or OCC conflicts -- Low-freshness read paths are using reactivity where point-in-time reads would do -- OCC conflict errors or excessive mutation retries -- High subscription count or slow UI updates -- Functions approaching execution or transaction limits -- The same performance pattern needs fixing across sibling functions - -## When Not to Use - -- Initial Convex setup, auth setup, or component extraction -- Pure schema migrations with no performance goal -- One-off micro-optimizations without a user-visible or deployment-visible problem - -## Guardrails - -- Prefer simpler code when scale is small, traffic is modest, or the available signals are weak -- Do not recommend digest tables, document splitting, fetch-strategy changes, or migration-heavy rollouts unless there is a measured signal, a clearly unbounded path, or a known hot read/write path -- In Convex, a simple scan on a small table is often acceptable. Do not invent structural work just because a pattern is not ideal at large scale - -## First Step: Gather Signals - -Start with the strongest signal available: - -1. If deployment Health insights are already available from the user or the current context, treat them as a first-class source of performance signals. -2. If CLI insights are available, run `npx convex insights --details`. Use `--prod`, `--preview-name`, or `--deployment-name` when needed. - - If the local repo's Convex CLI is too old to support `insights`, try `npx -y convex@latest insights --details` before giving up. -3. If the repo already uses `convex-doctor`, you may treat its findings as hints. Do not require it, and do not treat it as the source of truth. -4. If runtime signals are unavailable, audit from code anyway, but keep the guardrails above in mind. Lack of insights is not proof of health, but it is also not proof that a large refactor is warranted. - -## Signal Routing - -After gathering signals, identify the problem class and read the matching reference file. - -| Signal | Reference | -|---|---| -| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | -| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | -| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | -| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | -| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | - -Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain. - -## Escalate Larger Fixes - -If the likely fix is invasive, cross-cutting, or migration-heavy, stop and present options before editing. - -Examples: - -- introducing digest or summary tables across multiple flows -- splitting documents to isolate frequently-updated fields -- reworking pagination or fetch strategy across several screens -- switching to a new index or denormalized field that needs migration-safe rollout - -When correctness depends on handling old and new states during a rollout, consult `skills/convex-migration-helper/SKILL.md` for the migration workflow. - -## Workflow - -### 1. Scope the problem - -Pick one concrete user flow from the actual project. Look at the codebase, client pages, and API surface to find the flow that matches the symptom. - -Write down: - -- entrypoint functions -- client callsites using `useQuery`, `usePaginatedQuery`, or `useMutation` -- tables read -- tables written -- whether the path is high-read, high-write, or both - -### 2. Trace the full read and write set - -For each function in the path: - -1. Trace every `ctx.db.get()` and `ctx.db.query()` -2. Trace every `ctx.db.patch()`, `ctx.db.replace()`, and `ctx.db.insert()` -3. Note foreign-key lookups, JS-side filtering, and full-document reads -4. Identify all sibling functions touching the same tables -5. Identify reactive stats, aggregates, or widgets rendered on the same page - -In Convex, every extra read increases transaction work, and every write can invalidate reactive subscribers. Treat read amplification and invalidation amplification as first-class problems. - -### 3. Apply fixes from the relevant reference - -Read the reference file matching your problem class. Each reference includes specific patterns, code examples, and a recommended fix order. - -Do not stop at the single function named by an insight. Trace sibling readers and writers touching the same tables. - -### 4. Fix sibling functions together - -When one function touching a table has a performance bug, audit sibling functions for the same pattern. - -After finding one problem, inspect both sibling readers and sibling writers for the same table family, including companion digest or summary tables. - -Examples: - -- If one list query switches from full docs to a digest table, inspect the other list queries for that table -- If one mutation needs no-op write protection, inspect the other writers to the same table -- If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk - -Do not leave one path fixed and another path on the old pattern unless there is a clear product reason. - -### 5. Verify before finishing - -Confirm all of these: - -1. Results are the same as before, no dropped records -2. Eliminated reads or writes are no longer in the path where expected -3. Fallback behavior works when denormalized or indexed fields are missing -4. New writes avoid unnecessary invalidation when data is unchanged -5. Every relevant sibling reader and writer was inspected, not just the original function - -## Reference Files - -- `references/hot-path-rules.md` - Read amplification, invalidation, denormalization, indexes, digest tables -- `references/occ-conflicts.md` - Write contention, OCC resolution, hot document splitting -- `references/subscription-cost.md` - Reactive query cost, subscription granularity, point-in-time reads -- `references/function-budget.md` - Execution limits, transaction size, large documents, payload size - -Also check the official [Convex Best Practices](https://docs.convex.dev/understanding/best-practices/) page for additional patterns covering argument validation, access control, and code organization that may surface during the audit. - -## Checklist - -- [ ] Gathered signals from insights, dashboard, or code audit -- [ ] Identified the problem class and read the matching reference -- [ ] Scoped one concrete user flow or function path -- [ ] Traced every read and write in that path -- [ ] Identified sibling functions touching the same tables -- [ ] Applied fixes from the reference, following the recommended fix order -- [ ] Fixed sibling functions consistently -- [ ] Verified behavior and confirmed no regressions diff --git a/.agent/skills/convex-performance-audit/agents/openai.yaml b/.agent/skills/convex-performance-audit/agents/openai.yaml deleted file mode 100644 index 9a21f387..00000000 --- a/.agent/skills/convex-performance-audit/agents/openai.yaml +++ /dev/null @@ -1,10 +0,0 @@ -interface: - display_name: "Convex Performance Audit" - short_description: "Audit slow Convex reads, subscriptions, OCC conflicts, and limits." - icon_small: "./assets/icon.svg" - icon_large: "./assets/icon.svg" - brand_color: "#EF4444" - default_prompt: "Audit this Convex app for performance issues. Start with the strongest signal available, identify the problem class, and suggest the smallest high-impact fix before proposing bigger structural changes." - -policy: - allow_implicit_invocation: true diff --git a/.agent/skills/convex-performance-audit/assets/icon.svg b/.agent/skills/convex-performance-audit/assets/icon.svg deleted file mode 100644 index 7ab9e09c..00000000 --- a/.agent/skills/convex-performance-audit/assets/icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - diff --git a/.agent/skills/convex-performance-audit/references/function-budget.md b/.agent/skills/convex-performance-audit/references/function-budget.md deleted file mode 100644 index c71d14cb..00000000 --- a/.agent/skills/convex-performance-audit/references/function-budget.md +++ /dev/null @@ -1,232 +0,0 @@ -# Function Budget - -Use these rules when functions are hitting execution limits, transaction size errors, or returning excessively large payloads to the client. - -## Core Principle - -Convex functions run inside transactions with budgets for time, reads, and writes. Staying well within these limits is not just about avoiding errors, it reduces latency and contention. - -## Limits to Know - -These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers. - -| Resource | Limit | -|---|---| -| Query/mutation execution time | 1 second (user code only, excludes DB operations) | -| Action execution time | 10 minutes | -| Data read per transaction | 16 MiB | -| Data written per transaction | 16 MiB | -| Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | -| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | -| Documents written per transaction | 16,000 | -| Individual document size | 1 MiB | -| Function return value size | 16 MiB | - -## Symptoms - -- "Function execution took too long" errors -- "Transaction too large" or read/write set size errors -- Slow queries that read many documents -- Client receiving large payloads that slow down page load -- `npx convex insights --details` showing high bytes read - -## Common Causes - -### Unbounded collection - -A query that calls `.collect()` on a table without a reasonable limit. As the table grows, the query reads more and more documents. - -### Large document reads on hot paths - -Reading documents with large fields (rich text, embedded media references, long arrays) when only a small subset of the data is needed for the current view. - -### Mutation doing too much work - -A single mutation that updates hundreds of documents, backfills data, or rebuilds derived state in one transaction. - -### Returning too much data to the client - -A query returning full documents when the client only needs a few fields. - -## Fix Order - -### 1. Bound your reads - -Never `.collect()` without a limit on a table that can grow unbounded. - -```ts -// Bad: unbounded read, breaks as the table grows -const messages = await ctx.db.query("messages").collect(); -``` - -```ts -// Good: paginate or limit -const messages = await ctx.db - .query("messages") - .withIndex("by_channel", (q) => q.eq("channelId", channelId)) - .order("desc") - .take(50); -``` - -### 2. Read smaller shapes - -If the list page only needs title, author, and date, do not read full documents with rich content fields. - -Use digest or summary tables for hot list pages. See `hot-path-rules.md` for the digest table pattern. - -### 3. Break large mutations into batches - -If a mutation needs to update hundreds of documents, split it into a self-scheduling chain. - -```ts -// Bad: one mutation updating every row -export const backfillAll = internalMutation({ - handler: async (ctx) => { - const docs = await ctx.db.query("items").collect(); - for (const doc of docs) { - await ctx.db.patch(doc._id, { newField: computeValue(doc) }); - } - }, -}); -``` - -```ts -// Good: cursor-based batch processing -export const backfillBatch = internalMutation({ - args: { cursor: v.optional(v.string()), batchSize: v.optional(v.number()) }, - handler: async (ctx, args) => { - const batchSize = args.batchSize ?? 100; - const result = await ctx.db - .query("items") - .paginate({ cursor: args.cursor ?? null, numItems: batchSize }); - - for (const doc of result.page) { - if (doc.newField === undefined) { - await ctx.db.patch(doc._id, { newField: computeValue(doc) }); - } - } - - if (!result.isDone) { - await ctx.scheduler.runAfter(0, internal.items.backfillBatch, { - cursor: result.continueCursor, - batchSize, - }); - } - }, -}); -``` - -### 4. Move heavy work to actions - -Queries and mutations run inside Convex's transactional runtime with strict budgets. If you need to do CPU-intensive computation, call external APIs, or process large files, use an action instead. - -Actions run outside the transaction and can call mutations to write results back. - -```ts -// Bad: heavy computation inside a mutation -export const processUpload = mutation({ - handler: async (ctx, args) => { - const result = expensiveComputation(args.data); - await ctx.db.insert("results", result); - }, -}); -``` - -```ts -// Good: action for heavy work, mutation for the write -export const processUpload = action({ - handler: async (ctx, args) => { - const result = expensiveComputation(args.data); - await ctx.runMutation(internal.results.store, { result }); - }, -}); -``` - -### 5. Trim return values - -Only return what the client needs. If a query fetches full documents but the component only renders a few fields, map the results before returning. - -```ts -// Bad: returns full documents including large content fields -export const list = query({ - handler: async (ctx) => { - return await ctx.db.query("articles").take(20); - }, -}); -``` - -```ts -// Good: project to only the fields the client needs -export const list = query({ - handler: async (ctx) => { - const articles = await ctx.db.query("articles").take(20); - return articles.map((a) => ({ - _id: a._id, - title: a.title, - author: a.author, - createdAt: a._creationTime, - })); - }, -}); -``` - -### 6. Replace `ctx.runQuery` and `ctx.runMutation` with helper functions - -Inside queries and mutations, `ctx.runQuery` and `ctx.runMutation` have overhead compared to calling a plain TypeScript helper function. They run in the same transaction but pay extra per-call cost. - -```ts -// Bad: unnecessary overhead from ctx.runQuery inside a mutation -export const createProject = mutation({ - handler: async (ctx, args) => { - const user = await ctx.runQuery(api.users.getCurrentUser); - await ctx.db.insert("projects", { ...args, ownerId: user._id }); - }, -}); -``` - -```ts -// Good: plain helper function, no extra overhead -export const createProject = mutation({ - handler: async (ctx, args) => { - const user = await getCurrentUser(ctx); - await ctx.db.insert("projects", { ...args, ownerId: user._id }); - }, -}); -``` - -Exception: components require `ctx.runQuery`/`ctx.runMutation`. Use them there, but prefer helpers everywhere else. - -### 7. Avoid unnecessary `runAction` calls - -`runAction` from within an action creates a separate function invocation with its own memory and CPU budget. The parent action just sits idle waiting. Replace with a plain TypeScript function call unless you need a different runtime (e.g. calling Node.js code from the Convex runtime). - -```ts -// Bad: runAction overhead for no reason -export const processItems = action({ - handler: async (ctx, args) => { - for (const item of args.items) { - await ctx.runAction(internal.items.processOne, { item }); - } - }, -}); -``` - -```ts -// Good: plain function call -export const processItems = action({ - handler: async (ctx, args) => { - for (const item of args.items) { - await processOneItem(ctx, { item }); - } - }, -}); -``` - -## Verification - -1. No function execution or transaction size errors -2. `npx convex insights --details` shows reduced bytes read -3. Large mutations are batched and self-scheduling -4. Client payloads are reasonably sized for the UI they serve -5. `ctx.runQuery`/`ctx.runMutation` in queries and mutations replaced with helpers where possible -6. Sibling functions with similar patterns were checked diff --git a/.agent/skills/convex-performance-audit/references/hot-path-rules.md b/.agent/skills/convex-performance-audit/references/hot-path-rules.md deleted file mode 100644 index 96a7b94e..00000000 --- a/.agent/skills/convex-performance-audit/references/hot-path-rules.md +++ /dev/null @@ -1,359 +0,0 @@ -# Hot Path Rules - -Use these rules when the top-level workflow points to read amplification, denormalization, index rollout, reactive query cost, or invalidation-heavy writes. - -## Core Principle - -Every byte read or written multiplies with concurrency. - -Think: - -`cost x calls_per_second x 86400` - -In Convex, every write can also fan out into reactive invalidation, replication work, and downstream sync. - -## Consistency Rule - -If you fix a hot-path pattern for one function, audit sibling functions touching the same tables for the same pattern. - -Do this especially for: - -- multiple list queries over the same table -- multiple writers to the same table -- public browse and search queries over the same records -- helper functions reused by more than one endpoint - -## 1. Push Filters To Storage - -Both JavaScript `.filter()` and the Convex query `.filter()` method after a DB scan mean you already paid for the read. The Convex `.filter()` method has the same performance as filtering in JS, it does not push the predicate to the storage layer. Only `.withIndex()` and `.withSearchIndex()` actually reduce the documents scanned. - -Prefer: - -- `withIndex(...)` -- `.withSearchIndex(...)` for text search -- narrower tables -- summary tables - -before accepting a scan-plus-filter pattern. - -```ts -// Bad: scans then filters in JavaScript -export const listOpen = query({ - args: {}, - handler: async (ctx) => { - const tasks = await ctx.db.query("tasks").collect(); - return tasks.filter((task) => task.status === "open"); - }, -}); -``` - -```ts -// Also bad: Convex .filter() does not push to storage either -export const listOpen = query({ - args: {}, - handler: async (ctx) => { - return await ctx.db - .query("tasks") - .filter((q) => q.eq(q.field("status"), "open")) - .collect(); - }, -}); -``` - -```ts -// Good: use an index so storage does the filtering -export const listOpen = query({ - args: {}, - handler: async (ctx) => { - return await ctx.db - .query("tasks") - .withIndex("by_status", (q) => q.eq("status", "open")) - .collect(); - }, -}); -``` - -### Migration rule for indexes - -New indexes on partially backfilled fields can create correctness bugs during rollout. - -Important Convex detail: - -`undefined !== false` - -If an older document is missing a field entirely, it will not match a compound index entry that expects `false`. - -Do not trust old comments saying a field is "not backfilled" or "already backfilled". Verify. - -If correctness depends on handling old and new states during rollout, do not improvise a partial-backfill workaround in the hot path. Use a migration-safe rollout and consult `skills/convex-migration-helper/SKILL.md`. - -```ts -// Bad: optional booleans can miss older rows where the field is undefined -const projects = await ctx.db - .query("projects") - .withIndex("by_archived_and_updated", (q) => q.eq("isArchived", false)) - .order("desc") - .take(20); -``` - -```ts -// Good: switch hot-path reads only after the rollout is migration-safe -// See the migration helper skill for dual-read / backfill / cutover patterns. -``` - -### Check for redundant indexes - -Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need `by_foo_and_bar`, since you can query it with just the `foo` condition and omit `bar`. Extra indexes add storage cost and write overhead on every insert, patch, and delete. - -```ts -// Bad: two indexes where one would do -defineTable({ team: v.id("teams"), user: v.id("users") }) - .index("by_team", ["team"]) - .index("by_team_and_user", ["team", "user"]) -``` - -```ts -// Good: single compound index serves both query patterns -defineTable({ team: v.id("teams"), user: v.id("users") }) - .index("by_team_and_user", ["team", "user"]) -``` - -Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first. - -## 2. Minimize Data Sources - -Trace every read. - -If a function resolves a foreign key for a tiny display field and a denormalized copy already exists, prefer the denormalized field on the hot path. - -### When to denormalize - -Denormalize when all of these are true: - -- the path is hot -- the joined document is much larger than the field you need -- many readers are paying that join cost repeatedly - -Useful mental model: - -`join_cost = rows_per_page x foreign_doc_size x pages_per_second` - -Small-table joins are often fine. Large-document joins for tiny fields on hot list pages are usually not. - -### Fallback rule - -Denormalized data is an optimization. Live data is the correctness path. - -Rules: - -- If the denormalized field is missing or null, fall back to the live read -- Do not show placeholders instead of falling back -- In lookup maps, only include fully populated entries - -```ts -// Bad: missing denormalized data becomes a placeholder and blocks correctness -const ownerName = project.ownerName ?? "Unknown owner"; -``` - -```ts -// Good: denormalized data is an optimization, not the only source of truth -const ownerName = - project.ownerName ?? - (await ctx.db.get(project.ownerId))?.name ?? - null; -``` - -Bad lookup map pattern: - -```ts -const ownersById = { - [project.ownerId]: { ownerName: null }, -}; -``` - -That blocks fallback because the map says "I have data" when it does not. - -Good lookup map pattern: - -```ts -const ownersById = - project.ownerName !== undefined && project.ownerName !== null - ? { [project.ownerId]: { ownerName: project.ownerName } } - : {}; -``` - -### No denormalized copy yet - -Prefer adding fields to an existing summary, companion, or digest table instead of bloating the primary hot-path table. - -If introducing the new field or table requires a staged rollout, backfill, or old/new-shape handling, use the migration helper skill for the rollout plan. - -Rollout order: - -1. Update schema -2. Update write path -3. Backfill -4. Switch read path - -## 3. Minimize Row Size - -Hot list pages should read the smallest document shape that still answers the UI. - -Prefer summary or digest tables over full source tables when: - -- the list page only needs a subset of fields -- source documents are large -- the query is high volume - -An 800 byte summary row is materially cheaper than a 3 KB full document on a hot page. - -Digest tables are a tradeoff, not a default: - -- Worth it when the path is clearly hot, the source rows are much larger than the UI needs, or many readers are repeatedly paying the same join and payload cost -- Probably not worth it when an indexed read on the source table is already cheap enough, the table is still small, or the extra write and migration complexity would dominate the benefit - -```ts -// Bad: list page reads source docs, then joins owner data per row -const projects = await ctx.db - .query("projects") - .withIndex("by_public", (q) => q.eq("isPublic", true)) - .collect(); -``` - -```ts -// Good: list page reads the smaller digest shape first -const projects = await ctx.db - .query("projectDigests") - .withIndex("by_public_and_updated", (q) => q.eq("isPublic", true)) - .order("desc") - .take(20); -``` - -## 4. Skip No-Op Writes - -No-op writes still cost work in Convex: - -- invalidation -- replication -- trigger execution -- downstream sync - -Before `patch` or `replace`, compare against the existing document and skip the write if nothing changed. - -Apply this across sibling writers too. One careful writer does not help much if three other mutations still patch unconditionally. - -```ts -// Bad: patching unchanged values still triggers invalidation and downstream work -await ctx.db.patch(settings._id, { - theme: args.theme, - locale: args.locale, -}); -``` - -```ts -// Good: only write when something actually changed -if (settings.theme !== args.theme || settings.locale !== args.locale) { - await ctx.db.patch(settings._id, { - theme: args.theme, - locale: args.locale, - }); -} -``` - -## 5. Match Consistency To Read Patterns - -Choose read strategy based on traffic shape. - -### High-read, low-write - -Examples: - -- public browse pages -- search results -- landing pages -- directory listings - -Prefer: - -- point-in-time reads where appropriate -- explicit refresh -- local state for pagination -- caching where appropriate - -Do not treat subscriptions as automatically wrong here. Prefer point-in-time reads only when the product does not need live freshness and the reactive cost is material. See `subscription-cost.md` for detailed patterns. - -### High-read, high-write - -Examples: - -- collaborative editors -- live dashboards -- presence-heavy views - -Reactive queries may be worth the ongoing cost. - -## Convex-Specific Notes - -### Reactive queries - -Every `ctx.db.get()` and `ctx.db.query()` contributes to the invalidation set for the query. - -On the client: - -- `useQuery` creates a live subscription -- `usePaginatedQuery` creates a live subscription per page - -For low-freshness flows, consider a point-in-time read instead of a live subscription only when the product does not need updates pushed automatically. - -### Point-in-time reads - -Framework helpers, server-rendered fetches, or one-shot client reads can avoid ongoing subscription cost when live updates are not useful. - -Use them for: - -- aggregate snapshots -- reports -- low-churn listings -- pages where explicit refresh is fine - -### Triggers and fan-out - -Triggers fire on every write, including writes that did not materially change the document. - -When a write exists only to keep derived state in sync: - -- diff before patching -- move expensive non-blocking work to `ctx.scheduler.runAfter` when appropriate - -### Aggregates - -Reactive global counts invalidate frequently on busy tables. - -Prefer: - -- one-shot aggregate fetches -- periodic recomputation -- precomputed summary rows - -for global stats that do not need live updates every second. - -### Backfills - -For larger backfills, use cursor-based, self-scheduling `internalMutation` jobs or the migrations component. - -Deploy code that can handle both states before running the backfill. - -During the gap: - -- writes should populate the new shape -- reads should fall back safely - -## Verification - -Before closing the audit, confirm: - -1. Same results as before, no dropped records -2. The removed table or lookup is no longer in the hot-path read set -3. Tests or validation cover fallback behavior -4. Migration safety is preserved while fields or indexes are unbackfilled -5. Sibling functions were fixed consistently diff --git a/.agent/skills/convex-performance-audit/references/occ-conflicts.md b/.agent/skills/convex-performance-audit/references/occ-conflicts.md deleted file mode 100644 index a96d0466..00000000 --- a/.agent/skills/convex-performance-audit/references/occ-conflicts.md +++ /dev/null @@ -1,126 +0,0 @@ -# OCC Conflict Resolution - -Use these rules when insights, logs, or dashboard health show OCC (Optimistic Concurrency Control) conflicts, mutation retries, or write contention on hot tables. - -## Core Principle - -Convex uses optimistic concurrency control. When two transactions read or write overlapping data, one succeeds and the other retries automatically. High contention means wasted work and increased latency. - -## Symptoms - -- OCC conflict errors in deployment logs or health page -- Mutations retrying multiple times before succeeding -- User-visible latency spikes on write-heavy pages -- `npx convex insights --details` showing high conflict rates - -## Common Causes - -### Hot documents - -Multiple mutations writing to the same document concurrently. Classic examples: a global counter, a shared settings row, or a "last updated" timestamp on a parent record. - -### Broad read sets causing false conflicts - -A query that scans a large table range creates a broad read set. If any write touches that range, the query's transaction conflicts even if the specific document the query cared about was not modified. - -### Fan-out from triggers or cascading writes - -A single user action triggers multiple mutations that all touch related documents. Each mutation competes with the others. - -Database triggers (e.g. from `convex-helpers`) run inside the same transaction as the mutation that caused them. If a trigger does heavy work, reads extra tables, or writes to many documents, it extends the transaction's read/write set and increases the window for conflicts. Keep trigger logic minimal, or move expensive derived work to a scheduled function. - -### Write-then-read chains - -A mutation writes a document, then a reactive query re-reads it, then another mutation writes it again. Under load, these chains stack up. - -## Fix Order - -### 1. Reduce read set size - -Narrower reads mean fewer false conflicts. - -```ts -// Bad: broad scan creates a wide conflict surface -const allTasks = await ctx.db.query("tasks").collect(); -const mine = allTasks.filter((t) => t.ownerId === userId); -``` - -```ts -// Good: indexed query touches only relevant documents -const mine = await ctx.db - .query("tasks") - .withIndex("by_owner", (q) => q.eq("ownerId", userId)) - .collect(); -``` - -### 2. Split hot documents - -When many writers target the same document, split the contention point. - -```ts -// Bad: every vote increments the same counter document -const counter = await ctx.db.get(pollCounterId); -await ctx.db.patch(pollCounterId, { count: counter!.count + 1 }); -``` - -```ts -// Good: shard the counter across multiple documents, aggregate on read -const shardIndex = Math.floor(Math.random() * SHARD_COUNT); -const shardId = shardIds[shardIndex]; -const shard = await ctx.db.get(shardId); -await ctx.db.patch(shardId, { count: shard!.count + 1 }); -``` - -Aggregate the shards in a query or scheduled job when you need the total. - -### 3. Skip no-op writes - -Writes that do not change data still participate in conflict detection and trigger invalidation. - -```ts -// Bad: patches even when nothing changed -await ctx.db.patch(doc._id, { status: args.status }); -``` - -```ts -// Good: only write when the value actually differs -if (doc.status !== args.status) { - await ctx.db.patch(doc._id, { status: args.status }); -} -``` - -### 4. Move non-critical work to scheduled functions - -If a mutation does primary work plus secondary bookkeeping (analytics, notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. - -```ts -// Bad: analytics update in the same transaction as the user action -await ctx.db.patch(userId, { lastActiveAt: Date.now() }); -await ctx.db.insert("analytics", { event: "action", userId, ts: Date.now() }); -``` - -```ts -// Good: schedule the bookkeeping so the primary transaction is smaller -await ctx.db.patch(userId, { lastActiveAt: Date.now() }); -await ctx.scheduler.runAfter(0, internal.analytics.recordEvent, { - event: "action", - userId, -}); -``` - -### 5. Combine competing writes - -If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows. - -Do not introduce artificial locks or queues unless the above steps have been tried first. - -## Related: Invalidation Scope - -Splitting hot documents also reduces subscription invalidation, not just OCC contention. If a document is written frequently and read by many queries, those queries re-run on every write even when the fields they care about have not changed. See `subscription-cost.md` section 4 ("Isolate frequently-updated fields") for that pattern. - -## Verification - -1. OCC conflict rate has dropped in insights or dashboard -2. Mutation latency is lower and more consistent -3. No data correctness regressions from splitting or scheduling changes -4. Sibling writers to the same hot documents were fixed consistently diff --git a/.agent/skills/convex-performance-audit/references/subscription-cost.md b/.agent/skills/convex-performance-audit/references/subscription-cost.md deleted file mode 100644 index ae7d1adb..00000000 --- a/.agent/skills/convex-performance-audit/references/subscription-cost.md +++ /dev/null @@ -1,252 +0,0 @@ -# Subscription Cost - -Use these rules when the problem is too many reactive subscriptions, queries invalidating too frequently, or React components re-rendering excessively due to Convex state changes. - -## Core Principle - -Every `useQuery` and `usePaginatedQuery` call creates a live subscription. The server tracks the query's read set and re-executes the query whenever any document in that read set changes. Subscription cost scales with: - -`subscriptions x invalidation_frequency x query_cost` - -Subscriptions are not inherently bad. Convex reactivity is often the right default. The goal is to reduce unnecessary invalidation work, not to eliminate subscriptions on principle. - -## Symptoms - -- Dashboard shows high active subscription count -- UI feels sluggish or laggy despite fast individual queries -- React profiling shows frequent re-renders from Convex state -- Pages with many components each running their own `useQuery` -- Paginated lists where every loaded page stays subscribed - -## Common Causes - -### Reactive queries on low-freshness flows - -Some user flows are read-heavy and do not need live updates every time the underlying data changes. In those cases, ongoing subscriptions may cost more than they are worth. - -### Overly broad queries - -A query that returns a large result set invalidates whenever any document in that set changes. The broader the query, the more frequent the invalidation. - -### Too many subscriptions per page - -A page with 20 list items, each running its own `useQuery` to fetch related data, creates 20+ subscriptions per visitor. - -### Paginated queries keeping all pages live - -`usePaginatedQuery` with `loadMore` keeps every loaded page subscribed. On a page where a user has scrolled through 10 pages, all 10 stay reactive. - -### Frequently-updated fields on widely-read documents - -A document that many queries touch gets a frequently-updated field (like `lastSeen`, `lastActiveAt`, or a counter). Every write to that field invalidates every subscription that reads the document, even if those subscriptions never use the field. This is different from OCC conflicts (see `occ-conflicts.md`), which are write-vs-write contention. This is write-vs-subscription: the write succeeds fine, but it forces hundreds of queries to re-run for no reason. - -## Fix Order - -### 1. Use point-in-time reads when live updates are not valuable - -Keep `useQuery` and `usePaginatedQuery` by default when the product benefits from fresh live data. - -Consider a point-in-time read instead when all of these are true: - -- the flow is high-read -- the underlying data changes less often than users need to see -- explicit refresh, periodic refresh, or a fresh read on navigation is acceptable - -Possible implementations depend on environment: - -- a server-rendered fetch -- a framework helper like `fetchQuery` -- a point-in-time client read such as `ConvexHttpClient.query()` - -```ts -// Reactive by default when fresh live data matters -function TeamPresence() { - const presence = useQuery(api.teams.livePresence, { teamId }); - return ; -} -``` - -```ts -// Point-in-time read when explicit refresh is acceptable -import { ConvexHttpClient } from "convex/browser"; - -const client = new ConvexHttpClient(import.meta.env.VITE_CONVEX_URL); - -function SnapshotView() { - const [items, setItems] = useState([]); - - useEffect(() => { - client.query(api.items.snapshot).then(setItems); - }, []); - - return ; -} -``` - -Good candidates for point-in-time reads: - -- aggregate snapshots -- reports -- low-churn listings -- flows where explicit refresh is already acceptable - -Keep reactive for: - -- collaborative editing -- live dashboards -- presence-heavy views -- any surface where users expect fresh changes to appear automatically - -### 2. Batch related data into fewer queries - -Instead of N components each fetching their own related data, fetch it in a single query. - -```ts -// Bad: each card fetches its own author -function ProjectCard({ project }: { project: Project }) { - const author = useQuery(api.users.get, { id: project.authorId }); - return ; -} -``` - -```ts -// Good: parent query returns projects with author names included -function ProjectList() { - const projects = useQuery(api.projects.listWithAuthors); - return projects?.map((p) => ( - - )); -} -``` - -This can use denormalized fields or server-side joins in the query handler. Either way, it is one subscription instead of N. - -This is not automatically better. If the combined query becomes much broader and invalidates much more often, several narrower subscriptions may be the better tradeoff. Optimize for total invalidation cost, not raw subscription count. - -### 3. Use skip to avoid unnecessary subscriptions - -The `"skip"` value prevents a subscription from being created when the arguments are not ready. - -```ts -// Bad: subscribes with undefined args, wastes a subscription slot -const profile = useQuery(api.users.getProfile, { userId: selectedId! }); -``` - -```ts -// Good: skip when there is nothing to fetch -const profile = useQuery( - api.users.getProfile, - selectedId ? { userId: selectedId } : "skip", -); -``` - -### 4. Isolate frequently-updated fields into separate documents - -If a document is widely read but has a field that changes often, move that field to a separate document. Queries that do not need the field will no longer be invalidated by its writes. - -```ts -// Bad: lastSeen lives on the user doc, every heartbeat invalidates -// every query that reads this user -const users = defineTable({ - name: v.string(), - email: v.string(), - lastSeen: v.number(), -}); -``` - -```ts -// Good: lastSeen lives in a separate heartbeat doc -const users = defineTable({ - name: v.string(), - email: v.string(), - heartbeatId: v.id("heartbeats"), -}); - -const heartbeats = defineTable({ - lastSeen: v.number(), -}); -``` - -Queries that only need `name` and `email` no longer re-run on every heartbeat. Queries that actually need online status fetch the heartbeat document explicitly. - -For an even further optimization, if you only need a coarse online/offline boolean rather than the exact `lastSeen` timestamp, add a separate presence document with an `isOnline` flag. Update it immediately when a user comes online, and use a cron to batch-mark users offline when their heartbeat goes stale. This way the presence query only invalidates when online status actually changes, not on every heartbeat. - -### 5. Use the aggregate component for counts and sums - -Reactive global counts (`SELECT COUNT(*)` equivalent) invalidate on every insert or delete to the table. The [`@convex-dev/aggregate`](https://www.npmjs.com/package/@convex-dev/aggregate) component maintains denormalized COUNT, SUM, and MAX values efficiently so you do not need a reactive query scanning the full table. - -Use it for leaderboards, totals, "X items" badges, or any stat that would otherwise require scanning many rows reactively. - -If the aggregate component is not appropriate, prefer point-in-time reads for global stats, or precomputed summary rows updated by a cron or trigger, over reactive queries that scan large tables. - -### 6. Narrow query read sets - -Queries that return less data and touch fewer documents invalidate less often. - -```ts -// Bad: returns all fields, invalidates on any field change -export const list = query({ - handler: async (ctx) => { - return await ctx.db.query("projects").collect(); - }, -}); -``` - -```ts -// Good: use a digest table with only the fields the list needs -export const listDigests = query({ - handler: async (ctx) => { - return await ctx.db.query("projectDigests").collect(); - }, -}); -``` - -Writes to fields not in the digest table do not invalidate the digest query. - -### 7. Remove `Date.now()` from queries - -Using `Date.now()` inside a query defeats Convex's query cache. The cache is invalidated frequently to avoid showing stale time-dependent results, which increases database work even when the underlying data has not changed. - -```ts -// Bad: Date.now() defeats query caching and causes frequent re-evaluation -const releasedPosts = await ctx.db - .query("posts") - .withIndex("by_released_at", (q) => q.lte("releasedAt", Date.now())) - .take(100); -``` - -```ts -// Good: use a boolean field updated by a scheduled function -const releasedPosts = await ctx.db - .query("posts") - .withIndex("by_is_released", (q) => q.eq("isReleased", true)) - .take(100); -``` - -If the query must compare against a time value, pass it as an explicit argument from the client and round it to a coarse interval (e.g. the most recent minute) so requests within that window share the same cache entry. - -### 8. Consider pagination strategy - -For long lists where users scroll through many pages: - -- If the data does not need live updates, use point-in-time fetching with manual "load more" -- If it does need live updates, accept the subscription cost but limit the number of loaded pages -- Consider whether older pages can be unloaded as the user scrolls forward - -### 9. Separate backend cost from UI churn - -If the main problem is loading flash or UI churn when query arguments change, stabilizing the reactive UI behavior may be better than replacing reactivity altogether. - -Treat this as a UX problem first when: - -- the underlying query is already reasonably cheap -- the complaint is flicker, loading flashes, or re-render churn -- live updates are still desirable once fresh data arrives - -## Verification - -1. Subscription count in dashboard is lower for the affected pages -2. UI responsiveness has improved -3. React profiling shows fewer unnecessary re-renders -4. Surfaces that do not need live updates are not paying for persistent subscriptions unnecessarily -5. Sibling pages with similar patterns were updated consistently diff --git a/.agent/skills/convex-quickstart/SKILL.md b/.agent/skills/convex-quickstart/SKILL.md deleted file mode 100644 index 369a6c9b..00000000 --- a/.agent/skills/convex-quickstart/SKILL.md +++ /dev/null @@ -1,337 +0,0 @@ ---- -name: convex-quickstart -description: Initialize a new Convex project from scratch or add Convex to an existing app. Use when starting a new project with Convex, scaffolding a Convex app, or integrating Convex into an existing frontend. ---- - -# Convex Quickstart - -Set up a working Convex project as fast as possible. - -## When to Use - -- Starting a brand new project with Convex -- Adding Convex to an existing React, Next.js, Vue, Svelte, or other app -- Scaffolding a Convex app for prototyping - -## When Not to Use - -- The project already has Convex installed and `convex/` exists - just start building -- You only need to add auth to an existing Convex app - use the `convex-setup-auth` skill - -## Workflow - -1. Determine the starting point: new project or existing app -2. If new project, pick a template and scaffold with `npm create convex@latest` -3. If existing app, install `convex` and wire up the provider -4. Run `npx convex dev` to connect a deployment and start the dev loop -5. Verify the setup works - -## Path 1: New Project (Recommended) - -Use the official scaffolding tool. It creates a complete project with the frontend framework, Convex backend, and all config wired together. - -### Pick a template - -| Template | Stack | -|----------|-------| -| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | -| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | -| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | -| `nextjs-clerk` | Next.js + Clerk auth | -| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | -| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | -| `bare` | Convex backend only, no frontend | - -If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes. - -You can also use any GitHub repo as a template: - -```bash -npm create convex@latest my-app -- -t owner/repo -npm create convex@latest my-app -- -t owner/repo#branch -``` - -### Scaffold the project - -Always pass the project name and template flag to avoid interactive prompts: - -```bash -npm create convex@latest my-app -- -t react-vite-shadcn -cd my-app -npm install -``` - -The scaffolding tool creates files but does not run `npm install`, so you must run it yourself. - -To scaffold in the current directory (if it is empty): - -```bash -npm create convex@latest . -- -t react-vite-shadcn -npm install -``` - -### Start the dev loop - -`npx convex dev` is a long-running watcher process that syncs backend code to a Convex deployment on every save. It also requires authentication on first run (browser-based OAuth). Both of these make it unsuitable for an agent to run directly. - -**Ask the user to run this themselves:** - -Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will: -- Create a Convex project and dev deployment -- Write the deployment URL to `.env.local` -- Create the `convex/` directory with generated types -- Watch for changes and sync continuously - -The user should keep `npx convex dev` running in the background while you work on code. The watcher will automatically pick up any files you create or edit in `convex/`. - -**Exception - cloud agents (Codex, Jules, Devin):** These environments cannot open a browser for login. See the Agent Mode section below for how to run anonymously without user interaction. - -### Start the frontend - -The user should also run the frontend dev server in a separate terminal: - -```bash -npm run dev -``` - -Vite apps serve on `http://localhost:5173`, Next.js on `http://localhost:3000`. - -### What you get - -After scaffolding, the project structure looks like: - -``` -my-app/ - convex/ # Backend functions and schema - _generated/ # Auto-generated types (check this into git) - schema.ts # Database schema (if template includes one) - src/ # Frontend code (or app/ for Next.js) - package.json - .env.local # CONVEX_URL / VITE_CONVEX_URL / NEXT_PUBLIC_CONVEX_URL -``` - -The template already has: -- `ConvexProvider` wired into the app root -- Correct env var names for the framework -- Tailwind and shadcn/ui ready (for shadcn templates) -- Auth provider configured (for auth templates) - -You are ready to start adding schema, functions, and UI. - -## Path 2: Add Convex to an Existing App - -Use this when the user already has a frontend project and wants to add Convex as the backend. - -### Install - -```bash -npm install convex -``` - -### Initialize and start dev loop - -Ask the user to run `npx convex dev` in their terminal. This handles login, creates the `convex/` directory, writes the deployment URL to `.env.local`, and starts the file watcher. See the notes in Path 1 about why the agent should not run this directly. - -### Wire up the provider - -The Convex client must wrap the app at the root. The setup varies by framework. - -Create the `ConvexReactClient` at module scope, not inside a component: - -```tsx -// Bad: re-creates the client on every render -function App() { - const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); - return ...; -} - -// Good: created once at module scope -const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); -function App() { - return ...; -} -``` - -#### React (Vite) - -```tsx -// src/main.tsx -import { StrictMode } from "react"; -import { createRoot } from "react-dom/client"; -import { ConvexProvider, ConvexReactClient } from "convex/react"; -import App from "./App"; - -const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); - -createRoot(document.getElementById("root")!).render( - - - - - , -); -``` - -#### Next.js (App Router) - -```tsx -// app/ConvexClientProvider.tsx -"use client"; - -import { ConvexProvider, ConvexReactClient } from "convex/react"; -import { ReactNode } from "react"; - -const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); - -export function ConvexClientProvider({ children }: { children: ReactNode }) { - return {children}; -} -``` - -```tsx -// app/layout.tsx -import { ConvexClientProvider } from "./ConvexClientProvider"; - -export default function RootLayout({ children }: { children: React.ReactNode }) { - return ( - - - {children} - - - ); -} -``` - -#### Other frameworks - -For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the matching quickstart guide: - -- [Vue](https://docs.convex.dev/quickstart/vue) -- [Svelte](https://docs.convex.dev/quickstart/svelte) -- [React Native](https://docs.convex.dev/quickstart/react-native) -- [TanStack Start](https://docs.convex.dev/quickstart/tanstack-start) -- [Remix](https://docs.convex.dev/quickstart/remix) -- [Node.js (no frontend)](https://docs.convex.dev/quickstart/nodejs) - -### Environment variables - -The env var name depends on the framework: - -| Framework | Variable | -|-----------|----------| -| Vite | `VITE_CONVEX_URL` | -| Next.js | `NEXT_PUBLIC_CONVEX_URL` | -| Remix | `CONVEX_URL` | -| React Native | `EXPO_PUBLIC_CONVEX_URL` | - -`npx convex dev` writes the correct variable to `.env.local` automatically. - -## Agent Mode (Cloud-Based Agents) - -When running in a cloud-based agent environment (Codex, Jules, Devin, Cursor Background Agents) where you cannot log in interactively, set `CONVEX_AGENT_MODE=anonymous` to use a local anonymous deployment. - -Add `CONVEX_AGENT_MODE=anonymous` to `.env.local`, or set it inline: - -```bash -CONVEX_AGENT_MODE=anonymous npx convex dev -``` - -This runs a local Convex backend on the VM without requiring authentication, and avoids conflicting with the user's personal dev deployment. - -## Verify the Setup - -After setup, confirm everything is working: - -1. The user confirms `npx convex dev` is running without errors -2. The `convex/_generated/` directory exists and has `api.ts` and `server.ts` -3. `.env.local` contains the deployment URL - -## Writing Your First Function - -Once the project is set up, create a schema and a query to verify the full loop works. - -`convex/schema.ts`: - -```ts -import { defineSchema, defineTable } from "convex/server"; -import { v } from "convex/values"; - -export default defineSchema({ - tasks: defineTable({ - text: v.string(), - completed: v.boolean(), - }), -}); -``` - -`convex/tasks.ts`: - -```ts -import { query, mutation } from "./_generated/server"; -import { v } from "convex/values"; - -export const list = query({ - args: {}, - handler: async (ctx) => { - return await ctx.db.query("tasks").collect(); - }, -}); - -export const create = mutation({ - args: { text: v.string() }, - handler: async (ctx, args) => { - await ctx.db.insert("tasks", { text: args.text, completed: false }); - }, -}); -``` - -Use in a React component (adjust the import path based on your file location relative to `convex/`): - -```tsx -import { useQuery, useMutation } from "convex/react"; -import { api } from "../convex/_generated/api"; - -function Tasks() { - const tasks = useQuery(api.tasks.list); - const create = useMutation(api.tasks.create); - - return ( -
- - {tasks?.map((t) =>
{t.text}
)} -
- ); -} -``` - -## Development vs Production - -Always use `npx convex dev` during development. It runs against your personal dev deployment and syncs code on save. - -When ready to ship, deploy to production: - -```bash -npx convex deploy -``` - -This pushes to the production deployment, which is separate from dev. Do not use `deploy` during development. - -## Next Steps - -- Add authentication: use the `convex-setup-auth` skill -- Design your schema: see [Schema docs](https://docs.convex.dev/database/schemas) -- Build components: use the `convex-create-component` skill -- Plan a migration: use the `convex-migration-helper` skill -- Add file storage: see [File Storage docs](https://docs.convex.dev/file-storage) -- Set up cron jobs: see [Scheduling docs](https://docs.convex.dev/scheduling) - -## Checklist - -- [ ] Determined starting point: new project or existing app -- [ ] If new project: scaffolded with `npm create convex@latest` using appropriate template -- [ ] If existing app: installed `convex` and wired up the provider -- [ ] User has `npx convex dev` running and connected to a deployment -- [ ] `convex/_generated/` directory exists with types -- [ ] `.env.local` has the deployment URL -- [ ] Verified a basic query/mutation round-trip works diff --git a/.agent/skills/convex-quickstart/agents/openai.yaml b/.agent/skills/convex-quickstart/agents/openai.yaml deleted file mode 100644 index a51a6d09..00000000 --- a/.agent/skills/convex-quickstart/agents/openai.yaml +++ /dev/null @@ -1,10 +0,0 @@ -interface: - display_name: "Convex Quickstart" - short_description: "Start a new Convex app or add Convex to an existing frontend." - icon_small: "./assets/icon.svg" - icon_large: "./assets/icon.svg" - brand_color: "#F97316" - default_prompt: "Set up Convex for this project as fast as possible. First decide whether this is a new app or an existing app, then scaffold or integrate Convex and verify the setup works." - -policy: - allow_implicit_invocation: true diff --git a/.agent/skills/convex-quickstart/assets/icon.svg b/.agent/skills/convex-quickstart/assets/icon.svg deleted file mode 100644 index d83a73f3..00000000 --- a/.agent/skills/convex-quickstart/assets/icon.svg +++ /dev/null @@ -1,4 +0,0 @@ - diff --git a/.agent/skills/convex-setup-auth/SKILL.md b/.agent/skills/convex-setup-auth/SKILL.md deleted file mode 100644 index 5c0c994a..00000000 --- a/.agent/skills/convex-setup-auth/SKILL.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -name: convex-setup-auth -description: Set up Convex authentication with proper user management, identity mapping, and access control patterns. Use when implementing auth flows. ---- - -# Convex Authentication Setup - -Implement secure authentication in Convex with user management and access control. - -## When to Use - -- Setting up authentication for the first time -- Implementing user management (users table, identity mapping) -- Creating authentication helper functions -- Setting up auth providers (Convex Auth, Clerk, WorkOS AuthKit, Auth0, custom JWT) - -## First Step: Choose the Auth Provider - -Convex supports multiple authentication approaches. Do not assume a provider. - -Before writing setup code: - -1. Ask the user which auth solution they want, unless the repository already makes it obvious -2. If the repo already uses a provider, continue with that provider unless the user wants to switch -3. If the user has not chosen a provider and the repo does not make it obvious, ask before proceeding - -Common options: - -- [Convex Auth](https://docs.convex.dev/auth/convex-auth) - good default when the user wants auth handled directly in Convex -- [Clerk](https://docs.convex.dev/auth/clerk) - use when the app already uses Clerk or the user wants Clerk's hosted auth features -- [WorkOS AuthKit](https://docs.convex.dev/auth/authkit/) - use when the app already uses WorkOS or the user wants AuthKit specifically -- [Auth0](https://docs.convex.dev/auth/auth0) - use when the app already uses Auth0 -- Custom JWT provider - use when integrating an existing auth system not covered above - -Look for signals in the repo before asking: - -- Dependencies such as `@clerk/*`, `@workos-inc/*`, `@auth0/*`, or Convex Auth packages -- Existing files such as `convex/auth.config.ts`, auth middleware, provider wrappers, or login components -- Environment variables that clearly point at a provider - -## After Choosing a Provider - -Read the provider's official guide and the matching local reference file: - -- Convex Auth: [official docs](https://docs.convex.dev/auth/convex-auth), then `references/convex-auth.md` -- Clerk: [official docs](https://docs.convex.dev/auth/clerk), then `references/clerk.md` -- WorkOS AuthKit: [official docs](https://docs.convex.dev/auth/authkit/), then `references/workos-authkit.md` -- Auth0: [official docs](https://docs.convex.dev/auth/auth0), then `references/auth0.md` - -The local reference files contain the concrete workflow, expected files and env vars, gotchas, and validation checks. - -Use those sources for: - -- package installation -- client provider wiring -- environment variables -- `convex/auth.config.ts` setup -- login and logout UI patterns -- framework-specific setup for React, Vite, or Next.js - -For shared auth behavior, use the official Convex docs as the source of truth: - -- [Auth in Functions](https://docs.convex.dev/auth/functions-auth) for `ctx.auth.getUserIdentity()` -- [Storing Users in the Convex Database](https://docs.convex.dev/auth/database-auth) for optional app-level user storage -- [Authentication](https://docs.convex.dev/auth) for general auth and authorization guidance -- [Convex Auth Authorization](https://labs.convex.dev/auth/authz) when the provider is Convex Auth - -Do not invent a provider-agnostic user sync pattern from memory. -For third-party providers, only add app-level user storage if the app actually needs user documents in Convex. -For Convex Auth, do not add a parallel `users` table plus `storeUser` flow. Follow the Convex Auth docs and built-in auth tables instead. - -Do not invent provider-specific setup from memory when the docs are available. -Do not assume provider initialization commands finish the entire integration. Verify generated files and complete the post-init wiring steps the provider reference calls out. - -## Workflow - -1. Determine the provider, either by asking the user or inferring from the repo -2. Ask whether the user wants local-only setup or production-ready setup now -3. Read the matching provider reference file -4. Follow the official provider docs for current setup details -5. Follow the official Convex docs for shared backend auth behavior, user storage, and authorization patterns -6. Only add app-level user storage if the docs and app requirements call for it -7. Add authorization checks for ownership, roles, or team access only where the app needs them -8. Verify login state, protected queries, environment variables, and production configuration if requested - -If the flow blocks on interactive provider or deployment setup, ask the user explicitly for the exact human step needed, then continue after they complete it. -For UI-facing auth flows, offer to validate the real sign-up or sign-in flow after setup is done. -If the environment has browser automation tools, you can use them. -If it does not, give the user a short manual validation checklist instead. - -## Reference Files - -### Provider References - -- `references/convex-auth.md` -- `references/clerk.md` -- `references/workos-authkit.md` -- `references/auth0.md` - -## Checklist - -- [ ] Chosen the correct auth provider before writing setup code -- [ ] Read the relevant provider reference file -- [ ] Asked whether the user wants local-only setup or production-ready setup -- [ ] Used the official provider docs for provider-specific wiring -- [ ] Used the official Convex docs for shared auth behavior and authorization patterns -- [ ] Only added app-level user storage if the app actually needs it -- [ ] Did not invent a cross-provider `users` table or `storeUser` flow for Convex Auth -- [ ] Added authentication checks in protected backend functions -- [ ] Added authorization checks where the app actually needs them -- [ ] Clear error messages ("Not authenticated", "Unauthorized") -- [ ] Client auth provider configured for the chosen provider -- [ ] If requested, production auth setup is covered too diff --git a/.agent/skills/convex-setup-auth/agents/openai.yaml b/.agent/skills/convex-setup-auth/agents/openai.yaml deleted file mode 100644 index d1c90a14..00000000 --- a/.agent/skills/convex-setup-auth/agents/openai.yaml +++ /dev/null @@ -1,10 +0,0 @@ -interface: - display_name: "Convex Setup Auth" - short_description: "Set up Convex auth, user identity mapping, and access control." - icon_small: "./assets/icon.svg" - icon_large: "./assets/icon.svg" - brand_color: "#2563EB" - default_prompt: "Set up authentication for this Convex app. Figure out the provider first, then wire up the user model, identity mapping, and access control with the smallest solid implementation." - -policy: - allow_implicit_invocation: true diff --git a/.agent/skills/convex-setup-auth/assets/icon.svg b/.agent/skills/convex-setup-auth/assets/icon.svg deleted file mode 100644 index 4917dbb4..00000000 --- a/.agent/skills/convex-setup-auth/assets/icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - diff --git a/.agent/skills/convex-setup-auth/references/auth0.md b/.agent/skills/convex-setup-auth/references/auth0.md deleted file mode 100644 index 9c729c5a..00000000 --- a/.agent/skills/convex-setup-auth/references/auth0.md +++ /dev/null @@ -1,116 +0,0 @@ -# Auth0 - -Official docs: - -- https://docs.convex.dev/auth/auth0 -- https://auth0.github.io/auth0-cli/ -- https://auth0.github.io/auth0-cli/auth0_apps_create.html - -Use this when the app already uses Auth0 or the user wants Auth0 specifically. - -## Workflow - -1. Confirm the user wants Auth0 -2. Determine the app framework and whether Auth0 is already partly set up -3. Ask whether the user wants local-only setup or production-ready setup now -4. Read the official Convex and Auth0 guides before making changes -5. Ask whether they want the fastest setup path by installing the Auth0 CLI -6. If they agree, install the Auth0 CLI and do as much of the Auth0 app setup as possible through the CLI -7. If they do not want the CLI path, use the Auth0 dashboard path instead -8. Complete the relevant Auth0 frontend quickstart if the app does not already have Auth0 wired up -9. Configure `convex/auth.config.ts` with the Auth0 domain and client ID -10. Set environment variables for local and production environments -11. Wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` -12. Gate Convex-backed UI with Convex auth state -13. Try to verify Convex reports the user as authenticated after Auth0 login -14. If the refresh-token path fails, stop improvising and send the user back to the official docs -15. If the user wants production-ready setup, make sure the production Auth0 tenant and env vars are also covered - -## What To Do - -- Read the official Convex and Auth0 guide before writing setup code -- Prefer the Auth0 CLI path for mechanical setup if the user is willing to install it, but do not present it as a fully validated end-to-end path yet -- Ask the user directly: "The fastest path is to install the Auth0 CLI so I can do more of this for you. If you want, I can install it and then only ask you to log in when needed. Would you like me to do that?" -- Make sure the app has already completed the relevant Auth0 quickstart for its frontend -- Use the official examples for `Auth0Provider` and `ConvexProviderWithAuth0` -- If the Auth0 login or refresh flow starts failing in a way that is not clearly explained by the docs, say that plainly and fall back to the official docs instead of pretending the flow is validated - -## Key Setup Areas - -- install the Auth0 SDK for the app's framework -- configure `convex/auth.config.ts` with the Auth0 domain and client ID -- set environment variables for local and production environments -- wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` -- use Convex auth state when gating Convex-backed UI - -## Files and Env Vars To Expect - -- `convex/auth.config.ts` -- frontend app entry or provider wrapper -- Auth0 CLI install docs: `https://auth0.github.io/auth0-cli/` -- Auth0 environment variables commonly include: - - `AUTH0_DOMAIN` - - `AUTH0_CLIENT_ID` - - `VITE_AUTH0_DOMAIN` - - `VITE_AUTH0_CLIENT_ID` - -## Concrete Steps - -1. Start by reading `https://docs.convex.dev/auth/auth0` and the relevant Auth0 quickstart for the app's framework -2. Ask whether the user wants the Auth0 CLI path -3. If yes, install Auth0 CLI and have the user authenticate it with `auth0 login` -4. Use `auth0 apps create` with SPA settings, callback URL, logout URL, and web origins if creating a new app -5. If not using the CLI path, complete the relevant Auth0 frontend quickstart and create the Auth0 app in the dashboard -6. Get the Auth0 domain and client ID from the CLI output or the Auth0 dashboard -7. Install the Auth0 SDK for the app's framework -8. Create or update `convex/auth.config.ts` with the Auth0 domain and client ID -9. Set frontend and backend environment variables -10. Wrap the app in `Auth0Provider` -11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithAuth0` -12. Run the normal Convex dev or deploy flow after backend config changes -13. Try the official provider config shown in the Convex docs -14. If login works but Convex auth or token refresh fails in a way you cannot clearly resolve, stop and tell the user to follow the official docs manually for now -15. Only claim success if the user can sign in and Convex recognizes the authenticated session -16. If the user wants production-ready setup, configure the production Auth0 tenant values and production environment variables too - -## Gotchas - -- The Convex docs assume the Auth0 side is already set up, so do not skip the Auth0 quickstart if the app is starting from scratch -- The Auth0 CLI is often the fastest path for a fresh setup, but it still requires the user to authenticate the CLI to their Auth0 tenant -- If the user agrees to install the Auth0 CLI, do the mechanical setup yourself instead of bouncing them through the dashboard -- If login succeeds but Convex still reports unauthenticated, double-check `convex/auth.config.ts` and whether the backend config was synced -- We were able to automate Auth0 app creation and Convex config wiring, but we did not fully validate the refresh-token path end to end -- In validation, the documented `useRefreshTokens={true}` and `cacheLocation="localstorage"` setup hit refresh-token failures, so do not present that path as settled -- If you hit Auth0 errors like `Unknown or invalid refresh token`, do not keep inventing fixes indefinitely, send the user back to the official docs and explain that this path is still under investigation -- Keep dev and prod tenants separate if the project uses different Auth0 environments -- Do not confuse "Auth0 login works" with "Convex can validate the Auth0 token". Both need to work. -- If the repo already uses Auth0, preserve existing redirect and tenant configuration unless the user asked to change it. -- Do not assume the local Auth0 tenant settings match production. Verify the production domain, client ID, and callback URLs separately. -- For local dev, make sure the Auth0 app settings match the app's real local port for callback URLs, logout URLs, and web origins - -## Production - -- Ask whether the user wants dev-only setup or production-ready setup -- If the answer is production-ready, make sure the production Auth0 tenant values, callback URLs, and Convex deployment config are all covered -- Verify production environment variables and redirect settings before calling the task complete -- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. - -## Validation - -- Verify the user can complete the Auth0 login flow -- Verify Convex-authenticated UI renders only after Convex auth state is ready -- Verify protected Convex queries succeed after login -- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions -- Verify the Auth0 app settings match the real local callback and logout URLs during development -- If the Auth0 refresh-token path fails, mark the setup as not fully validated and direct the user to the official docs instead of claiming the skill completed successfully -- If production-ready setup was requested, verify the production Auth0 configuration is also covered - -## Checklist - -- [ ] Confirm the user wants Auth0 -- [ ] Ask whether the user wants local-only setup or production-ready setup -- [ ] Complete the relevant Auth0 frontend setup -- [ ] Configure `convex/auth.config.ts` -- [ ] Set environment variables -- [ ] Verify Convex authenticated state after login, or explicitly tell the user this path is still under investigation and send them to the official docs -- [ ] If requested, configure the production deployment too diff --git a/.agent/skills/convex-setup-auth/references/clerk.md b/.agent/skills/convex-setup-auth/references/clerk.md deleted file mode 100644 index 7dbde194..00000000 --- a/.agent/skills/convex-setup-auth/references/clerk.md +++ /dev/null @@ -1,113 +0,0 @@ -# Clerk - -Official docs: - -- https://docs.convex.dev/auth/clerk -- https://clerk.com/docs/guides/development/integrations/databases/convex - -Use this when the app already uses Clerk or the user wants Clerk's hosted auth features. - -## Workflow - -1. Confirm the user wants Clerk -2. Make sure the user has a Clerk account and a Clerk application -3. Determine the app framework: - - React - - Next.js - - TanStack Start -4. Ask whether the user wants local-only setup or production-ready setup now -5. Gather the Clerk keys and the Clerk Frontend API URL -6. Follow the correct framework section in the official docs -7. Complete the backend and client wiring -8. Verify Convex reports the user as authenticated after login -9. If the user wants production-ready setup, make sure the production Clerk config is also covered - -## What To Do - -- Read the official Convex and Clerk guide before writing setup code -- If the user does not already have Clerk set up, send them to `https://dashboard.clerk.com/sign-up` to create an account and `https://dashboard.clerk.com/apps/new` to create an application -- Send the user to `https://dashboard.clerk.com/apps/setup/convex` if the Convex integration is not already active -- Match the guide to the app's framework, usually React, Next.js, or TanStack Start -- Use the official examples for `ConvexProviderWithClerk`, `ClerkProvider`, and `useAuth` - -## Key Setup Areas - -- install the Clerk SDK for the framework in use -- configure `convex/auth.config.ts` with the Clerk issuer domain -- set the required Clerk environment variables -- wrap the app with `ClerkProvider` and `ConvexProviderWithClerk` -- use Convex auth-aware UI patterns such as `Authenticated`, `Unauthenticated`, and `AuthLoading` - -## Files and Env Vars To Expect - -- `convex/auth.config.ts` -- React or Vite client entry such as `src/main.tsx` -- Next.js client wrapper for Convex if using App Router -- Clerk account sign-up page: `https://dashboard.clerk.com/sign-up` -- Clerk app creation page: `https://dashboard.clerk.com/apps/new` -- Clerk Convex integration page: `https://dashboard.clerk.com/apps/setup/convex` -- Clerk API keys page: `https://dashboard.clerk.com/last-active?path=api-keys` -- Clerk environment variables: - - `CLERK_JWT_ISSUER_DOMAIN` for Convex backend validation in the Convex docs - - `CLERK_FRONTEND_API_URL` in the Clerk docs - - `VITE_CLERK_PUBLISHABLE_KEY` for Vite apps - - `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` for Next.js apps - - `CLERK_SECRET_KEY` for Next.js server-side Clerk setup where required - -`CLERK_JWT_ISSUER_DOMAIN` and `CLERK_FRONTEND_API_URL` refer to the same Clerk Frontend API URL value. Do not treat them as two different URLs. - -## Concrete Steps - -1. If needed, create a Clerk account at `https://dashboard.clerk.com/sign-up` -2. If needed, create a Clerk application at `https://dashboard.clerk.com/apps/new` -3. Open `https://dashboard.clerk.com/last-active?path=api-keys` and copy the publishable key, plus the secret key for Next.js where needed -4. Open `https://dashboard.clerk.com/apps/setup/convex` -5. Activate the Convex integration in Clerk if it is not already active -6. Copy the Clerk Frontend API URL shown there -7. Install the Clerk package for the app's framework -8. Create or update `convex/auth.config.ts` so Convex validates Clerk tokens -9. Set the publishable key in the frontend environment -10. Set the issuer domain or Frontend API URL so Convex can validate the JWT -11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithClerk` -12. Wrap the app in `ClerkProvider` -13. Use Convex auth helpers for authenticated rendering -14. Run the normal Convex dev or deploy flow after updating backend auth config -15. If the user wants production-ready setup, configure the production Clerk values and production issuer domain too - -## Gotchas - -- Prefer `useConvexAuth()` over raw Clerk auth state when deciding whether Convex-authenticated UI can render -- For Next.js, keep server and client boundaries in mind when creating the Convex provider wrapper -- After changing `convex/auth.config.ts`, run the normal Convex dev or deploy flow so the backend picks up the new config -- Do not stop at "Clerk login works". The important check is that Convex also sees the session and can authenticate requests. -- If the repo already uses Clerk, preserve its existing auth flow unless the user asked to change it. -- Do not assume the same Clerk values work for both dev and production. Check the production issuer domain and publishable key separately. -- The Convex setup page is where you get the Clerk Frontend API URL for Convex. Keep using the Clerk API keys page for the publishable key and the secret key. -- If Convex says no auth provider matched the token, first confirm the Clerk Convex integration was activated at `https://dashboard.clerk.com/apps/setup/convex` -- After activating the Clerk Convex integration, sign out completely and sign back in before retesting. An old Clerk session can keep using a token that Convex rejects. - -## Production - -- Ask whether the user wants dev-only setup or production-ready setup -- If the answer is production-ready, make sure production Clerk keys and issuer configuration are included -- Verify production redirect URLs and any production Clerk domain values before calling the task complete -- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. - -## Validation - -- Verify the user can sign in with Clerk -- If the Clerk integration was just activated, verify after a full Clerk sign-out and fresh sign-in -- Verify `useConvexAuth()` reaches the authenticated state after Clerk login -- Verify protected Convex queries run successfully inside authenticated UI -- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions -- If production-ready setup was requested, verify the production Clerk configuration is also covered - -## Checklist - -- [ ] Confirm the user wants Clerk -- [ ] Ask whether the user wants local-only setup or production-ready setup -- [ ] Follow the correct framework section in the official guide -- [ ] Set Clerk environment variables -- [ ] Configure `convex/auth.config.ts` -- [ ] Verify Convex authenticated state after login -- [ ] If requested, configure the production deployment too diff --git a/.agent/skills/convex-setup-auth/references/convex-auth.md b/.agent/skills/convex-setup-auth/references/convex-auth.md deleted file mode 100644 index d4824d24..00000000 --- a/.agent/skills/convex-setup-auth/references/convex-auth.md +++ /dev/null @@ -1,143 +0,0 @@ -# Convex Auth - -Official docs: https://docs.convex.dev/auth/convex-auth -Setup guide: https://labs.convex.dev/auth/setup - -Use this when the user wants auth handled directly in Convex rather than through a third-party provider. - -## Workflow - -1. Confirm the user wants Convex Auth specifically -2. Determine which sign-in methods the app needs: - - magic links or OTPs - - OAuth providers - - passwords and password reset -3. Ask whether the user wants local-only setup or production-ready setup now -4. Read the Convex Auth setup guide before writing code -5. Make sure the project has a configured Convex deployment: - - run `npx convex dev` first if `CONVEX_DEPLOYMENT` is not set - - if CLI configuration requires interactive human input, stop and ask the user to complete that step before continuing -6. Install the auth packages: - - `npm install @convex-dev/auth @auth/core@0.37.0` -7. Run the initialization command: - - `npx @convex-dev/auth` -8. Confirm the initializer created: - - `convex/auth.config.ts` - - `convex/auth.ts` - - `convex/http.ts` -9. Add the required `authTables` to `convex/schema.ts` -10. Replace plain `ConvexProvider` wiring with `ConvexAuthProvider` -11. Configure at least one auth method in `convex/auth.ts` -12. Run `npx convex dev --once` or the normal dev flow to push the updated schema and generated code -13. Verify the client can sign in successfully -14. Verify Convex receives authenticated identity in backend functions -15. If the user wants production-ready setup, make sure the same auth setup is configured for the production deployment as well -16. Only add a `users` table and `storeUser` flow if the app needs app-level user records inside Convex - -## What This Reference Is For - -- choosing Convex Auth as the default provider for a new Convex app -- understanding whether the app wants magic links, OTPs, OAuth, or passwords -- keeping the setup provider-specific while using the official Convex Auth docs for identity and authorization behavior - -## What To Do - -- Read the Convex Auth setup guide before writing setup code -- Follow the setup flow from the docs rather than recreating it from memory -- If the app is new, consider starting from the official starter flow instead of hand-wiring everything -- Treat `npx @convex-dev/auth` as a required initialization step for existing apps, not an optional extra - -## Concrete Steps - -1. Install `@convex-dev/auth` and `@auth/core@0.37.0` -2. Run `npx convex dev` if the project does not already have a configured deployment -3. If `npx convex dev` blocks on interactive setup, ask the user explicitly to finish configuring the Convex deployment -4. Run `npx @convex-dev/auth` -5. Confirm the generated auth setup is present before continuing: - - `convex/auth.config.ts` - - `convex/auth.ts` - - `convex/http.ts` -6. Add `authTables` to `convex/schema.ts` -7. Replace `ConvexProvider` with `ConvexAuthProvider` in the app entry -8. Configure the selected auth methods in `convex/auth.ts` -9. Run `npx convex dev --once` or the normal dev flow so the updated schema and auth files are pushed -10. Verify login locally -11. If the user wants production-ready setup, repeat the required auth configuration against the production deployment - -## Expected Files and Decisions - -- `convex/schema.ts` -- frontend app entry such as `src/main.tsx` or the framework-equivalent provider file -- generated Convex Auth setup produced by `npx @convex-dev/auth` -- an existing configured Convex deployment, or the ability to create one with `npx convex dev` -- `convex/auth.ts` starts with `providers: []` until the app configures actual sign-in methods - -- Decide whether the user is creating a new app or adding auth to an existing app -- For a new app, prefer the official starter flow instead of rebuilding setup by hand -- Decide which auth methods the app needs: - - magic links or OTPs - - OAuth providers - - passwords -- Decide whether the user wants local-only setup or production-ready setup now -- Decide whether the app actually needs a `users` table inside Convex, or whether provider identity alone is enough - -## Gotchas - -- Do not assume a specific sign-in method. Ask which methods the app needs before wiring UI and backend behavior. -- `npx @convex-dev/auth` is important because it initializes the auth setup, including the key material. Do not skip it when adding Convex Auth to an existing project. -- `npx @convex-dev/auth` will fail if the project does not already have a configured `CONVEX_DEPLOYMENT`. -- `npx convex dev` may require interactive setup for deployment creation or project selection. If that happens, ask the user explicitly for that human step instead of guessing. -- `npx @convex-dev/auth` does not finish the whole integration by itself. You still need to add `authTables`, swap in `ConvexAuthProvider`, and configure at least one auth method. -- A project can still build even if `convex/auth.ts` still has `providers: []`, so do not treat a successful build as proof that sign-in is fully configured. -- Convex Auth does not mean every app needs a `users` table. If the app only needs authentication gates, `ctx.auth.getUserIdentity()` may be enough. -- If the app is greenfield, starting from the official starter flow is usually better than partially recreating it by hand. -- Do not stop at local dev setup if the user expects production-ready auth. The production deployment needs the auth setup too. -- Keep provider-specific setup and Convex Auth authorization behavior in the official docs instead of inventing shared patterns from memory. - -## Production - -- Ask whether the user wants dev-only setup or production-ready setup -- If the answer is production-ready, make sure the auth configuration is applied to the production deployment, not just the dev deployment -- Verify production-specific redirect URLs, auth method configuration, and deployment settings before calling the task complete -- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. - -## Human Handoff - -If `npx convex dev` or deployment setup requires human input: - -- stop and explain exactly what the user needs to do -- say why that step is required -- resume the auth setup immediately after the user confirms it is done - -## Validation - -- Verify the user can complete a sign-in flow -- Offer to validate sign up, sign out, and sign back in with the configured auth method -- If browser automation is available in the environment, you can do this directly -- If browser automation is not available, give the user a short manual validation checklist instead -- Verify `ctx.auth.getUserIdentity()` returns an identity in protected backend functions -- Verify protected UI only renders after Convex-authenticated state is ready -- Verify environment variables and redirect settings match the current app environment -- Verify `convex/auth.ts` no longer has an empty `providers: []` configuration once the app is meant to support real sign-in -- Run `npx convex dev --once` or the normal dev flow after setup changes and confirm Convex codegen and push succeed -- If production-ready setup was requested, verify the production deployment is also configured correctly - -## Checklist - -- [ ] Confirm the user wants Convex Auth specifically -- [ ] Ask whether the user wants local-only setup or production-ready setup -- [ ] Ensure a Convex deployment is configured before running auth initialization -- [ ] Install `@convex-dev/auth` and `@auth/core@0.37.0` -- [ ] Run `npx convex dev` first if needed -- [ ] Run `npx @convex-dev/auth` -- [ ] Confirm `convex/auth.config.ts`, `convex/auth.ts`, and `convex/http.ts` were created -- [ ] Follow the setup guide for package install and wiring -- [ ] Add `authTables` to `convex/schema.ts` -- [ ] Replace `ConvexProvider` with `ConvexAuthProvider` -- [ ] Configure at least one auth method in `convex/auth.ts` -- [ ] Run `npx convex dev --once` or the normal dev flow after setup changes -- [ ] Confirm which sign-in methods the app needs -- [ ] Verify the client can sign in and the backend receives authenticated identity -- [ ] Offer end-to-end validation of sign up, sign out, and sign back in -- [ ] If requested, configure the production deployment too -- [ ] Only add extra `users` table sync if the app needs app-level user records diff --git a/.agent/skills/convex-setup-auth/references/workos-authkit.md b/.agent/skills/convex-setup-auth/references/workos-authkit.md deleted file mode 100644 index 038cb9f3..00000000 --- a/.agent/skills/convex-setup-auth/references/workos-authkit.md +++ /dev/null @@ -1,114 +0,0 @@ -# WorkOS AuthKit - -Official docs: - -- https://docs.convex.dev/auth/authkit/ -- https://docs.convex.dev/auth/authkit/add-to-app -- https://docs.convex.dev/auth/authkit/auto-provision - -Use this when the app already uses WorkOS or the user wants AuthKit specifically. - -## Workflow - -1. Confirm the user wants WorkOS AuthKit -2. Determine whether they want: - - a Convex-managed WorkOS team - - an existing WorkOS team -3. Ask whether the user wants local-only setup or production-ready setup now -4. Read the official Convex and WorkOS AuthKit guide -5. Create or update `convex.json` for the app's framework and real local port -6. Follow the correct branch of the setup flow based on that choice -7. Configure the required WorkOS environment variables -8. Configure `convex/auth.config.ts` for WorkOS-issued JWTs -9. Wire the client provider and callback flow -10. Verify authenticated requests reach Convex -11. If the user wants production-ready setup, make sure the production WorkOS configuration is covered too -12. Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex - -## What To Do - -- Read the official Convex and WorkOS AuthKit guide before writing setup code -- Determine whether the user wants a Convex-managed WorkOS team or an existing WorkOS team -- Treat `convex.json` as a first-class part of the AuthKit setup, not an optional extra -- Follow the current setup flow from the docs instead of relying on older examples - -## Key Setup Areas - -- package installation for the app's framework -- `convex.json` with the `authKit` section for dev, and preview or prod if needed -- environment variables such as `WORKOS_CLIENT_ID`, `WORKOS_API_KEY`, and redirect configuration -- `convex/auth.config.ts` wiring for WorkOS-issued JWTs -- client provider setup and token flow into Convex -- login callback and redirect configuration - -## Files and Env Vars To Expect - -- `convex.json` -- `convex/auth.config.ts` -- frontend auth provider wiring -- callback or redirect route setup where the framework requires it -- WorkOS environment variables commonly include: - - `WORKOS_CLIENT_ID` - - `WORKOS_API_KEY` - - `WORKOS_COOKIE_PASSWORD` - - `VITE_WORKOS_CLIENT_ID` - - `VITE_WORKOS_REDIRECT_URI` - - `NEXT_PUBLIC_WORKOS_REDIRECT_URI` - -For a managed WorkOS team, `convex dev` can provision the AuthKit environment and write local env vars such as `VITE_WORKOS_CLIENT_ID` and `VITE_WORKOS_REDIRECT_URI` into `.env.local` for Vite apps. - -## Concrete Steps - -1. Choose Convex-managed or existing WorkOS team -2. Create or update `convex.json` with the `authKit` section for the framework in use -3. Make sure the dev `redirectUris`, `appHomepageUrl`, `corsOrigins`, and local redirect env vars match the app's actual local port -4. For a managed WorkOS team, run `npx convex dev` and follow the interactive onboarding flow -5. For an existing WorkOS team, get `WORKOS_CLIENT_ID` and `WORKOS_API_KEY` from the WorkOS dashboard and set them with `npx convex env set` -6. Create or update `convex/auth.config.ts` for WorkOS JWT validation -7. Run the normal Convex dev or deploy flow so backend config is synced -8. Wire the WorkOS client provider in the app -9. Configure callback and redirect handling -10. Verify the user can sign in and return to the app -11. Verify Convex sees the authenticated user after login -12. If the user wants production-ready setup, configure the production client ID, API key, redirect URI, and deployment settings too - -## Gotchas - -- The docs split setup between Convex-managed and existing WorkOS teams, so ask which path the user wants if it is not obvious -- Keep dev and prod WorkOS configuration separate where the docs call for different client IDs or API keys -- Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex -- Do not mix dev and prod WorkOS credentials or redirect URIs -- If the repo already contains WorkOS setup, preserve the current tenant model unless the user wants to change it -- For managed WorkOS setup, `convex dev` is interactive the first time. In non-interactive terminals, stop and ask the user to complete the onboarding prompts. -- `convex.json` is not optional for the managed AuthKit flow. It drives redirect URI, homepage URL, CORS configuration, and local env var generation. -- If the frontend starts on a different port than the one in `convex.json`, the hosted WorkOS sign-in flow will point to the wrong callback URL. Update `convex.json`, update the local redirect env var, and run `npx convex dev` again. -- Vite can fall off `5173` if other apps are already running. Do not assume the default port still matches the generated AuthKit config. -- A successful WorkOS sign-in should redirect back to the local callback route and then reach a Convex-authenticated state. Do not stop at "the hosted WorkOS page loaded." - -## Production - -- Ask whether the user wants dev-only setup or production-ready setup -- If the answer is production-ready, make sure the production WorkOS client ID, API key, redirect URI, and Convex deployment config are all covered -- Verify the production redirect and callback settings before calling the task complete -- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. - -## Validation - -- Verify the user can complete the login flow and return to the app -- Verify the callback URL matches the real frontend port in local dev -- Verify Convex receives authenticated requests after login -- Verify `convex.json` matches the framework and chosen WorkOS setup path -- Verify `convex/auth.config.ts` matches the chosen WorkOS setup path -- Verify environment variables differ correctly between local and production where needed -- If production-ready setup was requested, verify the production WorkOS configuration is also covered - -## Checklist - -- [ ] Confirm the user wants WorkOS AuthKit -- [ ] Ask whether the user wants local-only setup or production-ready setup -- [ ] Choose Convex-managed or existing WorkOS team -- [ ] Create or update `convex.json` -- [ ] Configure WorkOS environment variables -- [ ] Configure `convex/auth.config.ts` -- [ ] Verify authenticated requests reach Convex after login -- [ ] If requested, configure the production deployment too diff --git a/.agents/skills/convex-create-component/SKILL.md b/.agents/skills/convex-create-component/SKILL.md deleted file mode 100644 index bf10992d..00000000 --- a/.agents/skills/convex-create-component/SKILL.md +++ /dev/null @@ -1,322 +0,0 @@ ---- -name: convex-create-component -description: - Builds reusable Convex components with isolated tables and app-facing APIs. - Use for new components, reusable backend modules, integrations, or component - boundary work. ---- - -# Convex Create Component - -Create reusable Convex components with clear boundaries and a small app-facing -API. - -## When to Use - -- Creating a new Convex component in an existing app -- Extracting reusable backend logic into a component -- Building a third-party integration that should own its own tables and - workflows -- Packaging Convex functionality for reuse across multiple apps - -## When Not to Use - -- One-off business logic that belongs in the main app -- Thin utilities that do not need Convex tables or functions -- App-level orchestration that should stay in `convex/` -- Cases where a normal TypeScript library is enough - -## Workflow - -1. Ask the user what they are building and what the end goal is. If the repo - already makes the answer obvious, say so and confirm before proceeding. -2. Choose the shape using the decision tree below and read the matching - reference file. -3. Decide whether a component is justified. Prefer normal app code or a regular - library if the feature does not need isolated tables, backend functions, or - reusable persistent state. -4. Make a short plan for: - - what tables the component owns - - what public functions it exposes - - what data must be passed in from the app (auth, env vars, parent IDs) - - what stays in the app as wrappers or HTTP mounts -5. Create the component structure with `convex.config.ts`, `schema.ts`, and - function files. -6. Implement functions using the component's own `./_generated/server` imports, - not the app's generated files. -7. Wire the component into the app with `app.use(...)`. If the app does not - already have `convex/convex.config.ts`, create it. -8. Call the component from the app through `components.` using - `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction`. -9. If React clients, HTTP callers, or public APIs need access, create wrapper - functions in the app instead of exposing component functions directly. -10. Run `npx convex dev` and fix codegen, type, or boundary issues before - finishing. - -## Choose the Shape - -Ask the user, then pick one path: - -| Goal | Shape | Reference | -| ------------------------------------------------- | ---------------- | ----------------------------------- | -| Component for this app only | Local | `references/local-components.md` | -| Publish or share across apps | Packaged | `references/packaged-components.md` | -| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | -| Not sure | Default to local | `references/local-components.md` | - -Read exactly one reference file before proceeding. - -## Default Approach - -Unless the user explicitly wants an npm package, default to a local component: - -- Put it under `convex/components//` -- Define it with `defineComponent(...)` in its own `convex.config.ts` -- Install it from the app's `convex/convex.config.ts` with `app.use(...)` -- Let `npx convex dev` generate the component's own `_generated/` files - -## Component Skeleton - -A minimal local component with a table and two functions, plus the app wiring. - -```ts -// convex/components/notifications/convex.config.ts -import { defineComponent } from "convex/server"; - -export default defineComponent("notifications"); -``` - -```ts -// convex/components/notifications/schema.ts -import { defineSchema, defineTable } from "convex/server"; -import { v } from "convex/values"; - -export default defineSchema({ - notifications: defineTable({ - userId: v.string(), - message: v.string(), - read: v.boolean(), - }).index("by_user", ["userId"]), -}); -``` - -```ts -// convex/components/notifications/lib.ts -import { v } from "convex/values"; -import { mutation, query } from "./_generated/server.js"; - -export const send = mutation({ - args: { userId: v.string(), message: v.string() }, - returns: v.id("notifications"), - handler: async (ctx, args) => { - return await ctx.db.insert("notifications", { - userId: args.userId, - message: args.message, - read: false, - }); - }, -}); - -export const listUnread = query({ - args: { userId: v.string() }, - returns: v.array( - v.object({ - _id: v.id("notifications"), - _creationTime: v.number(), - userId: v.string(), - message: v.string(), - read: v.boolean(), - }), - ), - handler: async (ctx, args) => { - return await ctx.db - .query("notifications") - .withIndex("by_user", (q) => q.eq("userId", args.userId)) - .filter((q) => q.eq(q.field("read"), false)) - .collect(); - }, -}); -``` - -```ts -// convex/convex.config.ts -import { defineApp } from "convex/server"; -import notifications from "./components/notifications/convex.config.js"; - -const app = defineApp(); -app.use(notifications); - -export default app; -``` - -```ts -// convex/notifications.ts (app-side wrapper) -import { v } from "convex/values"; -import { mutation, query } from "./_generated/server"; -import { components } from "./_generated/api"; -import { getAuthUserId } from "@convex-dev/auth/server"; - -export const sendNotification = mutation({ - args: { message: v.string() }, - returns: v.null(), - handler: async (ctx, args) => { - const userId = await getAuthUserId(ctx); - if (!userId) throw new Error("Not authenticated"); - - await ctx.runMutation(components.notifications.lib.send, { - userId, - message: args.message, - }); - return null; - }, -}); - -export const myUnread = query({ - args: {}, - handler: async (ctx) => { - const userId = await getAuthUserId(ctx); - if (!userId) throw new Error("Not authenticated"); - - return await ctx.runQuery(components.notifications.lib.listUnread, { - userId, - }); - }, -}); -``` - -Note the reference path shape: a function in -`convex/components/notifications/lib.ts` is called as -`components.notifications.lib.send` from the app. - -## Critical Rules - -- Keep authentication in the app, because `ctx.auth` is not available inside - components. -- Keep environment access in the app, because component functions cannot read - `process.env`. -- Pass parent app IDs across the boundary as strings, because `Id` types become - plain strings in the app-facing `ComponentApi`. -- Do not use `v.id("parentTable")` for app-owned tables inside component args or - schema, because the component has no access to the app's table namespace. -- Import `query`, `mutation`, and `action` from the component's own - `./_generated/server`, not the app's generated files. -- Do not expose component functions directly to clients. Create app wrappers - when client access is needed, because components are internal and need - auth/env wiring the app provides. -- If the component defines HTTP handlers, mount the routes in the app's - `convex/http.ts`, because components cannot register their own HTTP routes. -- If the component needs pagination, use `paginator` from `convex-helpers` - instead of built-in `.paginate()`, because `.paginate()` does not work across - the component boundary. -- Add `args` and `returns` validators to all public component functions, because - the component boundary requires explicit type contracts. - -## Patterns - -### Authentication and environment access - -```ts -// Bad: component code cannot rely on app auth or env -const identity = await ctx.auth.getUserIdentity(); -const apiKey = process.env.OPENAI_API_KEY; -``` - -```ts -// Good: the app resolves auth and env, then passes explicit values -const userId = await getAuthUserId(ctx); -if (!userId) throw new Error("Not authenticated"); - -await ctx.runAction(components.translator.translate, { - userId, - apiKey: process.env.OPENAI_API_KEY, - text: args.text, -}); -``` - -### Client-facing API - -```ts -// Bad: assuming a component function is directly callable by clients -export const send = components.notifications.send; -``` - -```ts -// Good: re-export through an app mutation or query -export const sendNotification = mutation({ - args: { message: v.string() }, - returns: v.null(), - handler: async (ctx, args) => { - const userId = await getAuthUserId(ctx); - if (!userId) throw new Error("Not authenticated"); - - await ctx.runMutation(components.notifications.lib.send, { - userId, - message: args.message, - }); - return null; - }, -}); -``` - -### IDs across the boundary - -```ts -// Bad: parent app table IDs are not valid component validators -args: { - userId: v.id("users"); -} -``` - -```ts -// Good: treat parent-owned IDs as strings at the boundary -args: { - userId: v.string(); -} -``` - -### Advanced Patterns - -For additional patterns including function handles for callbacks, deriving -validators from schema, static configuration with a globals table, and -class-based client wrappers, see `references/advanced-patterns.md`. - -## Validation - -Try validation in this order: - -1. `npx convex codegen --component-dir convex/components/` -2. `npx convex codegen` -3. `npx convex dev` - -Important: - -- Fresh repos may fail these commands until `CONVEX_DEPLOYMENT` is configured. -- Until codegen runs, component-local `./_generated/*` imports and app-side - `components....` references will not typecheck. -- If validation blocks on Convex login or deployment setup, stop and ask the - user for that exact step instead of guessing. - -## Reference Files - -Read exactly one of these after the user confirms the goal: - -- `references/local-components.md` -- `references/packaged-components.md` -- `references/hybrid-components.md` - -Official docs: -[Authoring Components](https://docs.convex.dev/components/authoring) - -## Checklist - -- [ ] Asked the user what they want to build and confirmed the shape -- [ ] Read the matching reference file -- [ ] Confirmed a component is the right abstraction -- [ ] Planned tables, public API, boundaries, and app wrappers -- [ ] Component lives under `convex/components//` (or package layout if - publishing) -- [ ] Component imports from its own `./_generated/server` -- [ ] Auth, env access, and HTTP routes stay in the app -- [ ] Parent app IDs cross the boundary as `v.string()` -- [ ] Public functions have `args` and `returns` validators -- [ ] Ran `npx convex dev` and fixed codegen or type issues diff --git a/.agents/skills/convex-create-component/agents/openai.yaml b/.agents/skills/convex-create-component/agents/openai.yaml deleted file mode 100644 index bf58a4c4..00000000 --- a/.agents/skills/convex-create-component/agents/openai.yaml +++ /dev/null @@ -1,14 +0,0 @@ -interface: - display_name: "Convex Create Component" - short_description: - "Design and build reusable Convex components with clear boundaries." - icon_small: "./assets/icon.svg" - icon_large: "./assets/icon.svg" - brand_color: "#14B8A6" - default_prompt: - "Help me create a Convex component for this feature. First check that a - component is actually justified, then design the tables, API surface, and - app-facing wrappers before implementing it." - -policy: - allow_implicit_invocation: true diff --git a/.agents/skills/convex-create-component/references/advanced-patterns.md b/.agents/skills/convex-create-component/references/advanced-patterns.md deleted file mode 100644 index 9e560801..00000000 --- a/.agents/skills/convex-create-component/references/advanced-patterns.md +++ /dev/null @@ -1,140 +0,0 @@ -# Advanced Component Patterns - -Additional patterns for Convex components that go beyond the basics covered in -the main skill file. - -## Function Handles for callbacks - -When the app needs to pass a callback function to the component, use function -handles. This is common for components that run app-defined logic on a schedule -or in a workflow. - -```ts -// App side: create a handle and pass it to the component -import { createFunctionHandle } from "convex/server"; - -export const startJob = mutation({ - handler: async (ctx) => { - const handle = await createFunctionHandle(internal.myModule.processItem); - await ctx.runMutation(components.workpool.enqueue, { - callback: handle, - }); - }, -}); -``` - -```ts -// Component side: accept and invoke the handle -import { v } from "convex/values"; -import type { FunctionHandle } from "convex/server"; -import { mutation } from "./_generated/server.js"; - -export const enqueue = mutation({ - args: { callback: v.string() }, - handler: async (ctx, args) => { - const handle = args.callback as FunctionHandle<"mutation">; - await ctx.scheduler.runAfter(0, handle, {}); - }, -}); -``` - -## Deriving validators from schema - -Instead of manually repeating field types in return validators, extend the -schema validator: - -```ts -import { v } from "convex/values"; -import schema from "./schema.js"; - -const notificationDoc = schema.tables.notifications.validator.extend({ - _id: v.id("notifications"), - _creationTime: v.number(), -}); - -export const getLatest = query({ - args: {}, - returns: v.nullable(notificationDoc), - handler: async (ctx) => { - return await ctx.db.query("notifications").order("desc").first(); - }, -}); -``` - -## Static configuration with a globals table - -A common pattern for component configuration is a single-document "globals" -table: - -```ts -// schema.ts -export default defineSchema({ - globals: defineTable({ - maxRetries: v.number(), - webhookUrl: v.optional(v.string()), - }), - // ... other tables -}); -``` - -```ts -// lib.ts -export const configure = mutation({ - args: { maxRetries: v.number(), webhookUrl: v.optional(v.string()) }, - returns: v.null(), - handler: async (ctx, args) => { - const existing = await ctx.db.query("globals").first(); - if (existing) { - await ctx.db.patch(existing._id, args); - } else { - await ctx.db.insert("globals", args); - } - return null; - }, -}); -``` - -## Class-based client wrappers - -For components with many functions or configuration options, a class-based -client provides a cleaner API. This pattern is common in published components. - -```ts -// src/client/index.ts -import type { GenericMutationCtx, GenericDataModel } from "convex/server"; -import type { ComponentApi } from "../component/_generated/component.js"; - -type MutationCtx = Pick, "runMutation">; - -export class Notifications { - constructor( - private component: ComponentApi, - private options?: { defaultChannel?: string }, - ) {} - - async send(ctx: MutationCtx, args: { userId: string; message: string }) { - return await ctx.runMutation(this.component.lib.send, { - ...args, - channel: this.options?.defaultChannel ?? "default", - }); - } -} -``` - -```ts -// App usage -import { Notifications } from "@convex-dev/notifications"; -import { components } from "./_generated/api"; - -const notifications = new Notifications(components.notifications, { - defaultChannel: "alerts", -}); - -export const send = mutation({ - args: { message: v.string() }, - handler: async (ctx, args) => { - const userId = await getAuthUserId(ctx); - await notifications.send(ctx, { userId, message: args.message }); - }, -}); -``` diff --git a/.agents/skills/convex-create-component/references/hybrid-components.md b/.agents/skills/convex-create-component/references/hybrid-components.md deleted file mode 100644 index 657a7348..00000000 --- a/.agents/skills/convex-create-component/references/hybrid-components.md +++ /dev/null @@ -1,38 +0,0 @@ -# Hybrid Convex Components - -Read this file only when the user explicitly wants a hybrid setup. - -## What This Means - -A hybrid component combines a local Convex component with shared library code. - -This can help when: - -- the user wants a local install but also shared package logic -- the component needs extension points or override hooks -- some logic should live in normal TypeScript code outside the component - boundary - -## Default Advice - -Treat hybrid as an advanced option, not the default. - -Before choosing it, ask: - -- Why is a plain local component not enough? -- Why is a packaged component not enough? -- What exactly needs to stay overridable or shared? - -If the answer is vague, fall back to local or packaged. - -## Risks - -- More moving parts -- Harder upgrades and backwards compatibility -- Easier to blur the component boundary - -## Checklist - -- [ ] User explicitly needs hybrid behavior -- [ ] Local-only and packaged-only options were considered first -- [ ] The extension points are clearly defined before coding diff --git a/.agents/skills/convex-create-component/references/local-components.md b/.agents/skills/convex-create-component/references/local-components.md deleted file mode 100644 index 8d4af172..00000000 --- a/.agents/skills/convex-create-component/references/local-components.md +++ /dev/null @@ -1,39 +0,0 @@ -# Local Convex Components - -Read this file when the component should live inside the current app and does -not need to be published as an npm package. - -## When to Choose This - -- The user wants the simplest path -- The component only needs to work in this repo -- The goal is extracting app logic into a cleaner boundary - -## Default Layout - -Use this structure unless the repo already has a clear alternative pattern: - -```text -convex/ - convex.config.ts - components/ - / - convex.config.ts - schema.ts - .ts -``` - -## Workflow Notes - -- Define the component with `defineComponent("")` -- Install it from the app with `defineApp()` and `app.use(...)` -- Keep auth, env access, public API wrappers, and HTTP route mounting in the app -- Let the component own isolated tables and reusable backend workflows -- Add app wrappers if clients need to call into the component - -## Checklist - -- [ ] Component is inside `convex/components//` -- [ ] App installs it with `app.use(...)` -- [ ] Component owns only its own tables -- [ ] App wrappers handle client-facing calls when needed diff --git a/.agents/skills/convex-create-component/references/packaged-components.md b/.agents/skills/convex-create-component/references/packaged-components.md deleted file mode 100644 index 553cd3d5..00000000 --- a/.agents/skills/convex-create-component/references/packaged-components.md +++ /dev/null @@ -1,54 +0,0 @@ -# Packaged Convex Components - -Read this file when the user wants a reusable npm package or a component shared -across multiple apps. - -## When to Choose This - -- The user wants to publish the component -- The user wants a stable reusable package boundary -- The component will be shared across multiple apps or teams - -## Default Approach - -- Prefer starting from `npx create-convex@latest --component` when possible -- Keep the official authoring docs as the source of truth for package layout and - exports -- Validate the bundled package through an example app, not just the source files - -## Build Flow - -When building a packaged component, make sure the bundled output exists before -the example app tries to consume it. - -Recommended order: - -1. `npx convex codegen --component-dir ./path/to/component` -2. Run the package build command -3. Run `npx convex dev --typecheck-components` in the example app - -Do not assume normal app codegen is enough for packaged component workflows. - -## Package Exports - -If publishing to npm, make sure the package exposes the entry points apps need: - -- package root for client helpers, types, or classes -- `./convex.config.js` for installing the component -- `./_generated/component.js` for the app-facing `ComponentApi` type -- `./test` for testing helpers when applicable - -## Testing - -- Use `convex-test` for component logic -- Register the component schema and modules with the test instance -- Test app-side wrapper code from an example app that installs the package -- Export a small helper from `./test` if consumers need easy test registration - -## Checklist - -- [ ] Packaging is actually required -- [ ] Build order avoids bundle and codegen races -- [ ] Package exports include install and typing entry points -- [ ] Example app exercises the packaged component -- [ ] Core behavior is covered by tests diff --git a/.agents/skills/convex-migration-helper/SKILL.md b/.agents/skills/convex-migration-helper/SKILL.md deleted file mode 100644 index 8ce9874b..00000000 --- a/.agents/skills/convex-migration-helper/SKILL.md +++ /dev/null @@ -1,178 +0,0 @@ ---- -name: convex-migration-helper -description: - Plans Convex schema and data migrations with widen-migrate-narrow and - @convex-dev/migrations. Use for breaking schema changes, backfills, table - reshaping, or zero-downtime rollouts. ---- - -# Convex Migration Helper - -Safely migrate Convex schemas and data when making breaking changes. - -## When to Use - -- Adding new required fields to existing tables -- Changing field types or structure -- Splitting or merging tables -- Renaming or deleting fields -- Migrating from nested to relational data - -## When Not to Use - -- Greenfield schema with no existing data in production or dev -- Adding optional fields that do not need backfilling -- Adding new tables with no existing data to migrate -- Adding or removing indexes with no correctness concern -- Questions about Convex schema design without a migration need - -## Key Concepts - -### Schema Validation Drives the Workflow - -Convex will not let you deploy a schema that does not match the data at rest. -This is the fundamental constraint that shapes every migration: - -- You cannot add a required field if existing documents don't have it -- You cannot change a field's type if existing documents have the old type -- You cannot remove a field from the schema if existing documents still have it - -This means migrations follow a predictable pattern: **widen the schema, migrate -the data, narrow the schema**. - -### Online Migrations - -Convex migrations run online, meaning the app continues serving requests while -data is updated asynchronously in batches. During the migration window, your -code must handle both old and new data formats. - -### Prefer New Fields Over Changing Types - -When changing the shape of data, create a new field rather than modifying an -existing one. This makes the transition safer and easier to roll back. - -### Don't Delete Data - -Unless you are certain, prefer deprecating fields over deleting them. Mark the -field as `v.optional` and add a code comment explaining it is deprecated and why -it existed. - -## Safe Changes (No Migration Needed) - -### Adding Optional Field - -```typescript -// Before -users: defineTable({ - name: v.string(), -}); - -// After - safe, new field is optional -users: defineTable({ - name: v.string(), - bio: v.optional(v.string()), -}); -``` - -### Adding New Table - -```typescript -posts: defineTable({ - userId: v.id("users"), - title: v.string(), -}).index("by_user", ["userId"]); -``` - -### Adding Index - -```typescript -users: defineTable({ - name: v.string(), - email: v.string(), -}).index("by_email", ["email"]); -``` - -## Breaking Changes: The Deployment Workflow - -Every breaking migration follows the same multi-deploy pattern: - -**Deploy 1 - Widen the schema:** - -1. Update schema to allow both old and new formats (e.g., add optional new - field) -2. Update code to handle both formats when reading -3. Update code to write the new format for new documents -4. Deploy - -**Between deploys - Migrate data:** - -5. Run migration to backfill existing documents -6. Verify all documents are migrated - -**Deploy 2 - Narrow the schema:** - -7. Update schema to require the new format only -8. Remove code that handles the old format -9. Deploy - -## Using the Migrations Component - -For any non-trivial migration, use the -[`@convex-dev/migrations`](https://www.convex.dev/components/migrations) -component. It handles batching, cursor-based pagination, state tracking, resume -from failure, dry runs, and progress monitoring. - -See `references/migrations-component.md` for installation, setup, defining and -running migrations directly with `npx convex run migrations:myMigration`, dry -runs, status monitoring, and configuration options. - -## Common Migration Patterns - -See `references/migration-patterns.md` for complete patterns with code examples -covering: - -- Adding a required field -- Deleting a field -- Changing a field type -- Splitting nested data into a separate table -- Cleaning up orphaned documents -- Zero-downtime strategies (dual write, dual read) -- Small table shortcut (single internalMutation without the component) -- Verifying a migration is complete - -## Common Pitfalls - -1. **Making a field required before migrating data**: Convex rejects the deploy - because existing documents lack the field. Always widen the schema first. -2. **Using `.collect()` on large tables**: Hits transaction limits or causes - timeouts. Use the migrations component for proper batched pagination. - `.collect()` is only safe for tables you know are small. -3. **Not writing the new format before migrating**: Documents created during the - migration window will be missed, leaving unmigrated data after the migration - "completes." -4. **Skipping the dry run**: Use `dryRun: true` to validate migration logic - before committing changes to production data. Catches bugs before they touch - real documents. -5. **Deleting fields prematurely**: Prefer deprecating with `v.optional` and a - comment. Only delete after you are confident the data is no longer needed and - no code references it. -6. **Using crons for migration batches**: The migrations component handles - batching via recursive scheduling internally. Crons require manual cleanup - and an extra deploy to remove. - -## Migration Checklist - -- [ ] Identify the breaking change and plan the multi-deploy workflow -- [ ] Update schema to allow both old and new formats -- [ ] Update code to handle both formats when reading -- [ ] Update code to write the new format for new documents -- [ ] Deploy widened schema and updated code -- [ ] Define migration using the `@convex-dev/migrations` component -- [ ] Test with `npx convex run migrations:myMigration '{"dryRun": true}'` -- [ ] Run migration directly with `npx convex run migrations:myMigration` and - monitor status -- [ ] Verify all documents are migrated -- [ ] Update schema to require new format only -- [ ] Clean up code that handled old format -- [ ] Deploy final schema and code -- [ ] Remove migration code once confirmed stable diff --git a/.agents/skills/convex-migration-helper/agents/openai.yaml b/.agents/skills/convex-migration-helper/agents/openai.yaml deleted file mode 100644 index 5f027dd9..00000000 --- a/.agents/skills/convex-migration-helper/agents/openai.yaml +++ /dev/null @@ -1,13 +0,0 @@ -interface: - display_name: "Convex Migration Helper" - short_description: "Plan and run safe Convex schema and data migrations." - icon_small: "./assets/icon.svg" - icon_large: "./assets/icon.svg" - brand_color: "#8B5CF6" - default_prompt: - "Help me plan and execute this Convex migration safely. Start by identifying - the schema change, the existing data shape, and the widen-migrate-narrow - path before making edits." - -policy: - allow_implicit_invocation: true diff --git a/.agents/skills/convex-migration-helper/references/migration-patterns.md b/.agents/skills/convex-migration-helper/references/migration-patterns.md deleted file mode 100644 index 9d8eb607..00000000 --- a/.agents/skills/convex-migration-helper/references/migration-patterns.md +++ /dev/null @@ -1,243 +0,0 @@ -# Migration Patterns Reference - -Common migration patterns, zero-downtime strategies, and verification techniques -for Convex schema and data migrations. - -## Adding a Required Field - -```typescript -// Deploy 1: Schema allows both states -users: defineTable({ - name: v.string(), - role: v.optional(v.union(v.literal("user"), v.literal("admin"))), -}); - -// Migration: backfill the field -export const addDefaultRole = migrations.define({ - table: "users", - migrateOne: async (ctx, user) => { - if (user.role === undefined) { - await ctx.db.patch(user._id, { role: "user" }); - } - }, -}); - -// Deploy 2: After migration completes, make it required -users: defineTable({ - name: v.string(), - role: v.union(v.literal("user"), v.literal("admin")), -}); -``` - -## Deleting a Field - -Mark the field optional first, migrate data to remove it, then remove from -schema: - -```typescript -// Deploy 1: Make optional -// isPro: v.boolean() --> isPro: v.optional(v.boolean()) - -// Migration -export const removeIsPro = migrations.define({ - table: "teams", - migrateOne: async (ctx, team) => { - if (team.isPro !== undefined) { - await ctx.db.patch(team._id, { isPro: undefined }); - } - }, -}); - -// Deploy 2: Remove isPro from schema entirely -``` - -## Changing a Field Type - -Prefer creating a new field. You can combine adding and deleting in one -migration: - -```typescript -// Deploy 1: Add new field, keep old field optional -// isPro: v.boolean() --> isPro: v.optional(v.boolean()), plan: v.optional(...) - -// Migration: convert old field to new field -export const convertToEnum = migrations.define({ - table: "teams", - migrateOne: async (ctx, team) => { - if (team.plan === undefined) { - await ctx.db.patch(team._id, { - plan: team.isPro ? "pro" : "basic", - isPro: undefined, - }); - } - }, -}); - -// Deploy 2: Remove isPro from schema, make plan required -``` - -## Splitting Nested Data Into a Separate Table - -```typescript -export const extractPreferences = migrations.define({ - table: "users", - migrateOne: async (ctx, user) => { - if (user.preferences === undefined) return; - - const existing = await ctx.db - .query("userPreferences") - .withIndex("by_user", (q) => q.eq("userId", user._id)) - .first(); - - if (!existing) { - await ctx.db.insert("userPreferences", { - userId: user._id, - ...user.preferences, - }); - } - - await ctx.db.patch(user._id, { preferences: undefined }); - }, -}); -``` - -Make sure your code is already writing to the new `userPreferences` table for -new users before running this migration, so you don't miss documents created -during the migration window. - -## Cleaning Up Orphaned Documents - -```typescript -export const deleteOrphanedEmbeddings = migrations.define({ - table: "embeddings", - migrateOne: async (ctx, doc) => { - const chunk = await ctx.db - .query("chunks") - .withIndex("by_embedding", (q) => q.eq("embeddingId", doc._id)) - .first(); - - if (!chunk) { - await ctx.db.delete(doc._id); - } - }, -}); -``` - -## Zero-Downtime Strategies - -During the migration window, your app must handle both old and new data formats. -There are two main strategies. - -### Dual Write (Preferred) - -Write to both old and new structures. Read from the old structure until -migration is complete. - -1. Deploy code that writes both formats, reads old format -2. Run migration on existing data -3. Deploy code that reads new format, still writes both -4. Deploy code that only reads and writes new format - -This is preferred because you can safely roll back at any point, the old format -is always up to date. - -```typescript -// Bad: only writing to new structure before migration is done -export const createTeam = mutation({ - args: { name: v.string(), isPro: v.boolean() }, - handler: async (ctx, args) => { - await ctx.db.insert("teams", { - name: args.name, - plan: args.isPro ? "pro" : "basic", - }); - }, -}); - -// Good: writing to both structures during migration -export const createTeam = mutation({ - args: { name: v.string(), isPro: v.boolean() }, - handler: async (ctx, args) => { - const plan = args.isPro ? "pro" : "basic"; - await ctx.db.insert("teams", { - name: args.name, - isPro: args.isPro, - plan, - }); - }, -}); -``` - -### Dual Read - -Read both formats. Write only the new format. - -1. Deploy code that reads both formats (preferring new), writes only new format -2. Run migration on existing data -3. Deploy code that reads and writes only new format - -This avoids duplicating writes, which is useful when having two copies of data -could cause inconsistencies. The downside is that rolling back to before step 1 -is harder, since new documents only have the new format. - -```typescript -// Good: reading both formats, preferring new -function getTeamPlan(team: Doc<"teams">): "basic" | "pro" { - if (team.plan !== undefined) return team.plan; - return team.isPro ? "pro" : "basic"; -} -``` - -## Small Table Shortcut - -For small tables (a few thousand documents at most), you can migrate in a single -`internalMutation` without the component: - -```typescript -import { internalMutation } from "./_generated/server"; - -export const backfillSmallTable = internalMutation({ - handler: async (ctx) => { - const docs = await ctx.db.query("smallConfig").collect(); - for (const doc of docs) { - if (doc.newField === undefined) { - await ctx.db.patch(doc._id, { newField: "default" }); - } - } - }, -}); -``` - -```bash -npx convex run migrations:backfillSmallTable -``` - -Only use `.collect()` when you are certain the table is small. For anything -larger, use the migrations component. - -## Verifying a Migration - -Query to check remaining unmigrated documents: - -```typescript -import { query } from "./_generated/server"; - -export const verifyMigration = query({ - handler: async (ctx) => { - const remaining = await ctx.db - .query("users") - .filter((q) => q.eq(q.field("role"), undefined)) - .take(10); - - return { - complete: remaining.length === 0, - sampleRemaining: remaining.map((u) => u._id), - }; - }, -}); -``` - -Or use the component's built-in status monitoring: - -```bash -npx convex run --component migrations lib:getStatus --watch -``` diff --git a/.agents/skills/convex-migration-helper/references/migrations-component.md b/.agents/skills/convex-migration-helper/references/migrations-component.md deleted file mode 100644 index f4daa65b..00000000 --- a/.agents/skills/convex-migration-helper/references/migrations-component.md +++ /dev/null @@ -1,219 +0,0 @@ -# Migrations Component Reference - -Complete guide to the -[`@convex-dev/migrations`](https://www.convex.dev/components/migrations) -component for batched, resumable Convex data migrations. - -## Installation - -```bash -npm install @convex-dev/migrations -``` - -## Setup - -```typescript -// convex/convex.config.ts -import { defineApp } from "convex/server"; -import migrations from "@convex-dev/migrations/convex.config.js"; - -const app = defineApp(); -app.use(migrations); -export default app; -``` - -```typescript -// convex/migrations.ts -import { Migrations } from "@convex-dev/migrations"; -import { components } from "./_generated/api.js"; -import { DataModel } from "./_generated/dataModel.js"; - -export const migrations = new Migrations(components.migrations); -``` - -The `DataModel` type parameter is optional but provides type safety for -migration definitions. - -## Define a Migration - -The `migrateOne` function processes a single document. The component handles -batching and pagination automatically. - -```typescript -// convex/migrations.ts -export const addDefaultRole = migrations.define({ - table: "users", - migrateOne: async (ctx, user) => { - if (user.role === undefined) { - await ctx.db.patch(user._id, { role: "user" }); - } - }, -}); -``` - -Shorthand: if you return an object, it is applied as a patch automatically. - -```typescript -export const clearDeprecatedField = migrations.define({ - table: "users", - migrateOne: () => ({ legacyField: undefined }), -}); -``` - -## Run a Migration - -From the CLI: - -```bash -npx convex run migrations:addDefaultRole - -# Pass --prod to run in production. -npx convex run migrations:addDefaultRole --prod -``` - -The migration exported by `migrations.define` is directly callable from the CLI -or dashboard. You do not need a separate one-off runner for normal single -migrations. - -If you want a general-purpose runner that accepts a migration name, define one: - -```typescript -export const run = migrations.runner(); -``` - -Then call it with the full function name: - -```bash -npx convex run migrations:run '{"fn": "migrations:addDefaultRole"}' -``` - -Programmatically from another Convex function: - -```typescript -await migrations.runOne(ctx, internal.migrations.addDefaultRole); -``` - -## Run Multiple Migrations in Order - -For a short ad hoc series, pass `next` when starting the first migration: - -```bash -npx convex run migrations:addDefaultRole '{"next":["migrations:clearDeprecatedField","migrations:normalizeEmails"]}' -``` - -For a reusable series, define a runner: - -```typescript -export const runAll = migrations.runner([ - internal.migrations.addDefaultRole, - internal.migrations.clearDeprecatedField, - internal.migrations.normalizeEmails, -]); -``` - -```bash -npx convex run migrations:runAll -``` - -If one fails, it stops and will not continue to the next. Call it again to retry -from where it left off. Completed migrations are skipped automatically. - -Programmatically from another Convex function: - -```typescript -await migrations.runSerially(ctx, [ - internal.migrations.addDefaultRole, - internal.migrations.clearDeprecatedField, - internal.migrations.normalizeEmails, -]); -``` - -## Dry Run - -Test a migration before committing changes: - -```bash -npx convex run migrations:addDefaultRole '{"dryRun": true}' -``` - -This runs one batch and then rolls back, so you can see what it would do without -changing any data. - -## Restart a Migration - -Pass `reset: true` to restart a migration from the beginning: - -```bash -npx convex run migrations:addDefaultRole '{"reset": true}' -``` - -If you specify `next` or run a defined series, `reset: true` resets the cursor -for all migrations in the group. - -## Check Migration Status - -```bash -npx convex run --component migrations lib:getStatus --watch -``` - -## Cancel a Running Migration - -```bash -npx convex run --component migrations lib:cancel '{"name": "migrations:addDefaultRole"}' -``` - -Or programmatically: - -```typescript -await migrations.cancel(ctx, internal.migrations.addDefaultRole); -``` - -## Run Migrations on Deploy - -Chain migration execution after deploying: - -```bash -npx convex deploy --cmd 'npm run build' && npx convex run migrations:runAll --prod -``` - -## Configuration Options - -### Custom Batch Size - -If documents are large or the table has heavy write traffic, reduce the batch -size to avoid transaction limits or OCC conflicts: - -```typescript -export const migrateHeavyTable = migrations.define({ - table: "largeDocuments", - batchSize: 10, - migrateOne: async (ctx, doc) => { - // migration logic - }, -}); -``` - -### Migrate a Subset Using an Index - -Process only matching documents instead of the full table: - -```typescript -export const fixEmptyNames = migrations.define({ - table: "users", - customRange: (query) => query.withIndex("by_name", (q) => q.eq("name", "")), - migrateOne: () => ({ name: "" }), -}); -``` - -### Parallelize Within a Batch - -By default each document in a batch is processed serially. Enable parallel -processing if your migration logic does not depend on ordering: - -```typescript -export const clearField = migrations.define({ - table: "myTable", - parallelize: true, - migrateOne: () => ({ optionalField: undefined }), -}); -``` diff --git a/.agents/skills/convex-performance-audit/SKILL.md b/.agents/skills/convex-performance-audit/SKILL.md deleted file mode 100644 index 909168f0..00000000 --- a/.agents/skills/convex-performance-audit/SKILL.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -name: convex-performance-audit -description: - Audits Convex performance for reads, subscriptions, write contention, and - function limits. Use for slow features, insights findings, OCC conflicts, or - read amplification. ---- - -# Convex Performance Audit - -Diagnose and fix performance problems in Convex applications, one problem class -at a time. - -## When to Use - -- A Convex page or feature feels slow or expensive -- `npx convex insights --details` reports high bytes read, documents read, or - OCC conflicts -- Low-freshness read paths are using reactivity where point-in-time reads would - do -- OCC conflict errors or excessive mutation retries -- High subscription count or slow UI updates -- Functions approaching execution or transaction limits -- The same performance pattern needs fixing across sibling functions - -## When Not to Use - -- Initial Convex setup, auth setup, or component extraction -- Pure schema migrations with no performance goal -- One-off micro-optimizations without a user-visible or deployment-visible - problem - -## Guardrails - -- Prefer simpler code when scale is small, traffic is modest, or the available - signals are weak -- Do not recommend digest tables, document splitting, fetch-strategy changes, or - migration-heavy rollouts unless there is a measured signal, a clearly - unbounded path, or a known hot read/write path -- In Convex, a simple scan on a small table is often acceptable. Do not invent - structural work just because a pattern is not ideal at large scale - -## First Step: Gather Signals - -Start with the strongest signal available: - -1. If deployment Health insights are already available from the user or the - current context, treat them as a first-class source of performance signals. -2. If CLI insights are available, run `npx convex insights --details`. Use - `--prod`, `--preview-name`, or `--deployment-name` when needed. - - If the local repo's Convex CLI is too old to support `insights`, try - `npx -y convex@latest insights --details` before giving up. -3. If the repo already uses `convex-doctor`, you may treat its findings as - hints. Do not require it, and do not treat it as the source of truth. -4. If runtime signals are unavailable, audit from code anyway, but keep the - guardrails above in mind. Lack of insights is not proof of health, but it is - also not proof that a large refactor is warranted. - -## Signal Routing - -After gathering signals, identify the problem class and read the matching -reference file. - -| Signal | Reference | -| -------------------------------------------------------------- | ----------------------------------------- | -| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | -| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | -| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | -| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | -| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | - -Multiple problem classes can overlap. Read the most relevant reference first, -then check the others if symptoms remain. - -## Escalate Larger Fixes - -If the likely fix is invasive, cross-cutting, or migration-heavy, stop and -present options before editing. - -Examples: - -- introducing digest or summary tables across multiple flows -- splitting documents to isolate frequently-updated fields -- reworking pagination or fetch strategy across several screens -- switching to a new index or denormalized field that needs migration-safe - rollout - -When correctness depends on handling old and new states during a rollout, -consult `skills/convex-migration-helper/SKILL.md` for the migration workflow. - -## Workflow - -### 1. Scope the problem - -Pick one concrete user flow from the actual project. Look at the codebase, -client pages, and API surface to find the flow that matches the symptom. - -Write down: - -- entrypoint functions -- client callsites using `useQuery`, `usePaginatedQuery`, or `useMutation` -- tables read -- tables written -- whether the path is high-read, high-write, or both - -### 2. Trace the full read and write set - -For each function in the path: - -1. Trace every `ctx.db.get()` and `ctx.db.query()` -2. Trace every `ctx.db.patch()`, `ctx.db.replace()`, and `ctx.db.insert()` -3. Note foreign-key lookups, JS-side filtering, and full-document reads -4. Identify all sibling functions touching the same tables -5. Identify reactive stats, aggregates, or widgets rendered on the same page - -In Convex, every extra read increases transaction work, and every write can -invalidate reactive subscribers. Treat read amplification and invalidation -amplification as first-class problems. - -### 3. Apply fixes from the relevant reference - -Read the reference file matching your problem class. Each reference includes -specific patterns, code examples, and a recommended fix order. - -Do not stop at the single function named by an insight. Trace sibling readers -and writers touching the same tables. - -### 4. Fix sibling functions together - -When one function touching a table has a performance bug, audit sibling -functions for the same pattern. - -After finding one problem, inspect both sibling readers and sibling writers for -the same table family, including companion digest or summary tables. - -Examples: - -- If one list query switches from full docs to a digest table, inspect the other - list queries for that table -- If one mutation isolates a frequently-updated field or splits a hot document, - inspect the other writers to the same table -- If one read path needs a migration-safe rollout for an unbackfilled field, - inspect sibling reads for the same rollout risk - -Do not leave one path fixed and another path on the old pattern unless there is -a clear product reason. - -### 5. Verify before finishing - -Confirm all of these: - -1. Results are the same as before, no dropped records -2. Eliminated reads or writes are no longer in the path where expected -3. Fallback behavior works when denormalized or indexed fields are missing -4. Frequently-updated fields are isolated from widely-read documents where - needed -5. Every relevant sibling reader and writer was inspected, not just the original - function - -## Reference Files - -- `references/hot-path-rules.md` - Read amplification, invalidation, - denormalization, indexes, digest tables -- `references/occ-conflicts.md` - Write contention, OCC resolution, hot document - splitting -- `references/subscription-cost.md` - Reactive query cost, subscription - granularity, point-in-time reads -- `references/function-budget.md` - Execution limits, transaction size, large - documents, payload size - -Also check the official -[Convex Best Practices](https://docs.convex.dev/understanding/best-practices/) -page for additional patterns covering argument validation, access control, and -code organization that may surface during the audit. - -## Checklist - -- [ ] Gathered signals from insights, dashboard, or code audit -- [ ] Identified the problem class and read the matching reference -- [ ] Scoped one concrete user flow or function path -- [ ] Traced every read and write in that path -- [ ] Identified sibling functions touching the same tables -- [ ] Applied fixes from the reference, following the recommended fix order -- [ ] Fixed sibling functions consistently -- [ ] Verified behavior and confirmed no regressions diff --git a/.agents/skills/convex-performance-audit/agents/openai.yaml b/.agents/skills/convex-performance-audit/agents/openai.yaml deleted file mode 100644 index 0a1d7889..00000000 --- a/.agents/skills/convex-performance-audit/agents/openai.yaml +++ /dev/null @@ -1,14 +0,0 @@ -interface: - display_name: "Convex Performance Audit" - short_description: - "Audit slow Convex reads, subscriptions, OCC conflicts, and limits." - icon_small: "./assets/icon.svg" - icon_large: "./assets/icon.svg" - brand_color: "#EF4444" - default_prompt: - "Audit this Convex app for performance issues. Start with the strongest - signal available, identify the problem class, and suggest the smallest - high-impact fix before proposing bigger structural changes." - -policy: - allow_implicit_invocation: true diff --git a/.agents/skills/convex-performance-audit/references/function-budget.md b/.agents/skills/convex-performance-audit/references/function-budget.md deleted file mode 100644 index 3e8dfef4..00000000 --- a/.agents/skills/convex-performance-audit/references/function-budget.md +++ /dev/null @@ -1,254 +0,0 @@ -# Function Budget - -Use these rules when functions are hitting execution limits, transaction size -errors, or returning excessively large payloads to the client. - -## Core Principle - -Convex functions run inside transactions with budgets for time, reads, and -writes. Staying well within these limits is not just about avoiding errors, it -reduces latency and contention. - -## Limits to Know - -These are the current values from the -[Convex limits docs](https://docs.convex.dev/production/state/limits). Check -that page for the latest numbers. - -| Resource | Limit | -| --------------------------------- | ----------------------------------------------------- | -| Query/mutation execution time | 1 second (user code only, excludes DB operations) | -| Action execution time | 10 minutes | -| Data read per transaction | 16 MiB | -| Data written per transaction | 16 MiB | -| Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | -| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | -| Documents written per transaction | 16,000 | -| Individual document size | 1 MiB | -| Function return value size | 16 MiB | - -## Symptoms - -- "Function execution took too long" errors -- "Transaction too large" or read/write set size errors -- Slow queries that read many documents -- Client receiving large payloads that slow down page load -- `npx convex insights --details` showing high bytes read - -## Common Causes - -### Unbounded collection - -A query that calls `.collect()` on a table without a reasonable limit. As the -table grows, the query reads more and more documents. - -### Large document reads on hot paths - -Reading documents with large fields (rich text, embedded media references, long -arrays) when only a small subset of the data is needed for the current view. - -### Mutation doing too much work - -A single mutation that updates hundreds of documents, backfills data, or -rebuilds derived state in one transaction. - -### Returning too much data to the client - -A query returning full documents when the client only needs a few fields. - -## Fix Order - -### 1. Bound your reads - -Never `.collect()` without a limit on a table that can grow unbounded. - -```ts -// Bad: unbounded read, breaks as the table grows -const messages = await ctx.db.query("messages").collect(); -``` - -```ts -// Good: paginate or limit -const messages = await ctx.db - .query("messages") - .withIndex("by_channel", (q) => q.eq("channelId", channelId)) - .order("desc") - .take(50); -``` - -### 2. Read smaller shapes - -If the list page only needs title, author, and date, do not read full documents -with rich content fields. - -Use digest or summary tables for hot list pages. See `hot-path-rules.md` for the -digest table pattern. - -### 3. Break large mutations into batches - -If a mutation needs to update hundreds of documents, split it into a -self-scheduling chain. - -```ts -// Bad: one mutation updating every row -export const backfillAll = internalMutation({ - handler: async (ctx) => { - const docs = await ctx.db.query("items").collect(); - for (const doc of docs) { - await ctx.db.patch(doc._id, { newField: computeValue(doc) }); - } - }, -}); -``` - -```ts -// Good: cursor-based batch processing -export const backfillBatch = internalMutation({ - args: { cursor: v.optional(v.string()), batchSize: v.optional(v.number()) }, - handler: async (ctx, args) => { - const batchSize = args.batchSize ?? 100; - const result = await ctx.db - .query("items") - .paginate({ cursor: args.cursor ?? null, numItems: batchSize }); - - for (const doc of result.page) { - if (doc.newField === undefined) { - await ctx.db.patch(doc._id, { newField: computeValue(doc) }); - } - } - - if (!result.isDone) { - await ctx.scheduler.runAfter(0, internal.items.backfillBatch, { - cursor: result.continueCursor, - batchSize, - }); - } - }, -}); -``` - -### 4. Move heavy work to actions - -Queries and mutations run inside Convex's transactional runtime with strict -budgets. If you need to do CPU-intensive computation, call external APIs, or -process large files, use an action instead. - -Actions run outside the transaction and can call mutations to write results -back. - -```ts -// Bad: heavy computation inside a mutation -export const processUpload = mutation({ - handler: async (ctx, args) => { - const result = expensiveComputation(args.data); - await ctx.db.insert("results", result); - }, -}); -``` - -```ts -// Good: action for heavy work, mutation for the write -export const processUpload = action({ - handler: async (ctx, args) => { - const result = expensiveComputation(args.data); - await ctx.runMutation(internal.results.store, { result }); - }, -}); -``` - -### 5. Trim return values - -Only return what the client needs. If a query fetches full documents but the -component only renders a few fields, map the results before returning. - -```ts -// Bad: returns full documents including large content fields -export const list = query({ - handler: async (ctx) => { - return await ctx.db.query("articles").take(20); - }, -}); -``` - -```ts -// Good: project to only the fields the client needs -export const list = query({ - handler: async (ctx) => { - const articles = await ctx.db.query("articles").take(20); - return articles.map((a) => ({ - _id: a._id, - title: a.title, - author: a.author, - createdAt: a._creationTime, - })); - }, -}); -``` - -### 6. Replace `ctx.runQuery` and `ctx.runMutation` with helper functions - -Inside queries and mutations, `ctx.runQuery` and `ctx.runMutation` have overhead -compared to calling a plain TypeScript helper function. They run in the same -transaction but pay extra per-call cost. - -```ts -// Bad: unnecessary overhead from ctx.runQuery inside a mutation -export const createProject = mutation({ - handler: async (ctx, args) => { - const user = await ctx.runQuery(api.users.getCurrentUser); - await ctx.db.insert("projects", { ...args, ownerId: user._id }); - }, -}); -``` - -```ts -// Good: plain helper function, no extra overhead -export const createProject = mutation({ - handler: async (ctx, args) => { - const user = await getCurrentUser(ctx); - await ctx.db.insert("projects", { ...args, ownerId: user._id }); - }, -}); -``` - -Exception: components require `ctx.runQuery`/`ctx.runMutation`. Use them there, -but prefer helpers everywhere else. - -### 7. Avoid unnecessary `runAction` calls - -`runAction` from within an action creates a separate function invocation with -its own memory and CPU budget. The parent action just sits idle waiting. Replace -with a plain TypeScript function call unless you need a different runtime (e.g. -calling Node.js code from the Convex runtime). - -```ts -// Bad: runAction overhead for no reason -export const processItems = action({ - handler: async (ctx, args) => { - for (const item of args.items) { - await ctx.runAction(internal.items.processOne, { item }); - } - }, -}); -``` - -```ts -// Good: plain function call -export const processItems = action({ - handler: async (ctx, args) => { - for (const item of args.items) { - await processOneItem(ctx, { item }); - } - }, -}); -``` - -## Verification - -1. No function execution or transaction size errors -2. `npx convex insights --details` shows reduced bytes read -3. Large mutations are batched and self-scheduling -4. Client payloads are reasonably sized for the UI they serve -5. `ctx.runQuery`/`ctx.runMutation` in queries and mutations replaced with - helpers where possible -6. Sibling functions with similar patterns were checked diff --git a/.agents/skills/convex-performance-audit/references/hot-path-rules.md b/.agents/skills/convex-performance-audit/references/hot-path-rules.md deleted file mode 100644 index d51f88e8..00000000 --- a/.agents/skills/convex-performance-audit/references/hot-path-rules.md +++ /dev/null @@ -1,411 +0,0 @@ -# Hot Path Rules - -Use these rules when the top-level workflow points to read amplification, -denormalization, index rollout, reactive query cost, or invalidation-heavy -writes. - -## Contents - -- Core Principle -- Consistency Rule -- 1. Push Filters To Storage (indexes, migration rule, redundant indexes) -- 2. Minimize Data Sources (denormalization, fallback rule) -- 3. Minimize Row Size (digest tables) -- 4. Skip No-Op Writes -- 5. Match Consistency To Read Patterns (high-read/low-write, - high-read/high-write) -- Convex-Specific Notes (reactive queries, point-in-time reads, triggers, - aggregates, backfills) -- Verification - -## Core Principle - -Every byte read or written multiplies with concurrency. - -Think: - -`cost x calls_per_second x 86400` - -In Convex, every write can also fan out into reactive invalidation, replication -work, and downstream sync. - -## Consistency Rule - -If you fix a hot-path pattern for one function, audit sibling functions touching -the same tables for the same pattern. - -Do this especially for: - -- multiple list queries over the same table -- multiple writers to the same table -- public browse and search queries over the same records -- helper functions reused by more than one endpoint - -## 1. Push Filters To Storage - -Both JavaScript `.filter()` and the Convex query `.filter()` method after a DB -scan mean you already paid for the read. The Convex `.filter()` method has the -same performance as filtering in JS, it does not push the predicate to the -storage layer. Only `.withIndex()` and `.withSearchIndex()` actually reduce the -documents scanned. - -Prefer: - -- `withIndex(...)` -- `.withSearchIndex(...)` for text search -- narrower tables -- summary tables - -before accepting a scan-plus-filter pattern. - -```ts -// Bad: scans then filters in JavaScript -export const listOpen = query({ - args: {}, - handler: async (ctx) => { - const tasks = await ctx.db.query("tasks").collect(); - return tasks.filter((task) => task.status === "open"); - }, -}); -``` - -```ts -// Also bad: Convex .filter() does not push to storage either -export const listOpen = query({ - args: {}, - handler: async (ctx) => { - return await ctx.db - .query("tasks") - .filter((q) => q.eq(q.field("status"), "open")) - .collect(); - }, -}); -``` - -```ts -// Good: use an index so storage does the filtering -export const listOpen = query({ - args: {}, - handler: async (ctx) => { - return await ctx.db - .query("tasks") - .withIndex("by_status", (q) => q.eq("status", "open")) - .collect(); - }, -}); -``` - -### Migration rule for indexes - -New indexes on partially backfilled fields can create correctness bugs during -rollout. - -Important Convex detail: - -`undefined !== false` - -If an older document is missing a field entirely, it will not match a compound -index entry that expects `false`. - -Do not trust old comments saying a field is "not backfilled" or "already -backfilled". Verify. - -If correctness depends on handling old and new states during rollout, do not -improvise a partial-backfill workaround in the hot path. Use a migration-safe -rollout and consult `skills/convex-migration-helper/SKILL.md`. - -```ts -// Bad: optional booleans can miss older rows where the field is undefined -const projects = await ctx.db - .query("projects") - .withIndex("by_archived_and_updated", (q) => q.eq("isArchived", false)) - .order("desc") - .take(20); -``` - -```ts -// Good: switch hot-path reads only after the rollout is migration-safe -// See the migration helper skill for dual-read / backfill / cutover patterns. -``` - -### Check for redundant indexes - -Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need -`by_foo_and_bar`, since you can query it with just the `foo` condition and omit -`bar`. Extra indexes add storage cost and write overhead on every insert, patch, -and delete. - -```ts -// Bad: two indexes where one would do -defineTable({ team: v.id("teams"), user: v.id("users") }) - .index("by_team", ["team"]) - .index("by_team_and_user", ["team", "user"]); -``` - -```ts -// Good: single compound index serves both query patterns -defineTable({ team: v.id("teams"), user: v.id("users") }).index( - "by_team_and_user", - ["team", "user"], -); -``` - -Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + -`_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + -`bar` + `_creationTime`. If you need results sorted by `foo` then -`_creationTime`, you need the single-field index because the compound one would -sort by `bar` first. - -## 2. Minimize Data Sources - -Trace every read. - -If a function resolves a foreign key for a tiny display field and a denormalized -copy already exists, prefer the denormalized field on the hot path. - -### When to denormalize - -Denormalize when all of these are true: - -- the path is hot -- the joined document is much larger than the field you need -- many readers are paying that join cost repeatedly - -Useful mental model: - -`join_cost = rows_per_page x foreign_doc_size x pages_per_second` - -Small-table joins are often fine. Large-document joins for tiny fields on hot -list pages are usually not. - -### Fallback rule - -Denormalized data is an optimization. Live data is the correctness path. - -Rules: - -- If the denormalized field is missing or null, fall back to the live read -- Do not show placeholders instead of falling back -- In lookup maps, only include fully populated entries - -```ts -// Bad: missing denormalized data becomes a placeholder and blocks correctness -const ownerName = project.ownerName ?? "Unknown owner"; -``` - -```ts -// Good: denormalized data is an optimization, not the only source of truth -const ownerName = - project.ownerName ?? (await ctx.db.get(project.ownerId))?.name ?? null; -``` - -Bad lookup map pattern: - -```ts -const ownersById = { - [project.ownerId]: { ownerName: null }, -}; -``` - -That blocks fallback because the map says "I have data" when it does not. - -Good lookup map pattern: - -```ts -const ownersById = - project.ownerName !== undefined && project.ownerName !== null - ? { [project.ownerId]: { ownerName: project.ownerName } } - : {}; -``` - -### No denormalized copy yet - -Prefer adding fields to an existing summary, companion, or digest table instead -of bloating the primary hot-path table. - -If introducing the new field or table requires a staged rollout, backfill, or -old/new-shape handling, use the migration helper skill for the rollout plan. - -Rollout order: - -1. Update schema -2. Update write path -3. Backfill -4. Switch read path - -## 3. Minimize Row Size - -Hot list pages should read the smallest document shape that still answers the -UI. - -Prefer summary or digest tables over full source tables when: - -- the list page only needs a subset of fields -- source documents are large -- the query is high volume - -An 800 byte summary row is materially cheaper than a 3 KB full document on a hot -page. - -Digest tables are a tradeoff, not a default: - -- Worth it when the path is clearly hot, the source rows are much larger than - the UI needs, or many readers are repeatedly paying the same join and payload - cost -- Probably not worth it when an indexed read on the source table is already - cheap enough, the table is still small, or the extra write and migration - complexity would dominate the benefit - -```ts -// Bad: list page reads source docs, then joins owner data per row -const projects = await ctx.db - .query("projects") - .withIndex("by_public", (q) => q.eq("isPublic", true)) - .collect(); -``` - -```ts -// Good: list page reads the smaller digest shape first -const projects = await ctx.db - .query("projectDigests") - .withIndex("by_public_and_updated", (q) => q.eq("isPublic", true)) - .order("desc") - .take(20); -``` - -## 4. Isolate Frequently-Updated Fields - -Convex already no-ops unchanged writes. The invalidation problem here is real -writes hitting documents that many queries subscribe to. - -Move high-churn fields like `lastSeen`, counters, presence, or ephemeral status -off widely-read documents when most readers do not need them. - -Apply this across sibling writers too. Splitting one write path does not help -much if three other mutations still update the same widely-read document. - -```ts -// Bad: every presence heartbeat invalidates subscribers to the whole profile -await ctx.db.patch(user._id, { - name: args.name, - avatarUrl: args.avatarUrl, - lastSeen: Date.now(), -}); -``` - -```ts -// Good: keep profile reads stable, move heartbeat updates to a separate document -await ctx.db.patch(user._id, { - name: args.name, - avatarUrl: args.avatarUrl, -}); - -await ctx.db.patch(presence._id, { - lastSeen: Date.now(), -}); -``` - -## 5. Match Consistency To Read Patterns - -Choose read strategy based on traffic shape. - -### High-read, low-write - -Examples: - -- public browse pages -- search results -- landing pages -- directory listings - -Prefer: - -- point-in-time reads where appropriate -- explicit refresh -- local state for pagination -- caching where appropriate - -Do not treat subscriptions as automatically wrong here. Prefer point-in-time -reads only when the product does not need live freshness and the reactive cost -is material. See `subscription-cost.md` for detailed patterns. - -### High-read, high-write - -Examples: - -- collaborative editors -- live dashboards -- presence-heavy views - -Reactive queries may be worth the ongoing cost. - -## Convex-Specific Notes - -### Reactive queries - -Every `ctx.db.get()` and `ctx.db.query()` contributes to the invalidation set -for the query. - -On the client: - -- `useQuery` creates a live subscription -- `usePaginatedQuery` creates a live subscription per page - -For low-freshness flows, consider a point-in-time read instead of a live -subscription only when the product does not need updates pushed automatically. - -### Point-in-time reads - -Framework helpers, server-rendered fetches, or one-shot client reads can avoid -ongoing subscription cost when live updates are not useful. - -Use them for: - -- aggregate snapshots -- reports -- low-churn listings -- pages where explicit refresh is fine - -### Triggers and fan-out - -Triggers fire on every write, including writes that did not materially change -the document. - -When a write exists only to keep derived state in sync: - -- diff before patching -- move expensive non-blocking work to `ctx.scheduler.runAfter` when appropriate - -### Aggregates - -Reactive global counts invalidate frequently on busy tables. - -Prefer: - -- one-shot aggregate fetches -- periodic recomputation -- precomputed summary rows - -for global stats that do not need live updates every second. - -### Backfills - -For larger backfills, use cursor-based, self-scheduling `internalMutation` jobs -or the migrations component. - -Deploy code that can handle both states before running the backfill. - -During the gap: - -- writes should populate the new shape -- reads should fall back safely - -## Verification - -Before closing the audit, confirm: - -1. Same results as before, no dropped records -2. The removed table or lookup is no longer in the hot-path read set -3. Tests or validation cover fallback behavior -4. Migration safety is preserved while fields or indexes are unbackfilled -5. Sibling functions were fixed consistently diff --git a/.agents/skills/convex-performance-audit/references/occ-conflicts.md b/.agents/skills/convex-performance-audit/references/occ-conflicts.md deleted file mode 100644 index e7d0954e..00000000 --- a/.agents/skills/convex-performance-audit/references/occ-conflicts.md +++ /dev/null @@ -1,137 +0,0 @@ -# OCC Conflict Resolution - -Use these rules when insights, logs, or dashboard health show OCC (Optimistic -Concurrency Control) conflicts, mutation retries, or write contention on hot -tables. - -## Core Principle - -Convex uses optimistic concurrency control. When two transactions read or write -overlapping data, one succeeds and the other retries automatically. High -contention means wasted work and increased latency. - -## Symptoms - -- OCC conflict errors in deployment logs or health page -- Mutations retrying multiple times before succeeding -- User-visible latency spikes on write-heavy pages -- `npx convex insights --details` showing high conflict rates - -## Common Causes - -### Hot documents - -Multiple mutations writing to the same document concurrently. Classic examples: -a global counter, a shared settings row, or a "last updated" timestamp on a -parent record. - -### Broad read sets causing false conflicts - -A query that scans a large table range creates a broad read set. If any write -touches that range, the query's transaction conflicts even if the specific -document the query cared about was not modified. - -### Fan-out from triggers or cascading writes - -A single user action triggers multiple mutations that all touch related -documents. Each mutation competes with the others. - -Database triggers (e.g. from `convex-helpers`) run inside the same transaction -as the mutation that caused them. If a trigger does heavy work, reads extra -tables, or writes to many documents, it extends the transaction's read/write set -and increases the window for conflicts. Keep trigger logic minimal, or move -expensive derived work to a scheduled function. - -### Write-then-read chains - -A mutation writes a document, then a reactive query re-reads it, then another -mutation writes it again. Under load, these chains stack up. - -## Fix Order - -### 1. Reduce read set size - -Narrower reads mean fewer false conflicts. - -```ts -// Bad: broad scan creates a wide conflict surface -const allTasks = await ctx.db.query("tasks").collect(); -const mine = allTasks.filter((t) => t.ownerId === userId); -``` - -```ts -// Good: indexed query touches only relevant documents -const mine = await ctx.db - .query("tasks") - .withIndex("by_owner", (q) => q.eq("ownerId", userId)) - .collect(); -``` - -### 2. Split hot documents - -When many writers target the same document, split the contention point. - -```ts -// Bad: every vote increments the same counter document -const counter = await ctx.db.get(pollCounterId); -await ctx.db.patch(pollCounterId, { count: counter!.count + 1 }); -``` - -```ts -// Good: shard the counter across multiple documents, aggregate on read -const shardIndex = Math.floor(Math.random() * SHARD_COUNT); -const shardId = shardIds[shardIndex]; -const shard = await ctx.db.get(shardId); -await ctx.db.patch(shardId, { count: shard!.count + 1 }); -``` - -Aggregate the shards in a query or scheduled job when you need the total. - -### 3. Move non-critical work to scheduled functions - -If a mutation does primary work plus secondary bookkeeping (analytics, -non-critical notifications, cache warming), the bookkeeping extends the -transaction's lifetime and read/write set. - -```ts -// Bad: canonical write and derived work happen in the same transaction -await ctx.db.patch(userId, { name: args.name }); -await ctx.db.insert("userUpdateAnalytics", { - userId, - kind: "name_changed", - name: args.name, -}); -``` - -```ts -// Good: keep the primary write small, defer the analytics work -await ctx.db.patch(userId, { name: args.name }); -await ctx.scheduler.runAfter(0, internal.users.recordNameChangeAnalytics, { - userId, - name: args.name, -}); -``` - -### 4. Combine competing writes - -If two mutations must update the same document atomically, consider whether they -can be combined into a single mutation call from the client, reducing round -trips and conflict windows. - -Do not introduce artificial locks or queues unless the above steps have been -tried first. - -## Related: Invalidation Scope - -Splitting hot documents also reduces subscription invalidation, not just OCC -contention. If a document is written frequently and read by many queries, those -queries re-run on every write even when the fields they care about have not -changed. See `subscription-cost.md` section 4 ("Isolate frequently-updated -fields") for that pattern. - -## Verification - -1. OCC conflict rate has dropped in insights or dashboard -2. Mutation latency is lower and more consistent -3. No data correctness regressions from splitting or scheduling changes -4. Sibling writers to the same hot documents were fixed consistently diff --git a/.agents/skills/convex-performance-audit/references/subscription-cost.md b/.agents/skills/convex-performance-audit/references/subscription-cost.md deleted file mode 100644 index 78f05b0e..00000000 --- a/.agents/skills/convex-performance-audit/references/subscription-cost.md +++ /dev/null @@ -1,300 +0,0 @@ -# Subscription Cost - -Use these rules when the problem is too many reactive subscriptions, queries -invalidating too frequently, or React components re-rendering excessively due to -Convex state changes. - -## Core Principle - -Every `useQuery` and `usePaginatedQuery` call creates a live subscription. The -server tracks the query's read set and re-executes the query whenever any -document in that read set changes. Subscription cost scales with: - -`subscriptions x invalidation_frequency x query_cost` - -Subscriptions are not inherently bad. Convex reactivity is often the right -default. The goal is to reduce unnecessary invalidation work, not to eliminate -subscriptions on principle. - -## Symptoms - -- Dashboard shows high active subscription count -- UI feels sluggish or laggy despite fast individual queries -- React profiling shows frequent re-renders from Convex state -- Pages with many components each running their own `useQuery` -- Paginated lists where every loaded page stays subscribed - -## Common Causes - -### Reactive queries on low-freshness flows - -Some user flows are read-heavy and do not need live updates every time the -underlying data changes. In those cases, ongoing subscriptions may cost more -than they are worth. - -### Overly broad queries - -A query that returns a large result set invalidates whenever any document in -that set changes. The broader the query, the more frequent the invalidation. - -### Too many subscriptions per page - -A page with 20 list items, each running its own `useQuery` to fetch related -data, creates 20+ subscriptions per visitor. - -### Paginated queries keeping all pages live - -`usePaginatedQuery` with `loadMore` keeps every loaded page subscribed. On a -page where a user has scrolled through 10 pages, all 10 stay reactive. - -### Frequently-updated fields on widely-read documents - -A document that many queries touch gets a frequently-updated field (like -`lastSeen`, `lastActiveAt`, or a counter). Every write to that field invalidates -every subscription that reads the document, even if those subscriptions never -use the field. This is different from OCC conflicts (see `occ-conflicts.md`), -which are write-vs-write contention. This is write-vs-subscription: the write -succeeds fine, but it forces hundreds of queries to re-run for no reason. - -## Fix Order - -### 1. Use point-in-time reads when live updates are not valuable - -Keep `useQuery` and `usePaginatedQuery` by default when the product benefits -from fresh live data. - -Consider a point-in-time read instead when all of these are true: - -- the flow is high-read -- the underlying data changes less often than users need to see -- explicit refresh, periodic refresh, or a fresh read on navigation is - acceptable - -Possible implementations depend on environment: - -- a server-rendered fetch -- a framework helper like `fetchQuery` -- a point-in-time client read such as `ConvexHttpClient.query()` - -```ts -// Reactive by default when fresh live data matters -function TeamPresence() { - const presence = useQuery(api.teams.livePresence, { teamId }); - return ; -} -``` - -```ts -// Point-in-time read when explicit refresh is acceptable -import { ConvexHttpClient } from "convex/browser"; - -const client = new ConvexHttpClient(import.meta.env.VITE_CONVEX_URL); - -function SnapshotView() { - const [items, setItems] = useState([]); - - useEffect(() => { - client.query(api.items.snapshot).then(setItems); - }, []); - - return ; -} -``` - -Good candidates for point-in-time reads: - -- aggregate snapshots -- reports -- low-churn listings -- flows where explicit refresh is already acceptable - -Keep reactive for: - -- collaborative editing -- live dashboards -- presence-heavy views -- any surface where users expect fresh changes to appear automatically - -### 2. Batch related data into fewer queries - -Instead of N components each fetching their own related data, fetch it in a -single query. - -```ts -// Bad: each card fetches its own author -function ProjectCard({ project }: { project: Project }) { - const author = useQuery(api.users.get, { id: project.authorId }); - return ; -} -``` - -```ts -// Good: parent query returns projects with author names included -function ProjectList() { - const projects = useQuery(api.projects.listWithAuthors); - return projects?.map((p) => ( - - )); -} -``` - -This can use denormalized fields or server-side joins in the query handler. -Either way, it is one subscription instead of N. - -This is not automatically better. If the combined query becomes much broader and -invalidates much more often, several narrower subscriptions may be the better -tradeoff. Optimize for total invalidation cost, not raw subscription count. - -### 3. Use skip to avoid unnecessary subscriptions - -The `"skip"` value prevents a subscription from being created when the arguments -are not ready. - -```ts -// Bad: subscribes with undefined args, wastes a subscription slot -const profile = useQuery(api.users.getProfile, { userId: selectedId! }); -``` - -```ts -// Good: skip when there is nothing to fetch -const profile = useQuery( - api.users.getProfile, - selectedId ? { userId: selectedId } : "skip", -); -``` - -### 4. Isolate frequently-updated fields into separate documents - -If a document is widely read but has a field that changes often, move that field -to a separate document. Queries that do not need the field will no longer be -invalidated by its writes. - -```ts -// Bad: lastSeen lives on the user doc, every heartbeat invalidates -// every query that reads this user -const users = defineTable({ - name: v.string(), - email: v.string(), - lastSeen: v.number(), -}); -``` - -```ts -// Good: lastSeen lives in a separate heartbeat doc -const users = defineTable({ - name: v.string(), - email: v.string(), - heartbeatId: v.id("heartbeats"), -}); - -const heartbeats = defineTable({ - lastSeen: v.number(), -}); -``` - -Queries that only need `name` and `email` no longer re-run on every heartbeat. -Queries that actually need online status fetch the heartbeat document -explicitly. - -For an even further optimization, if you only need a coarse online/offline -boolean rather than the exact `lastSeen` timestamp, add a separate presence -document with an `isOnline` flag. Update it immediately when a user comes -online, and use a cron to batch-mark users offline when their heartbeat goes -stale. This way the presence query only invalidates when online status actually -changes, not on every heartbeat. - -### 5. Use the aggregate component for counts and sums - -Reactive global counts (`SELECT COUNT(*)` equivalent) invalidate on every insert -or delete to the table. The -[`@convex-dev/aggregate`](https://www.npmjs.com/package/@convex-dev/aggregate) -component maintains denormalized COUNT, SUM, and MAX values efficiently so you -do not need a reactive query scanning the full table. - -Use it for leaderboards, totals, "X items" badges, or any stat that would -otherwise require scanning many rows reactively. - -If the aggregate component is not appropriate, prefer point-in-time reads for -global stats, or precomputed summary rows updated by a cron or trigger, over -reactive queries that scan large tables. - -### 6. Narrow query read sets - -Queries that return less data and touch fewer documents invalidate less often. - -```ts -// Bad: returns all fields, invalidates on any field change -export const list = query({ - handler: async (ctx) => { - return await ctx.db.query("projects").collect(); - }, -}); -``` - -```ts -// Good: use a digest table with only the fields the list needs -export const listDigests = query({ - handler: async (ctx) => { - return await ctx.db.query("projectDigests").collect(); - }, -}); -``` - -Writes to fields not in the digest table do not invalidate the digest query. - -### 7. Remove `Date.now()` from queries - -Using `Date.now()` inside a query defeats Convex's query cache. The cache is -invalidated frequently to avoid showing stale time-dependent results, which -increases database work even when the underlying data has not changed. - -```ts -// Bad: Date.now() defeats query caching and causes frequent re-evaluation -const releasedPosts = await ctx.db - .query("posts") - .withIndex("by_released_at", (q) => q.lte("releasedAt", Date.now())) - .take(100); -``` - -```ts -// Good: use a boolean field updated by a scheduled function -const releasedPosts = await ctx.db - .query("posts") - .withIndex("by_is_released", (q) => q.eq("isReleased", true)) - .take(100); -``` - -If the query must compare against a time value, pass it as an explicit argument -from the client and round it to a coarse interval (e.g. the most recent minute) -so requests within that window share the same cache entry. - -### 8. Consider pagination strategy - -For long lists where users scroll through many pages: - -- If the data does not need live updates, use point-in-time fetching with manual - "load more" -- If it does need live updates, accept the subscription cost but limit the - number of loaded pages -- Consider whether older pages can be unloaded as the user scrolls forward - -### 9. Separate backend cost from UI churn - -If the main problem is loading flash or UI churn when query arguments change, -stabilizing the reactive UI behavior may be better than replacing reactivity -altogether. - -Treat this as a UX problem first when: - -- the underlying query is already reasonably cheap -- the complaint is flicker, loading flashes, or re-render churn -- live updates are still desirable once fresh data arrives - -## Verification - -1. Subscription count in dashboard is lower for the affected pages -2. UI responsiveness has improved -3. React profiling shows fewer unnecessary re-renders -4. Surfaces that do not need live updates are not paying for persistent - subscriptions unnecessarily -5. Sibling pages with similar patterns were updated consistently diff --git a/.agents/skills/convex-quickstart/SKILL.md b/.agents/skills/convex-quickstart/SKILL.md deleted file mode 100644 index 09400d39..00000000 --- a/.agents/skills/convex-quickstart/SKILL.md +++ /dev/null @@ -1,451 +0,0 @@ ---- -name: convex-quickstart -description: - Creates or adds Convex to an app. Use for new Convex projects, npm create - convex@latest, frontend setup, env vars, or the first npx convex dev run. ---- - -# Convex Quickstart - -Set up a working Convex project as fast as possible. - -## When to Use - -- Starting a brand new project with Convex -- Adding Convex to an existing React, Next.js, Vue, Svelte, or other app -- Scaffolding a Convex app for prototyping - -## When Not to Use - -- The project already has Convex installed and `convex/` exists - just start - building -- You only need to add auth to an existing Convex app - use the - `convex-setup-auth` skill - -## Workflow - -1. Determine the starting point: new project or existing app -2. If new project, pick a template and scaffold with `npm create convex@latest` -3. If existing app, install `convex` and wire up the provider -4. Run `npx convex dev --once` to provision a local anonymous deployment, push - the current `convex/` code, typecheck it, and regenerate types — all in one - shot, exiting cleanly. The output tells the agent whether the schema and - functions are valid. -5. Ask the user (or, for cloud agents, start in the background) `npm run dev` — - Convex templates wire the watcher and the frontend into a single command. If - the project has no combined dev script, use `npx convex dev` for the watcher - and run the frontend separately. -6. Verify the setup works - -## Path 1: New Project (Recommended) - -Use the official scaffolding tool. It creates a complete project with the -frontend framework, Convex backend, and all config wired together. - -### Pick a template - -| Template | Stack | -| -------------------------- | ----------------------------------------- | -| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | -| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | -| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | -| `nextjs-clerk` | Next.js + Clerk auth | -| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | -| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | -| `bare` | Convex backend only, no frontend | - -If the user has not specified a preference, default to `react-vite-shadcn` for -simple apps or `nextjs-shadcn` for apps that need SSR or API routes. - -You can also use any GitHub repo as a template: - -```bash -npm create convex@latest my-app -- -t owner/repo -npm create convex@latest my-app -- -t owner/repo#branch -``` - -### Scaffold the project - -Always pass the project name and template flag to avoid interactive prompts: - -```bash -npm create convex@latest my-app -- -t react-vite-shadcn -cd my-app -npm install -``` - -The scaffolding tool creates files but does not run `npm install`, so you must -run it yourself. - -To scaffold in the current directory (if it is empty): - -```bash -npm create convex@latest . -- -t react-vite-shadcn -npm install -``` - -### Provision the deployment and push code - -Run this yourself — it is a one-shot command that exits cleanly: - -```bash -npx convex dev --once -``` - -In a non-TTY environment (which is true for almost every agent run), this: - -- Provisions an _anonymous_ local Convex backend bound to `127.0.0.1`. No - browser login, no team/project prompts. -- Writes `CONVEX_DEPLOYMENT` and the framework's `*_CONVEX_URL` variables to - `.env.local`. -- Generates `convex/_generated/`. -- Pushes the current `convex/` code to the deployment, **typechecks it**, and - **validates the schema**. The agent reads this output to find out if the code - it just wrote is broken. - -To be explicit (recommended), set `CONVEX_AGENT_MODE=anonymous` so the behavior -does not depend on TTY detection: - -```bash -CONVEX_AGENT_MODE=anonymous npx convex dev --once -``` - -The deployment lives under `~/.convex/` and persists across runs. Re-running -`convex dev --once` after editing `convex/` files is the agent's main feedback -loop while the user-launched `npm run dev` is not in use. - -If the template's `package.json` defines a `predev` script (Convex Auth -templates and similar do), `npm run predev` runs `convex init` plus any one-time -setup (e.g. minting auth keys). Use it _in addition to_ `convex dev --once` when -present — `predev` handles the one-time setup, `convex dev --once` pushes and -validates the code. - -### Start the dev loop - -In most Convex templates, `npm run dev` runs both the Convex watcher and the -frontend dev server together (typically `convex dev --start 'vite --open'` or -the Next.js equivalent). That is what the user should run. - -```bash -npm run dev -``` - -If the project does not have a combined `dev` script — e.g. the `bare` template, -or an existing app where you haven't wired the frontend dev server into Convex's -`--start` flag — the user can run the Convex watcher directly: - -```bash -npx convex dev -``` - -`npx convex dev` is the same long-running watcher `npm run dev` invokes under -the hood; it just doesn't start the frontend. Use it when there is no frontend, -or when the user prefers to run the frontend in a separate terminal. - -Either way, the agent should not invoke the watcher in the foreground because it -does not exit. Two options: - -- **Local development (user is at the keyboard):** ask the user to run - `npm run dev` (or `npx convex dev`) in a terminal. The deployment provisioned - by `convex dev --once` above is already selected, so the watcher picks up - immediately with no prompts. -- **Cloud or headless agents:** start `npm run dev` (or `npx convex dev`) in the - background. - -Vite apps serve on `http://localhost:5173`, Next.js on `http://localhost:3000`. - -### What you get - -After scaffolding, the project structure looks like: - -``` -my-app/ - convex/ # Backend functions and schema - _generated/ # Auto-generated types (check this into git) - schema.ts # Database schema (if template includes one) - src/ # Frontend code (or app/ for Next.js) - package.json - .env.local # CONVEX_URL / VITE_CONVEX_URL / NEXT_PUBLIC_CONVEX_URL -``` - -The template already has: - -- `ConvexProvider` wired into the app root -- Correct env var names for the framework -- Tailwind and shadcn/ui ready (for shadcn templates) -- Auth provider configured (for auth templates) - -Proceed to adding schema, functions, and UI. - -## Path 2: Add Convex to an Existing App - -Use this when the user already has a frontend project and wants to add Convex as -the backend. - -### Install - -```bash -npm install convex -``` - -### Provision and push - -Run `npx convex dev --once` yourself to provision a local anonymous deployment, -write `.env.local`, generate types, push the current `convex/` code, and -typecheck it. This is one-shot and exits: - -```bash -npx convex dev --once -``` - -The output tells you whether the schema and functions are valid — use it as your -feedback loop while iterating. - -Then ask the user to start the watcher (or, for cloud/headless agents, start it -in the background). You have two options: - -- **Wire Convex into `npm run dev`** — change the existing app's `dev` script to - `convex dev --start ''`. That's the standard pattern - Convex templates use; the user then runs a single `npm run dev` to start both. -- **Run them separately** — leave `npm run dev` for the frontend and tell the - user to run `npx convex dev` in a second terminal for the Convex watcher. - -See "Start the dev loop" above for why the agent should not run the watcher in -the foreground. - -### Wire up the provider - -The Convex client must wrap the app at the root. The setup varies by framework. - -Create the `ConvexReactClient` at module scope, not inside a component: - -```tsx -// Bad: re-creates the client on every render -function App() { - const convex = new ConvexReactClient( - import.meta.env.VITE_CONVEX_URL as string, - ); - return ...; -} - -// Good: created once at module scope -const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); -function App() { - return ...; -} -``` - -#### React (Vite) - -```tsx -// src/main.tsx -import { StrictMode } from "react"; -import { createRoot } from "react-dom/client"; -import { ConvexProvider, ConvexReactClient } from "convex/react"; -import App from "./App"; - -const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); - -createRoot(document.getElementById("root")!).render( - - - - - , -); -``` - -#### Next.js (App Router) - -```tsx -// app/ConvexClientProvider.tsx -"use client"; - -import { ConvexProvider, ConvexReactClient } from "convex/react"; -import { ReactNode } from "react"; - -const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); - -export function ConvexClientProvider({ children }: { children: ReactNode }) { - return {children}; -} -``` - -```tsx -// app/layout.tsx -import { ConvexClientProvider } from "./ConvexClientProvider"; - -export default function RootLayout({ - children, -}: { - children: React.ReactNode; -}) { - return ( - - - {children} - - - ); -} -``` - -#### Other frameworks - -For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the -matching quickstart guide: - -- [Vue](https://docs.convex.dev/quickstart/vue) -- [Svelte](https://docs.convex.dev/quickstart/svelte) -- [React Native](https://docs.convex.dev/quickstart/react-native) -- [TanStack Start](https://docs.convex.dev/quickstart/tanstack-start) -- [Remix](https://docs.convex.dev/quickstart/remix) -- [Node.js (no frontend)](https://docs.convex.dev/quickstart/nodejs) - -### Environment variables - -The env var name depends on the framework: - -| Framework | Variable | -| ------------ | ------------------------ | -| Vite | `VITE_CONVEX_URL` | -| Next.js | `NEXT_PUBLIC_CONVEX_URL` | -| Remix | `CONVEX_URL` | -| React Native | `EXPO_PUBLIC_CONVEX_URL` | - -`npx convex dev` writes the correct variable to `.env.local` automatically. - -## Agent Mode - -`CONVEX_AGENT_MODE=anonymous` forces an unauthenticated local backend. It is -already the implicit default for any non-TTY run of `npx convex init` or -`npx convex dev`, but set it explicitly so the behavior does not depend on TTY -detection: - -```bash -CONVEX_AGENT_MODE=anonymous npx convex dev --once -``` - -Use it for: - -- Any AI coding agent (local or cloud). -- CI-like setup scripts. -- Cases where the user is logged in but you do not want to touch their personal - dev deployment. - -The resulting backend runs on `127.0.0.1` and is not associated with any team or -project until the user later claims it via `npx convex login` and the -`npx convex deployment` commands. - -## Verify the Setup - -After setup, confirm everything is working: - -1. `npx convex dev --once` exited without errors (deployment provisioned, code - pushed, schema validated, typecheck clean) -2. The `convex/_generated/` directory exists and has `api.ts` and `server.ts` -3. `.env.local` contains a `CONVEX_DEPLOYMENT` value and the framework's - `*_CONVEX_URL` variable -4. (If applicable) `npm run dev` (or `npx convex dev` for the watcher alone) is - running without errors in another terminal or in the background - -## Writing Your First Function - -Once the project is set up, create a schema and a query to verify the full loop -works. - -`convex/schema.ts`: - -```ts -import { defineSchema, defineTable } from "convex/server"; -import { v } from "convex/values"; - -export default defineSchema({ - tasks: defineTable({ - text: v.string(), - completed: v.boolean(), - }), -}); -``` - -`convex/tasks.ts`: - -```ts -import { query, mutation } from "./_generated/server"; -import { v } from "convex/values"; - -export const list = query({ - args: {}, - handler: async (ctx) => { - return await ctx.db.query("tasks").collect(); - }, -}); - -export const create = mutation({ - args: { text: v.string() }, - handler: async (ctx, args) => { - await ctx.db.insert("tasks", { text: args.text, completed: false }); - }, -}); -``` - -Use in a React component (adjust the import path based on your file location -relative to `convex/`): - -```tsx -import { useQuery, useMutation } from "convex/react"; -import { api } from "../convex/_generated/api"; - -function Tasks() { - const tasks = useQuery(api.tasks.list); - const create = useMutation(api.tasks.create); - - return ( -
- - {tasks?.map((t) => ( -
{t.text}
- ))} -
- ); -} -``` - -## Development vs Production - -Always use `npx convex dev` during development. It runs against your personal -dev deployment and syncs code on save. - -When ready to ship, deploy to production: - -```bash -npx convex deploy -``` - -This pushes to the production deployment, which is separate from dev. Do not use -`deploy` during development. - -## Next Steps - -- Add authentication: use the `convex-setup-auth` skill -- Design your schema: see - [Schema docs](https://docs.convex.dev/database/schemas) -- Build components: use the `convex-create-component` skill -- Plan a migration: use the `convex-migration-helper` skill -- Add file storage: see - [File Storage docs](https://docs.convex.dev/file-storage) -- Set up cron jobs: see [Scheduling docs](https://docs.convex.dev/scheduling) - -## Checklist - -- [ ] Determined starting point: new project or existing app -- [ ] If new project: scaffolded with `npm create convex@latest` using - appropriate template -- [ ] If existing app: installed `convex` and wired up the provider -- [ ] Agent ran `npx convex dev --once`: deployment provisioned, code pushed, - typecheck clean -- [ ] `npm run dev` (or `npx convex dev` for the watcher alone) is running — - user-launched terminal, or background for cloud agents -- [ ] `convex/_generated/` directory exists with types -- [ ] `.env.local` has the deployment URL -- [ ] Verified a basic query/mutation round-trip works diff --git a/.agents/skills/convex-quickstart/agents/openai.yaml b/.agents/skills/convex-quickstart/agents/openai.yaml deleted file mode 100644 index 0347a50e..00000000 --- a/.agents/skills/convex-quickstart/agents/openai.yaml +++ /dev/null @@ -1,14 +0,0 @@ -interface: - display_name: "Convex Quickstart" - short_description: - "Start a new Convex app or add Convex to an existing frontend." - icon_small: "./assets/icon.svg" - icon_large: "./assets/icon.svg" - brand_color: "#F97316" - default_prompt: - "Set up Convex for this project as fast as possible. First decide whether - this is a new app or an existing app, then scaffold or integrate Convex and - verify the setup works." - -policy: - allow_implicit_invocation: true diff --git a/.agents/skills/convex-setup-auth/SKILL.md b/.agents/skills/convex-setup-auth/SKILL.md deleted file mode 100644 index 410198f0..00000000 --- a/.agents/skills/convex-setup-auth/SKILL.md +++ /dev/null @@ -1,187 +0,0 @@ ---- -name: convex-setup-auth -description: - Sets up Convex auth, identity mapping, and access control. Use for login, auth - providers, users tables, protected functions, or roles in a Convex app. ---- - -# Convex Authentication Setup - -Implement secure authentication in Convex with user management and access -control. - -## When to Use - -- Setting up authentication for the first time -- Implementing user management (users table, identity mapping) -- Creating authentication helper functions -- Setting up auth providers (Convex Auth, Clerk, WorkOS AuthKit, Auth0, custom - JWT) - -## When Not to Use - -- Auth for a non-Convex backend -- Pure OAuth/OIDC documentation without a Convex implementation -- Debugging unrelated bugs that happen to surface near auth code -- The auth provider is already fully configured and the user only needs a - one-line fix - -## First Step: Choose the Auth Provider - -Convex supports multiple authentication approaches. Do not assume a provider. - -Before writing setup code: - -1. Ask the user which auth solution they want, unless the repository already - makes it obvious -2. If the repo already uses a provider, continue with that provider unless the - user wants to switch -3. If the user has not chosen a provider and the repo does not make it obvious, - ask before proceeding - -Common options: - -- [Convex Auth](https://docs.convex.dev/auth/convex-auth) - good default when - the user wants auth handled directly in Convex -- [Clerk](https://docs.convex.dev/auth/clerk) - use when the app already uses - Clerk or the user wants Clerk's hosted auth features -- [WorkOS AuthKit](https://docs.convex.dev/auth/authkit/) - use when the app - already uses WorkOS or the user wants AuthKit specifically -- [Auth0](https://docs.convex.dev/auth/auth0) - use when the app already uses - Auth0 -- Custom JWT provider - use when integrating an existing auth system not covered - above - -Look for signals in the repo before asking: - -- Dependencies such as `@clerk/*`, `@workos-inc/*`, `@auth0/*`, or Convex Auth - packages -- Existing files such as `convex/auth.config.ts`, auth middleware, provider - wrappers, or login components -- Environment variables that clearly point at a provider - -## After Choosing a Provider - -Read the provider's official guide and the matching local reference file: - -- Convex Auth: [official docs](https://docs.convex.dev/auth/convex-auth), then - `references/convex-auth.md` -- Clerk: [official docs](https://docs.convex.dev/auth/clerk), then - `references/clerk.md` -- WorkOS AuthKit: [official docs](https://docs.convex.dev/auth/authkit/), then - `references/workos-authkit.md` -- Auth0: [official docs](https://docs.convex.dev/auth/auth0), then - `references/auth0.md` - -The local reference files contain the concrete workflow, expected files and env -vars, gotchas, and validation checks. - -Use those sources for: - -- package installation -- client provider wiring -- environment variables -- `convex/auth.config.ts` setup -- login and logout UI patterns -- framework-specific setup for React, Vite, or Next.js - -For shared auth behavior, use the official Convex docs as the source of truth: - -- [Auth in Functions](https://docs.convex.dev/auth/functions-auth) for - `ctx.auth.getUserIdentity()` -- [Storing Users in the Convex Database](https://docs.convex.dev/auth/database-auth) - for optional app-level user storage -- [Authentication](https://docs.convex.dev/auth) for general auth and - authorization guidance -- [Convex Auth Authorization](https://labs.convex.dev/auth/authz) when the - provider is Convex Auth - -Prefer official docs over recalled steps, because provider CLIs and Convex Auth -internals change between versions. Inventing setup from memory risks outdated -patterns. For third-party providers, only add app-level user storage if the app -actually needs user documents in Convex. Not every app needs a `users` table. -For Convex Auth, follow the Convex Auth docs and built-in auth tables rather -than adding a parallel `users` table plus `storeUser` flow, because Convex Auth -already manages user records internally. After running provider initialization -commands, verify generated files and complete the post-init wiring steps the -provider reference calls out. Initialization commands rarely finish the entire -integration. - -## Core Pattern: Protecting Backend Functions - -The most common auth task is checking identity in Convex functions. - -```ts -// Bad: trusting a client-provided userId -export const getMyProfile = query({ - args: { userId: v.id("users") }, - handler: async (ctx, args) => { - return await ctx.db.get(args.userId); - }, -}); -``` - -```ts -// Good: verifying identity server-side -export const getMyProfile = query({ - args: {}, - handler: async (ctx) => { - const identity = await ctx.auth.getUserIdentity(); - if (!identity) throw new Error("Not authenticated"); - - return await ctx.db - .query("users") - .withIndex("by_tokenIdentifier", (q) => - q.eq("tokenIdentifier", identity.tokenIdentifier), - ) - .unique(); - }, -}); -``` - -## Workflow - -1. Determine the provider, either by asking the user or inferring from the repo -2. Ask whether the user wants local-only setup or production-ready setup now -3. Read the matching provider reference file -4. Follow the official provider docs for current setup details -5. Follow the official Convex docs for shared backend auth behavior, user - storage, and authorization patterns -6. Only add app-level user storage if the docs and app requirements call for it -7. Add authorization checks for ownership, roles, or team access only where the - app needs them -8. Verify login state, protected queries, environment variables, and production - configuration if requested - -If the flow blocks on interactive provider or deployment setup, ask the user -explicitly for the exact human step needed, then continue after they complete -it. For UI-facing auth flows, offer to validate the real sign-up or sign-in flow -after setup is done. If the environment has browser automation tools, you can -use them. If it does not, give the user a short manual validation checklist -instead. - -## Reference Files - -### Provider References - -- `references/convex-auth.md` -- `references/clerk.md` -- `references/workos-authkit.md` -- `references/auth0.md` - -## Checklist - -- [ ] Chosen the correct auth provider before writing setup code -- [ ] Read the relevant provider reference file -- [ ] Asked whether the user wants local-only setup or production-ready setup -- [ ] Used the official provider docs for provider-specific wiring -- [ ] Used the official Convex docs for shared auth behavior and authorization - patterns -- [ ] Only added app-level user storage if the app actually needs it -- [ ] Did not invent a cross-provider `users` table or `storeUser` flow for - Convex Auth -- [ ] Added authentication checks in protected backend functions -- [ ] Added authorization checks where the app actually needs them -- [ ] Clear error messages ("Not authenticated", "Unauthorized") -- [ ] Client auth provider configured for the chosen provider -- [ ] If requested, production auth setup is covered too diff --git a/.agents/skills/convex-setup-auth/agents/openai.yaml b/.agents/skills/convex-setup-auth/agents/openai.yaml deleted file mode 100644 index f7e207c9..00000000 --- a/.agents/skills/convex-setup-auth/agents/openai.yaml +++ /dev/null @@ -1,14 +0,0 @@ -interface: - display_name: "Convex Setup Auth" - short_description: - "Set up Convex auth, user identity mapping, and access control." - icon_small: "./assets/icon.svg" - icon_large: "./assets/icon.svg" - brand_color: "#2563EB" - default_prompt: - "Set up authentication for this Convex app. Figure out the provider first, - then wire up the user model, identity mapping, and access control with the - smallest solid implementation." - -policy: - allow_implicit_invocation: true diff --git a/.agents/skills/convex-setup-auth/references/auth0.md b/.agents/skills/convex-setup-auth/references/auth0.md deleted file mode 100644 index c1e08a5a..00000000 --- a/.agents/skills/convex-setup-auth/references/auth0.md +++ /dev/null @@ -1,156 +0,0 @@ -# Auth0 - -Official docs: - -- https://docs.convex.dev/auth/auth0 -- https://auth0.github.io/auth0-cli/ -- https://auth0.github.io/auth0-cli/auth0_apps_create.html - -Use this when the app already uses Auth0 or the user wants Auth0 specifically. - -## Workflow - -1. Confirm the user wants Auth0 -2. Determine the app framework and whether Auth0 is already partly set up -3. Ask whether the user wants local-only setup or production-ready setup now -4. Read the official Convex and Auth0 guides before making changes -5. Ask whether they want the fastest setup path by installing the Auth0 CLI -6. If they agree, install the Auth0 CLI and do as much of the Auth0 app setup as - possible through the CLI -7. If they do not want the CLI path, use the Auth0 dashboard path instead -8. Complete the relevant Auth0 frontend quickstart if the app does not already - have Auth0 wired up -9. Configure `convex/auth.config.ts` with the Auth0 domain and client ID -10. Set environment variables for local and production environments -11. Wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` -12. Gate Convex-backed UI with Convex auth state -13. Try to verify Convex reports the user as authenticated after Auth0 login -14. If the refresh-token path fails, stop improvising and send the user back to - the official docs -15. If the user wants production-ready setup, make sure the production Auth0 - tenant and env vars are also covered - -## What To Do - -- Read the official Convex and Auth0 guide before writing setup code -- Prefer the Auth0 CLI path for mechanical setup if the user is willing to - install it, but do not present it as a fully validated end-to-end path yet -- Ask the user directly: "The fastest path is to install the Auth0 CLI so I can - do more of this for you. If you want, I can install it and then only ask you - to log in when needed. Would you like me to do that?" -- Make sure the app has already completed the relevant Auth0 quickstart for its - frontend -- Use the official examples for `Auth0Provider` and `ConvexProviderWithAuth0` -- If the Auth0 login or refresh flow starts failing in a way that is not clearly - explained by the docs, say that plainly and fall back to the official docs - instead of pretending the flow is validated - -## Key Setup Areas - -- install the Auth0 SDK for the app's framework -- configure `convex/auth.config.ts` with the Auth0 domain and client ID -- set environment variables for local and production environments -- wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` -- use Convex auth state when gating Convex-backed UI - -## Files and Env Vars To Expect - -- `convex/auth.config.ts` -- frontend app entry or provider wrapper -- Auth0 CLI install docs: `https://auth0.github.io/auth0-cli/` -- Auth0 environment variables commonly include: - - `AUTH0_DOMAIN` - - `AUTH0_CLIENT_ID` - - `VITE_AUTH0_DOMAIN` - - `VITE_AUTH0_CLIENT_ID` - -## Concrete Steps - -1. Start by reading `https://docs.convex.dev/auth/auth0` and the relevant Auth0 - quickstart for the app's framework -2. Ask whether the user wants the Auth0 CLI path -3. If yes, install Auth0 CLI and have the user authenticate it with - `auth0 login` -4. Use `auth0 apps create` with SPA settings, callback URL, logout URL, and web - origins if creating a new app -5. If not using the CLI path, complete the relevant Auth0 frontend quickstart - and create the Auth0 app in the dashboard -6. Get the Auth0 domain and client ID from the CLI output or the Auth0 dashboard -7. Install the Auth0 SDK for the app's framework -8. Create or update `convex/auth.config.ts` with the Auth0 domain and client ID -9. Set frontend and backend environment variables -10. Wrap the app in `Auth0Provider` -11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithAuth0` -12. Run the normal Convex dev or deploy flow after backend config changes -13. Try the official provider config shown in the Convex docs -14. If login works but Convex auth or token refresh fails in a way you cannot - clearly resolve, stop and tell the user to follow the official docs manually - for now -15. Only claim success if the user can sign in and Convex recognizes the - authenticated session -16. If the user wants production-ready setup, configure the production Auth0 - tenant values and production environment variables too - -## Gotchas - -- The Convex docs assume the Auth0 side is already set up, so do not skip the - Auth0 quickstart if the app is starting from scratch -- The Auth0 CLI is often the fastest path for a fresh setup, but it still - requires the user to authenticate the CLI to their Auth0 tenant -- If the user agrees to install the Auth0 CLI, do the mechanical setup yourself - instead of bouncing them through the dashboard -- If login succeeds but Convex still reports unauthenticated, double-check - `convex/auth.config.ts` and whether the backend config was synced -- We were able to automate Auth0 app creation and Convex config wiring, but we - did not fully validate the refresh-token path end to end -- In validation, the documented `useRefreshTokens={true}` and - `cacheLocation="localstorage"` setup hit refresh-token failures, so do not - present that path as settled -- If you hit Auth0 errors like `Unknown or invalid refresh token`, do not keep - inventing fixes indefinitely, send the user back to the official docs and - explain that this path is still under investigation -- Keep dev and prod tenants separate if the project uses different Auth0 - environments -- Do not confuse "Auth0 login works" with "Convex can validate the Auth0 token". - Both need to work. -- If the repo already uses Auth0, preserve existing redirect and tenant - configuration unless the user asked to change it. -- Do not assume the local Auth0 tenant settings match production. Verify the - production domain, client ID, and callback URLs separately. -- For local dev, make sure the Auth0 app settings match the app's real local - port for callback URLs, logout URLs, and web origins - -## Production - -- Ask whether the user wants dev-only setup or production-ready setup -- If the answer is production-ready, make sure the production Auth0 tenant - values, callback URLs, and Convex deployment config are all covered -- Verify production environment variables and redirect settings before calling - the task complete -- Do not silently write a notes file into the repo by default. If the user wants - rollout or handoff docs, create one explicitly. - -## Validation - -- Verify the user can complete the Auth0 login flow -- Verify Convex-authenticated UI renders only after Convex auth state is ready -- Verify protected Convex queries succeed after login -- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions -- Verify the Auth0 app settings match the real local callback and logout URLs - during development -- If the Auth0 refresh-token path fails, mark the setup as not fully validated - and direct the user to the official docs instead of claiming the skill - completed successfully -- If production-ready setup was requested, verify the production Auth0 - configuration is also covered - -## Checklist - -- [ ] Confirm the user wants Auth0 -- [ ] Ask whether the user wants local-only setup or production-ready setup -- [ ] Complete the relevant Auth0 frontend setup -- [ ] Configure `convex/auth.config.ts` -- [ ] Set environment variables -- [ ] Verify Convex authenticated state after login, or explicitly tell the user - this path is still under investigation and send them to the official docs -- [ ] If requested, configure the production deployment too diff --git a/.agents/skills/convex-setup-auth/references/clerk.md b/.agents/skills/convex-setup-auth/references/clerk.md deleted file mode 100644 index 20f37dd7..00000000 --- a/.agents/skills/convex-setup-auth/references/clerk.md +++ /dev/null @@ -1,141 +0,0 @@ -# Clerk - -Official docs: - -- https://docs.convex.dev/auth/clerk -- https://clerk.com/docs/guides/development/integrations/databases/convex - -Use this when the app already uses Clerk or the user wants Clerk's hosted auth -features. - -## Workflow - -1. Confirm the user wants Clerk -2. Make sure the user has a Clerk account and a Clerk application -3. Determine the app framework: - - React - - Next.js - - TanStack Start -4. Ask whether the user wants local-only setup or production-ready setup now -5. Gather the Clerk keys and the Clerk Frontend API URL -6. Follow the correct framework section in the official docs -7. Complete the backend and client wiring -8. Verify Convex reports the user as authenticated after login -9. If the user wants production-ready setup, make sure the production Clerk - config is also covered - -## What To Do - -- Read the official Convex and Clerk guide before writing setup code -- If the user does not already have Clerk set up, send them to - `https://dashboard.clerk.com/sign-up` to create an account and - `https://dashboard.clerk.com/apps/new` to create an application -- Send the user to `https://dashboard.clerk.com/apps/setup/convex` if the Convex - integration is not already active -- Match the guide to the app's framework, usually React, Next.js, or TanStack - Start -- Use the official examples for `ConvexProviderWithClerk`, `ClerkProvider`, and - `useAuth` - -## Key Setup Areas - -- install the Clerk SDK for the framework in use -- configure `convex/auth.config.ts` with the Clerk issuer domain -- set the required Clerk environment variables -- wrap the app with `ClerkProvider` and `ConvexProviderWithClerk` -- use Convex auth-aware UI patterns such as `Authenticated`, `Unauthenticated`, - and `AuthLoading` - -## Files and Env Vars To Expect - -- `convex/auth.config.ts` -- React or Vite client entry such as `src/main.tsx` -- Next.js client wrapper for Convex if using App Router -- Clerk account sign-up page: `https://dashboard.clerk.com/sign-up` -- Clerk app creation page: `https://dashboard.clerk.com/apps/new` -- Clerk Convex integration page: `https://dashboard.clerk.com/apps/setup/convex` -- Clerk API keys page: `https://dashboard.clerk.com/last-active?path=api-keys` -- Clerk environment variables: - - `CLERK_JWT_ISSUER_DOMAIN` for Convex backend validation in the Convex docs - - `CLERK_FRONTEND_API_URL` in the Clerk docs - - `VITE_CLERK_PUBLISHABLE_KEY` for Vite apps - - `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` for Next.js apps - - `CLERK_SECRET_KEY` for Next.js server-side Clerk setup where required - -`CLERK_JWT_ISSUER_DOMAIN` and `CLERK_FRONTEND_API_URL` refer to the same Clerk -Frontend API URL value. Do not treat them as two different URLs. - -## Concrete Steps - -1. If needed, create a Clerk account at `https://dashboard.clerk.com/sign-up` -2. If needed, create a Clerk application at - `https://dashboard.clerk.com/apps/new` -3. Open `https://dashboard.clerk.com/last-active?path=api-keys` and copy the - publishable key, plus the secret key for Next.js where needed -4. Open `https://dashboard.clerk.com/apps/setup/convex` -5. Activate the Convex integration in Clerk if it is not already active -6. Copy the Clerk Frontend API URL shown there -7. Install the Clerk package for the app's framework -8. Create or update `convex/auth.config.ts` so Convex validates Clerk tokens -9. Set the publishable key in the frontend environment -10. Set the issuer domain or Frontend API URL so Convex can validate the JWT -11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithClerk` -12. Wrap the app in `ClerkProvider` -13. Use Convex auth helpers for authenticated rendering -14. Run the normal Convex dev or deploy flow after updating backend auth config -15. If the user wants production-ready setup, configure the production Clerk - values and production issuer domain too - -## Gotchas - -- Prefer `useConvexAuth()` over raw Clerk auth state when deciding whether - Convex-authenticated UI can render -- For Next.js, keep server and client boundaries in mind when creating the - Convex provider wrapper -- After changing `convex/auth.config.ts`, run the normal Convex dev or deploy - flow so the backend picks up the new config -- Do not stop at "Clerk login works". The important check is that Convex also - sees the session and can authenticate requests. -- If the repo already uses Clerk, preserve its existing auth flow unless the - user asked to change it. -- Do not assume the same Clerk values work for both dev and production. Check - the production issuer domain and publishable key separately. -- The Convex setup page is where you get the Clerk Frontend API URL for Convex. - Keep using the Clerk API keys page for the publishable key and the secret key. -- If Convex says no auth provider matched the token, first confirm the Clerk - Convex integration was activated at - `https://dashboard.clerk.com/apps/setup/convex` -- After activating the Clerk Convex integration, sign out completely and sign - back in before retesting. An old Clerk session can keep using a token that - Convex rejects. - -## Production - -- Ask whether the user wants dev-only setup or production-ready setup -- If the answer is production-ready, make sure production Clerk keys and issuer - configuration are included -- Verify production redirect URLs and any production Clerk domain values before - calling the task complete -- Do not silently write a notes file into the repo by default. If the user wants - rollout or handoff docs, create one explicitly. - -## Validation - -- Verify the user can sign in with Clerk -- If the Clerk integration was just activated, verify after a full Clerk - sign-out and fresh sign-in -- Verify `useConvexAuth()` reaches the authenticated state after Clerk login -- Verify protected Convex queries run successfully inside authenticated UI -- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions -- If production-ready setup was requested, verify the production Clerk - configuration is also covered - -## Checklist - -- [ ] Confirm the user wants Clerk -- [ ] Ask whether the user wants local-only setup or production-ready setup -- [ ] Follow the correct framework section in the official guide -- [ ] Set Clerk environment variables -- [ ] Configure `convex/auth.config.ts` -- [ ] Verify Convex authenticated state after login -- [ ] If requested, configure the production deployment too diff --git a/.agents/skills/convex-setup-auth/references/convex-auth.md b/.agents/skills/convex-setup-auth/references/convex-auth.md deleted file mode 100644 index 480672e9..00000000 --- a/.agents/skills/convex-setup-auth/references/convex-auth.md +++ /dev/null @@ -1,188 +0,0 @@ -# Convex Auth - -Official docs: https://docs.convex.dev/auth/convex-auth Setup guide: -https://labs.convex.dev/auth/setup - -Use this when the user wants auth handled directly in Convex rather than through -a third-party provider. - -## Workflow - -1. Confirm the user wants Convex Auth specifically -2. Determine which sign-in methods the app needs: - - magic links or OTPs - - OAuth providers - - passwords and password reset -3. Ask whether the user wants local-only setup or production-ready setup now -4. Read the Convex Auth setup guide before writing code -5. Make sure the project has a configured Convex deployment: - - run `npx convex dev` first if `CONVEX_DEPLOYMENT` is not set - - if CLI configuration requires interactive human input, stop and ask the - user to complete that step before continuing -6. Install the auth packages: - - `npm install @convex-dev/auth @auth/core@0.37.0` -7. Run the initialization command: - - `npx @convex-dev/auth` -8. Confirm the initializer created: - - `convex/auth.config.ts` - - `convex/auth.ts` - - `convex/http.ts` -9. Add the required `authTables` to `convex/schema.ts` -10. Replace plain `ConvexProvider` wiring with `ConvexAuthProvider` -11. Configure at least one auth method in `convex/auth.ts` -12. Run `npx convex dev --once` or the normal dev flow to push the updated - schema and generated code -13. Verify the client can sign in successfully -14. Verify Convex receives authenticated identity in backend functions -15. If the user wants production-ready setup, make sure the same auth setup is - configured for the production deployment as well -16. Only add a `users` table and `storeUser` flow if the app needs app-level - user records inside Convex - -## What This Reference Is For - -- choosing Convex Auth as the default provider for a new Convex app -- understanding whether the app wants magic links, OTPs, OAuth, or passwords -- keeping the setup provider-specific while using the official Convex Auth docs - for identity and authorization behavior - -## What To Do - -- Read the Convex Auth setup guide before writing setup code -- Follow the setup flow from the docs rather than recreating it from memory -- If the app is new, consider starting from the official starter flow instead of - hand-wiring everything -- Treat `npx @convex-dev/auth` as a required initialization step for existing - apps, not an optional extra - -## Concrete Steps - -1. Install `@convex-dev/auth` and `@auth/core@0.37.0` -2. Run `npx convex dev` if the project does not already have a configured - deployment -3. If `npx convex dev` blocks on interactive setup, ask the user explicitly to - finish configuring the Convex deployment -4. Run `npx @convex-dev/auth` -5. Confirm the generated auth setup is present before continuing: - - `convex/auth.config.ts` - - `convex/auth.ts` - - `convex/http.ts` -6. Add `authTables` to `convex/schema.ts` -7. Replace `ConvexProvider` with `ConvexAuthProvider` in the app entry -8. Configure the selected auth methods in `convex/auth.ts` -9. Run `npx convex dev --once` or the normal dev flow so the updated schema and - auth files are pushed -10. Verify login locally -11. If the user wants production-ready setup, repeat the required auth - configuration against the production deployment - -## Expected Files and Decisions - -- `convex/schema.ts` -- frontend app entry such as `src/main.tsx` or the framework-equivalent provider - file -- generated Convex Auth setup produced by `npx @convex-dev/auth` -- an existing configured Convex deployment, or the ability to create one with - `npx convex dev` -- `convex/auth.ts` starts with `providers: []` until the app configures actual - sign-in methods - -- Decide whether the user is creating a new app or adding auth to an existing - app -- For a new app, prefer the official starter flow instead of rebuilding setup by - hand -- Decide which auth methods the app needs: - - magic links or OTPs - - OAuth providers - - passwords -- Decide whether the user wants local-only setup or production-ready setup now -- Decide whether the app actually needs a `users` table inside Convex, or - whether provider identity alone is enough - -## Gotchas - -- Do not assume a specific sign-in method. Ask which methods the app needs - before wiring UI and backend behavior. -- `npx @convex-dev/auth` is important because it initializes the auth setup, - including the key material. Do not skip it when adding Convex Auth to an - existing project. -- `npx @convex-dev/auth` will fail if the project does not already have a - configured `CONVEX_DEPLOYMENT`. -- `npx convex dev` may require interactive setup for deployment creation or - project selection. If that happens, ask the user explicitly for that human - step instead of guessing. -- `npx @convex-dev/auth` does not finish the whole integration by itself. You - still need to add `authTables`, swap in `ConvexAuthProvider`, and configure at - least one auth method. -- A project can still build even if `convex/auth.ts` still has `providers: []`, - so do not treat a successful build as proof that sign-in is fully configured. -- Convex Auth does not mean every app needs a `users` table. If the app only - needs authentication gates, `ctx.auth.getUserIdentity()` may be enough. -- If the app is greenfield, starting from the official starter flow is usually - better than partially recreating it by hand. -- Do not stop at local dev setup if the user expects production-ready auth. The - production deployment needs the auth setup too. -- Keep provider-specific setup and Convex Auth authorization behavior in the - official docs instead of inventing shared patterns from memory. - -## Production - -- Ask whether the user wants dev-only setup or production-ready setup -- If the answer is production-ready, make sure the auth configuration is applied - to the production deployment, not just the dev deployment -- Verify production-specific redirect URLs, auth method configuration, and - deployment settings before calling the task complete -- Do not silently write a notes file into the repo by default. If the user wants - rollout or handoff docs, create one explicitly. - -## Human Handoff - -If `npx convex dev` or deployment setup requires human input: - -- stop and explain exactly what the user needs to do -- say why that step is required -- resume the auth setup immediately after the user confirms it is done - -## Validation - -- Verify the user can complete a sign-in flow -- Offer to validate sign up, sign out, and sign back in with the configured auth - method -- If browser automation is available in the environment, you can do this - directly -- If browser automation is not available, give the user a short manual - validation checklist instead -- Verify `ctx.auth.getUserIdentity()` returns an identity in protected backend - functions -- Verify protected UI only renders after Convex-authenticated state is ready -- Verify environment variables and redirect settings match the current app - environment -- Verify `convex/auth.ts` no longer has an empty `providers: []` configuration - once the app is meant to support real sign-in -- Run `npx convex dev --once` or the normal dev flow after setup changes and - confirm Convex codegen and push succeed -- If production-ready setup was requested, verify the production deployment is - also configured correctly - -## Checklist - -- [ ] Confirm the user wants Convex Auth specifically -- [ ] Ask whether the user wants local-only setup or production-ready setup -- [ ] Ensure a Convex deployment is configured before running auth - initialization -- [ ] Install `@convex-dev/auth` and `@auth/core@0.37.0` -- [ ] Run `npx convex dev` first if needed -- [ ] Run `npx @convex-dev/auth` -- [ ] Confirm `convex/auth.config.ts`, `convex/auth.ts`, and `convex/http.ts` - were created -- [ ] Follow the setup guide for package install and wiring -- [ ] Add `authTables` to `convex/schema.ts` -- [ ] Replace `ConvexProvider` with `ConvexAuthProvider` -- [ ] Configure at least one auth method in `convex/auth.ts` -- [ ] Run `npx convex dev --once` or the normal dev flow after setup changes -- [ ] Confirm which sign-in methods the app needs -- [ ] Verify the client can sign in and the backend receives authenticated - identity -- [ ] Offer end-to-end validation of sign up, sign out, and sign back in -- [ ] If requested, configure the production deployment too -- [ ] Only add extra `users` table sync if the app needs app-level user records diff --git a/.agents/skills/convex-setup-auth/references/workos-authkit.md b/.agents/skills/convex-setup-auth/references/workos-authkit.md deleted file mode 100644 index 7c031b33..00000000 --- a/.agents/skills/convex-setup-auth/references/workos-authkit.md +++ /dev/null @@ -1,147 +0,0 @@ -# WorkOS AuthKit - -Official docs: - -- https://docs.convex.dev/auth/authkit/ -- https://docs.convex.dev/auth/authkit/add-to-app -- https://docs.convex.dev/auth/authkit/auto-provision - -Use this when the app already uses WorkOS or the user wants AuthKit -specifically. - -## Workflow - -1. Confirm the user wants WorkOS AuthKit -2. Determine whether they want: - - a Convex-managed WorkOS team - - an existing WorkOS team -3. Ask whether the user wants local-only setup or production-ready setup now -4. Read the official Convex and WorkOS AuthKit guide -5. Create or update `convex.json` for the app's framework and real local port -6. Follow the correct branch of the setup flow based on that choice -7. Configure the required WorkOS environment variables -8. Configure `convex/auth.config.ts` for WorkOS-issued JWTs -9. Wire the client provider and callback flow -10. Verify authenticated requests reach Convex -11. If the user wants production-ready setup, make sure the production WorkOS - configuration is covered too -12. Only add `storeUser` or a `users` table if the app needs first-class user - rows inside Convex - -## What To Do - -- Read the official Convex and WorkOS AuthKit guide before writing setup code -- Determine whether the user wants a Convex-managed WorkOS team or an existing - WorkOS team -- Treat `convex.json` as a first-class part of the AuthKit setup, not an - optional extra -- Follow the current setup flow from the docs instead of relying on older - examples - -## Key Setup Areas - -- package installation for the app's framework -- `convex.json` with the `authKit` section for dev, and preview or prod if - needed -- environment variables such as `WORKOS_CLIENT_ID`, `WORKOS_API_KEY`, and - redirect configuration -- `convex/auth.config.ts` wiring for WorkOS-issued JWTs -- client provider setup and token flow into Convex -- login callback and redirect configuration - -## Files and Env Vars To Expect - -- `convex.json` -- `convex/auth.config.ts` -- frontend auth provider wiring -- callback or redirect route setup where the framework requires it -- WorkOS environment variables commonly include: - - `WORKOS_CLIENT_ID` - - `WORKOS_API_KEY` - - `WORKOS_COOKIE_PASSWORD` - - `VITE_WORKOS_CLIENT_ID` - - `VITE_WORKOS_REDIRECT_URI` - - `NEXT_PUBLIC_WORKOS_REDIRECT_URI` - -For a managed WorkOS team, `convex dev` can provision the AuthKit environment -and write local env vars such as `VITE_WORKOS_CLIENT_ID` and -`VITE_WORKOS_REDIRECT_URI` into `.env.local` for Vite apps. - -## Concrete Steps - -1. Choose Convex-managed or existing WorkOS team -2. Create or update `convex.json` with the `authKit` section for the framework - in use -3. Make sure the dev `redirectUris`, `appHomepageUrl`, `corsOrigins`, and local - redirect env vars match the app's actual local port -4. For a managed WorkOS team, run `npx convex dev` and follow the interactive - onboarding flow -5. For an existing WorkOS team, get `WORKOS_CLIENT_ID` and `WORKOS_API_KEY` from - the WorkOS dashboard and set them with `npx convex env set` -6. Create or update `convex/auth.config.ts` for WorkOS JWT validation -7. Run the normal Convex dev or deploy flow so backend config is synced -8. Wire the WorkOS client provider in the app -9. Configure callback and redirect handling -10. Verify the user can sign in and return to the app -11. Verify Convex sees the authenticated user after login -12. If the user wants production-ready setup, configure the production client - ID, API key, redirect URI, and deployment settings too - -## Gotchas - -- The docs split setup between Convex-managed and existing WorkOS teams, so ask - which path the user wants if it is not obvious -- Keep dev and prod WorkOS configuration separate where the docs call for - different client IDs or API keys -- Only add `storeUser` or a `users` table if the app needs first-class user rows - inside Convex -- Do not mix dev and prod WorkOS credentials or redirect URIs -- If the repo already contains WorkOS setup, preserve the current tenant model - unless the user wants to change it -- For managed WorkOS setup, `convex dev` is interactive the first time. In - non-interactive terminals, stop and ask the user to complete the onboarding - prompts. -- `convex.json` is not optional for the managed AuthKit flow. It drives redirect - URI, homepage URL, CORS configuration, and local env var generation. -- If the frontend starts on a different port than the one in `convex.json`, the - hosted WorkOS sign-in flow will point to the wrong callback URL. Update - `convex.json`, update the local redirect env var, and run `npx convex dev` - again. -- Vite can fall off `5173` if other apps are already running. Do not assume the - default port still matches the generated AuthKit config. -- A successful WorkOS sign-in should redirect back to the local callback route - and then reach a Convex-authenticated state. Do not stop at "the hosted WorkOS - page loaded." - -## Production - -- Ask whether the user wants dev-only setup or production-ready setup -- If the answer is production-ready, make sure the production WorkOS client ID, - API key, redirect URI, and Convex deployment config are all covered -- Verify the production redirect and callback settings before calling the task - complete -- Do not silently write a notes file into the repo by default. If the user wants - rollout or handoff docs, create one explicitly. - -## Validation - -- Verify the user can complete the login flow and return to the app -- Verify the callback URL matches the real frontend port in local dev -- Verify Convex receives authenticated requests after login -- Verify `convex.json` matches the framework and chosen WorkOS setup path -- Verify `convex/auth.config.ts` matches the chosen WorkOS setup path -- Verify environment variables differ correctly between local and production - where needed -- If production-ready setup was requested, verify the production WorkOS - configuration is also covered - -## Checklist - -- [ ] Confirm the user wants WorkOS AuthKit -- [ ] Ask whether the user wants local-only setup or production-ready setup -- [ ] Choose Convex-managed or existing WorkOS team -- [ ] Create or update `convex.json` -- [ ] Configure WorkOS environment variables -- [ ] Configure `convex/auth.config.ts` -- [ ] Verify authenticated requests reach Convex after login -- [ ] If requested, configure the production deployment too diff --git a/.agents/skills/convex/SKILL.md b/.agents/skills/convex/SKILL.md deleted file mode 100644 index 08c67f14..00000000 --- a/.agents/skills/convex/SKILL.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -name: convex -description: - Routes general Convex requests to the right project skill. Use when the user - asks which Convex skill to use or gives an underspecified Convex app task. ---- - -# Convex - -Use this as the routing skill for Convex work in this repo. - -If a more specific Convex skill clearly matches the request, use that instead. - -## Start Here - -If the project does not already have Convex AI guidance installed, or the -existing guidance looks stale, strongly recommend installing it first. - -Preferred: - -```bash -npx convex ai-files install -``` - -This installs or refreshes the managed Convex AI files. It is the recommended -starting point for getting the official Convex guidelines in place and following -the current Convex AI setup described in the docs: - -- [Convex AI docs](https://docs.convex.dev/ai) - -Simple fallback: - -- [convex_rules.txt](https://convex.link/convex_rules.txt) - -Prefer `npx convex ai-files install` over copying rules by hand when possible. - -## Route to the Right Skill - -After that, use the most specific Convex skill for the task: - -- New project or adding Convex to an app: `convex-quickstart` -- Authentication setup: `convex-setup-auth` -- Building a reusable Convex component: `convex-create-component` -- Planning or running a migration: `convex-migration-helper` -- Investigating performance issues: `convex-performance-audit` - -If one of those clearly matches the user's goal, switch to it instead of staying -in this skill. - -## When Not to Use - -- The user has already named a more specific Convex workflow -- Another Convex skill obviously fits the request better diff --git a/.agents/skills/impeccable/SKILL.md b/.agents/skills/impeccable/SKILL.md deleted file mode 100644 index 25044b37..00000000 --- a/.agents/skills/impeccable/SKILL.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -name: impeccable -description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks. ---- - -Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft. - -## Setup (non-optional) - -Before any design work or file edits, pass these gates. Skipping them produces generic output that ignores the project. - -| Gate | Required check | If fail | -|---|---|---| -| Context | The PRODUCT.md / DESIGN.md loader result is known from `node .agents/skills/impeccable/scripts/load-context.mjs`. | Run the loader before continuing. | -| Product | PRODUCT.md exists and is not empty or placeholder (`[TODO]` markers, <200 chars). | Run `$impeccable teach`, refresh context, then resume. Never synthesize PRODUCT.md from the user's original prompt alone. | -| Command | The matching command reference is loaded when a sub-command is used. | Load the reference before continuing. | -| Craft | `$impeccable craft` has a user-confirmed shape brief for this task. `teach` / PRODUCT.md never counts as shape. | Run `$impeccable shape` and wait for explicit brief confirmation. | -| Image | Required visual probes / mocks are generated or skipped with a reason. | Resolve the image-generation gate in `shape.md` or `craft.md` before code. | -| Mutation | All active gates above pass. | Do not edit project files yet. | - -Codex-style agents must state this before editing files: - -```text -IMPECCABLE_PREFLIGHT: context=pass product=pass command_reference=pass shape=pass|not_required image_gate=pass|skipped: mutation=open -``` - -For `$impeccable craft`, `shape=pass` is only valid after a separate user response approving the shape design brief, or when the user provided an already-confirmed brief in the request. Do not mark `shape=pass` after writing PRODUCT.md, summarizing assumptions, or drafting an unconfirmed brief yourself. - -Other harnesses should follow the same checklist when they can expose this state. - -### 1. Context gathering - -Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd). - -- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles. -- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components. - -Load both in one call: - -```bash -node .agents/skills/impeccable/scripts/load-context.mjs -``` - -Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from. - -If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `$impeccable teach` or `$impeccable document` (they rewrite the files), or the user manually edited one. - -`$impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session. - -If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `$impeccable teach`, then resume the user's original task with the fresh context. If the original task was `$impeccable craft`, resume into `$impeccable shape` before any implementation work. - -If DESIGN.md is missing: nudge once per session (*"Run `$impeccable document` for more on-brand output"*), then proceed. - -### 2. Register - -Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product). - -Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins. - -If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `$impeccable teach` to add the field explicitly. - -Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both. - -## Shared design laws - -Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. GPT is capable of extraordinary work. Don't hold back. - -### Color - -- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish. -- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough). -- Pick a **color strategy** before picking colors. Four steps on the commitment axis: - - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism. - - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages. - - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz. - - **Drenched**: the surface IS the color. Brand heroes, campaign pages. -- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex. - -### Theme - -Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe." - -Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does. - -"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category. - -### Typography - -- Cap body line length at 65–75ch. -- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales. - -### Layout - -- Vary spacing for rhythm. Same padding everywhere is monotony. -- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong. -- Don't wrap everything in a container. Most things don't need one. - -### Motion - -- Don't animate CSS layout properties. -- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic. - -### Absolute bans - -Match-and-refuse. If you're about to write any of these, rewrite the element with different structure. - -- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing. -- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size. -- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing. -- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché. -- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly. -- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first. - -### Copy - -- Every word earns its place. No restated headings, no intros that repeat the title. -- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`. - -### The AI slop test - -If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference. - -**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses. - -- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain. -- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families. - -## Commands - -| Command | Category | Description | Reference | -|---|---|---|---| -| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) | -| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) | -| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) | -| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) | -| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) | -| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) | -| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) | -| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) | -| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) | -| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) | -| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) | -| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) | -| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) | -| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) | -| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) | -| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) | -| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) | -| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) | -| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) | -| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) | -| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) | -| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) | -| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) | - -Plus two management commands: `pin ` and `unpin `, detailed below. - -### Routing rules - -1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do. -2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target. -3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context. - -Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `$impeccable`. - -If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target. - -## Pin / Unpin - -**Pin** creates a standalone shortcut so `$` invokes `$impeccable ` directly. **Unpin** removes it. The script writes to every harness directory present in the project. - -```bash -node .agents/skills/impeccable/scripts/pin.mjs -``` - -Valid `` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error. \ No newline at end of file diff --git a/.agents/skills/impeccable/agents/openai.yaml b/.agents/skills/impeccable/agents/openai.yaml deleted file mode 100644 index ee6cae77..00000000 --- a/.agents/skills/impeccable/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: Impeccable - short_description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify,... - default_prompt: Use Impeccable to redesign, critique, audit, or polish this frontend. \ No newline at end of file diff --git a/.agents/skills/impeccable/reference/adapt.md b/.agents/skills/impeccable/reference/adapt.md deleted file mode 100644 index 21bb0255..00000000 --- a/.agents/skills/impeccable/reference/adapt.md +++ /dev/null @@ -1,190 +0,0 @@ -> **Additional context needed**: target platforms/devices and usage contexts. - -Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context. - - ---- - -## Assess Adaptation Challenge - -Understand what needs adaptation and why: - -1. **Identify the source context**: - - What was it designed for originally? (Desktop web? Mobile app?) - - What assumptions were made? (Large screen? Mouse input? Fast connection?) - - What works well in current context? - -2. **Understand target context**: - - **Device**: Mobile, tablet, desktop, TV, watch, print? - - **Input method**: Touch, mouse, keyboard, voice, gamepad? - - **Screen constraints**: Size, resolution, orientation? - - **Connection**: Fast wifi, slow 3G, offline? - - **Usage context**: On-the-go vs desk, quick glance vs focused reading? - - **User expectations**: What do users expect on this platform? - -3. **Identify adaptation challenges**: - - What won't fit? (Content, navigation, features) - - What won't work? (Hover states on touch, tiny touch targets) - - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop) - -**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels. - -## Plan Adaptation Strategy - -Create context-appropriate strategy: - -### Mobile Adaptation (Desktop → Mobile) - -**Layout Strategy**: -- Single column instead of multi-column -- Vertical stacking instead of side-by-side -- Full-width components instead of fixed widths -- Bottom navigation instead of top/side navigation - -**Interaction Strategy**: -- Touch targets 44x44px minimum (not hover-dependent) -- Swipe gestures where appropriate (lists, carousels) -- Bottom sheets instead of dropdowns -- Thumbs-first design (controls within thumb reach) -- Larger tap areas with more spacing - -**Content Strategy**: -- Progressive disclosure (don't show everything at once) -- Prioritize primary content (secondary content in tabs/accordions) -- Shorter text (more concise) -- Larger text (16px minimum) - -**Navigation Strategy**: -- Hamburger menu or bottom navigation -- Reduce navigation complexity -- Sticky headers for context -- Back button in navigation flow - -### Tablet Adaptation (Hybrid Approach) - -**Layout Strategy**: -- Two-column layouts (not single or three-column) -- Side panels for secondary content -- Master-detail views (list + detail) -- Adaptive based on orientation (portrait vs landscape) - -**Interaction Strategy**: -- Support both touch and pointer -- Touch targets 44x44px but allow denser layouts than phone -- Side navigation drawers -- Multi-column forms where appropriate - -### Desktop Adaptation (Mobile → Desktop) - -**Layout Strategy**: -- Multi-column layouts (use horizontal space) -- Side navigation always visible -- Multiple information panels simultaneously -- Fixed widths with max-width constraints (don't stretch to 4K) - -**Interaction Strategy**: -- Hover states for additional information -- Keyboard shortcuts -- Right-click context menus -- Drag and drop where helpful -- Multi-select with Shift/Cmd - -**Content Strategy**: -- Show more information upfront (less progressive disclosure) -- Data tables with many columns -- Richer visualizations -- More detailed descriptions - -### Print Adaptation (Screen → Print) - -**Layout Strategy**: -- Page breaks at logical points -- Remove navigation, footer, interactive elements -- Black and white (or limited color) -- Proper margins for binding - -**Content Strategy**: -- Expand shortened content (show full URLs, hidden sections) -- Add page numbers, headers, footers -- Include metadata (print date, page title) -- Convert charts to print-friendly versions - -### Email Adaptation (Web → Email) - -**Layout Strategy**: -- Narrow width (600px max) -- Single column only -- Inline CSS (no external stylesheets) -- Table-based layouts (for email client compatibility) - -**Interaction Strategy**: -- Large, obvious CTAs (buttons not text links) -- No hover states (not reliable) -- Deep links to web app for complex interactions - -## Implement Adaptations - -Apply changes systematically: - -### Responsive Breakpoints - -Choose appropriate breakpoints: -- Mobile: 320px-767px -- Tablet: 768px-1023px -- Desktop: 1024px+ -- Or content-driven breakpoints (where design breaks) - -### Layout Adaptation Techniques - -- **CSS Grid/Flexbox**: Reflow layouts automatically -- **Container Queries**: Adapt based on container, not viewport -- **`clamp()`**: Fluid sizing between min and max -- **Media queries**: Different styles for different contexts -- **Display properties**: Show/hide elements per context - -### Touch Adaptation - -- Increase touch target sizes (44x44px minimum) -- Add more spacing between interactive elements -- Remove hover-dependent interactions -- Add touch feedback (ripples, highlights) -- Consider thumb zones (easier to reach bottom than top) - -### Content Adaptation - -- Use `display: none` sparingly (still downloads) -- Progressive enhancement (core content first, enhancements on larger screens) -- Lazy loading for off-screen content -- Responsive images (`srcset`, `picture` element) - -### Navigation Adaptation - -- Transform complex nav to hamburger/drawer on mobile -- Bottom nav bar for mobile apps -- Persistent side navigation on desktop -- Breadcrumbs on smaller screens for context - -**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect. - -**NEVER**: -- Hide core functionality on mobile (if it matters, make it work) -- Assume desktop = powerful device (consider accessibility, older machines) -- Use different information architecture across contexts (confusing) -- Break user expectations for platform (mobile users expect mobile patterns) -- Forget landscape orientation on mobile/tablet -- Use generic breakpoints blindly (use content-driven breakpoints) -- Ignore touch on desktop (many desktop devices have touch) - -## Verify Adaptations - -Test thoroughly across contexts: - -- **Real devices**: Test on actual phones, tablets, desktops -- **Different orientations**: Portrait and landscape -- **Different browsers**: Safari, Chrome, Firefox, Edge -- **Different OS**: iOS, Android, Windows, macOS -- **Different input methods**: Touch, mouse, keyboard -- **Edge cases**: Very small screens (320px), very large screens (4K) -- **Slow connections**: Test on throttled network - -When the adaptation feels native to each context, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/animate.md b/.agents/skills/impeccable/reference/animate.md deleted file mode 100644 index 48b5e268..00000000 --- a/.agents/skills/impeccable/reference/animate.md +++ /dev/null @@ -1,175 +0,0 @@ -> **Additional context needed**: performance constraints. - -Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it. - ---- - -## Register - -Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions. - -Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it. - ---- - -## Assess Animation Opportunities - -Analyze where motion would improve the experience: - -1. **Identify static areas**: - - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.) - - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes) - - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious - - **Lack of delight**: Functional but joyless interactions - - **Missed guidance**: Opportunities to direct attention or explain behavior - -2. **Understand the context**: - - What's the personality? (Playful vs serious, energetic vs calm) - - What's the performance budget? (Mobile-first? Complex page?) - - Who's the audience? (Motion-sensitive users? Power users who want speed?) - - What matters most? (One hero animation vs many micro-interactions?) - -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. - -**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them. - -## Plan Animation Strategy - -Create a purposeful animation plan: - -- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?) -- **Feedback layer**: Which interactions need acknowledgment? -- **Transition layer**: Which state changes need smoothing? -- **Delight layer**: Where can we surprise and delight? - -**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments. - -## Implement Animations - -Add motion systematically across these categories: - -### Entrance Animations -- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations -- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects) -- **Content reveals**: Scroll-triggered animations using intersection observer -- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management - -### Micro-interactions -- **Button feedback**: - - Hover: Subtle scale (1.02-1.05), color shift, shadow increase - - Click: Quick scale down then up (0.95 → 1), ripple effect - - Loading: Spinner or pulse state -- **Form interactions**: - - Input focus: Border color transition, slight scale or glow - - Validation: Shake on error, check mark on success, smooth color transitions -- **Toggle switches**: Smooth slide + color transition (200-300ms) -- **Checkboxes/radio**: Check mark animation, ripple effect -- **Like/favorite**: Scale + rotation, particle effects, color transition - -### State Transitions -- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms) -- **Expand/collapse**: Height transition with overflow handling, icon rotation -- **Loading states**: Skeleton screen fades, spinner animations, progress bars -- **Success/error**: Color transitions, icon animations, gentle scale pulse -- **Enable/disable**: Opacity transitions, cursor changes - -### Navigation & Flow -- **Page transitions**: Crossfade between routes, shared element transitions -- **Tab switching**: Slide indicator, content fade/slide -- **Carousel/slider**: Smooth transforms, snap points, momentum -- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators - -### Feedback & Guidance -- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights -- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning -- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation -- **Focus flow**: Highlight path through form or workflow - -### Delight Moments -- **Empty states**: Subtle floating animations on illustrations -- **Completed actions**: Confetti, check mark flourish, success celebrations -- **Easter eggs**: Hidden interactions for discovery -- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches - -## Technical Implementation - -Use appropriate techniques for each animation: - -### Timing & Easing - -**Durations by purpose:** -- **100-150ms**: Instant feedback (button press, toggle) -- **200-300ms**: State changes (hover, menu open) -- **300-500ms**: Layout changes (accordion, modal) -- **500-800ms**: Entrance animations (page load) - -**Easing curves (use these, not CSS defaults):** -```css -/* Recommended: natural deceleration */ ---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */ ---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */ ---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */ - -/* AVOID: feel dated and tacky */ -/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */ -/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */ -``` - -**Exit animations are faster than entrances.** Use ~75% of enter duration. - -### CSS Animations -```css -/* Prefer for simple, declarative animations */ -- transitions for state changes -- @keyframes for complex sequences -- transform and opacity for reliable movement -- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth -``` - -### JavaScript Animation -```javascript -/* Use for complex, interactive animations */ -- Web Animations API for programmatic control -- Framer Motion for React -- GSAP for complex sequences -``` - -### Performance -- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect -- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins) -- **will-change**: Add sparingly for known expensive animations -- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate -- **Monitor FPS**: Ensure 60fps on target devices - -### Accessibility -```css -@media (prefers-reduced-motion: reduce) { - * { - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - } -} -``` - -**NEVER**: -- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself -- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work -- Use durations over 500ms for feedback (it feels laggy) -- Animate without purpose (every animation needs a reason) -- Ignore `prefers-reduced-motion` (this is an accessibility violation) -- Animate everything (animation fatigue makes interfaces feel exhausting) -- Block interaction during animations unless intentional - -## Verify Quality - -Test animations thoroughly: - -- **Smooth at 60fps**: No jank on target devices -- **Feels natural**: Easing curves feel organic, not robotic -- **Appropriate timing**: Not too fast (jarring) or too slow (laggy) -- **Reduced motion works**: Animations disabled or simplified appropriately -- **Doesn't block**: Users can interact during/after animations -- **Adds value**: Makes interface clearer or more delightful - -When the motion clarifies state instead of decorating it, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/audit.md b/.agents/skills/impeccable/reference/audit.md deleted file mode 100644 index 10f5572f..00000000 --- a/.agents/skills/impeccable/reference/audit.md +++ /dev/null @@ -1,133 +0,0 @@ -Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address. - -This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation. - -## Diagnostic Scan - -Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below. - -### 1. Accessibility (A11y) - -**Check for**: -- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA) -- **Missing ARIA**: Interactive elements without proper roles, labels, or states -- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps -- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons -- **Alt text**: Missing or poor image descriptions -- **Form issues**: Inputs without labels, poor error messaging, missing required indicators - -**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA) - -### 2. Performance - -**Check for**: -- **Layout thrashing**: Reading/writing layout properties in loops -- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames -- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change -- **Bundle size**: Unnecessary imports, unused dependencies -- **Render performance**: Unnecessary re-renders, missing memoization - -**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized) - -### 3. Theming - -**Check for**: -- **Hard-coded colors**: Colors not using design tokens -- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme -- **Inconsistent tokens**: Using wrong tokens, mixing token types -- **Theme switching issues**: Values that don't update on theme change - -**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly) - -### 4. Responsive Design - -**Check for**: -- **Fixed widths**: Hard-coded widths that break on mobile -- **Touch targets**: Interactive elements < 44x44px -- **Horizontal scroll**: Content overflow on narrow viewports -- **Text scaling**: Layouts that break when text size increases -- **Missing breakpoints**: No mobile/tablet variants - -**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets) - -### 5. Anti-Patterns (CRITICAL) - -Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy). - -**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design) - -## Generate Report - -### Audit Health Score - -| # | Dimension | Score | Key Finding | -|---|-----------|-------|-------------| -| 1 | Accessibility | ? | [most critical a11y issue or "--"] | -| 2 | Performance | ? | | -| 3 | Responsive Design | ? | | -| 4 | Theming | ? | | -| 5 | Anti-Patterns | ? | | -| **Total** | | **??/20** | **[Rating band]** | - -**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues) - -### Anti-Patterns Verdict -**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest. - -### Executive Summary -- Audit Health Score: **??/20** ([rating band]) -- Total issues found (count by severity: P0/P1/P2/P3) -- Top 3-5 critical issues -- Recommended next steps - -### Detailed Findings by Severity - -Tag every issue with **P0-P3 severity**: -- **P0 Blocking**: Prevents task completion. Fix immediately -- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release -- **P2 Minor**: Annoyance, workaround exists. Fix in next pass -- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits - -For each issue, document: -- **[P?] Issue name** -- **Location**: Component, file, line -- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern -- **Impact**: How it affects users -- **WCAG/Standard**: Which standard it violates (if applicable) -- **Recommendation**: How to fix it -- **Suggested command**: Which command to use (prefer: $impeccable adapt, $impeccable animate, $impeccable audit, $impeccable bolder, $impeccable clarify, $impeccable colorize, $impeccable critique, $impeccable delight, $impeccable distill, $impeccable document, $impeccable harden, $impeccable layout, $impeccable onboard, $impeccable optimize, $impeccable overdrive, $impeccable polish, $impeccable quieter, $impeccable shape, $impeccable typeset) - -### Patterns & Systemic Issues - -Identify recurring problems that indicate systemic gaps rather than one-off mistakes: -- "Hard-coded colors appear in 15+ components, should use design tokens" -- "Touch targets consistently too small (<44px) throughout mobile experience" - -### Positive Findings - -Note what's working well: good practices to maintain and replicate. - -## Recommended Actions - -List recommended commands in priority order (P0 first, then P1, then P2): - -1. **[P?] `$command-name`**: Brief description (specific context from audit findings) -2. **[P?] `$command-name`**: Brief description (specific context) - -**Rules**: Only recommend commands from: $impeccable adapt, $impeccable animate, $impeccable audit, $impeccable bolder, $impeccable clarify, $impeccable colorize, $impeccable critique, $impeccable delight, $impeccable distill, $impeccable document, $impeccable harden, $impeccable layout, $impeccable onboard, $impeccable optimize, $impeccable overdrive, $impeccable polish, $impeccable quieter, $impeccable shape, $impeccable typeset. Map findings to the most appropriate command. End with `$impeccable polish` as the final step if any fixes were recommended. - -After presenting the summary, tell the user: - -> You can ask me to run these one at a time, all at once, or in any order you prefer. -> -> Re-run `$impeccable audit` after fixes to see your score improve. - -**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters. - -**NEVER**: -- Report issues without explaining impact (why does this matter?) -- Provide generic recommendations (be specific and actionable) -- Skip positive findings (celebrate what works) -- Forget to prioritize (everything can't be P0) -- Report false positives without verification - diff --git a/.agents/skills/impeccable/reference/bolder.md b/.agents/skills/impeccable/reference/bolder.md deleted file mode 100644 index 25e94d59..00000000 --- a/.agents/skills/impeccable/reference/bolder.md +++ /dev/null @@ -1,113 +0,0 @@ -When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type. - ---- - -## Register - -Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV. - -Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama. - ---- - -## Assess Current State - -Analyze what makes the design feel too safe or boring: - -1. **Identify weakness sources**: - - **Generic choices**: System fonts, basic colors, standard layouts - - **Timid scale**: Everything is medium-sized with no drama - - **Low contrast**: Everything has similar visual weight - - **Static**: No motion, no energy, no life - - **Predictable**: Standard patterns with no surprises - - **Flat hierarchy**: Nothing stands out or commands attention - -2. **Understand the context**: - - What's the brand personality? (How far can we push?) - - What's the purpose? (Marketing can be bolder than financial dashboards) - - Who's the audience? (What will resonate?) - - What are the constraints? (Brand guidelines, accessibility, performance) - -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. - -**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos. - -**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects." - -## Plan Amplification - -Create a strategy to increase impact while maintaining coherence: - -- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing) -- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane. -- **Risk budget**: How experimental can we be? Push boundaries within constraints. -- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast) - -**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration. - -## Amplify the Design - -Systematically increase impact across these dimensions: - -### Typography Amplification -- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration) -- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x) -- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400 -- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default) - -### Color Intensification -- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon) -- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop -- **Dominant color strategy**: Let one bold color own 60% of the design -- **Sharp accents**: High-contrast accent colors that pop -- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette -- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue) - -### Spatial Drama -- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings -- **Break the grid**: Let hero elements escape containers and cross boundaries -- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry -- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px) -- **Overlap**: Layer elements intentionally for depth - -### Visual Effects -- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles) -- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue) -- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop) -- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side) -- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand - -### Motion & Animation -- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays -- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences -- **Micro-interactions**: Satisfying hover effects, click feedback, state changes -- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect) - -### Composition Boldness -- **Hero moments**: Create clear focal points with dramatic treatment -- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements -- **Full-bleed elements**: Use full viewport width/height for impact -- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits - -**NEVER**: -- Add effects randomly without purpose (chaos ≠ bold) -- Sacrifice readability for aesthetics (body text must be readable) -- Make everything bold (then nothing is bold; you need contrast) -- Ignore accessibility (bold design must still meet WCAG standards) -- Overwhelm with motion (animation fatigue is real) -- Copy trendy aesthetics blindly (bold means distinctive, not derivative) - -## Verify Quality - -Ensure amplification maintains usability and coherence: - -- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over. -- **Still functional**: Can users accomplish tasks without distraction? -- **Coherent**: Does everything feel intentional and unified? -- **Memorable**: Will users remember this experience? -- **Performant**: Do all these effects run smoothly? -- **Accessible**: Does it still meet accessibility standards? - -**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects." - -When the result feels right, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/brand.md b/.agents/skills/impeccable/reference/brand.md deleted file mode 100644 index b069f255..00000000 --- a/.agents/skills/impeccable/reference/brand.md +++ /dev/null @@ -1,114 +0,0 @@ -# Brand register - -When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made. - -The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look. - -## The brand slop test - -If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?" - -Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home. - -**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register. - -## Typography - -### Font selection procedure - -Every project. Never skip. - -1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words. -2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture. -3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy." -4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over. - -### Reflex-reject list - -Training-data defaults. Ban list. Look further: - -Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif - -### Reflex-reject aesthetic lanes - -Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further. - -- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery. - -(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.) - -The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md). - -### Pairing and voice - -Distinctive + refined is the goal. The specific shape depends on the brand: - -- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape). -- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family. -- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif. -- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice. - -Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair. - -Vary across projects. If the last brief was a serif-display landing page, this one isn't. - -### Scale - -Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted. - -Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room. - -## Color - -Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register. - -- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige. -- Palette IS voice. A calm brand and a restless brand should not share palette mechanics. -- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit. -- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not. - -## Layout - -- Asymmetric compositions are one option. Break the grid intentionally for emphasis. -- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings. -- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack. -- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template. -- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness. - -## Imagery - -Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo. - -**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. - -- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. Pick real Unsplash photo IDs you're confident exist (`photo-1559339352-11d035aa65de`, `photo-1590490360182-c33d57733427`, etc.); if unsure, pick fewer photos but don't substitute colored `
` placeholders. -- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel". -- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one. -- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish". - -Tech / dev-tool brands are the exception where zero imagery can be correct; a developer landing page often carries its voice through typography, code samples, diagrams. Know which kind of brand you're working on. - -## Motion - -- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice. -- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`. - -## Brand bans (on top of the shared absolute bans) - -- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume. -- Large rounded-corner icons above every heading. Screams template. -- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.) -- All-caps body copy. Reserve caps for short labels and headings. -- Timid palettes and average layouts. Safe = invisible. -- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs. -- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic. - -## Brand permissions - -Brand can afford things product can't. Take them. - -- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography. -- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing. -- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero. -- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics. -- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment. diff --git a/.agents/skills/impeccable/reference/clarify.md b/.agents/skills/impeccable/reference/clarify.md deleted file mode 100644 index 07b9d8d2..00000000 --- a/.agents/skills/impeccable/reference/clarify.md +++ /dev/null @@ -1,174 +0,0 @@ -> **Additional context needed**: audience technical level and users' mental state in context. - -Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task. - - ---- - -## Assess Current Copy - -Identify what makes the text unclear or ineffective: - -1. **Find clarity problems**: - - **Jargon**: Technical terms users won't understand - - **Ambiguity**: Multiple interpretations possible - - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file" - - **Length**: Too wordy or too terse - - **Assumptions**: Assuming user knowledge they don't have - - **Missing context**: Users don't know what to do or why - - **Tone mismatch**: Too formal, too casual, or inappropriate for situation - -2. **Understand the context**: - - Who's the audience? (Technical? General? First-time users?) - - What's the user's mental state? (Stressed during error? Confident during success?) - - What's the action? (What do we want users to do?) - - What's the constraint? (Character limits? Space limitations?) - -**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets. - -## Plan Copy Improvements - -Create a strategy for clearer communication: - -- **Primary message**: What's the ONE thing users need to know? -- **Action needed**: What should users do next (if anything)? -- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?) -- **Constraints**: Length limits, brand voice, localization considerations - -**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words. - -## Improve Copy Systematically - -Refine text across these common areas: - -### Error Messages -**Bad**: "Error 403: Forbidden" -**Good**: "You don't have permission to view this page. Contact your admin for access." - -**Bad**: "Invalid input" -**Good**: "Email addresses need an @ symbol. Try: name@example.com" - -**Principles**: -- Explain what went wrong in plain language -- Suggest how to fix it -- Don't blame the user -- Include examples when helpful -- Link to help/support if applicable - -### Form Labels & Instructions -**Bad**: "DOB (MM/DD/YYYY)" -**Good**: "Date of birth" (with placeholder showing format) - -**Bad**: "Enter value here" -**Good**: "Your email address" or "Company name" - -**Principles**: -- Use clear, specific labels (not generic placeholders) -- Show format expectations with examples -- Explain why you're asking (when not obvious) -- Put instructions before the field, not after -- Keep required field indicators clear - -### Button & CTA Text -**Bad**: "Click here" | "Submit" | "OK" -**Good**: "Create account" | "Save changes" | "Got it, thanks" - -**Principles**: -- Describe the action specifically -- Use active voice (verb + noun) -- Match user's mental model -- Be specific ("Save" is better than "OK") - -### Help Text & Tooltips -**Bad**: "This is the username field" -**Good**: "Choose a username. You can change this later in Settings." - -**Principles**: -- Add value (don't just repeat the label) -- Answer the implicit question ("What is this?" or "Why do you need this?") -- Keep it brief but complete -- Link to detailed docs if needed - -### Empty States -**Bad**: "No items" -**Good**: "No projects yet. Create your first project to get started." - -**Principles**: -- Explain why it's empty (if not obvious) -- Show next action clearly -- Make it welcoming, not dead-end - -### Success Messages -**Bad**: "Success" -**Good**: "Settings saved! Your changes will take effect immediately." - -**Principles**: -- Confirm what happened -- Explain what happens next (if relevant) -- Be brief but complete -- Match the user's emotional moment (celebrate big wins) - -### Loading States -**Bad**: "Loading..." (for 30+ seconds) -**Good**: "Analyzing your data... this usually takes 30-60 seconds" - -**Principles**: -- Set expectations (how long?) -- Explain what's happening (when it's not obvious) -- Show progress when possible -- Offer escape hatch if appropriate ("Cancel") - -### Confirmation Dialogs -**Bad**: "Are you sure?" -**Good**: "Delete 'Project Alpha'? This can't be undone." - -**Principles**: -- State the specific action -- Explain consequences (especially for destructive actions) -- Use clear button labels ("Delete project" not "Yes") -- Don't overuse confirmations (only for risky actions) - -### Navigation & Wayfinding -**Bad**: Generic labels like "Items" | "Things" | "Stuff" -**Good**: Specific labels like "Your projects" | "Team members" | "Settings" - -**Principles**: -- Be specific and descriptive -- Use language users understand (not internal jargon) -- Make hierarchy clear -- Consider information scent (breadcrumbs, current location) - -## Apply Clarity Principles - -Every piece of copy should follow these rules: - -1. **Be specific**: "Enter email" not "Enter value" -2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity) -3. **Be active**: "Save changes" not "Changes will be saved" -4. **Be human**: "Oops, something went wrong" not "System error encountered" -5. **Tell users what to do**, not just what happened -6. **Be consistent**: Use same terms throughout (don't vary for variety) - -**NEVER**: -- Use jargon without explanation -- Blame users ("You made an error" → "This field is required") -- Be vague ("Something went wrong" without explanation) -- Use passive voice unnecessarily -- Write overly long explanations (be concise) -- Use humor for errors (be empathetic instead) -- Assume technical knowledge -- Vary terminology (pick one term and stick with it) -- Repeat information (headers restating intros, redundant explanations) -- Use placeholders as the only labels (they disappear when users type) - -## Verify Improvements - -Test that copy improvements work: - -- **Comprehension**: Can users understand without context? -- **Actionability**: Do users know what to do next? -- **Brevity**: Is it as short as possible while remaining clear? -- **Consistency**: Does it match terminology elsewhere? -- **Tone**: Is it appropriate for the situation? - -When the copy reads cleanly, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/cognitive-load.md b/.agents/skills/impeccable/reference/cognitive-load.md deleted file mode 100644 index 48f8ad58..00000000 --- a/.agents/skills/impeccable/reference/cognitive-load.md +++ /dev/null @@ -1,106 +0,0 @@ -# Cognitive Load Assessment - -Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload. - ---- - -## Three Types of Cognitive Load - -### Intrinsic Load: The Task Itself -Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it. - -**Manage it by**: -- Breaking complex tasks into discrete steps -- Providing scaffolding (templates, defaults, examples) -- Progressive disclosure: show what's needed now, hide the rest -- Grouping related decisions together - -### Extraneous Load: Bad Design -Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste. - -**Common sources**: -- Confusing navigation that requires mental mapping -- Unclear labels that force users to guess meaning -- Visual clutter competing for attention -- Inconsistent patterns that prevent learning -- Unnecessary steps between user intent and result - -### Germane Load: Learning Effort -Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery. - -**Support it by**: -- Progressive disclosure that reveals complexity gradually -- Consistent patterns that reward learning -- Feedback that confirms correct understanding -- Onboarding that teaches through action, not walls of text - ---- - -## Cognitive Load Checklist - -Evaluate the interface against these 8 items: - -- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements? -- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)? -- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)? -- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen? -- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next? -- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)? -- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one? -- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it? - -**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed). - ---- - -## The Working Memory Rule - -**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001). - -At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider: -- **≤4 items**: Within working memory limits, manageable -- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure -- **8+ items**: Overloaded; users will skip, misclick, or abandon - -**Practical applications**: -- Navigation menus: ≤5 top-level items (group the rest under clear categories) -- Form sections: ≤4 fields visible per group before a visual break -- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu -- Dashboard widgets: ≤4 key metrics visible without scrolling -- Pricing tiers: ≤3 options (more causes analysis paralysis) - ---- - -## Common Cognitive Load Violations - -### 1. The Wall of Options -**Problem**: Presenting 10+ choices at once with no hierarchy. -**Fix**: Group into categories, highlight recommended, use progressive disclosure. - -### 2. The Memory Bridge -**Problem**: User must remember info from step 1 to complete step 3. -**Fix**: Keep relevant context visible, or repeat it where it's needed. - -### 3. The Hidden Navigation -**Problem**: User must build a mental map of where things are. -**Fix**: Always show current location (breadcrumbs, active states, progress indicators). - -### 4. The Jargon Barrier -**Problem**: Technical or domain language forces translation effort. -**Fix**: Use plain language. If domain terms are unavoidable, define them inline. - -### 5. The Visual Noise Floor -**Problem**: Every element has the same visual weight; nothing stands out. -**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted. - -### 6. The Inconsistent Pattern -**Problem**: Similar actions work differently in different places. -**Fix**: Standardize interaction patterns. Same type of action = same type of UI. - -### 7. The Multi-Task Demand -**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating). -**Fix**: Sequence the steps. Let the user do one thing at a time. - -### 8. The Context Switch -**Problem**: User must jump between screens/tabs/modals to gather info for a single decision. -**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth. diff --git a/.agents/skills/impeccable/reference/color-and-contrast.md b/.agents/skills/impeccable/reference/color-and-contrast.md deleted file mode 100644 index 110c2ee4..00000000 --- a/.agents/skills/impeccable/reference/color-and-contrast.md +++ /dev/null @@ -1,105 +0,0 @@ -# Color & Contrast - -## Color Spaces: Use OKLCH - -**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark. - -The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish. - -The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand. - -## Building Functional Palettes - -### Tinted Neutrals - -**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces. - -The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette. - -**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects. - -### Palette Structure - -A complete system needs: - -| Role | Purpose | Example | -|------|---------|---------| -| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades | -| **Neutral** | Text, backgrounds, borders | 9-11 shade scale | -| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each | -| **Surface** | Cards, modals, overlays | 2-3 elevation levels | - -**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise. - -### The 60-30-10 Rule (Applied Correctly) - -This rule is about **visual weight**, not pixel count: - -- **60%**: Neutral backgrounds, white space, base surfaces -- **30%**: Secondary colors: text, borders, inactive states -- **10%**: Accent: CTAs, highlights, focus states - -The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power. - -## Contrast & Accessibility - -### WCAG Requirements - -| Content Type | AA Minimum | AAA Target | -|--------------|------------|------------| -| Body text | 4.5:1 | 7:1 | -| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 | -| UI components, icons | 3:1 | 4.5:1 | -| Non-essential decorations | None | None | - -**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG. - -### Dangerous Color Combinations - -These commonly fail contrast or cause readability issues: - -- Light gray text on white (the #1 accessibility fail) -- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency -- Red text on green background (or vice versa): 8% of men can't distinguish these -- Blue text on red background (vibrates visually) -- Yellow text on white (almost always fails) -- Thin light text on images (unpredictable contrast) - -### Never Use Pure Gray or Pure Black - -Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.) - -### Testing - -Don't trust your eyes. Use tools: - -- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/) -- Browser DevTools → Rendering → Emulate vision deficiencies -- [Polypane](https://polypane.app/) for real-time testing - -## Theming: Light & Dark Mode - -### Dark Mode Is Not Inverted Light Mode - -You can't just swap colors. Dark mode requires different design decisions: - -| Light Mode | Dark Mode | -|------------|-----------| -| Shadows for depth | Lighter surfaces for depth (no shadows) | -| Dark text on light | Light text on dark (reduce font weight) | -| Vibrant accents | Desaturate accents slightly | -| White backgrounds | Never pure black; use dark gray (oklch 12-18%) | - -In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light. - -### Token Hierarchy - -Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same. - -## Alpha Is A Design Smell - -Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed. - ---- - -**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected). diff --git a/.agents/skills/impeccable/reference/colorize.md b/.agents/skills/impeccable/reference/colorize.md deleted file mode 100644 index a6ddfb29..00000000 --- a/.agents/skills/impeccable/reference/colorize.md +++ /dev/null @@ -1,154 +0,0 @@ -> **Additional context needed**: existing brand colors. - -Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit. - ---- - -## Register - -Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it. - -Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen. - ---- - -## Assess Color Opportunity - -Analyze the current state and identify opportunities: - -1. **Understand current state**: - - **Color absence**: Pure grayscale? Limited neutrals? One timid accent? - - **Missed opportunities**: Where could color add meaning, hierarchy, or delight? - - **Context**: What's appropriate for this domain and audience? - - **Brand**: Are there existing brand colors we should use? - -2. **Identify where color adds value**: - - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue) - - **Hierarchy**: Drawing attention to important elements - - **Categorization**: Different sections, types, or states - - **Emotional tone**: Warmth, energy, trust, creativity - - **Wayfinding**: Helping users navigate and understand structure - - **Delight**: Moments of visual interest and personality - -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. - -**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose. - -## Plan Color Strategy - -Create a purposeful color introduction plan: - -- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals) -- **Dominant color**: Which color owns 60% of colored elements? -- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%) -- **Application strategy**: Where does each color appear and why? - -**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more. - -## Introduce Color Strategically - -Add color systematically across these dimensions: - -### Semantic Color -- **State indicators**: - - Success: Green tones (emerald, forest, mint) - - Error: Red/pink tones (rose, crimson, coral) - - Warning: Orange/amber tones - - Info: Blue tones (sky, ocean, indigo) - - Neutral: Gray/slate for inactive states - -- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.) -- **Progress indicators**: Colored bars, rings, or charts showing completion or health - -### Accent Color Application -- **Primary actions**: Color the most important buttons/CTAs -- **Links**: Add color to clickable text (maintain accessibility) -- **Icons**: Colorize key icons for recognition and personality -- **Headers/titles**: Add color to section headers or key labels -- **Hover states**: Introduce color on interaction - -### Background & Surfaces -- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`) -- **Colored sections**: Use subtle background colors to separate areas -- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue) -- **Cards & surfaces**: Tint cards or surfaces slightly for warmth - -**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales. - -### Data Visualization -- **Charts & graphs**: Use color to encode categories or values -- **Heatmaps**: Color intensity shows density or importance -- **Comparison**: Color coding for different datasets or timeframes - -### Borders & Accents -- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`) -- **Underlines**: Color underlines for emphasis or active states -- **Dividers**: Subtle colored dividers instead of gray lines -- **Focus rings**: Colored focus indicators matching brand -- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe - -**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe. - -### Typography Color -- **Colored headings**: Use brand colors for section headings (maintain contrast) -- **Highlight text**: Color for emphasis or categories -- **Labels & tags**: Small colored labels for metadata or categories - -### Decorative Elements -- **Illustrations**: Add colored illustrations or icons -- **Shapes**: Geometric shapes in brand colors as background elements -- **Gradients**: Colorful gradient overlays or mesh backgrounds -- **Blobs/organic shapes**: Soft colored shapes for visual interest - -## Balance & Refinement - -Ensure color addition improves rather than overwhelms: - -### Maintain Hierarchy -- **Dominant color** (60%): Primary brand color or most used accent -- **Secondary color** (30%): Supporting color for variety -- **Accent color** (10%): High contrast for key moments -- **Neutrals** (remaining): Gray/black/white for structure - -### Accessibility -- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components) -- **Don't rely on color alone**: Use icons, labels, or patterns alongside color -- **Test for color blindness**: Verify red/green combinations work for all users - -### Cohesion -- **Consistent palette**: Use colors from defined palette, not arbitrary choices -- **Systematic application**: Same color meanings throughout (green always = success) -- **Temperature consistency**: Warm palette stays warm, cool stays cool - -**NEVER**: -- Use every color in the rainbow (choose 2-4 colors beyond neutrals) -- Apply color randomly without semantic meaning -- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead -- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth -- Use pure black (`#000`) or pure white (`#fff`) for large areas -- Violate WCAG contrast requirements -- Use color as the only indicator (accessibility issue) -- Make everything colorful (defeats the purpose) -- Default to purple-blue gradients (AI slop aesthetic) - -## Verify Color Addition - -Test that colorization improves the experience: - -- **Better hierarchy**: Does color guide attention appropriately? -- **Clearer meaning**: Does color help users understand states/categories? -- **More engaging**: Does the interface feel warmer and more inviting? -- **Still accessible**: Do all color combinations meet WCAG standards? -- **Not overwhelming**: Is color balanced and purposeful? - -When the palette earns its place, hand off to `$impeccable polish` for the final pass. - -## Live-mode signature params - -When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage. - -```json -{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"} -``` - -Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract. diff --git a/.agents/skills/impeccable/reference/craft.md b/.agents/skills/impeccable/reference/craft.md deleted file mode 100644 index 337b5c9b..00000000 --- a/.agents/skills/impeccable/reference/craft.md +++ /dev/null @@ -1,193 +0,0 @@ -# Craft Flow - -Build a feature with impeccable UX and UI quality through a structured process: shape the design, land the visual direction, build real production code, then inspect and improve in-browser until the result meets a high-end studio bar. - -## Build Gate - -Craft cannot build until all of these are true: - -1. PRODUCT context is valid and current. -2. The shape design brief is explicitly confirmed by the user for this task, unless the user already provided a confirmed brief. -3. Implementation references from the brief are loaded. -4. The shape visual probe decision is recorded: generated, skipped with reason, or already resolved. -5. The north-star mock decision is recorded: generated, skipped with reason, or not applicable. - -PRODUCT.md and `teach` answers do **not** satisfy the shape gate. They are project context only. A compact self-authored brief does not satisfy the shape gate either. `shape=pass` requires a separate user response approving the shape brief or an already-confirmed brief supplied by the user. - -Invalid image-skip reasons include: "the final implementation will be semantic HTML/CSS/SVG", "the diagram should stay editable", "a raster mock would not be used directly", or "the product is fictional." Generated probes and mocks are direction artifacts; they are not implementation assets. - -## Craft Contract - -Craft is not a first pass. It is a loop with these required artifacts: - -1. Confirmed design brief from `shape`. -2. Approved visual direction, from generated probes / mocks when image generation is available. -3. Mock fidelity inventory: the visible ingredients from the approved direction that must survive into code. -4. Semantic, functional implementation using the project's real stack and conventions. -5. Browser evidence across relevant viewports. -6. At least one critique-and-fix pass after the first browser inspection, unless the first pass has no material defects. - -Do not let generated mockups replace interface structure, copy, accessibility, responsive behavior, or state design. But do treat the approved mock as a concrete visual contract for composition, hierarchy, density, atmosphere, signature motifs, image needs, and distinctive visual moves. "North star" means "preserve the important visible ingredients in semantic code," not "use it as loose mood." - -## Step 1: Shape the Design - -Run $impeccable shape, passing along whatever feature description the user provided. - -Wait for the design brief to be fully confirmed by the user before proceeding. The brief is your blueprint, and every implementation decision should trace back to it. - -If this craft run resumed after `teach` created PRODUCT.md, run shape now. Do not treat the teach interview, PRODUCT.md, or a summary of project context as a substitute for shape. Shape is task-specific and must cover scope, content/states, visual direction, constraints, anti-goals, probes when applicable, and explicit brief confirmation. - -If the user has already run $impeccable shape and has a confirmed design brief, skip this step and use the existing brief. - -## Step 2: Load References - -Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult: - -- [spatial-design.md](spatial-design.md) for layout and spacing -- [typography.md](typography.md) for type hierarchy - -Then add references based on the brief's needs: -- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md) -- Animation or transitions? Consult [motion-design.md](motion-design.md) -- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md) -- Responsive requirements? Consult [responsive-design.md](responsive-design.md) -- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md) - -## Step 3: Land the Visual Direction (Capability-Gated) - -Before implementation, generate high-fidelity visual comps when all of these are true: - -- The work is **net-new** or visually open-ended enough that composition exploration will improve the build. -- The brief's scope is **mid-fi, high-fi, or production-ready**. -- The current harness has **built-in image generation capability** (for example, Codex with a native image tool). Do **not** ask the user to set up external APIs, shell scripts, or one-off tooling just to do this. - -When those conditions are met, this step is mandatory for **both brand and product work** in Codex and any harness with built-in image generation. Use native image generation; in Codex, use the built-in `image_gen` tool via the imagegen skill. If image generation is unavailable, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. - -Do not skip this step because the eventual UI should be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration. - -### Purpose - -Use the mock step to find a stronger visual lane than code-first generation would reliably discover on its own. The brief remains authoritative on user, purpose, content, constraints, states, and anti-goals. The mock clarifies composition, hierarchy, density, typography, and visual tone. - -### What to generate - -Generate **1 to 3** high-fidelity north-star comps based on the confirmed brief. If shape already produced direction probes, use those results as input and generate a more resolved mock from the winning lane, not another unrelated exploration. - -- For brand work, push visual identity, composition, and mood aggressively. -- For product work, still push hierarchy, topology, density, and tone, but keep the comps grounded in realistic product structure and states. -- For landing pages and long-form brand surfaces, show enough of the next section or second fold to establish the system beyond the hero. - -The comps must be genuinely different in primary visual direction, not just color variants. - -### Approval loop - -Show the comps and ask what should carry forward. If the user asks for changes or the best direction is still weak, generate a focused revision before implementation. Continue until one direction is approved, or until the user explicitly delegates the choice. - -If the user delegates, pick the strongest direction and explain the decision using the brief, not personal taste. - -Before moving to implementation, summarize: - -- What to carry into code -- What **not** to literalize from the mock - -This summary is required before Step 4. It is the handoff between visual exploration and semantic implementation. - -### Mock fidelity inventory - -Before building, inventory the approved mock's major visible ingredients: - -- Hero silhouette and dominant composition. -- Signature motifs: planets, devices, portraits, charts, route lines, insets, badges, or other memorable objects. -- Nav and primary CTA treatment. -- Section sequence visible in the mock, especially the second fold. -- Image-native content the concept depends on. -- Typography, density, color/material treatment, and motion cues. - -For each ingredient, decide how it will be implemented: semantic HTML/CSS/SVG, generated asset, sourced project asset, icon library, canvas/WebGL, or an explicitly accepted omission. Do not substitute a different hero composition or new visual driver after approval unless the user approves the change. - -Treat the mock as a **north star**, not a screenshot to trace. Do **not** rasterize core UI text or let the mock override the confirmed brief. But if the live result lacks the mock's major visible ingredients, the implementation is wrong. - -## Step 4: Asset Extraction (Need-Gated) - -If the chosen direction includes image-native visual ingredients that would materially improve the implementation, generate them as separate assets before building. - -Good candidates: - -- stickers -- badges -- seals -- tickets -- graphic labels -- textures -- abstract objects -- decorative marks -- non-semantic scene elements - -For travel, editorial, portfolio, venue, product showcase, entertainment, education, or any other image-led brand surface, visual assets are usually core content, not decoration. Do not ship abstract CSS panels where the approved mock or subject matter calls for real imagery, generated plates, illustrations, maps, product/object renders, or destination scenes. - -Do **not** export assets for core UI text, navigation, body copy, or any structure that should stay semantic and editable in code. - -Usually **1 to 5** extracted assets is enough. If the design can be built cleanly in HTML/CSS/SVG, prefer that over raster assets. If the mock contains major visual content that cannot be built credibly in code, asset extraction is not optional. - -## Step 5: Build to Production Quality - -Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration. - -### Production bar - -- Use real or realistic content. Remove placeholder copy, placeholder images, dead links, fake controls, and unused scaffold before presenting. -- Preserve the approved mock's major ingredients. Missing hero objects, missing world/product imagery, different section structure, downgraded CTA/nav treatment, or generic replacements for distinctive motifs are blocking defects unless the user accepted the change. -- Build semantically first: real headings, landmarks, labels, form associations, button/link semantics, accessible names, and state announcements where needed. -- Calibrate spacing, alignment, grid placement, and vertical rhythm deliberately. Do not accept default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment. -- Make typography intentional: chosen font loading strategy, clear hierarchy, readable measure, stable line breaks, tuned wrapping, and no overflow at mobile or large desktop sizes. -- Design realistic state coverage: default, hover where supported, focus-visible, active, disabled, loading, error, success, empty, overflow, long text, short text, and first-run states where relevant. -- Make interaction quality feel finished: keyboard paths, touch targets, feedback timing, scroll behavior, transitions between states, and no hover-only functionality. -- Use icons from the project's established icon set when available. If no set exists, choose a coherent library or use accessible text controls; do not mix unrelated icon styles. -- Optimize imagery and media: correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset` / `picture` for raster assets, and no project-referenced asset left outside the workspace. -- Make motion feel premium: use atmospheric blur, filter, mask, shadow, or reveal effects when they improve the experience; avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion. -- Preserve maintainability: reusable local patterns, clear component boundaries, project conventions, no rasterized UI text, and no hard-coded one-off hacks when a better local pattern exists. -- Fit the technical context: production build passes, no obvious console errors, no avoidable layout shift, no needless dependency, and no broken asset path. -- If you discover a design question that materially changes the brief or approved direction, stop and ask rather than guessing. - -## Step 6: Browser-Based Iteration - -**This step is critical.** Do not stop after the first implementation pass. - -Open the result in a browser. In Codex, use browser-use or equivalent browser automation when available; otherwise use Playwright or ask the user for screenshots. Inspect screenshots, not just DOM or terminal output. - -### Required viewport pass - -Check the experience at the viewports that matter for the brief. Default minimum: - -- Mobile narrow -- Tablet or small laptop -- Desktop wide - -For each viewport, capture or inspect the rendered state and look for visual defects: overlap, clipping, weak hierarchy, off-grid alignment, awkward whitespace, cramped controls, unreadable type, broken imagery, hover-only functionality, layout shift, and text overflow. - -### Critique and fix loop - -After the first browser pass, write a short critique for yourself and patch the implementation. Repeat browser inspection after fixes. Continue until no material issues remain against this checklist: - -1. **Does it match the brief?** Compare the live result against every section of the design brief. Fix discrepancies. -2. **Does it match the approved mock?** Compare screenshots against the mock fidelity inventory: hero silhouette, major motifs, imagery, nav/CTA, section sequence, density, color/materials, and second-fold substance. Missing major ingredients are P0 defects. -3. **Does it pass the AI slop test?** If someone saw this and said "AI made this," would they believe it immediately? If yes, it needs more design intention. -4. **Check against impeccable's DON'T guidelines.** Fix any anti-pattern violations. -5. **Check every state.** Navigate through empty, error, loading, and edge case states. Each one should feel intentional, not like an afterthought. -6. **Check responsive behavior.** The design should adapt compositionally, not merely shrink. -7. **Check craft details.** Spacing consistency, optical alignment, type hierarchy, color contrast, image quality, icon coherence, interactive feedback, motion timing, and focus treatment. -8. **Check performance basics.** No obviously oversized images, avoidable layout thrash, blocking animations, or heavy assets without a reason. - -The exit bar is not "it works." It is: the rendered result looks intentional at all checked viewports, all expected states are handled, no placeholders remain unless explicitly accepted, and the implementation quality would be defensible in a high-end studio review. - -## Step 7: Present - -Present the result to the user: -- Show the feature in its primary state -- Summarize the browser/viewports checked and the most important fixes made after inspection -- Walk through the key states (empty, error, responsive) -- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients. -- Note any remaining limitations or follow-up risks honestly -- Ask: "What's working? What isn't?" - -Iterate based on feedback. Good design is rarely right on the first pass. diff --git a/.agents/skills/impeccable/reference/critique.md b/.agents/skills/impeccable/reference/critique.md deleted file mode 100644 index 4e9b73db..00000000 --- a/.agents/skills/impeccable/reference/critique.md +++ /dev/null @@ -1,213 +0,0 @@ -> **Additional context needed**: what the interface is trying to accomplish. - -### Gather Assessments - -Launch two independent assessments. **Neither may see the other's output.** This isolation is what makes the combined score honest. Running both in one head silently anchors them to each other; do not shortcut it for cost, speed, or context-size reasons. - -Delegate each assessment to a separate sub-agent (Claude Code's `Agent` tool, Codex's subagent spawning, etc.). Each returns structured findings as text. Do NOT output findings to the user yet. - -Fall back to sequential in-head work only if the environment genuinely cannot spawn sub-agents. - -**Tab isolation**: When browser automation is available, each assessment MUST create its own new tab. Never reuse an existing tab, even if one is already open at the correct URL. This prevents the two assessments from interfering with each other's page state. - -#### Assessment A: LLM Design Review - -Read the relevant source files (HTML, CSS, JS/TS) and, if browser automation is available, visually inspect the live page. **Create a new tab** for this; do not reuse existing tabs. After navigation, label the tab by setting the document title: -```javascript -document.title = '[LLM] ' + document.title; -``` -Think like a design director. Evaluate: - -**AI Slop Detection (CRITICAL)**: Does this look like every other AI-generated interface? Review against ALL **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Check for AI color palette, gradient text, dark glows, glassmorphism, hero metric layouts, identical card grids, generic fonts, and all other tells. **The test**: If someone said "AI made this," would you believe them immediately? - -**Holistic Design Review**: visual hierarchy (eye flow, primary action clarity), information architecture (structure, grouping, cognitive load), emotional resonance (does it match brand and audience?), discoverability (are interactive elements obvious?), composition (balance, whitespace, rhythm), typography (hierarchy, readability, font choices), color (purposeful use, cohesion, accessibility), states & edge cases (empty, loading, error, success), microcopy (clarity, tone, helpfulness). - -**Cognitive Load** (consult [cognitive-load](cognitive-load.md)): -- Run the 8-item cognitive load checklist. Report failure count: 0-1 = low (good), 2-3 = moderate, 4+ = critical. -- Count visible options at each decision point. If >4, flag it. -- Check for progressive disclosure: is complexity revealed only when needed? - -**Emotional Journey**: -- What emotion does this interface evoke? Is that intentional? -- **Peak-end rule**: Is the most intense moment positive? Does the experience end well? -- **Emotional valleys**: Check for anxiety spikes at high-stakes moments (payment, delete, commit). Are there design interventions (progress indicators, reassurance copy, undo options)? - -**Nielsen's Heuristics** (consult [heuristics-scoring](heuristics-scoring.md)): -Score each of the 10 heuristics 0-4. This scoring will be presented in the report. - -Return structured findings covering: AI slop verdict, heuristic scores, cognitive load assessment, what's working (2-3 items), priority issues (3-5 with what/why/fix), minor observations, and provocative questions. - -#### Assessment B: Automated Detection - -Run the bundled deterministic detector, which flags 27 specific patterns (AI slop tells + general design quality). - -**CLI scan**: -```bash -npx impeccable --json [--fast] [target] -``` - -- Pass HTML/JSX/TSX/Vue/Svelte files or directories as `[target]` (anything with markup). Do not pass CSS-only files. -- For URLs, skip the CLI scan (it requires Puppeteer). Use browser visualization instead. -- For large directories (200+ scannable files), use `--fast` (regex-only, skips jsdom) -- For 500+ files, narrow scope or ask the user -- Exit code 0 = clean, 2 = findings - -**Browser visualization**: **required** when browser automation tools are available AND the target is a viewable page. The `[Human]` overlay tab is the user-facing deliverable; the critique is incomplete without it. Skip only if the target is not a viewable page (CSS-only file, non-browser target). - -The overlay is a **visual aid for the user**. It highlights issues directly in their browser. Do NOT scroll through the page to screenshot overlays. Instead, read the console output to get the results programmatically. - -1. **Start the live detection server**: - ```bash - npx impeccable live & - ``` - Note the port printed to stdout (auto-assigned). Use `--port=PORT` to fix it. -2. **Create a new tab** and navigate to the page (use dev server URL for local files, or direct URL). Do not reuse existing tabs. -3. **Label the tab** via `javascript_tool` so the user can distinguish it: - ```javascript - document.title = '[Human] ' + document.title; - ``` -4. **Scroll to top** to ensure the page is scrolled to the very top before injection -5. **Inject** via `javascript_tool` (replace PORT with the port from step 1): - ```javascript - const s = document.createElement('script'); s.src = 'http://localhost:PORT/detect.js'; document.head.appendChild(s); - ``` -6. Wait 2-3 seconds for the detector to render overlays -7. **Read results from console** using `read_console_messages` with pattern `impeccable`. The detector logs all findings with the `[impeccable]` prefix. Do NOT scroll through the page to take screenshots of the overlays. -8. **Cleanup**: Stop the live server when done: - ```bash - npx impeccable live stop - ``` - -For multi-view targets, inject on 3-5 representative pages. If injection fails, continue with CLI results only. - -Return: CLI findings (JSON), browser console findings (if applicable), and any false positives noted. - -### Generate Combined Critique Report - -Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives. - -Structure your feedback as a design director would: - -#### Design Health Score -> *Consult [heuristics-scoring](heuristics-scoring.md)* - -Present the Nielsen's 10 heuristics scores as a table: - -| # | Heuristic | Score | Key Issue | -|---|-----------|-------|-----------| -| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] | -| 2 | Match System / Real World | ? | | -| 3 | User Control and Freedom | ? | | -| 4 | Consistency and Standards | ? | | -| 5 | Error Prevention | ? | | -| 6 | Recognition Rather Than Recall | ? | | -| 7 | Flexibility and Efficiency | ? | | -| 8 | Aesthetic and Minimalist Design | ? | | -| 9 | Error Recovery | ? | | -| 10 | Help and Documentation | ? | | -| **Total** | | **??/40** | **[Rating band]** | - -Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32. - -#### Anti-Patterns Verdict - -**Start here.** Does this look AI-generated? - -**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality. - -**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives. - -**Visual overlays** (if browser was used): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. - -#### Overall Impression -A brief gut reaction: what works, what doesn't, and the single biggest opportunity. - -#### What's Working -Highlight 2-3 things done well. Be specific about why they work. - -#### Priority Issues -The 3-5 most impactful design problems, ordered by importance. - -For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions): -- **[P?] What**: Name the problem clearly -- **Why it matters**: How this hurts users or undermines goals -- **Fix**: What to do about it (be concrete) -- **Suggested command**: Which command could address this (from: $impeccable adapt, $impeccable animate, $impeccable audit, $impeccable bolder, $impeccable clarify, $impeccable colorize, $impeccable critique, $impeccable delight, $impeccable distill, $impeccable document, $impeccable harden, $impeccable layout, $impeccable onboard, $impeccable optimize, $impeccable overdrive, $impeccable polish, $impeccable quieter, $impeccable shape, $impeccable typeset) - -#### Persona Red Flags -> *Consult [personas](personas.md)* - -Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `AGENTS.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info. - -For each selected persona, walk through the primary user action and list specific red flags found: - -**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk. - -**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2. - -Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them. - -#### Minor Observations -Quick notes on smaller issues worth addressing. - -#### Questions to Consider -Provocative questions that might unlock better solutions: -- "What if the primary action were more prominent?" -- "Does this need to feel this complex?" -- "What would a confident version of this look like?" - -**Remember**: -- Be direct. Vague feedback wastes everyone's time. -- Be specific. "The submit button," not "some elements." -- Say what's wrong AND why it matters to users. -- Give concrete suggestions. Cut "consider exploring..." entirely. -- Prioritize ruthlessly. If everything is important, nothing is. -- Don't soften criticism. Developers need honest feedback to ship great design. - -### Ask the User - -**After presenting findings**, use targeted questions based on what was actually found. STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. These answers will shape the action plan. - -Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions): - -1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options. - -2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found. - -3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only". - -4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done. - -**Rules for questions**: -- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions. -- Keep it to 2-4 questions maximum. Respect the user's time. -- Offer concrete options, not open-ended prompts. -- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions. - -### Recommended Actions - -**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User. - -#### Action Summary - -List recommended commands in priority order, based on the user's answers: - -1. **`$command-name`**: Brief description of what to fix (specific context from critique findings) -2. **`$command-name`**: Brief description (specific context) -... - -**Rules for recommendations**: -- Only recommend commands from: $impeccable adapt, $impeccable animate, $impeccable audit, $impeccable bolder, $impeccable clarify, $impeccable colorize, $impeccable critique, $impeccable delight, $impeccable distill, $impeccable document, $impeccable harden, $impeccable layout, $impeccable onboard, $impeccable optimize, $impeccable overdrive, $impeccable polish, $impeccable quieter, $impeccable shape, $impeccable typeset -- Order by the user's stated priorities first, then by impact -- Each item's description should carry enough context that the command knows what to focus on -- Map each Priority Issue to the appropriate command -- Skip commands that would address zero issues -- If the user chose a limited scope, only include items within that scope -- If the user marked areas as off-limits, exclude commands that would touch those areas -- End with `$impeccable polish` as the final step if any fixes were recommended - -After presenting the summary, tell the user: - -> You can ask me to run these one at a time, all at once, or in any order you prefer. -> -> Re-run `$impeccable critique` after fixes to see your score improve. diff --git a/.agents/skills/impeccable/reference/delight.md b/.agents/skills/impeccable/reference/delight.md deleted file mode 100644 index b3196705..00000000 --- a/.agents/skills/impeccable/reference/delight.md +++ /dev/null @@ -1,302 +0,0 @@ -> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant). - -Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise. - ---- - -## Register - -Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface. - -Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise. - ---- - -## Assess Delight Opportunities - -Identify where delight would enhance (not distract from) the experience: - -1. **Find natural delight moments**: - - **Success states**: Completed actions (save, send, publish) - - **Empty states**: First-time experiences, onboarding - - **Loading states**: Waiting periods that could be entertaining - - **Achievements**: Milestones, streaks, completions - - **Interactions**: Hover states, clicks, drags - - **Errors**: Softening frustrating moments - - **Easter eggs**: Hidden discoveries for curious users - -2. **Understand the context**: - - What's the brand personality? (Playful? Professional? Quirky? Elegant?) - - Who's the audience? (Tech-savvy? Creative? Corporate?) - - What's the emotional context? (Accomplishment? Exploration? Frustration?) - - What's appropriate? (Banking app ≠ gaming app) - -3. **Define delight strategy**: - - **Subtle sophistication**: Refined micro-interactions (luxury brands) - - **Playful personality**: Whimsical illustrations and copy (consumer apps) - - **Helpful surprises**: Anticipating needs before users ask (productivity tools) - - **Sensory richness**: Satisfying sounds, smooth animations (creative tools) - -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. - -**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far. - -## Delight Principles - -Follow these guidelines: - -### Delight Amplifies, Never Blocks -- Delight moments should be quick (< 1 second) -- Never delay core functionality for delight -- Make delight skippable or subtle -- Respect user's time and task focus - -### Surprise and Discovery -- Hide delightful details for users to discover -- Reward exploration and curiosity -- Don't announce every delight moment -- Let users share discoveries with others - -### Appropriate to Context -- Match delight to emotional moment (celebrate success, empathize with errors) -- Respect the user's state (don't be playful during critical errors) -- Match brand personality and audience expectations -- Cultural sensitivity (what's delightful varies by culture) - -### Compound Over Time -- Delight should remain fresh with repeated use -- Vary responses (not same animation every time) -- Reveal deeper layers with continued use -- Build anticipation through patterns - -## Delight Techniques - -Add personality and joy through these methods: - -### Micro-interactions & Animation - -**Button delight**: -```css -/* Satisfying button press */ -.button { - transition: transform 0.1s, box-shadow 0.1s; -} -.button:active { - transform: translateY(2px); - box-shadow: 0 2px 4px rgba(0,0,0,0.2); -} - -/* Ripple effect on click */ -/* Smooth lift on hover */ -.button:hover { - transform: translateY(-2px); - transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */ -} -``` - -**Loading delight**: -- Playful loading animations (not just spinners) -- Personality in loading messages (write product-specific ones, not generic AI filler) -- Progress indication with encouraging messages -- Skeleton screens with subtle animations - -**Success animations**: -- Checkmark draw animation -- Confetti burst for major achievements -- Gentle scale + fade for confirmation -- Satisfying sound effects (subtle) - -**Hover surprises**: -- Icons that animate on hover -- Color shifts or glow effects -- Tooltip reveals with personality -- Cursor changes (custom cursors for branded experiences) - -### Personality in Copy - -**Playful error messages**: -``` -"Error 404" -"This page is playing hide and seek. (And winning)" - -"Connection failed" -"Looks like the internet took a coffee break. Want to retry?" -``` - -**Encouraging empty states**: -``` -"No projects" -"Your canvas awaits. Create something amazing." - -"No messages" -"Inbox zero! You're crushing it today." -``` - -**Playful labels & tooltips**: -``` -"Delete" -"Send to void" (for playful brand) - -"Help" -"Rescue me" (tooltip) -``` - -**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm. - -### Illustrations & Visual Personality - -**Custom illustrations**: -- Empty state illustrations (not stock icons) -- Error state illustrations (friendly monsters, quirky characters) -- Loading state illustrations (animated characters) -- Success state illustrations (celebrations) - -**Icon personality**: -- Custom icon set matching brand personality -- Animated icons (subtle motion on hover/click) -- Illustrative icons (more detailed than generic) -- Consistent style across all icons - -**Background effects**: -- Subtle particle effects -- Gradient mesh backgrounds -- Geometric patterns -- Parallax depth -- Time-of-day themes (morning vs night) - -### Satisfying Interactions - -**Drag and drop delight**: -- Lift effect on drag (shadow, scale) -- Snap animation when dropped -- Satisfying placement sound -- Undo toast ("Dropped in wrong place? [Undo]") - -**Toggle switches**: -- Smooth slide with spring physics -- Color transition -- Haptic feedback on mobile -- Optional sound effect - -**Progress & achievements**: -- Streak counters with celebratory milestones -- Progress bars that "celebrate" at 100% -- Badge unlocks with animation -- Playful stats ("You're on fire! 5 days in a row") - -**Form interactions**: -- Input fields that animate on focus -- Checkboxes with a satisfying scale pulse when checked -- Success state that celebrates valid input -- Auto-grow textareas - -### Sound Design - -**Subtle audio cues** (when appropriate): -- Notification sounds (distinctive but not annoying) -- Success sounds (satisfying "ding") -- Error sounds (empathetic, not harsh) -- Typing sounds for chat/messaging -- Ambient background audio (very subtle) - -**IMPORTANT**: -- Respect system sound settings -- Provide mute option -- Keep volumes quiet (subtle cues, not alarms) -- Don't play on every interaction (sound fatigue is real) - -### Easter Eggs & Hidden Delights - -**Discovery rewards**: -- Konami code unlocks special theme -- Hidden keyboard shortcuts (Cmd+K for special features) -- Hover reveals on logos or illustrations -- Alt text jokes on images (for screen reader users too!) -- Console messages for developers ("Like what you see? We're hiring!") - -**Seasonal touches**: -- Holiday themes (subtle, tasteful) -- Seasonal color shifts -- Weather-based variations -- Time-based changes (dark at night, light during day) - -**Contextual personality**: -- Different messages based on time of day -- Responses to specific user actions -- Randomized variations (not same every time) -- Progressive reveals with continued use - -### Loading & Waiting States - -**Make waiting engaging**: -- Interesting loading messages that rotate -- Progress bars with personality -- Mini-games during long loads -- Fun facts or tips while waiting -- Countdown with encouraging messages - -``` -Loading messages: write ones specific to your product, not generic AI filler: -- "Crunching your latest numbers..." -- "Syncing with your team's changes..." -- "Preparing your dashboard..." -- "Checking for updates since yesterday..." -``` - -**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does. - -### Celebration Moments - -**Success celebrations**: -- Confetti for major milestones -- Animated checkmarks for completions -- Progress bar celebrations at 100% -- "Achievement unlocked" style notifications -- Personalized messages ("You published your 10th article!") - -**Milestone recognition**: -- First-time actions get special treatment -- Streak tracking and celebration -- Progress toward goals -- Anniversary celebrations - -## Implementation Patterns - -**Animation libraries**: -- Framer Motion (React) -- GSAP (universal) -- Lottie (After Effects animations) -- Canvas confetti (party effects) - -**Sound libraries**: -- Howler.js (audio management) -- Use-sound (React hook) - -**Physics libraries**: -- React Spring (spring physics) -- Popmotion (animation primitives) - -**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features. - -**NEVER**: -- Delay core functionality for delight -- Force users through delightful moments (make skippable) -- Use delight to hide poor UX -- Overdo it (less is more) -- Ignore accessibility (animate responsibly, provide alternatives) -- Make every interaction delightful (special moments should be special) -- Sacrifice performance for delight -- Be inappropriate for context (read the room) - -## Verify Delight Quality - -Test that delight actually delights: - -- **User reactions**: Do users smile? Share screenshots? -- **Doesn't annoy**: Still pleasant after 100th time? -- **Doesn't block**: Can users opt out or skip? -- **Performant**: No jank, no slowdown -- **Appropriate**: Matches brand and context -- **Accessible**: Works with reduced motion, screen readers - -When the moments feel earned, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/distill.md b/.agents/skills/impeccable/reference/distill.md deleted file mode 100644 index 2ac85043..00000000 --- a/.agents/skills/impeccable/reference/distill.md +++ /dev/null @@ -1,111 +0,0 @@ -Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity. - - ---- - -## Assess Current State - -Analyze what makes the design feel complex or cluttered: - -1. **Identify complexity sources**: - - **Too many elements**: Competing buttons, redundant information, visual clutter - - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose - - **Information overload**: Everything visible at once, no progressive disclosure - - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations - - **Confusing hierarchy**: Unclear what matters most - - **Feature creep**: Too many options, actions, or paths forward - -2. **Find the essence**: - - What's the primary user goal? (There should be ONE) - - What's actually necessary vs nice-to-have? - - What can be removed, hidden, or combined? - - What's the 20% that delivers 80% of value? - -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. - -**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence. - -## Plan Simplification - -Create a ruthless editing strategy: - -- **Core purpose**: What's the ONE thing this should accomplish? -- **Essential elements**: What's truly necessary to achieve that purpose? -- **Progressive disclosure**: What can be hidden until needed? -- **Consolidation opportunities**: What can be combined or integrated? - -**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless. - -## Simplify the Design - -Systematically remove complexity across these dimensions: - -### Information Architecture -- **Reduce scope**: Remove secondary actions, optional features, redundant information -- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows) -- **Combine related actions**: Merge similar buttons, consolidate forms, group related content -- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden -- **Remove redundancy**: If it's said elsewhere, don't repeat it here - -### Visual Simplification -- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors -- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights -- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function -- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards -- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead -- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps - -### Layout Simplification -- **Linear flow**: Replace complex grids with simple vertical flow where possible -- **Remove sidebars**: Move secondary content inline or hide it -- **Full-width**: Use available space generously instead of complex multi-column layouts -- **Consistent alignment**: Pick left or center, stick with it -- **Generous white space**: Let content breathe, don't pack everything tight - -### Interaction Simplification -- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real) -- **Smart defaults**: Make common choices automatic, only ask when necessary -- **Inline actions**: Replace modal flows with inline editing where possible -- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified? -- **Clear CTAs**: ONE obvious next step, not five competing actions - -### Content Simplification -- **Shorter copy**: Cut every sentence in half, then do it again -- **Active voice**: "Save changes" not "Changes will be saved" -- **Remove jargon**: Plain language always wins -- **Scannable structure**: Short paragraphs, bullet points, clear headings -- **Essential information only**: Remove marketing fluff, legalese, hedging -- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once - -### Code Simplification -- **Remove unused code**: Dead CSS, unused components, orphaned files -- **Flatten component trees**: Reduce nesting depth -- **Consolidate styles**: Merge similar styles, use utilities consistently -- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases? - -**NEVER**: -- Remove necessary functionality (simplicity ≠ feature-less) -- Sacrifice accessibility for simplicity (clear labels and ARIA still required) -- Make things so simple they're unclear (mystery ≠ minimalism) -- Remove information users need to make decisions -- Eliminate hierarchy completely (some things should stand out) -- Oversimplify complex domains (match complexity to actual task complexity) - -## Verify Simplification - -Ensure simplification improves usability: - -- **Faster task completion**: Can users accomplish goals more quickly? -- **Reduced cognitive load**: Is it easier to understand what to do? -- **Still complete**: Are all necessary features still accessible? -- **Clearer hierarchy**: Is it obvious what matters most? -- **Better performance**: Does simpler design load faster? - -## Document Removed Complexity - -If you removed features or options: -- Document why they were removed -- Consider if they need alternative access points -- Note any user feedback to monitor - -When the cuts feel right, hand off to `$impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away." diff --git a/.agents/skills/impeccable/reference/document.md b/.agents/skills/impeccable/reference/document.md deleted file mode 100644 index ebafe4f4..00000000 --- a/.agents/skills/impeccable/reference/document.md +++ /dev/null @@ -1,427 +0,0 @@ -Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand. - -DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.). - -## The frontmatter: token schema - -The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses. - -```yaml ---- -name: -description: -colors: - primary: "#b8422e" - neutral-bg: "#faf7f2" - # ...one entry per extracted color; key = descriptive slug -typography: - display: - fontFamily: "Cormorant Garamond, Georgia, serif" - fontSize: "clamp(2.5rem, 7vw, 4.5rem)" - fontWeight: 300 - lineHeight: 1 - letterSpacing: "normal" - body: - # ... -rounded: - sm: "4px" - md: "8px" -spacing: - sm: "8px" - md: "16px" -components: - button-primary: - backgroundColor: "{colors.primary}" - textColor: "{colors.neutral-bg}" - rounded: "{rounded.sm}" - padding: "16px 48px" - button-primary-hover: - backgroundColor: "{colors.primary-deep}" ---- -``` - -Rules that matter: - -- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other. -- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason. -- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b). -- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults. -- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys. - -## The markdown body: six sections (exact order) - -1. `## Overview` -2. `## Colors` -3. `## Typography` -4. `## Elevation` -5. `## Components` -6. `## Do's and Don'ts` - -Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs. - -## When to run - -- The user just ran `$impeccable teach` and needs the visual side documented. -- The skill noticed no `DESIGN.md` exists and nudged the user to create one. -- An existing `DESIGN.md` is stale (the design has drifted). -- Before a large redesign, to capture the current state as a reference. - -If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. whether to refresh, overwrite, or merge. - -## Two paths - -- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze. -- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked ``. Re-run in scan mode once there's code. - -Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `$impeccable document --seed` forces seed mode regardless of code presence. - -## Scan mode (approach C: auto-extract, then confirm descriptive language) - -### Step 1: Find the design assets - -Search the codebase in priority order: - -1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in. -2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow. -3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent. -4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format. -5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles. -6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments. -7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss. - -### Step 2: Auto-extract what can be auto-extracted - -Build a structured draft from the discovered tokens. For each token class: - -- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them. -- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio. -- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly. -- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding. -- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section. - -### Step 2b: Stage the frontmatter - -From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume. - -- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value. -- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`). -- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps). -- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead. - -Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec. - -### Step 3: Ask the user for qualitative language - -The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction: - -- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality. -- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like). -- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation. -- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural? -- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained"). - -Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward. - -### Step 4: Write DESIGN.md - -The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed. - -```markdown ---- -name: [Project Title] -description: [one-line tagline] -colors: - # ... staged frontmatter from Step 2b ---- - -# Design System: [Project Title] - -## 1. Overview - -**Creative North Star: "[Named metaphor in quotes]"** - -[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.] - -## 2. Colors - -[Describe the palette character in one sentence.] - -### Primary -- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.] - -### Secondary (optional; omit if the project has only one accent) -- **[Descriptive Name]** (#HEX): [Role.] - -### Tertiary (optional) -- **[Descriptive Name]** (#HEX): [Role.] - -### Neutral -- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.] -- [...] - -### Named Rules (optional, powerful) -**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."] - -## 3. Typography - -**Display Font:** [Family] (with [fallback]) -**Body Font:** [Family] (with [fallback]) -**Label/Mono Font:** [Family, if distinct] - -**Character:** [1-2 sentence personality description of the pairing.] - -### Hierarchy -- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.] -- **Headline** ([weight], [size], [line-height]): [Purpose.] -- **Title** ([weight], [size], [line-height]): [Purpose.] -- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.] -- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.] - -### Named Rules (optional) -**The [Rule Name] Rule.** [Short doctrine about type use.] - -## 4. Elevation - -[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.] - -### Shadow Vocabulary (if applicable) -- **[Role name]** (`box-shadow: [exact value]`): [When to use it.] -- [...] - -### Named Rules (optional) -**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."] - -## 5. Components - -For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior. - -### Buttons -- **Shape:** [radius described, exact value in parens] -- **Primary:** [color assignment + padding, in semantic + exact terms] -- **Hover / Focus:** [transitions, treatments] -- **Secondary / Ghost / Tertiary (if applicable):** [brief description] - -### Chips (if used) -- **Style:** [background, text color, border treatment] -- **State:** [selected / unselected, filter / action variants] - -### Cards / Containers -- **Corner Style:** [radius] -- **Background:** [colors used] -- **Shadow Strategy:** [reference Elevation section] -- **Border:** [if any] -- **Internal Padding:** [scale] - -### Inputs / Fields -- **Style:** [stroke, background, radius] -- **Focus:** [treatment, e.g. glow, border shift, etc.] -- **Error / Disabled:** [if applicable] - -### Navigation -- **Style, typography, default/hover/active states, mobile treatment.** - -### [Signature Component] (optional; if the project has a distinctive custom component worth documenting) -[Description.] - -## 6. Do's and Don'ts - -Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name. - -### Do: -- **Do** [specific prescription with exact values / named rule]. -- **Do** [...] - -### Don't: -- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"]. -- **Don't** [...] -- **Don't** [...] -``` - -### Step 4b: Write .impeccable/design.json sidecar (extensions only) - -The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it. - -Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`. - -#### Schema - -```json -{ - "schemaVersion": 2, - "generatedAt": "ISO-8601 string", - "title": "Design System: [Project Title]", - "extensions": { - "colorMeta": { - "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] }, - "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] } - }, - "typographyMeta": { - "display": { "displayName": "Display", "purpose": "Hero headlines only." } - }, - "shadows": [ - { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." } - ], - "motion": [ - { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." } - ], - "breakpoints": [ - { "name": "sm", "value": "640px" } - ] - }, - "components": [ - { - "name": "Primary Button", - "kind": "button | input | nav | chip | card | custom", - "refersTo": "button-primary", - "description": "One-line what and when.", - "html": "", - "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }" - } - ], - "narrative": { - "northStar": "The Editorial Sanctuary", - "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.", - "keyCharacteristics": ["...", "..."], - "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }], - "dos": ["Do use ..."], - "donts": ["Don't use ..."] - } -} -``` - -**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.`, `typographyMeta.`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them. - -#### Component translation rules - -The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime. - -1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained. -2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time. -3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or ``. A typical icon is 16-24px; copy the SVG path data directly. -4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive. -5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets. -6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM. - -#### What to include - -Aim for a tight set of **5-10 components** that best represent the visual system: - -- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card. -- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md. -- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive. - -If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero. - -#### Tonal ramps - -For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH. - -#### Narrative mapping - -Pull directly from the DESIGN.md you just wrote: - -- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview -- `narrative.overview` → the philosophy paragraphs from Overview -- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list -- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section` -- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim - -Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through. - -### Step 5: Confirm, refine, and refresh session cache - -1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules). -2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations. -3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?" -4. **Refresh the session cache.** Run `node .agents/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading. - -## Seed mode - -For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec. - -### Step 1: Confirm seed mode - -Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `$impeccable document` once there's code, to capture the real tokens and components. OK?" - -If the user prefers to skip, stop. No file. - -### Step 2: Five questions - -Group into one `AskUserQuestion` interaction. Options must be concrete. - -1. **Color strategy.** Pick one: - - Restrained: tinted neutrals + one accent ≤10% - - Committed: one saturated color carries 30–60% of the surface - - Full palette: 3–4 named color roles, each deliberate - - Drenched: the surface IS the color - - Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange"). - -2. **Typography direction.** Pick one (specific fonts come later): - - Serif display + sans body - - Single sans (warm / technical / geometric / humanist; pick a feel) - - Display + mono - - Mono-forward - - Editorial script + sans - -3. **Motion energy.** Pick one: - - Restrained: state changes only - - Responsive: feedback + transitions, no choreography - - Choreographed: orchestrated entrances, scroll-driven sequences - -4. **Three named references.** Brands, products, printed objects. Not adjectives. - -5. **One anti-reference.** What it should NOT feel like. Also named. - -### Step 3: Write seed DESIGN.md - -Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec. - -Lead the file with: - -```markdown - -``` - -Per-section guidance in seed mode: - -- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly. -- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`. -- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`. -- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence. -- **Components**: omit entirely; no components exist yet. -- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5. - -Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render. - -### Step 4: Confirm and refresh session cache - -1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment). -2. Tell the user: "Re-run `$impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar." -3. Run `node .agents/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session. - -## Style guidelines - -- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative. -- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line. -- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior). -- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description. -- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is. -- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description. -- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section. -- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone. -- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle. -- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase. -- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering. - -## Pitfalls - -- Don't paste raw CSS class names. Translate to descriptive language. -- Don't extract every token. Stop at what's actually reused; one-offs pollute the system. -- Don't invent components that don't exist. If the project only has buttons and cards, only document those. -- Don't overwrite an existing DESIGN.md without asking. -- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual. -- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs. -- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers. -- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative. -- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`. diff --git a/.agents/skills/impeccable/reference/extract.md b/.agents/skills/impeccable/reference/extract.md deleted file mode 100644 index f8d863ce..00000000 --- a/.agents/skills/impeccable/reference/extract.md +++ /dev/null @@ -1,69 +0,0 @@ -# Extract Flow - -Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse. - -## Step 1: Discover the Design System - -Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions. - -**CRITICAL**: If no design system exists, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. before creating one. Understand the preferred location and structure first. - -## Step 2: Identify Patterns - -Look for extraction opportunities in the target area: - -- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs) -- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens -- **Inconsistent variations**: Multiple implementations of the same concept -- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states) -- **Type styles**: Repeated font-size + weight + line-height combinations -- **Animation patterns**: Repeated easing, duration, or keyframe combinations - -Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication. - -## Step 3: Plan Extraction - -Create a systematic plan: - -- **Components to extract**: Which UI elements become reusable components? -- **Tokens to create**: Which hard-coded values become design tokens? -- **Variants to support**: What variations does each component need? -- **Naming conventions**: Component names, token names, prop names that match existing patterns -- **Migration path**: How to refactor existing uses to consume the new shared versions - -**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable. - -## Step 4: Extract & Enrich - -Build improved, reusable versions: - -- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples -- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token -- **Patterns**: When to use this pattern, code examples, variations and combinations - -## Step 5: Migrate - -Replace existing uses with the new shared versions: - -- **Find all instances**: Search for the patterns you extracted -- **Replace systematically**: Update each use to consume the shared version -- **Test thoroughly**: Ensure visual and functional parity -- **Delete dead code**: Remove the old implementations - -## Step 6: Document - -Update design system documentation: - -- Add new components to the component library -- Document token usage and values -- Add examples and guidelines -- Update any Storybook or component catalog - -**NEVER**: -- Extract one-off, context-specific implementations without generalization -- Create components so generic they are useless -- Extract without considering existing design system conventions -- Skip proper TypeScript types or prop documentation -- Create tokens for every single value (tokens should have semantic meaning) -- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate) - diff --git a/.agents/skills/impeccable/reference/harden.md b/.agents/skills/impeccable/reference/harden.md deleted file mode 100644 index 917be521..00000000 --- a/.agents/skills/impeccable/reference/harden.md +++ /dev/null @@ -1,347 +0,0 @@ -Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it. - -## Assess Hardening Needs - -Identify weaknesses and edge cases: - -1. **Test with extreme inputs**: - - Very long text (names, descriptions, titles) - - Very short text (empty, single character) - - Special characters (emoji, RTL text, accents) - - Large numbers (millions, billions) - - Many items (1000+ list items, 50+ options) - - No data (empty states) - -2. **Test error scenarios**: - - Network failures (offline, slow, timeout) - - API errors (400, 401, 403, 404, 500) - - Validation errors - - Permission errors - - Rate limiting - - Concurrent operations - -3. **Test internationalization**: - - Long translations (German is often 30% longer than English) - - RTL languages (Arabic, Hebrew) - - Character sets (Chinese, Japanese, Korean, emoji) - - Date/time formats - - Number formats (1,000 vs 1.000) - - Currency symbols - -**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality. - -## Hardening Dimensions - -Systematically improve resilience: - -### Text Overflow & Wrapping - -**Long text handling**: -```css -/* Single line with ellipsis */ -.truncate { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -/* Multi-line with clamp */ -.line-clamp { - display: -webkit-box; - -webkit-line-clamp: 3; - -webkit-box-orient: vertical; - overflow: hidden; -} - -/* Allow wrapping */ -.wrap { - word-wrap: break-word; - overflow-wrap: break-word; - hyphens: auto; -} -``` - -**Flex/Grid overflow**: -```css -/* Prevent flex items from overflowing */ -.flex-item { - min-width: 0; /* Allow shrinking below content size */ - overflow: hidden; -} - -/* Prevent grid items from overflowing */ -.grid-item { - min-width: 0; - min-height: 0; -} -``` - -**Responsive text sizing**: -- Use `clamp()` for fluid typography -- Set minimum readable sizes (14px on mobile) -- Test text scaling (zoom to 200%) -- Ensure containers expand with text - -### Internationalization (i18n) - -**Text expansion**: -- Add 30-40% space budget for translations -- Use flexbox/grid that adapts to content -- Test with longest language (usually German) -- Avoid fixed widths on text containers - -```jsx -// ❌ Bad: Assumes short English text - - -// ✅ Good: Adapts to content - -``` - -**RTL (Right-to-Left) support**: -```css -/* Use logical properties */ -margin-inline-start: 1rem; /* Not margin-left */ -padding-inline: 1rem; /* Not padding-left/right */ -border-inline-end: 1px solid; /* Not border-right */ - -/* Or use dir attribute */ -[dir="rtl"] .arrow { transform: scaleX(-1); } -``` - -**Character set support**: -- Use UTF-8 encoding everywhere -- Test with Chinese/Japanese/Korean (CJK) characters -- Test with emoji (they can be 2-4 bytes) -- Handle different scripts (Latin, Cyrillic, Arabic, etc.) - -**Date/Time formatting**: -```javascript -// ✅ Use Intl API for proper formatting -new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024 -new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024 - -new Intl.NumberFormat('en-US', { - style: 'currency', - currency: 'USD' -}).format(1234.56); // $1,234.56 -``` - -**Pluralization**: -```javascript -// ❌ Bad: Assumes English pluralization -`${count} item${count !== 1 ? 's' : ''}` - -// ✅ Good: Use proper i18n library -t('items', { count }) // Handles complex plural rules -``` - -### Error Handling - -**Network errors**: -- Show clear error messages -- Provide retry button -- Explain what happened -- Offer offline mode (if applicable) -- Handle timeout scenarios - -```jsx -// Error states with recovery -{error && ( - -

Failed to load data. {error.message}

- -
-)} -``` - -**Form validation errors**: -- Inline errors near fields -- Clear, specific messages -- Suggest corrections -- Don't block submission unnecessarily -- Preserve user input on error - -**API errors**: -- Handle each status code appropriately - - 400: Show validation errors - - 401: Redirect to login - - 403: Show permission error - - 404: Show not found state - - 429: Show rate limit message - - 500: Show generic error, offer support - -**Graceful degradation**: -- Core functionality works without JavaScript -- Images have alt text -- Progressive enhancement -- Fallbacks for unsupported features - -### Edge Cases & Boundary Conditions - -**Empty states**: -- No items in list -- No search results -- No notifications -- No data to display -- Provide clear next action - -**Loading states**: -- Initial load -- Pagination load -- Refresh -- Show what's loading ("Loading your projects...") -- Time estimates for long operations - -**Large datasets**: -- Pagination or virtual scrolling -- Search/filter capabilities -- Performance optimization -- Don't load all 10,000 items at once - -**Concurrent operations**: -- Prevent double-submission (disable button while loading) -- Handle race conditions -- Optimistic updates with rollback -- Conflict resolution - -**Permission states**: -- No permission to view -- No permission to edit -- Read-only mode -- Clear explanation of why - -**Browser compatibility**: -- Polyfills for modern features -- Fallbacks for unsupported CSS -- Feature detection (not browser detection) -- Test in target browsers - -### Input Validation & Sanitization - -**Client-side validation**: -- Required fields -- Format validation (email, phone, URL) -- Length limits -- Pattern matching -- Custom validation rules - -**Server-side validation** (always): -- Never trust client-side only -- Validate and sanitize all inputs -- Protect against injection attacks -- Rate limiting - -**Constraint handling**: -```html - - - - Letters and numbers only, up to 100 characters - -``` - -### Accessibility Resilience - -**Keyboard navigation**: -- All functionality accessible via keyboard -- Logical tab order -- Focus management in modals -- Skip links for long content - -**Screen reader support**: -- Proper ARIA labels -- Announce dynamic changes (live regions) -- Descriptive alt text -- Semantic HTML - -**Motion sensitivity**: -```css -@media (prefers-reduced-motion: reduce) { - * { - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - } -} -``` - -**High contrast mode**: -- Test in Windows high contrast mode -- Don't rely only on color -- Provide alternative visual cues - -### Performance Resilience - -**Slow connections**: -- Progressive image loading -- Skeleton screens -- Optimistic UI updates -- Offline support (service workers) - -**Memory leaks**: -- Clean up event listeners -- Cancel subscriptions -- Clear timers/intervals -- Abort pending requests on unmount - -**Throttling & Debouncing**: -```javascript -// Debounce search input -const debouncedSearch = debounce(handleSearch, 300); - -// Throttle scroll handler -const throttledScroll = throttle(handleScroll, 100); -``` - -## Testing Strategies - -**Manual testing**: -- Test with extreme data (very long, very short, empty) -- Test in different languages -- Test offline -- Test slow connection (throttle to 3G) -- Test with screen reader -- Test keyboard-only navigation -- Test on old browsers - -**Automated testing**: -- Unit tests for edge cases -- Integration tests for error scenarios -- E2E tests for critical paths -- Visual regression tests -- Accessibility tests (axe, WAVE) - -**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined. - -**NEVER**: -- Assume perfect input (validate everything) -- Ignore internationalization (design for global) -- Leave error messages generic ("Error occurred") -- Forget offline scenarios -- Trust client-side validation alone -- Use fixed widths for text -- Assume English-length text -- Block entire interface when one component errors - -## Verify Hardening - -Test thoroughly with edge cases: - -- **Long text**: Try names with 100+ characters -- **Emoji**: Use emoji in all text fields -- **RTL**: Test with Arabic or Hebrew -- **CJK**: Test with Chinese/Japanese/Korean -- **Network issues**: Disable internet, throttle connection -- **Large datasets**: Test with 1000+ items -- **Concurrent actions**: Click submit 10 times rapidly -- **Errors**: Force API errors, test all error states -- **Empty**: Remove all data, test empty states - -When edge cases are covered, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/heuristics-scoring.md b/.agents/skills/impeccable/reference/heuristics-scoring.md deleted file mode 100644 index edbe5028..00000000 --- a/.agents/skills/impeccable/reference/heuristics-scoring.md +++ /dev/null @@ -1,234 +0,0 @@ -# Heuristics Scoring Guide - -Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough." - -## Nielsen's 10 Heuristics - -### 1. Visibility of System Status - -Keep users informed about what's happening through timely, appropriate feedback. - -**Check for**: -- Loading indicators during async operations -- Confirmation of user actions (save, submit, delete) -- Progress indicators for multi-step processes -- Current location in navigation (breadcrumbs, active states) -- Form validation feedback (inline, not just on submit) - -**Scoring**: -| Score | Criteria | -|-------|----------| -| 0 | No feedback; user is guessing what happened | -| 1 | Rare feedback; most actions produce no visible response | -| 2 | Partial; some states communicated, major gaps remain | -| 3 | Good; most operations give clear feedback, minor gaps | -| 4 | Excellent; every action confirms, progress is always visible | - -### 2. Match Between System and Real World - -Speak the user's language. Follow real-world conventions. Information appears in natural, logical order. - -**Check for**: -- Familiar terminology (no unexplained jargon) -- Logical information order matching user expectations -- Recognizable icons and metaphors -- Domain-appropriate language for the target audience -- Natural reading flow (left-to-right, top-to-bottom priority) - -**Scoring**: -| Score | Criteria | -|-------|----------| -| 0 | Pure tech jargon, alien to users | -| 1 | Mostly confusing; requires domain expertise to navigate | -| 2 | Mixed; some plain language, some jargon leaks through | -| 3 | Mostly natural; occasional term needs context | -| 4 | Speaks the user's language fluently throughout | - -### 3. User Control and Freedom - -Users need a clear "emergency exit" from unwanted states without extended dialogue. - -**Check for**: -- Undo/redo functionality -- Cancel buttons on forms and modals -- Clear navigation back to safety (home, previous) -- Easy way to clear filters, search, selections -- Escape from long or multi-step processes - -**Scoring**: -| Score | Criteria | -|-------|----------| -| 0 | Users get trapped; no way out without refreshing | -| 1 | Difficult exits; must find obscure paths to escape | -| 2 | Some exits; main flows have escape, edge cases don't | -| 3 | Good control; users can exit and undo most actions | -| 4 | Full control; undo, cancel, back, and escape everywhere | - -### 4. Consistency and Standards - -Users shouldn't wonder whether different words, situations, or actions mean the same thing. - -**Check for**: -- Consistent terminology throughout the interface -- Same actions produce same results everywhere -- Platform conventions followed (standard UI patterns) -- Visual consistency (colors, typography, spacing, components) -- Consistent interaction patterns (same gesture = same behavior) - -**Scoring**: -| Score | Criteria | -|-------|----------| -| 0 | Inconsistent everywhere; feels like different products stitched together | -| 1 | Many inconsistencies; similar things look/behave differently | -| 2 | Partially consistent; main flows match, details diverge | -| 3 | Mostly consistent; occasional deviation, nothing confusing | -| 4 | Fully consistent; cohesive system, predictable behavior | - -### 5. Error Prevention - -Better than good error messages is a design that prevents problems in the first place. - -**Check for**: -- Confirmation before destructive actions (delete, overwrite) -- Constraints preventing invalid input (date pickers, dropdowns) -- Smart defaults that reduce errors -- Clear labels that prevent misunderstanding -- Autosave and draft recovery - -**Scoring**: -| Score | Criteria | -|-------|----------| -| 0 | Errors easy to make; no guardrails anywhere | -| 1 | Few safeguards; some inputs validated, most aren't | -| 2 | Partial prevention; common errors caught, edge cases slip | -| 3 | Good prevention; most error paths blocked proactively | -| 4 | Excellent; errors nearly impossible through smart constraints | - -### 6. Recognition Rather Than Recall - -Minimize memory load. Make objects, actions, and options visible or easily retrievable. - -**Check for**: -- Visible options (not buried in hidden menus) -- Contextual help when needed (tooltips, inline hints) -- Recent items and history -- Autocomplete and suggestions -- Labels on icons (not icon-only navigation) - -**Scoring**: -| Score | Criteria | -|-------|----------| -| 0 | Heavy memorization; users must remember paths and commands | -| 1 | Mostly recall; many hidden features, few visible cues | -| 2 | Some aids; main actions visible, secondary features hidden | -| 3 | Good recognition; most things discoverable, few memory demands | -| 4 | Everything discoverable; users never need to memorize | - -### 7. Flexibility and Efficiency of Use - -Accelerators, invisible to novices, speed up expert interaction. - -**Check for**: -- Keyboard shortcuts for common actions -- Customizable interface elements -- Recent items and favorites -- Bulk/batch actions -- Power user features that don't complicate the basics - -**Scoring**: -| Score | Criteria | -|-------|----------| -| 0 | One rigid path; no shortcuts or alternatives | -| 1 | Limited flexibility; few alternatives to the main path | -| 2 | Some shortcuts; basic keyboard support, limited bulk actions | -| 3 | Good accelerators; keyboard nav, some customization | -| 4 | Highly flexible; multiple paths, power features, customizable | - -### 8. Aesthetic and Minimalist Design - -Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose. - -**Check for**: -- Only necessary information visible at each step -- Clear visual hierarchy directing attention -- Purposeful use of color and emphasis -- No decorative clutter competing for attention -- Focused, uncluttered layouts - -**Scoring**: -| Score | Criteria | -|-------|----------| -| 0 | Overwhelming; everything competes for attention equally | -| 1 | Cluttered; too much noise, hard to find what matters | -| 2 | Some clutter; main content clear, periphery noisy | -| 3 | Mostly clean; focused design, minor visual noise | -| 4 | Perfectly minimal; every element earns its pixel | - -### 9. Help Users Recognize, Diagnose, and Recover from Errors - -Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution. - -**Check for**: -- Plain language error messages (no error codes for users) -- Specific problem identification ("Email is missing @" not "Invalid input") -- Actionable recovery suggestions -- Errors displayed near the source of the problem -- Non-blocking error handling (don't wipe the form) - -**Scoring**: -| Score | Criteria | -|-------|----------| -| 0 | Cryptic errors; codes, jargon, or no message at all | -| 1 | Vague errors; "Something went wrong" with no guidance | -| 2 | Clear but unhelpful; names the problem but not the fix | -| 3 | Clear with suggestions; identifies problem and offers next steps | -| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work | - -### 10. Help and Documentation - -Even if the system is usable without docs, help should be easy to find, task-focused, and concise. - -**Check for**: -- Searchable help or documentation -- Contextual help (tooltips, inline hints, guided tours) -- Task-focused organization (not feature-organized) -- Concise, scannable content -- Easy access without leaving current context - -**Scoring**: -| Score | Criteria | -|-------|----------| -| 0 | No help available anywhere | -| 1 | Help exists but hard to find or irrelevant | -| 2 | Basic help; FAQ or docs exist, not contextual | -| 3 | Good documentation; searchable, mostly task-focused | -| 4 | Excellent contextual help; right info at the right moment | - ---- - -## Score Summary - -**Total possible**: 40 points (10 heuristics × 4 max) - -| Score Range | Rating | What It Means | -|-------------|--------|---------------| -| 36–40 | Excellent | Minor polish only; ship it | -| 28–35 | Good | Address weak areas, solid foundation | -| 20–27 | Acceptable | Significant improvements needed before users are happy | -| 12–19 | Poor | Major UX overhaul required; core experience broken | -| 0–11 | Critical | Redesign needed; unusable in current state | - ---- - -## Issue Severity (P0–P3) - -Tag each individual issue found during scoring with a priority level: - -| Priority | Name | Description | Action | -|----------|------|-------------|--------| -| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper | -| **P1** | Major | Causes significant difficulty or confusion | Fix before release | -| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass | -| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits | - -**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1. diff --git a/.agents/skills/impeccable/reference/interaction-design.md b/.agents/skills/impeccable/reference/interaction-design.md deleted file mode 100644 index 15aed5b2..00000000 --- a/.agents/skills/impeccable/reference/interaction-design.md +++ /dev/null @@ -1,195 +0,0 @@ -# Interaction Design - -## The Eight Interactive States - -Every interactive element needs these states designed: - -| State | When | Visual Treatment | -|-------|------|------------------| -| **Default** | At rest | Base styling | -| **Hover** | Pointer over (not touch) | Subtle lift, color shift | -| **Focus** | Keyboard/programmatic focus | Visible ring (see below) | -| **Active** | Being pressed | Pressed in, darker | -| **Disabled** | Not interactive | Reduced opacity, no pointer | -| **Loading** | Processing | Spinner, skeleton | -| **Error** | Invalid state | Red border, icon, message | -| **Success** | Completed | Green check, confirmation | - -**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states. - -## Focus Rings: Do Them Right - -**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users: - -```css -/* Hide focus ring for mouse/touch */ -button:focus { - outline: none; -} - -/* Show focus ring for keyboard */ -button:focus-visible { - outline: 2px solid var(--color-accent); - outline-offset: 2px; -} -``` - -**Focus ring design**: -- High contrast (3:1 minimum against adjacent colors) -- 2-3px thick -- Offset from element (not inside it) -- Consistent across all interactive elements - -## Form Design: The Non-Obvious - -**Placeholders aren't labels.** They disappear on input. Always use visible `