diff --git a/.agents/settings.local.json b/.agents/settings.local.json deleted file mode 100644 index 4da993b0..00000000 --- a/.agents/settings.local.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "permissions": { - "defaultMode": "auto", - "deny": [ - "Bash(git commit *)", - "Bash(git commit)", - "Bash(git stash *)", - "Bash(git stash)", - "Bash(git push *)", - "Bash(git push)", - "Bash(git reset --hard *)", - "Bash(git reset *)", - - "Bash(pnpm dev)", - "Bash(pnpm dev *)", - "Bash(pnpm start)", - "Bash(pnpm start *)", - "Bash(pnpm run dev)", - "Bash(pnpm run dev *)", - "Bash(pnpm run start)", - "Bash(pnpm run start *)", - - "Bash(npm dev)", - "Bash(npm dev *)", - "Bash(npm start)", - "Bash(npm start *)", - "Bash(npm run dev)", - "Bash(npm run dev *)", - "Bash(npm run start)", - "Bash(npm run start *)", - - "Bash(bun dev)", - "Bash(bun dev *)", - "Bash(bun start)", - "Bash(bun start *)", - "Bash(bun run dev)", - "Bash(bun run dev *)", - "Bash(bun run start)", - "Bash(bun run start *)", - - "Bash(rm -rf *)", - - "Read(**/.env)", - "Read(**/.env.*)", - "Read(.env)", - "Read(.env.*)", - "Edit(**/.env)", - "Edit(**/.env.*)", - "Edit(.env)", - "Edit(.env.*)", - "Write(**/.env)", - "Write(**/.env.*)", - "Write(.env)", - "Write(.env.*)", - - "Bash(cat *.env)", - "Bash(cat *.env.*)", - "Bash(cat *.env*)", - "Bash(less *.env)", - "Bash(less *.env.*)", - "Bash(less *.env*)", - "Bash(more *.env)", - "Bash(more *.env.*)", - "Bash(more *.env*)", - "Bash(head *.env)", - "Bash(head *.env.*)", - "Bash(head *.env*)", - "Bash(tail *.env)", - "Bash(tail *.env.*)", - "Bash(tail *.env*)", - "Bash(grep *.env)", - "Bash(grep *.env.*)", - "Bash(grep *.env*)", - "Bash(rg *.env)", - "Bash(rg *.env.*)", - "Bash(rg *.env*)", - "Bash(sed *.env)", - "Bash(sed *.env.*)", - "Bash(sed *.env*)", - "Bash(awk *.env)", - "Bash(awk *.env.*)", - "Bash(awk *.env*)", - "Bash(cp *.env*)", - "Bash(mv *.env*)", - "Bash(xxd *.env*)", - "Bash(od *.env*)", - "Bash(strings *.env*)", - "Bash(tee *.env*)", - "Bash(cp .env*)", - "Bash(mv .env*)", - "Bash(cat .env*)", - "Bash(less .env*)", - "Bash(more .env*)", - "Bash(head .env*)", - "Bash(tail .env*)", - "Bash(grep * .env*)", - "Bash(rg * .env*)", - "Bash(sed * .env*)", - "Bash(awk * .env*)" - ] - } -} diff --git a/.agents/skills/.gitkeep b/.agents/skills/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/.agents/skills/react/SKILL.md b/.agents/skills/react/SKILL.md deleted file mode 100644 index c6be77cd..00000000 --- a/.agents/skills/react/SKILL.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -name: react -description: React coding standards for this project. Use when writing or modifying React components, hooks, or route files. ---- - -# React - -These are the React standards for this project. Follow them when writing or modifying any React code. For detailed rationale, examples, and edge cases on composition and data patterns, see the individual [reference files](references/). - -## Composition - -- Code should read like prose. Every file should have a clear, single purpose. -- Separate concerns by file: business logic in hooks/utilities, UI in components, data fetching config in query builders. Exception: a component and its dedicated hook may live in the same file when the hook serves only that component. -- Build complex behavior by composing small hooks and small components — do not let a single unit grow. -- **Route files**: All route-level configuration (search params, loader, beforeLoad, head, meta, error/pending components, static data, etc.) defined inline — never imported from a separate config file. A route file contains at most **one hook** (showing what data the page needs) and **one route component** (containing the actual page markup). Nothing else — no sub-components, constants, types, or extra hooks. Those belong in feature directories. Do not extract the entire route body into a single feature component; if the route would just render ``, that component's content belongs inline in the route component. If the page is simple, the route component just contains the markup directly. -- **Components**: Under ~80 lines or one distinct UI concern. Split if larger. Colocate tightly related sub-components in the same file when not reused elsewhere. -- **Hooks**: Under ~50 lines. Extract sub-hooks when larger. A coordinating hook should mostly be a sequence of calls to smaller hooks plus a return statement. -- Small inline handlers (a couple of lines) in components are fine. Anything more substantial should be extracted into a hook or utility. - -## State Management - -TanStack Query is the primary state management solution for server data. Components should pull data directly using hooks (`useSuspenseQuery`, `useSearch`, `useRouteContext`, `useStore`) at the leaf level where it's needed — **never prop drill data that a hook can provide directly**. - -1. **Query caches** (TanStack Query for all data sources): The default for server data. Query at the component level — no prop drilling required. Centralize all query definitions (including Convex) into `*Queries` files using `queryOptions`. -2. **URL state** (TanStack Router `validateSearch` + `useSearch`): For state that should persist across refreshes, be shareable via link, or be bookmarkable. -3. **Rostra stores**: Only for non-server state — form inputs before submission, global concerns (auth, theme), UI state shared across a subtree. See the `rostra` skill for implementation details. -4. **Prop drilling**: Least preferred, and usually unnecessary. One level of props is normal for component-specific configuration. Passing data available via hooks through multiple intermediary components is always wrong. Before prop drilling though, you should always ask yourself if one of the solutions above could be used instead, typically the answer is yes. - -When uncertain about the right choice, ask the user. - -## Data Loading - -- **Component + hook pattern**: Components with more than ~5 lines of business logic (queries, mutations, derived state, handlers) should pair with a co-located hook that owns all that logic. The hook returns only what the component actually uses — named variables and callbacks, never raw query objects or large data structures. The component is a thin renderer. For components with minimal data access (a single query call and a line or two of derivation), inline logic in the component body is fine — extracting a hook for 3 lines of logic adds ceremony without improving readability. -- **Route loaders**: Prefetch with `ensureQueryData` (or `ensureInfiniteQueryData`). Declare `loaderDeps` when the loader depends on search params. -- **Centralized query definitions**: All queries — Convex and non-Convex — should be centralized into `*Queries` files using `queryOptions`. For Convex, wrap `convexQuery()` in `queryOptions()` — no explicit `queryKey` needed since `convexQuery` generates keys automatically. -- **Centralized mutation definitions**: Use `mutationOptions` for all mutations. Convex mutations must be defined inside a hook (since `useConvexMutation` is a hook). -- **Components**: Consume prefetched data with `useSuspenseQuery`. Since the loader already populated the cache, this resolves synchronously. Pull data at the leaf component — do not drill it from parents. -- **Fine-grained data hooks**: Prefer many small hooks that each `select` the minimum data one consumer needs over a single shared hook that returns a large object. The query cache deduplicates fetches, so multiple hooks hitting the same query key with different `select` functions cost nothing. Name hooks after the data they provide (`useCartQuantity`, `useProductTitle`), not the query they read from. -- **Optimistic updates**: For TanStack Query — cancel in-flight queries in `onMutate`, snapshot previous data, apply optimistic change, roll back in `onError`. For Convex — use `.withOptimisticUpdate`. Prioritize for actions where perceived latency matters (cart ops, toggles, inline edits). -- **Loading/error states**: Do NOT manually write loading spinners or error checks. TanStack Start handles this at the route level via `defaultPendingComponent`, `defaultErrorComponent`, and `defaultNotFoundComponent`. Only check mutation status (`isPending`, `isError`) for mutation-driven UI feedback. - -## Performance - -- **Push state down**: Own state in the leaf component that needs it, not in a shared parent. -- **Split at render boundaries**: Separate frequently-changing state from expensive-to-render UI into different components. -- **Compose with children**: When a wrapper needs state but its children don't depend on it, pass children through as a prop to avoid re-rendering the subtree. -- **Stable references**: Hoist static objects/arrays to module scope. Inline object/array literals create new references every render, which matters when the receiver relies on referential equality. diff --git a/.agents/skills/react/references/composition.md b/.agents/skills/react/references/composition.md deleted file mode 100644 index 1a461bcc..00000000 --- a/.agents/skills/react/references/composition.md +++ /dev/null @@ -1,294 +0,0 @@ -# Composition - -## Overview - -Code should read like prose. When you look at a component, a hook, or a route file, you should be able to understand what it does with the same ease as reading a sentence. This means keeping things small, focused, and organized so that the intent is immediately obvious at every level. - -The single biggest failure mode for AI-generated React code is producing monolithic files that mix business logic, state management, and UI into one enormous blob. This makes code review painful because you cannot reason about any single concern without mentally filtering out everything else. Every file should have a clear purpose, and every function within it should earn its place. - -## Principles - -1. **Small over large.** A 40-line component that does one thing well is always better than a 200-line component that does five things. -2. **Separate concerns by file.** Business logic lives in hooks or utility functions. UI lives in components. Data fetching configuration lives in query builders. Exception: a component and its dedicated hook may live in the same file when the hook serves only that component. Shared or reusable hooks still belong in separate files. -3. **Compose, don't accumulate.** Build complex behavior by composing small hooks and small components rather than letting a single unit grow. -4. **Every file should answer one question at a glance.** A route file answers "what does this page look like and what data does it need?" A component file answers "what does this piece of UI render?" A hook answers "what behavior does this encapsulate?" - -## Route Files - -A route file is the entry point for a page. When someone opens it, they should immediately understand: - -- What data the page needs -- What the general layout looks like -- Where to go to dig deeper into any specific piece - -Route files should be concise. Search params, loaders, and the route component all live in the same file. - -A route file contains at most **one hook** and **one route component**. Nothing else. - -- The **hook** shows what data the page needs — queries, context, derived state. Not every route needs one; omit it when the route component has no data to fetch. -- The **route component** contains the actual page markup and layout. It calls the hook (if one exists) and renders the page using imported child components. If the page is simple enough, the route component just contains the markup directly — do not create sub-components for the sake of it. - -Do not extract the entire route component body into a single feature component and render only that. If the route component would just be ``, that component's content belongs inline in the route component itself. - -Sub-components, constants, types, hooks beyond the single route hook, and utilities do **not** belong in route files. Sub-components live in `components/` feature folders. Constants and types live in `lib/` feature folders. The route file imports them. The route file is a map — it shows you what data the page uses, how it uses it, and what the page looks like at a glance. - -### Example: A well-composed route file - -```tsx -import { useSuspenseQuery } from "@tanstack/react-query"; -import { createFileRoute, useRouteContext } from "@tanstack/react-router"; -import { z } from "zod"; - -import type { Viewport } from "~/features/pages/components/viewport-controls"; -import { env } from "~/env"; -import { OpenInNewTab } from "~/features/pages/components/open-in-new-tab"; -import { PreviewIframe } from "~/features/pages/components/preview-iframe"; -import { - defaultViewport, - ViewportToggle, - viewportValidator, -} from "~/features/pages/components/viewport-controls"; -import { pageQueries } from "~/features/pages/lib/page-queries"; - -export const Route = createFileRoute( - "/_authenticated/_authorized/pages/$pageId/", -)({ - component: PageHub, - validateSearch: z.object({ - viewport: viewportValidator.default(defaultViewport), - }), - loader: async ({ context }) => { - const { pageId } = context; - await Promise.all([ - context.queryClient.ensureQueryData( - pageQueries.listDraftsFirstPage(pageId), - ), - context.queryClient.ensureQueryData( - pageQueries.listRecentReleases(pageId), - ), - ]); - }, - shouldReload: false, -}); - -function PageHub() { - const { title, hasRelease, url, viewport, setViewport } = usePageHub(); - - if (!hasRelease) { - return ( -
-

- No version has been published yet -

-
- ); - } - - return ( -
-
- - -
- -
- ); -} - -function usePageHub() { - const pageId = useRouteContext({ - from: "/_authenticated/_authorized/pages/$pageId", - select: (ctx) => ctx.pageId, - }); - - const { data } = useSuspenseQuery({ - ...pageQueries.getById(pageId), - select: (data) => ({ - title: data.title, - path: data.path, - hasRelease: data.hasRelease, - }), - }); - - const viewport = Route.useSearch({ - select: (search) => search.viewport, - }); - - const navigate = Route.useNavigate(); - async function setViewport(newViewport: Viewport) { - await navigate({ search: { viewport: newViewport }, replace: true }); - } - - const url = `${env.VITE_SHOP_URL}${data.path}`; - - return { ...data, url, viewport, setViewport }; -} -``` - -Notice what this file gives you: the route configuration is self-contained at the top — search params, loader, and prefetching are all visible. The route component reads like a description of UI: if there's no release, show an empty state; otherwise show the preview toolbar and iframe. The hook reads like a description of behavior: get the page ID, select the three fields we need, read the viewport search param, wire up a navigation callback, derive the preview URL. Neither concern leaks into the other. Every query uses `select` to pull only what this specific component needs, and the hook returns only named primitives and callbacks. - -## Components - -Components with more than ~5 lines of business logic should pair with a co-located hook in the same file. The hook owns all data access — queries, mutations, derived state, navigation. The component is a thin renderer that calls the hook and renders UI based on what it returns. For components with minimal data access (a single query call and a line or two of derivation), inline logic in the component body is fine — extracting a hook for 3 lines of logic adds ceremony without improving readability. - -Components should be small and focused on a single piece of UI. When a component grows beyond a handful of concerns, split it into smaller components that each own one piece. The parent component then becomes a composition of those pieces, readable at a glance. - -Colocate tightly related sub-components in the same file when they are not reused elsewhere. The exported component is the public API of the file; internal sub-components and hooks are implementation details. - -### Example: A component with its co-located hook - -```tsx -export function PagePreview() { - const { title, hasRelease, url, viewport, setViewport } = usePagePreview(); - - if (!hasRelease) { - return ( -
-

- No version has been published yet -

-
- ); - } - - return ( -
-
- - -
- -
- ); -} - -function usePagePreview() { - const pageId = useRouteContext({ - from: "/_authenticated/_authorized/pages/$pageId", - select: (ctx) => ctx.pageId, - }); - - const { data } = useSuspenseQuery({ - ...pageQueries.getById(pageId), - select: (data) => ({ - title: data.title, - path: data.path, - hasRelease: data.hasRelease, - }), - }); - - const viewport = Route.useSearch({ - select: (search) => search.viewport, - }); - - const navigate = Route.useNavigate(); - async function setViewport(newViewport: Viewport) { - await navigate({ search: { viewport: newViewport }, replace: true }); - } - - const url = `${env.VITE_SHOP_URL}${data.path}`; - - return { ...data, url, viewport, setViewport }; -} -``` - -Reading this file, the component reads like a description of UI: if there's no release, show an empty state; otherwise show the preview toolbar and iframe. The hook reads like a description of behavior: get the page ID, select the three fields we need, read the viewport search param, derive the preview URL. Neither concern leaks into the other. - -Notice the hook's `select` — it pulls only `title`, `path`, and `hasRelease` from the page query, not the entire page object. The hook then returns only named primitives and callbacks that the component actually uses. This keeps the interface between hook and component tight and explicit. - -## Hooks - -Hooks should be small, single-purpose, and specific to their consumer. A hook's return value should be the minimum interface its consumer needs — named primitives and callbacks, not raw query objects or large data structures. - -The default pattern is a **co-located hook** — an unexported hook in the same file as the component it serves. This hook owns all business logic for that component: queries with fine-grained `select`, mutations, derived state, and navigation. The component calls the hook and renders what it returns. - -When a hook grows beyond ~50 lines, extract focused sub-hooks. But the goal is not to build a hierarchy of shared hooks that centralize data access — it's to keep each hook small and specific to the concern it serves. - -### Example: A co-located hook with fine-grained selection - -```tsx -function useDraftEditor() { - const draftId = useRouteContext({ - from: "/_authenticated/_authorized/pages/$pageId/draft/$draftId", - select: (ctx) => ctx.draftId, - }); - - const { data: draft } = useSuspenseQuery({ - ...pageQueries.getDraft(draftId), - select: (data) => ({ _id: data._id, content: data.content }), - }); - - const [content, setContent] = useState(draft.content); - - useAutosave({ draftId: draft._id, content }); - - const { mode, viewport } = Route.useSearch({ - select: (search) => ({ mode: search.mode, viewport: search.viewport }), - }); - - const navigate = Route.useNavigate(); - async function setMode(newMode: EditorMode) { - await navigate({ search: { mode: newMode, viewport }, replace: true }); - } - async function setViewport(newViewport: Viewport) { - await navigate({ search: { mode, viewport: newViewport }, replace: true }); - } - - const pageId = useRouteContext({ - from: "/_authenticated/_authorized/pages/$pageId", - select: (ctx) => ctx.pageId, - }); - - const { data: page } = useSuspenseQuery({ - ...pageQueries.getById(pageId), - select: (data) => ({ path: data.path }), - }); - - const previewUrl = `${env.VITE_SHOP_URL}${page.path}?draftId=${draftId}`; - - return { - content, - setContent, - mode, - viewport, - setMode, - setViewport, - previewUrl, - }; -} -``` - -This hook reads as a clear narrative: get the draft ID, select only the two fields we need from the draft, set up autosave, read search params, wire up navigation callbacks, compute the preview URL. Every query uses `select` to pull only what this specific component needs. The return value is a flat set of named primitives and callbacks — no raw query objects, no large data structures. - -### What to avoid: shared "kitchen sink" hooks - -Do not build shared hooks that return large objects for many consumers to pick from: - -```tsx -// ❌ WRONG — centralizes too much, returns more than any one consumer needs -function useCart() { - const cartQuery = useSuspenseQuery(cartQueries.detail(cartId)); - return { - cart: cartQuery.data, // entire cart object - cartQuantity: cartQuery.data.totalQuantity, - cartQuery, // raw query object leaked - }; -} -``` - -Instead, each component that needs cart data should have its own hook (or inline query) that selects only what it needs. The query cache deduplicates the underlying fetch, so multiple components hitting the same query key with different `select` functions cost nothing. See the `data-and-state` reference for details. - -## Rules of Thumb - -- **Route files**: Under ~100 lines. All route-level configuration (search params, loader, beforeLoad, head, meta, error/pending components, static data, etc.) must be defined inline in the route file — never in a separate config file that gets imported. The route file should read like a self-contained table of contents: configuration at the top, then a layout component that composes feature components. -- **Components**: If a component exceeds ~80 lines or handles more than one distinct UI concern, split it. -- **Hooks**: If a hook exceeds ~70 lines, extract sub-hooks. Co-located hooks should be specific to their component and return only what that component uses — never raw query objects or large data structures. -- **Business logic in components**: Small inline handlers (a couple of lines) are fine. Anything more substantial should be extracted into a hook or utility function so the component stays focused on rendering. diff --git a/.agents/skills/react/references/data-and-state.md b/.agents/skills/react/references/data-and-state.md deleted file mode 100644 index e0f09975..00000000 --- a/.agents/skills/react/references/data-and-state.md +++ /dev/null @@ -1,419 +0,0 @@ -# Data and State - -## Overview - -TanStack Query is both the data-fetching layer and the primary state management solution for server data. Most components should get their state by querying data directly via `useSuspenseQuery` rather than hoisting it into stores or drilling it through props. Rostra stores are reserved for state that lives outside the data-fetching lifecycle — form inputs, theme, auth. Each component should pair with a co-located hook that owns all business logic; the component itself is a thin renderer. - -## The Component + Hook Pattern - -The default architecture for any component that consumes data or performs actions is: one exported component and one unexported co-located hook in the same file. The hook owns all business logic — queries, mutations, derived state, navigation. The component owns rendering. - -```tsx -export function CreatePageButton() { - const { createPage, isCreating, isError } = useCreatePage(); - - return ( - - ); -} - -function useCreatePage() { - const navigate = useNavigate(); - const pageMutations = usePageMutations(); - const { mutate, isError } = useMutation({ - ...pageMutations.createPage, - onSuccess: (data) => { - void navigate({ - to: "/pages/$pageId", - params: { pageId: data.pageId }, - search: {}, - }); - }, - }); - const isCreating = useIsPending(pageMutations.createPage.mutationKey); - return { createPage: () => mutate({}), isCreating, isError }; -} -``` - -The component reads like a description of UI. The hook reads like a description of behavior. When an agent looks at this file, it sees both concerns clearly separated but co-located for discoverability. - -The co-located hook should return only what the component actually uses — named variables and callbacks, not raw query objects or large data structures. If the component needs a quantity and a delete action, the hook returns `{ quantity, deleteItem }`, not `{ cart, cartQuery }`. This keeps the interface between hook and component tight and explicit. - -When a hook is reused across multiple components, extract it to a shared hooks directory. See the `composition` reference for size limits — if the co-located hook exceeds ~50 lines, decompose it into sub-hooks. - -## Centralized Query and Mutation Definitions - -All queries and mutations — whether Shopify, REST, or Convex — should be centralized into `*Queries` / `*Mutations` files using `queryOptions` and `mutationOptions` from TanStack Query. This keeps query keys, fetch logic, and mutation logic organized by feature rather than scattered across components. - -### Non-Convex Queries (Shopify, REST, etc.) - -Use `queryOptions` with explicit `queryKey` and colocated `queryFn`. Build query keys hierarchically so broader invalidations work: - -```tsx -import { queryOptions } from "@tanstack/react-query"; - -export const productQueries = { - productByHandle: (handle: string) => - queryOptions({ - queryKey: ["product", handle], - queryFn: async () => { - const response = await shopify.request(getProduct, { - variables: { handle }, - }); - const product = response.data?.product; - if (!product) throw notFound(); - return product; - }, - }), -}; -``` - -### Convex Queries - -Wrap `convexQuery()` in `queryOptions()`. No explicit `queryKey` is needed — `convexQuery` generates stable query keys automatically under the hood: - -```tsx -import { queryOptions } from "@tanstack/react-query"; -import { convexQuery } from "@convex-dev/react-query"; - -import { api } from "@acme/convex/api"; - -export const pageQueries = { - list: () => queryOptions({ ...convexQuery(api.pages.list, {}) }), - getById: (pageId: Id<"pages">) => - queryOptions({ ...convexQuery(api.pages.getById, { pageId }) }), -}; -``` - -### Convex Mutations - -Wrap `useConvexMutation()` in `mutationOptions()` with an explicit `mutationKey`. Because `useConvexMutation` is a hook, these must be defined inside a hook: - -```tsx -import { mutationOptions } from "@tanstack/react-query"; -import { useConvexMutation } from "@convex-dev/react-query"; - -import { api } from "@acme/convex/api"; - -export function usePageMutations() { - return { - createPage: mutationOptions({ - mutationKey: ["create-page"], - mutationFn: useConvexMutation(api.pages.create), - }), - saveDraft: mutationOptions({ - mutationKey: ["save-draft"], - mutationFn: useConvexMutation(api.pages.saveDraft), - }), - }; -} -``` - -### Non-Convex Mutations - -Follow the same `mutationOptions` pattern. Since these don't use hooks, they can be plain objects: - -```tsx -export const cartMutations = { - lineAdd: mutationOptions({ - mutationKey: ["cart", "mutation", "line", "add"], - mutationFn: async (variables: { cartId?: string; merchandiseId: string }) => - addCartLineFn({ data: variables }), - }), -}; -``` - -Organize by feature: `page-queries.ts`, `cart-queries.ts`, `use-page-mutations.ts`, etc. - -## Route Loaders - -Route loaders are the entry point for data fetching. Prefetch data in the loader using `ensureQueryData` so it's already cached when the component tree mounts. Use the centralized query definitions: - -```tsx -export const Route = createFileRoute("/pages")({ - component: PagesRoute, - loader: async ({ context }) => { - await context.queryClient.ensureQueryData(pageQueries.list()); - }, -}); -``` - -When the loader depends on search params, declare the dependency with `loaderDeps`: - -```tsx -export const Route = createFileRoute("/dashboard")({ - component: DashboardRoute, - loaderDeps: ({ search }) => search, - loader: async ({ context, deps }) => { - await context.queryClient.ensureQueryData( - userAccessQueries.searchFirstPage(sanitizeSearch(deps.q)), - ); - }, - validateSearch: z.object({ - q: z.string(), - }), -}); -``` - -## Consuming Data in Components - -After the route loader has prefetched, consume cached data with `useSuspenseQuery`. Since the loader already populated the cache, this resolves synchronously: - -```tsx -const { data: pages } = useSuspenseQuery({ - ...pageQueries.list(), - select: (data) => - data.map((p) => ({ - _id: p._id, - title: p.title, - path: p.path, - })), -}); -``` - -Use `select` whenever the component only needs a slice of the query result. This is covered in detail in the `performance` reference, but it bears repeating: never subscribe to an entire query result when the component only uses part of it. - -Pull data at the leaf component where it's needed — never drill it down from a parent. - -## Fine-Grained Data Hooks - -Prefer many small hooks that each select the minimum data one consumer needs over a single shared hook that returns a large object. - -The query cache already holds all the data. Any component can call `useSuspenseQuery` with the same query key and a different `select` — TanStack Query deduplicates the underlying fetch. This means there is no cost to having multiple hooks hit the same query; each one just projects a different slice. - -```tsx -// ✅ CORRECT — each hook selects only what its consumer needs -function useCartQuantity() { - const { data: quantity } = useSuspenseQuery({ - ...cartQueries.detail(cartId), - select: (cart) => cart.totalQuantity, - }); - return quantity; -} - -function useCartCheckoutUrl() { - const { data: checkoutUrl } = useSuspenseQuery({ - ...cartQueries.detail(cartId), - select: (cart) => cart.checkoutUrl, - }); - return checkoutUrl; -} -``` - -```tsx -// ❌ WRONG — "kitchen sink" hook that returns a large object for many consumers -function useCart() { - const cartQuery = useSuspenseQuery(cartQueries.detail(cartId)); - return { - cart: cartQuery.data, // entire cart object - cartQuantity: cartQuery.data.totalQuantity, - cartQuery, // raw query object leaked to consumers - }; -} -``` - -The kitchen-sink pattern creates several problems: - -1. **Unnecessary re-renders.** Every consumer subscribes to the entire cart, so a price change re-renders the quantity badge. -2. **Hidden coupling.** Consumers depend on the full cart shape even when they only use one field, making refactors harder. -3. **Opaque intent.** When reading the consuming component, you can't tell which fields it actually needs — you have to trace through the returned object. - -When you need data from the same query in multiple components, write a small hook per concern that selects just what that concern needs. Name the hook after the data it provides (`useCartQuantity`, `useProductTitle`), not after the query it reads from. - -## Do Not Prop Drill — Pull Data Where You Need It - -This is the single most important rule for state flow in this project. Hooks like `useSearch`, `useSuspenseQuery`, `useRouteContext`, and `useStore` exist specifically so that any component in the tree can pull data directly. **If a hook gives a component direct access to the data it needs, use the hook. Do not pass that data through props from a parent.** - -```tsx -// ❌ WRONG — drilling search params through intermediaries -function ParentRoute() { - const search = useSearch({ from: "/products" }); - return ; -} -function Filters({ sortBy }: { sortBy: string }) { - return ; -} -``` - -```tsx -// ✅ CORRECT — pull data at the leaf where it's needed -function SortControl() { - const sortBy = useSearch({ - from: "/products", - select: (s) => s.sortBy, - }); - // use sortBy directly -} -``` - -This applies equally to query data, route context, store state, and search params. The same data that's available via `useSearch` at the route level is available via `useSearch` in any descendant component. The same query the loader prefetched can be consumed via `useSuspenseQuery` in any descendant. There is no reason to read data at a high level and pass it down. - -One level of props is normal for component-specific configuration (e.g. a `variant` prop on a button). But data available via hooks should always be pulled directly at the component that needs it. - -## URL State - -TanStack Start provides strong primitives for storing state in the URL. Define search param validators per route for validated, type-safe access: - -```tsx -export const Route = createFileRoute("/dashboard")({ - component: DashboardRoute, - validateSearch: z.object({ - q: z.string().optional(), - }), -}); -``` - -Any descendant component can access the params directly: - -```tsx -const searchTerm = useSearch({ - from: "/dashboard", - select: (search) => search.q, -}); -``` - -**Always use `select`** with `useSearch` so the component only re-renders when the specific param it uses changes. - -URL state is the right choice when you want state that: - -- Persists across full page refreshes -- Is shareable via link -- Survives if a user bookmarks the page - -## Mutations - -Mutations must always be driven by user events (clicks, form submissions, gestures). Never trigger a mutation from `useEffect`, render logic, or any other React lifecycle behavior. - -At the call site, spread the centralized mutation entry and add only the handlers you need: - -```tsx -const addToCart = useMutation({ - ...cartMutations.lineAdd, - onSuccess: (nextCart) => { - queryClient.setQueryData( - cartQueries.detail(nextCart.id).queryKey, - nextCart, - ); - }, -}); -``` - -For Convex mutations: - -```tsx -const pageMutations = usePageMutations(); -const { mutate } = useMutation({ - ...pageMutations.saveDraft, - onSuccess: () => { - /* ... */ - }, -}); -``` - -## Optimistic Updates - -Use optimistic updates for instant feedback on user actions. The approach differs between TanStack Query and Convex. - -**TanStack Query**: Cancel in-flight queries in `onMutate`, snapshot previous data, apply the optimistic change, and roll back in `onError`: - -```tsx -useMutation({ - ...cartMutations.lineUpdate, - onMutate: async (variables) => { - await queryClient.cancelQueries({ - queryKey: cartQueries.all().queryKey, - }); - const cartQueryKey = cartQueries.detail(variables.cartId).queryKey; - const previous = queryClient.getQueryData(cartQueryKey); - queryClient.setQueryData(cartQueryKey, (current) => - current ? applyOptimisticCartLineUpdate(current, variables) : current, - ); - return { previous }; - }, - onError: (_err, variables, context) => { - if (context?.previous) { - queryClient.setQueryData( - cartQueries.detail(variables.cartId).queryKey, - context.previous, - ); - } - }, -}); -``` - -**Convex**: Use the `.withOptimisticUpdate` API on the mutation: - -```tsx -const updateAccess = useConvexMutation( - api.users.updateUserAccessLevel, -).withOptimisticUpdate((localStore, args) => { - const results = localStore.getAllQueries(api.users.searchUsersPaginated); - for (const result of results) { - if (result.value === undefined) continue; - localStore.setQuery(api.users.searchUsersPaginated, result.args, { - ...result.value, - page: result.value.page.map((user) => - user._id === args.userId - ? { ...user, accessLevel: args.accessLevel } - : user, - ), - }); - } -}); -``` - -Prioritize optimistic updates for actions where perceived latency matters most: cart operations, toggles, and inline edits. - -## Rostra Stores — Non-Server State Only - -Rostra is for state that is **not** server data: form inputs before submission, global concerns (auth, theme), UI state shared across a subtree. - -```tsx -function useInternalStore({ initial }: { initial: PageFields }) { - const [title, setTitle] = useState(initial.title); - const [path, setPath] = useState(initial.path); - const [content, setContent] = useState(initial.content); - return { title, path, content, setTitle, setPath, setContent }; -} - -export const { Store: PageFormStore, useStore: usePageFormStore } = - createStore(useInternalStore); -``` - -This is a legitimate use of Rostra: collecting user edits in local state before they are submitted via a mutation. The form fields live outside the data-fetching lifecycle. - -**If the state is server data, use a query cache instead.** Do not duplicate server data into a Rostra store. See the `rostra` skill for API details. - -## Loading and Error States - -Do **not** manually write loading spinners or error messages based on query status. TanStack Start handles this at the route level through default components configured on the router: - -- `defaultPendingComponent` — shown while the route loader is in flight -- `defaultErrorComponent` — shown when the loader or component throws -- `defaultNotFoundComponent` — shown for 404s - -Any route using `ensureQueryData` in its loader gets loading and error handling for free. If a specific route needs custom error handling, override it on the route definition. - -The only place where you should check mutation status (`isPending`, `isError`, `isSuccess`) is for mutation-driven UI feedback (disabling buttons, showing inline toasts, etc.) — never for data-loading states. - -## Prop Drilling - -Avoid prop drilling by default. Passing props one level down is normal. Passing the same data through multiple intermediary components just to reach a deep leaf is a smell — use the hooks described in the "Do Not Prop Drill" section above. diff --git a/.agents/skills/refactor/SKILL.md b/.agents/skills/refactor/SKILL.md deleted file mode 100644 index c622fb71..00000000 --- a/.agents/skills/refactor/SKILL.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -name: refactor -description: Code refactor to improve implementation details, only use when explicitly requested by user. ---- - -# Overview - -This skill turns "it works" code into code that is robust, maintainable, and aligned with the project's standards. -Instead of reading every rule yourself and trying to apply them all at once, delegate to subagents, one per skill. Each subagent becomes a deep expert on its skill and evaluates the current changes entirely through that lens. - -## 1. Determine the scope - -The user may specify a scope — for example, "refactor the convex package" or "just look at the CMS app changes." When they do, pass that scope to each subagent so it only examines the relevant subset of changes. - -If the user does not specify a scope, the default is the entire active change set (all staged and unstaged changes across the repo). - -## 2. Spawn one subagent per skill - -Look at which files were changed and determine which skills are necessary to refactor. Once you've figured that out, spawn one subagent per skill so that that specific subagent focuses solely on that one skill. **_IMPORTANT_**: Typically, changes don't require every single skill to be used, so make sure you don't use skills that aren't relevant to the changes made. - -For each subagent, provide these instructions: - -1. **Role:** You are a senior engineer mentoring a junior teammate. You have been given a skill that describes coding standards the team has agreed on. Your job is to deeply internalize every rule in the skill, study the current changes, and produce a thorough assessment of how the code should be overhauled to fully align with these standards. -2. **Read-only constraint:** Do NOT edit, create, or delete any files. Your only job is to read code, analyze it, and return findings. -3. **Skill:** Read the skill file and all of its reference files carefully and completely before doing anything else. -4. **Getting the changes:** Run `git diff` and `git diff --cached` to see the current change set. If the user specified a scope (e.g. a specific package or app), filter to only those paths — for example `git diff -- packages/convex/` or `git diff -- apps/cms/`. Also read the full contents of every changed file so you have complete context, not just the diff hunks. -5. **What to return:** Report **every single finding** — no filtering, no prioritizing, no "I'll skip the small stuff." Every violation of the skill standards, from major architectural missteps down to the smallest style nit, must be included. Do not summarize or group findings to save space. Do not omit issues you consider minor. The main agent needs the complete, unabridged list to present to the user. Look for places where the implementation approach itself is wrong and needs to be overhauled — but also catch every small issue along the way. If the code uses the wrong patterns, the wrong architecture, the wrong abstractions - recommend ripping out the current approach and replacing it with one that properly aligns with the standards. Partial adjustments are not enough when the foundation is wrong. - For each finding, include: - - What is wrong with the current approach and why it does not satisfy the standard - - Where the problem is (file path and relevant code) - - What the correct approach looks like — described in enough detail that someone could implement it without having to re-read the skill - - Why this matters (what breaks, degrades, or becomes unmaintainable if left as-is) - -6. **If no issues are found:** Explicitly state that the current changes already satisfy the standards and no changes are needed. - -## 3. Synthesize findings - -Once all subagents have returned their findings, consolidate everything they reported. Identify overlaps, dependencies, and conflicts between findings from different skills. Do not leave out any details provided by subagents. - -Present the combined findings to the user as a proposed plan. Ask the user questions about how they want to proceed — which findings to act on, which to skip, and any tradeoffs between competing concerns. - -### Handling conflicts - -Different skills will sometimes recommend incompatible approaches for the same code. When this happens, do not resolve the conflict yourself. Present the conflict to the user, explain what each skill is asking for and why they are at odds, and let the user decide. Every conflict is its own question. Do not bundle multiple conflicts into a single question and do not silently pick a side. diff --git a/.agents/skills/rostra/SKILL.md b/.agents/skills/rostra/SKILL.md deleted file mode 100644 index 908d92e5..00000000 --- a/.agents/skills/rostra/SKILL.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -name: rostra -description: Guides correct usage of the Rostra state management library (createStore, Store, useStore), including store scoping, selectors, optional access, prop-driven initialization, and typing. Use only when the user asks you to work with an existing rostra store or to implement a new one. ---- - -## Overview - -The TL;DR is that its like React context, except with Zustand like selectors to improve performance. - -You define your state at a level where it can be shared with a subtree of components, and then pull it in at lower levels exactly where it's needed. It's designed to avoid prop drilling by allowing you to pull state directly into the leaf component where it is needed, even if the store component is many nodes higher in the tree. You write a React hook just like any other, but then Rostra turns it into a store component. Any child component of the store can pull in pieces of the state returned from the store using fine-grained selectors. - -## Core rules - -- `useInternalStore` is only used as an argument to `createStore`. Never call it directly from components. -- `useStore` is the only supported read/write access path for consumers. -- Wrap consumers in the matching `Store` provider. `useStore` throws if called outside its provider (unless `optional: true` is used). -- Keep stores as local as possible (feature-scoped) and only lift scope when multiple siblings need the state. - -## Default workflow - -1. Decide store scope - - A single feature/subtree → create a local store and wrap that subtree. - - Cross-cutting concerns (auth, theme) → create a higher-level store and wrap the app shell. -2. Implement the internal hook - - Use React state/hooks inside the internal hook. - - Return a plain object with state values and action functions. -3. Create the store - - Call `createStore(useInternalStore)` and export its `Store` and `useStore`. -4. Consume with selectors - - Select the smallest slice needed: `useStore(s => s.someValue)`. - - Select actions separately: `useStore(s => s.someAction)`. -5. Add optional access only when necessary - - Use `useStore(selector, { optional: true })` when the provider may not be present. - -## Examples - -### Minimal store - -```tsx -import { useState } from "react"; -import { createStore } from "rostra"; - -function useInternalStore() { - const [count, setCount] = useState(0); - const increment = () => setCount((prev) => prev + 1); - return { count, increment }; -} - -export const { Store, useStore } = createStore(useInternalStore); -``` - -```tsx -import { Store, useStore } from "./counter-store"; - -export function Counter() { - return ( - - - - - ); -} - -function Value() { - const count = useStore((s) => s.count); - return

Count: {count}

; -} - -function IncrementButton() { - const increment = useStore((s) => s.increment); - return ; -} -``` - -### Store props (initialization) - -```tsx -import { useState } from "react"; -import { createStore } from "rostra"; - -type StoreProps = { initialCount: number }; - -function useInternalStore({ initialCount }: StoreProps) { - const [count, setCount] = useState(initialCount); - const increment = () => setCount((prev) => prev + 1); - return { count, increment }; -} - -export const { Store, useStore } = createStore(useInternalStore); -``` - -```tsx -import { Store } from "./counter-store"; - -export function Counter() { - return ( - -
- - ); -} -``` - -### Strict typing (catch breaking changes early) - -Most stores can rely on inference. Reach for an explicit `StoreState` only when you intentionally want the store contract to be a checked public boundary and you want the internal hook to fail fast if that contract changes. - -```tsx -import { useState } from "react"; -import { createStore } from "rostra"; - -type StoreProps = { initialCount: number }; -type StoreState = { count: number; increment: () => void }; - -function useInternalStore({ initialCount }: StoreProps): StoreState { - const [count, setCount] = useState(initialCount); - const increment = () => setCount((prev) => prev + 1); - return { count, increment }; -} - -export const { Store, useStore } = createStore( - useInternalStore, -); -``` - -### Optional access (provider may not exist) - -```tsx -import { useStore } from "./counter-store"; - -export function MaybeCount() { - const count = useStore((s) => s.count, { optional: true }); - if (count === undefined) return null; - return

Count: {count}

; -} -``` diff --git a/.agents/skills/shopify/SKILL.md b/.agents/skills/shopify/SKILL.md deleted file mode 100644 index 9e37360a..00000000 --- a/.agents/skills/shopify/SKILL.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: shopify -description: Use whenever the scope of your task touches the shopify package or its uses anywhere in the project. ---- - -This project uses Shopify headless. `@acme/shopify` is configured so that GraphQL queries written inside the package will have TypeScript types generated for them. - -As you are working on any Shopify/GraphQL code in this project, make sure you STRICTLY adhere to the principles listed below. If you think there might actually be a valid use case for breaking them, pause and confirm first with the user. - -## Principles - -- Since the Shopify package generates types for the GraphQL queries written in it, you should ALWAYS write GraphQL queries inside the shopify package. Writing them directly in the app code will not result in generated types and will therefore not give you any type safety. -- You should always rely on type inference for getting the types of the data returned from GraphQL queries. You should NEVER have to use generics or type casting on the GraphQL operations being called from the app code. -- **AVOID AT ALL COSTS** normalizing the data returned from the GraphQL queries. You should not need to write custom functions to transform the data returned from them into a custom shape defined in the app code. You should ALWAYS rely on the types generated from the shopify package. - -## Required Actions - -After creating or modifying any GraphQL queries in the shopify package, you must always run: - -`pnpm --filter @acme/shopify run build` diff --git a/.agents/skills/typescript/SKILL.md b/.agents/skills/typescript/SKILL.md deleted file mode 100644 index 9f6b5c6b..00000000 --- a/.agents/skills/typescript/SKILL.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -name: typescript -description: TypeScript coding standards for this project. Use when writing or modifying TypeScript files. ---- - -# TypeScript - -These are the TypeScript standards for this project. Follow them when writing or modifying any TypeScript code. - -## Const Assertions - -Use `as const` to preserve exact literal types and `readonly`. This is the one acceptable use of `as` since it tightens types rather than loosening them. - -- Use on configuration objects, lookup maps, and any data that defines a fixed set of values. -- Use on arrays that represent a known set of options, then derive union types: `type Status = (typeof STATUS)[number]`. -- Prefer `as const` over manually writing literal union types when the source of truth is an array or object. -- Pair with `satisfies` when you need both exact literal types and structural validation. - -```typescript -const STATUS = ["idle", "loading", "success", "error"] as const; -type Status = (typeof STATUS)[number]; - -const PLAN_LIMITS = { - free: { projects: 3, storage: 500 }, - pro: { projects: 50, storage: 10_000 }, -} as const satisfies Record>; - -type Plan = keyof typeof PLAN_LIMITS; -``` - -## Early Returns - -- Guard against invalid or edge-case inputs at the top of the function and return/throw immediately. -- In multi-step transformations, validate and bail out between each step rather than wrapping everything in nested conditionals. -- This directly improves type narrowing — each early return eliminates a possibility, giving tighter types for the code that follows. - -## Discriminated Unions & Narrowing - -Model variants explicitly so the compiler forces you to handle each case. - -- Use a shared literal field (the discriminant) to distinguish between variants. Common discriminants: `type`, `status`, `kind`. -- Narrow using `if`/`switch` on the discriminant, not by checking for optional field existence. -- Avoid modeling variants as a single type with many optional fields — this forces consumers to handle impossible combinations. -- Prefer `switch` with exhaustiveness checking when there are three or more variants. The linter enforces exhaustive `switch` statements. - -```typescript -type Result = - | { status: "success"; data: Order } - | { status: "error"; error: string }; - -function handleResult(result: Result) { - switch (result.status) { - case "success": - return processOrder(result.data); - case "error": - return reportError(result.error); - } -} -``` - -## Inference Over Annotation - -- Never annotate a variable when the right-hand side already tells the compiler the type. -- Function parameters are the exception — they have no value to infer from, so explicit types are expected. -- Heavy annotations are a signal that the code structure should be rethought, not papered over with types. - -## Prohibited patterns - -- **No re-export shims.** When moving a function to a new module, update every import site to point to the new location. Never import a function into the old file and re-export it (under the same or a different name) just to avoid updating consumers. This creates indirection that makes the codebase harder to reason about and defeats the purpose of the refactor. The same applies to functions that are one line and simply just call another function. These add unnecessary complexity and should always be avoided. diff --git a/.agents/skills/uav/SKILL.md b/.agents/skills/uav/SKILL.md new file mode 100644 index 00000000..eb693944 --- /dev/null +++ b/.agents/skills/uav/SKILL.md @@ -0,0 +1,10 @@ +--- +name: uav +description: Use uav for shared project memory and coordination at the start of every project-work session, and when preserving context or reporting outcomes. +--- + +# uav + +uav is shared memory for project work. + +Run `uav help` for commands and `uav workflow` for current usage guidance. diff --git a/.agents/skills/unslop/SKILL.md b/.agents/skills/unslop/SKILL.md new file mode 100644 index 00000000..2a93c06b --- /dev/null +++ b/.agents/skills/unslop/SKILL.md @@ -0,0 +1,80 @@ +--- +name: unslop +description: Cut AI tells from any writing. Must always apply. +--- + +# Unslop + +Edit text to remove AI patterns and add human voice. + +## Process + +1. Scan for the patterns below. +2. Rewrite. Preserve meaning, match intended tone. +3. Add soul (see next section). +4. Self-audit: "What makes this obviously AI generated?" Fix remaining tells. + +## Adding soul + +Removing patterns is half the job. Sterile, voiceless writing is just as obvious. + +- **Have opinions.** React to facts instead of neutrally listing pros and cons. +- **Vary rhythm.** Short sentences. Then longer ones that take their time. Mix it up. +- **Acknowledge complexity.** "Impressive but also kind of unsettling" beats "impressive." +- **Use "I" when it fits.** First person isn't unprofessional. +- **Let some mess in.** Perfect structure looks machine-made. +- **Be specific.** Not "this is concerning" but "there's something unsettling about agents churning away at 3am." + +## Patterns to detect and fix + +### Content + +1. **Puffery.** "pivotal moment", "testament to", "evolving landscape", "setting the stage for", "indelible mark", "deeply rooted". Cut puffery, state what happened. +2. **Name-dropping.** Listing media outlets without context. Pick one, say what was said. +3. **Superficial -ing phrases.** "highlighting...", "ensuring...", "reflecting...", "showcasing...", "fostering...". Delete or expand with real sources. +4. **Promotional language.** "nestled", "vibrant", "breathtaking", "groundbreaking", "renowned", "stunning", "must-visit". Use neutral descriptions. +5. **Vague attributions.** "Experts believe", "Industry reports suggest", "Some critics argue". Name the source or delete. +6. **Formulaic challenges.** "Despite challenges... continues to thrive." Replace with specific facts. + +### Language + +7. **AI vocabulary.** Additionally, crucial, delve, enduring, enhance, fostering, garner, interplay, intricate, landscape (abstract), pivotal, showcase, tapestry (abstract), testament, underscore, vibrant. Replace with plain words. +8. **Fancy ways to say "is".** "serves as", "stands as", "boasts", "features". Just say "is" or "has". +9. **"Not just X, but Y."** State the point directly instead. +10. **Rule of three.** Forcing ideas into groups of three. Use the natural number. +11. **Synonym cycling.** Protagonist, main character, central figure, hero all in one paragraph. Pick one, repeat it. +12. **False ranges.** "from X to Y" where X and Y aren't on a meaningful scale. List topics directly. + +### Style + +13. **Em dash overuse.** Avoid em dashes entirely. Use periods or commas only (no parentheses, no en dashes, no hyphen-as-dash substitutes). Em dashes are an AI tell, and reaching for parentheses instead just trades one tell for another. If a thought needs separation, end the sentence or use a comma. +14. **Colon overuse.** Colons are fine before a list or example. Not as mid-sentence connectors. "If you're coming from traditional automation: instead of registering event handlers, you describe conditions" adds nothing with the colon. Rewrite to let the point stand on its own without comparison framing. "Describing when the scheduler should fire works best as plain English." Same meaning, no crutch punctuation. +15. **Boldface overuse.** Don't bold every proper noun or acronym. +16. **Inline-header lists.** The tell is a bold label and colon that restates the line: "**Performance:** Performance improved...". Convert those to prose. A bold lead-in that ends in a period, names the item, and is followed by genuinely new detail ("**Schema in TypeScript.** Tables live in one file.") is fine, not a tell. +17. **Title case headings.** Use sentence case. +18. **Decorative emojis.** Remove from headings and bullets. +19. **Curly quotes.** Replace with straight quotes. + +### Communication artifacts + +20. **Chatbot phrases.** "I hope this helps!", "Let me know if...", "Of course!", "Certainly!", "Found the smoking gun!" Remove. +21. **Cutoff disclaimers.** "While specific details are limited..." Find sources or remove. +22. **Sycophantic tone.** "Great question! You're absolutely right!" Respond directly. + +### Filler + +23. **Filler phrases.** "In order to" becomes "To". "Due to the fact that" becomes "Because". "It is important to note that" gets deleted. +24. **Excessive hedging.** "could potentially possibly be argued that it might" becomes "may". +25. **Generic conclusions.** "The future looks bright." State specific plans or facts. + +### Jargon + +26. **Abstract metaphor nouns.** Substrate, wedge, vector, locus, vantage, nexus, primitive (as noun), harness (as metaphor), surface (as in "API surface"), bedrock, scaffolding (as metaphor), modality, paradigm, gold-plating, ratchet (as metaphor), evacuate (for moving code), endgame, north star, flywheel. These read as technical but usually have a plainer concrete word. "Substrate" becomes "base". "Wedge in" becomes "add". "Vector" becomes "way" or "method". "Gold-plating" becomes "more than the job needs". "Ratchet" becomes the mechanism's real name or "a limit that only tightens". "Evacuate" becomes "move out". "Endgame" becomes "the last phase". Pick the concrete word. + +### Plain speech + +27. **Say what it does, not how it feels.** "the database stays close at hand", "SQL you can read", "types that follow your schema" name a feeling. The fix names the mechanism or a number: "`.toSQL()` returns the exact string sent to the database", "a column rename fails the build". Ask what the sentence tells the reader to do or know, then write that. If you can't restate it as a concrete instruction, fact, or number, cut it. One more check: if the sentence could appear unchanged in another project's docs, it says nothing about this one. Cut it. +28. **Shorten or split dense sentences.** If the reader has to backtrack to parse a sentence, break it in two or drop clauses. One idea per sentence. +29. **Active voice.** Prefer it. Catch "is/are/was/were + past participle" and name the actor: "queries are validated" becomes "the compiler validates queries", "the file is parsed by the loader" becomes "the loader parses the file". Passive is fine only when the actor is unknown or genuinely doesn't matter. +30. **Cut adverbs, or use a stronger verb.** "runs quickly" becomes "is fast" or the number. "significantly improves" becomes the measured delta. An adverb propping up a weak verb means the verb is wrong. +31. **Prefer the plain word.** "utilize" becomes "use", "leverage" becomes "use", "facilitate" becomes "help", "numerous" becomes "many", "in the event that" becomes "if". The fancier synonym is rarely clearer. diff --git a/AGENTS.md b/AGENTS.md index 8a95560e..caf03235 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,8 +2,7 @@ ## Repository Summary -- AI chat app -- Uses turbo repo to house apps for various platforms + the convex database +This project was initally an AI chat app, and is now being rebuilt as a decentralized, easily self-hostable messaing & email platform. ## Required Validation After Changes @@ -18,7 +17,22 @@ If all of these succeed, run: Then summarize changes for the user. -## Preferences - -- Do **_NOT_** leave excessive comments when writing code. Only leave comments when - the code itself does not clearly explain what it does +## Decentralized Convex Release Invariant + +All official `@decentralized-convex/*` packages and the wire protocol use one +exact ecosystem version. The source of truth is +`packages/decentralized-convex-core/src/release.ts`. + +- Never version one decentralized Convex package independently. +- On every release, bump every `@decentralized-convex/*` `package.json` and + every internal `workspace:` dependency together. +- Every package owns a root `metadata.ts` and exports its + `decentralizedConvexPackage` object from `./metadata`. Update that package's + `lastChanged` only when the package actually changes. +- Never add a registry of package metadata to core. Release tooling discovers + and validates the standardized package exports. +- Do not write a plugin protocol version manually; `definePluginProtocol` + injects the ecosystem version. +- Run `pnpm run decentralized-convex:check`; it is also enforced by lint. +- Component data upgrades belong behind the PDS management surface. Do not ask + application developers to run plugin-specific migration commands directly. diff --git a/LICENSE b/LICENSE index 85cb0a66..20f08db2 100644 --- a/LICENSE +++ b/LICENSE @@ -1,11 +1,675 @@ -Copyright 2026 Shawn Rodgers -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Preamble -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +The GNU General Public License is a free, copyleft license for +software and other kinds of works. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +1. Source Code. + +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + Decentralized Convex federation toolkit. + Copyright (C) 2026 Shawn Rodgers + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Vera Copyright (C) 2026 Shawn Rodgers + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + +You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + +The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/LICENSE.agent b/LICENSE.agent deleted file mode 100644 index eedc68be..00000000 --- a/LICENSE.agent +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. \ No newline at end of file diff --git a/LICENSE.t3 b/LICENSE.t3-turbo similarity index 100% rename from LICENSE.t3 rename to LICENSE.t3-turbo diff --git a/README.md b/README.md index db19fc82..95e5b9ed 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,105 @@ - +# Vera -
-
- Animated GIF of advertisement for Vera, showing off its search capability. -
-
-
-
- - vera.chat - -
-
-
-
-
+Vera is the reference application and current incubator for decentralized +Convex: a small toolkit for building applications whose data and realtime +subscriptions span independently hosted Convex deployments. -A great starting point for building agentic applications for the web. +The current branch proves one private, reactive conversation across two PDSs. +It is intentionally a vertical slice, not a production messaging product yet. -For more information, head over to the [docs](https://docs.vera.chat) +## Start here -
-
+Read these files in order to follow one request end to end: -[x.com/bentsignal](https://x.com/bentsignal) +1. `packages/decentralized-convex-messages/protocol.ts` defines the typed + Messages API and its dependency on Accounts. +2. `services/backend/convex/convex.config.ts` installs the PDS auth adapter, + Accounts, and Messages in one validated PDS app. +3. `services/backend/convex/pds.ts` exposes the canonical public dispatcher. +4. `packages/decentralized-convex-messages/dispatcher.ts` implements the + Messages operations inside its Component. +5. `apps/web/src/features/conversation/useConversation.ts` shows the complete + client API used for reactive reads and writes. -
+The longer explanation is in [docs/architecture.md](docs/architecture.md). +The lockstep `0.1.0` release and upgrade rules are in +[docs/versioning.md](docs/versioning.md). -
+## The default setup + +A PDS installs ordinary third-party Components and decentralized-convex +plugins declaratively: + +```ts +import accounts from "@decentralized-convex/accounts/convex.config"; +import messages from "@decentralized-convex/messages/convex.config"; +import { definePdsApp } from "@decentralized-convex/server"; +import { pdsAuth } from "../pds-auth"; + +export default definePdsApp({ + auth: pdsAuth, + plugins: [accounts, messages], +}); +``` + +Messages declares an exact dependency on Accounts at the shared ecosystem +version. Removing Accounts or +installing an incompatible version fails type-checking. The normal +`convex dev`, `convex deploy`, and `convex codegen` commands remain unchanged. + +The common client path uses the application's own TanStack hooks: + +```ts +import { useMutation, useQuery } from "@tanstack/react-query"; +import { pdsMutation, pdsQuery } from "@decentralized-convex/tanstack-query"; +import { pds } from "@vera/backend/pds"; + +const messages = useQuery( + pdsQuery({ + args: { conversationId }, + query: pds.messages.list, + }), +); +const sendMessage = useMutation( + pdsMutation({ mutation: pds.messages.send }), +); +``` + +The backend's `pds` export derives its plugin names, versions, operations, and +types from the same `definePdsApp` declaration. The web app never repeats the +installed plugin list, and the discovery manifest derives its capabilities +from the same protocol tuple. + +The query starts at the signed-in account's home PDS, reads routing identities +stored with the conversation, discovers their current deployments, and merges +live results. Mutations automatically target home. Ordinary TanStack options, +connection factories, explicit lower-level federation, and destination-aware +authentication remain available when an application needs control. + +## Workspace + +- `packages/decentralized-convex-plugin` — operation protocols and dependency + graph validation +- `packages/decentralized-convex-core` — the single ecosystem version and + last-changed release metadata +- `packages/decentralized-convex-server` — PDS installation, root dispatch, + Component dispatch, and discovery descriptors +- `packages/decentralized-convex-auth-better-auth` — Better Auth adapter for + the public PDS auth protocol +- `packages/decentralized-convex-client` — discovery, connections, typed calls, + federation, and subscriptions +- `packages/decentralized-convex-react` — client provider +- `packages/decentralized-convex-tanstack-query` — native TanStack option builders +- `packages/decentralized-convex-accounts` and `-messages` — first-party plugins +- `services/backend` — Vera's thin Better Auth PDS host +- `apps/web` — the Vera reference client +- `legacy` — the archived centralized Vera application + +## Development + +```sh +pnpm install +pnpm --filter @vera/web dev +``` + +The web app runs at `https://www.vera.localhost`. diff --git a/apps/web/.env.example b/apps/web/.env.example new file mode 100644 index 00000000..bc86437f --- /dev/null +++ b/apps/web/.env.example @@ -0,0 +1,4 @@ +VITE_HOME_A_CONVEX_URL=https://your-a-deployment.convex.cloud +VITE_HOME_A_SITE_URL=https://your-a-deployment.convex.site +VITE_HOME_B_CONVEX_URL=https://your-b-deployment.convex.cloud +VITE_HOME_B_SITE_URL=https://your-b-deployment.convex.site diff --git a/apps/web/README.md b/apps/web/README.md new file mode 100644 index 00000000..5469f7df --- /dev/null +++ b/apps/web/README.md @@ -0,0 +1,98 @@ +# Vera web + +A TanStack Start messaging client that reads one private conversation across +independent Convex PDS deployments. + +## Code tour + +- `features/account/AccountEntry.tsx` discovers a PDS from `username@domain`. +- `features/account/AccountSession.tsx` owns the local auth session and creates + the decentralized client. +- `features/pds/auth.ts` is the replaceable Better Auth federation adapter. +- `features/pds/model.ts` contains the explicitly temporary two-home fixture. +- `features/conversation/useConversation.ts` is the complete data path. +- `features/conversation/Conversation.tsx` is presentation only. + +```sh +pnpm --filter @vera/web dev +``` + +Open `https://www.vera.localhost` and: + +1. Enter a full Vera address such as `alice@a.vera.chat`. +2. Create or sign into that account on its discovered home PDS. +3. Send messages. Vera reads the conversation from both development PDSs with + the one home login. + +Home discovery happens before sign-in. The address entry screen resolves the +account domain and keeps that verified descriptor as `home`; both auth and the +decentralized client use the same value: + +```ts +const home = assertPdsCompatibility( + await discoverPds("alice@a.vera.chat"), + pds, +); + +const authClient = createHomeAuthClient(home); +const client = new DecentralizedConvexClient({ + getAuthToken, + pds: { home }, +}); +``` + +Signing in creates the authenticated session on that already-discovered home. +It does not produce or replace the `home` value. + +Each signup and outgoing message is stored only on the selected home +deployment. Each home keeps its own isolated Better Auth and Messages Component +data. The home PDS issues a short-lived, destination-bound identity proof; the +other PDS verifies it through discovery and returns a local Convex credential. +The selected account stores its conversation routing identities on its own PDS. +The client first subscribes there, discovers the current participant PDSs from +that response, then opens authenticated subscriptions and reconciles the +results through TanStack Query. + +The account address uses the PDS's public account domain, never its internal +`convex.cloud` transport hostname. Better Auth is Vera's current host adapter, +not a dependency of the reusable decentralized Convex packages. + +The checked-in `.env.example` documents the deployment configuration. Deploy +the same `convex/` backend to each target and set `SITE_URL` and +`FEDERATION_DOMAIN` on each deployment. Publish the single `_pds` TXT discovery +record described in the backend README. Free and Pro Convex deployments use the +same discovery flow; Convex custom domains are optional. + +The web app imports the typed `pds` API derived from Vera's backend app +definition. It does not declare a second plugin list or import either +deployment's generated message API; both homes expose the same canonical +`pds:dispatchQuery` and `pds:dispatchMutation` functions. + +The common read and write paths use the PDS query adapter with the +application's TanStack Query instance: + +```ts +import { useMutation, useQuery } from "@tanstack/react-query"; +import { pdsMutation, pdsQuery } from "@decentralized-convex/tanstack-query"; +import { pds } from "@vera/backend/pds"; + +const messages = useQuery( + pdsQuery({ + query: pds.messages.list, + args: { conversationId }, + }), +); + +if (messages.data.status === "success") { + messages.data.result; // Message[] +} + +messages.data.federation.sources; + +const sendMessage = useMutation(pdsMutation({ mutation: pds.messages.send })); +``` + +PDS reads hide partial results for `500ms` by default while participant homes +deliver their first snapshots. Set `options.revealPartialResultsAfter` in +`pdsQuery` to override the delay. Complete data returns immediately, and a +temporary disconnect retains the affected PDS's last known data. diff --git a/apps/web/eslint.config.ts b/apps/web/eslint.config.ts new file mode 100644 index 00000000..d9d8cf1b --- /dev/null +++ b/apps/web/eslint.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from "eslint/config"; + +import { baseConfig, strictConfig } from "@acme/eslint-config/base"; +import { reactConfig } from "@acme/eslint-config/react"; + +export default defineConfig( + { ignores: ["src/routeTree.gen.ts"] }, + baseConfig, + strictConfig, + reactConfig, +); diff --git a/apps/web/index.html b/apps/web/index.html deleted file mode 100644 index 9b390577..00000000 --- a/apps/web/index.html +++ /dev/null @@ -1,208 +0,0 @@ - - - - - - - - - Vera — Rebuilding - - - -
- -
-
A brief intermission
-

Vera

-

Vera is being rebuilt. Check back soon.

-
-
- Still thinking - vera.chat -
-
- - diff --git a/apps/web/package.json b/apps/web/package.json index dc1603d7..b8697709 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,23 +1,56 @@ { - "name": "@acme/web", + "name": "@vera/web", "version": "0.1.0", "private": true, "type": "module", + "imports": { + "#/*": "./src/*" + }, "scripts": { "build": "vite build", + "clean": "git clean -xdf .cache .turbo .output node_modules", "dev": "portless", "dev:app": "vite", - "preview": "vite preview", "format": "prettier --check . --ignore-path ../../.gitignore", "format:fix": "prettier --write . --ignore-path ../../.gitignore", - "clean": "git clean -xdf node_modules .cache .turbo dist" + "generate-routes": "tsr generate", + "lint": "eslint --flag unstable_native_nodejs_ts_config", + "preview": "vite preview", + "typecheck": "tsgo --noEmit" + }, + "dependencies": { + "@convex-dev/better-auth": "0.12.5", + "@decentralized-convex/client": "workspace:0.1.0", + "@decentralized-convex/messages": "workspace:0.1.0", + "@decentralized-convex/react": "workspace:0.1.0", + "@decentralized-convex/tanstack-query": "workspace:0.1.0", + "@tanstack/react-query": "catalog:", + "@tanstack/react-router": "catalog:", + "@tanstack/react-router-ssr-query": "catalog:", + "@tanstack/react-start": "catalog:", + "@vera/backend": "workspace:*", + "better-auth": "~1.6.15", + "convex": "catalog:", + "react": "catalog:react19", + "react-dom": "catalog:react19" }, "devDependencies": { + "@acme/eslint-config": "workspace:*", + "@acme/prettier-config": "workspace:*", + "@acme/tsconfig": "workspace:*", + "@tanstack/router-cli": "catalog:", + "@types/node": "catalog:", + "@types/react": "catalog:react19", + "@types/react-dom": "catalog:react19", + "@vitejs/plugin-react": "catalog:", + "eslint": "catalog:", "prettier": "catalog:", + "typescript": "catalog:", "vite": "catalog:" }, "portless": { "name": "www.vera", "script": "dev:app" - } + }, + "prettier": "@acme/prettier-config" } diff --git a/apps/web/src/env.d.ts b/apps/web/src/env.d.ts new file mode 100644 index 00000000..7b588745 --- /dev/null +++ b/apps/web/src/env.d.ts @@ -0,0 +1,10 @@ +interface ImportMetaEnv { + readonly VITE_HOME_A_CONVEX_URL: string; + readonly VITE_HOME_A_SITE_URL: string; + readonly VITE_HOME_B_CONVEX_URL: string; + readonly VITE_HOME_B_SITE_URL: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/web/src/features/account/AccountEntry.tsx b/apps/web/src/features/account/AccountEntry.tsx new file mode 100644 index 00000000..8d0e4638 --- /dev/null +++ b/apps/web/src/features/account/AccountEntry.tsx @@ -0,0 +1,77 @@ +import type { FormEvent } from "react"; +import { useState } from "react"; +import { + assertPdsCompatibility, + discoverPds, +} from "@decentralized-convex/client"; +import { pds } from "@vera/backend/pds"; + +import type { HomePds } from "../pds/model.ts"; + +interface AccountEntryProps { + onSelect: (selection: { home: HomePds; username: string }) => void; +} + +export function AccountEntry({ onSelect }: AccountEntryProps) { + const [address, setAddress] = useState(""); + const [error, setError] = useState(); + const [loading, setLoading] = useState(false); + + async function submit(event: FormEvent) { + event.preventDefault(); + setError(undefined); + const normalized = address.trim().toLowerCase(); + const separator = normalized.lastIndexOf("@"); + const username = normalized.slice(0, separator); + if (separator <= 0 || !/^[a-z0-9][a-z0-9._-]{1,31}$/.test(username)) { + setError("Enter a valid username@domain address."); + return; + } + + setLoading(true); + try { + const home = assertPdsCompatibility(await discoverPds(normalized), pds); + onSelect({ home, username }); + } catch (cause) { + setError(cause instanceof Error ? cause.message : "PDS discovery failed"); + } finally { + setLoading(false); + } + } + + return ( +
+
+
+ +
+

Vera

+

Sign in with your address on any compatible PDS.

+
+
+
void submit(event)}> + + {error === undefined ? null :

{error}

} + +
+
+
+ ); +} diff --git a/apps/web/src/features/account/AccountSession.tsx b/apps/web/src/features/account/AccountSession.tsx new file mode 100644 index 00000000..c48f168f --- /dev/null +++ b/apps/web/src/features/account/AccountSession.tsx @@ -0,0 +1,150 @@ +import type { AuthClient } from "@convex-dev/better-auth/react"; +import { useEffect, useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { ConvexBetterAuthProvider } from "@convex-dev/better-auth/react"; +import { DecentralizedConvexClient } from "@decentralized-convex/client"; +import { + DecentralizedConvexProvider, + useQuery, +} from "@decentralized-convex/react"; +import { PdsQueryClient } from "@decentralized-convex/tanstack-query"; +import { api } from "@vera/backend/api"; +import { ConvexReactClient, useConvexAuth } from "convex/react"; + +import type { HomeAuthClient } from "../pds/auth.ts"; +import type { HomePds } from "../pds/model.ts"; +import { Conversation } from "../conversation/Conversation.tsx"; +import { + createFederationAuthTokenFetcher, + createHomeAuthClient, +} from "../pds/auth.ts"; +import { SignInForm } from "./SignInForm.tsx"; + +interface AccountSessionProps { + home: HomePds; + initialUsername: string; + onBack: () => void; +} + +export function AccountSession(props: AccountSessionProps) { + const [authClient] = useState(() => createHomeAuthClient(props.home)); + const [convex] = useState( + () => + new ConvexReactClient(props.home.manifest.deploymentUrl, { + expectAuth: true, + }), + ); + // Better Auth's provider erases the concrete plugins returned by createAuthClient. + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + const providerAuthClient = authClient as unknown as AuthClient; + + return ( + + + + ); +} + +function SessionContent( + props: AccountSessionProps & { authClient: HomeAuthClient }, +) { + const { isAuthenticated, isLoading } = useConvexAuth(); + if (isLoading) return ; + if (!isAuthenticated) { + return ( + + ); + } + return ; +} + +function AuthenticatedAccount({ + authClient, + home, + onBack, +}: AccountSessionProps & { authClient: HomeAuthClient }) { + const user = useQuery(api.auth.currentUser); + const federation = useConversationFederation(authClient, home); + + if (federation !== undefined && "error" in federation) { + return ( +
+
+

Could not connect to the conversation

+

{federation.error.message}

+ +
+
+ ); + } + + if (user === undefined || user === null || federation === undefined) { + return ; + } + + return ( + + authClient.signOut()} + user={user} + /> + + ); +} + +function useConversationFederation(authClient: HomeAuthClient, home: HomePds) { + const queryClient = useQueryClient(); + const [federation, setFederation] = useState< + { client: DecentralizedConvexClient } | { error: Error } + >(); + + useEffect(() => { + let active = true; + let nextClient: DecentralizedConvexClient | undefined; + let nextDisconnect: (() => void) | undefined; + void Promise.resolve().then(() => { + if (!active) return; + try { + const client = new DecentralizedConvexClient({ + getAuthToken: createFederationAuthTokenFetcher({ authClient, home }), + pds: { home }, + }); + nextClient = client; + const pdsQueryClient = new PdsQueryClient(client); + nextDisconnect = pdsQueryClient.connect(queryClient); + setFederation({ client }); + } catch (cause) { + setFederation({ + error: cause instanceof Error ? cause : new Error("PDS setup failed"), + }); + } + }); + return () => { + active = false; + nextDisconnect?.(); + if (nextClient !== undefined) void nextClient.close(); + }; + }, [authClient, home, queryClient]); + + return federation; +} + +function Connecting({ home }: { home: HomePds }) { + return ( +
+
+ +

Connecting to {home.domain}

+
+
+ ); +} diff --git a/apps/web/src/features/account/SignInForm.tsx b/apps/web/src/features/account/SignInForm.tsx new file mode 100644 index 00000000..24f655ef --- /dev/null +++ b/apps/web/src/features/account/SignInForm.tsx @@ -0,0 +1,143 @@ +import type { FormEvent } from "react"; +import { useState } from "react"; + +import type { HomeAuthClient } from "../pds/auth.ts"; +import type { HomePds } from "../pds/model.ts"; + +interface SignInFormProps { + authClient: HomeAuthClient; + home: HomePds; + initialUsername: string; + onBack: () => void; +} + +export function SignInForm(props: SignInFormProps) { + const form = useSignInForm(props); + const isSignUp = form.mode === "sign-up"; + + return ( +
+
+ +
+ +
+

{isSignUp ? "Create account" : "Sign in"}

+

{props.home.domain}

+
+
+
void form.submit(event)}> + + + {form.error === undefined ? null : ( +

{form.error}

+ )} + +
+ +
+
+ ); +} + +function useSignInForm({ authClient, home, initialUsername }: SignInFormProps) { + const [error, setError] = useState(); + const [mode, setMode] = useState<"sign-in" | "sign-up">("sign-up"); + const [password, setPassword] = useState(""); + const [submitting, setSubmitting] = useState(false); + const [username, setUsername] = useState(initialUsername); + + async function submit(event: FormEvent) { + event.preventDefault(); + setError(undefined); + const normalized = username.trim().toLowerCase(); + if (!/^[a-z0-9][a-z0-9._-]{1,31}$/.test(normalized)) { + setError( + "Use 2–32 lowercase letters, numbers, dots, dashes, or underscores.", + ); + return; + } + + setSubmitting(true); + try { + const email = `${normalized}@${home.domain}`; + const result = + mode === "sign-up" + ? await authClient.signUp.email({ + email, + name: normalized, + password, + }) + : await authClient.signIn.email({ email, password }); + if (result.error !== null) { + setError(result.error.message ?? "Authentication failed"); + } + } finally { + setSubmitting(false); + } + } + + return { + error, + mode, + password, + setPassword, + setUsername, + submit, + submitting, + toggleMode: () => setMode(mode === "sign-up" ? "sign-in" : "sign-up"), + username, + }; +} diff --git a/apps/web/src/features/conversation/Conversation.tsx b/apps/web/src/features/conversation/Conversation.tsx new file mode 100644 index 00000000..379a54fb --- /dev/null +++ b/apps/web/src/features/conversation/Conversation.tsx @@ -0,0 +1,283 @@ +import type { + FederationSourceSnapshot, + PdsQueryData, +} from "@decentralized-convex/client"; +import type { Message as ChatMessage } from "@decentralized-convex/messages"; +import type { FormEvent } from "react"; + +import type { HomePds } from "../pds/model.ts"; +import { useConversation } from "./useConversation.ts"; + +interface ConversationProps { + home: HomePds; + onChangeAccount: () => void; + onSignOut: () => Promise; + user: { actor: string }; +} + +type ConversationMessages = ReturnType["messages"]; + +export function Conversation(props: ConversationProps) { + const conversation = useConversation(); + return ( +
+ +
+ + + +
+
+ ); +} + +function Sidebar({ + home, + onChangeAccount, + onSignOut, + user, +}: ConversationProps) { + return ( + + ); +} + +function ConversationHeader({ + home, + messages, +}: { + home: HomePds; + messages: ConversationMessages; +}) { + const { sources, status } = messages.data.federation; + const live = sources.filter((source) => source.status === "live").length; + const description = + messages.data.status === "loading" + ? "Connecting to participant home servers" + : messages.data.status === "partial" + ? `Incomplete history — ${live} of ${sources.length} homes connected` + : messages.data.status === "error" + ? "Unable to load conversation history" + : "Messages from every participant's home server"; + + return ( +
+
+

Prototype conversation

+

{description}

+
+
+ + + {live}/{sources.length} connected + + +
+
+ ); +} + +function ConnectionDiagnostics({ + home, + sources, +}: { + home: HomePds; + sources: readonly FederationSourceSnapshot[]; +}) { + return ( +
+ Debug +
+ Connections +
+ {sources.map((source) => ( +
+ + {new URL(source.target.url).hostname} + {source.status} +
+ ))} +
+
+
+
Write target
+
{home.domain}
+
+
+
Local auth
+
Better Auth
+
+
+
Remote reads
+
Authenticated per home server
+
+
+
+
+ ); +} + +function MessageList({ + home, + messages, +}: { + home: HomePds; + messages: { + data: PdsQueryData; + }; +}) { + const live = messages.data.federation.sources.filter( + (source) => source.status === "live", + ).length; + const total = messages.data.federation.sources.length; + + return ( +
+ {messages.data.status === "partial" ? ( + + ) : null} + {messages.data.status === "loading" ? ( +

Connecting to participant servers…

+ ) : null} + {messages.data.status === "error" ? ( +

{messages.data.error.message}

+ ) : null} + {(messages.data.status === "partial" || + messages.data.status === "success") && + messages.data.result.length === 0 ? ( +
+ # + No messages yet +

Start the conversation from {home.domain}.

+
+ ) : null} + {messages.data.status === "partial" || messages.data.status === "success" + ? messages.data.result.map((message) => ( + + )) + : null} +
+ ); +} + +function Message({ message }: { message: ChatMessage }) { + const domain = message.authorId.split("@")[1] ?? message.authorId; + return ( +
+ +
+
+ + {message.authorName || actorUsername(message.authorId)} + + @{domain} + +
+

{message.body}

+
+
+ ); +} + +function MessageComposer({ + draft, + error, + sending, + setDraft, + submit, +}: { + draft: string; + error?: string; + sending: boolean; + setDraft: (draft: string) => void; + submit: (event: FormEvent) => Promise; +}) { + return ( +
void submit(event)}> +