Skip to content

Latest commit

 

History

History
392 lines (274 loc) · 30.8 KB

AGENTS.md

File metadata and controls

392 lines (274 loc) · 30.8 KB

Project Overview

This is gitworkshop — a Nostr-native Git collaboration client (issues, PRs, repos via NIP-34 + NIP-22 comments, GRASP repo announcements) built with React 18, TailwindCSS 3, Vite, shadcn/ui, and Applesauce v7.

Technology Stack

  • React 18.x: hooks, concurrent rendering
  • TailwindCSS 3.x: utility-first styling
  • Vite: dev server + production bundler
  • shadcn/ui: 48+ unstyled accessible primitives in @/components/ui on Radix UI + Tailwind
  • Applesauce v7 (applesauce-core, applesauce-relay, applesauce-react, applesauce-loaders, applesauce-actions, applesauce-accounts, applesauce-signers, applesauce-common, applesauce-content): reactive Nostr SDK on RxJS
  • RxJS: state and reactive data flow via observables (load the react-rxjs-observables skill)
  • React Router: client-side routing with BrowserRouter and automatic scroll-to-top
  • TypeScript: type-safe JS. Never use any.
  • pnpm: preferred package manager. Nix and pnpm are not required for day-to-day development; npm is supported for installs and scripts when pnpm is unavailable. Dependency changes must be made with pnpm so pnpm-lock.yaml stays authoritative, then package-lock.json must be refreshed for npm users. Never use yarn.

Applesauce MCP — your primary reference

An Applesauce MCP server is configured at https://mcp.applesauce.build/mcp. Use it heavily. It serves up-to-date docs, method signatures, type definitions, and source examples directly from the Applesauce repo.

Always prefer the MCP over guessing or relying on this file when you need to:

  • Look up method signatures, types, or interfaces (applesauce_search_methods)
  • Find the right class, hook, or utility for a task (applesauce_search_docs, applesauce_search_examples)
  • Confirm correct usage of a model, cast, action, or loader (applesauce_read_doc, applesauce_read_example)
  • Check what's exported from a specific package

This file deliberately avoids enumerating models, casts, actions, hooks, and loaders that the MCP can answer better and more accurately.

Project Structure

  • /src/services/ — singletons. nostr.ts exports pool, eventStore, publish. Plus accounts.ts, actions.ts, outbox.ts, notificationStore.ts, cache.ts, settings.ts.
  • /src/lib/ — utilities. resilientSubscription.ts is the only sanctioned way to fetch events from relays (see "Querying" below).
  • /src/factories/ — typed EventFactory subclasses for project-specific kinds (NIP-34 issues, PRs, repo announcements, statuses). Shared relay-hint resolvers live in hints.ts.
  • /src/casts/ — typed EventCast wrappers around raw events with memoised computed properties (Issue, Patch, PR, Repository, RepositoryState).
  • /src/components/ — UI. ui/ is shadcn/ui primitives; auth/ has LoginArea, AuthModal, AccountSwitcher, etc.
  • /src/hooks/ — custom hooks (use$, useEventStore, useAccount, usePublish, useAction, plus dozens of feature hooks). List with ls src/hooks/.
  • /src/pages/ — page components used by React Router.
  • /src/types/ — TypeScript type definitions.
  • /src/test/ — testing utilities including TestApp.
  • /docs/ — long-form architecture documents (e.g. matainership.md covers the multi-maintainer repo model).
  • App.tsx — already configured with EventStoreProvider, AccountsProvider, UnheadProvider, AppProvider. Read before editing; changes are rarely needed.
  • AppRouter.tsx — React Router configuration.

Always read an existing file before modifying it. Never write over App.tsx, AppRouter.tsx, src/services/nostr.ts, or src/services/accounts.ts without first reading their contents.

UI Components

shadcn/ui primitives live in @/components/ui. List the directory (ls src/components/ui/) — all common primitives are present (buttons, inputs, dialogs, dropdowns, forms, tables, etc.). They use React.forwardRef and the cn() class-merge utility.

Avatars: Don't use Avatar directly to render another Nostr user's picture — use UserAvatar (or UserLink) from @/components/UserAvatar. They show the follow-indicator badge for users the current account follows, helping distinguish known contacts from impersonators. Raw Avatar is only appropriate for rendering your own account (AccountSwitcher, compose self-avatar) or non-user imagery.

Dependency Policy

  • Use pnpm when available and working. npm is supported as a fallback (npm ci, npm run dev, npm run pre-commit). Nix is optional; nix develop only provides a pinned Node/pnpm/e2e-test toolchain. For dependency updates, use pnpm first so pnpm-lock.yaml remains the source of truth, then refresh and commit package-lock.json for npm fresh clones (for example, npm install --package-lock-only).
  • Prefer patching upstream over working around bugs. When a dependency has a bug or missing feature, use the package manager's patch workflow and commit the resulting patch files/configuration rather than wrapping or duplicating logic in our codebase.

Dependency updates

When available, consult the local dependency update runbook for dependency changes and security reports. This Git-ignored file is optional and is not distributed with the repository. Keep its watchlist focused on active findings and upgrade constraints; remove resolved items. If it is absent, proceed with the normal dependency checks. Keep private watchlist details out of public documentation, commits, and PRs.

Android

Android builds and the branding-regeneration script are documented in docs/andriod.md.

Changelog

Update CHANGELOG.md for significant changes only, following Keep a Changelog. Keep Unreleased current and never remove it during release. Give each release a short descriptive title, followed by categorized changes. For larger releases, add a short summary between the title and the changes to explain the main themes.

Releases

For every stable release, the stable branch and matching v<version> tag MUST both point to the same approved release commit and MUST both be pushed to origin. Release candidates and other prereleases do not advance stable unless the user explicitly requests it. Never create or push the release tag before the user has reviewed the release commit.

Pre-commit and Test Scripts

The git pre-commit hook runs pnpm pre-commit (or npm run pre-commit when pnpm is unavailable or the local pnpm shim is broken), which runs tsc --noEmit, eslint, prettier --write . (auto-formats and re-stages), vitest run, and vite build. pnpm test / npm test is the same pipeline but with prettier --check (CI-style, no writes).

Don't run pnpm test, npm test, tsc, eslint, prettier, or vitest separately as part of finishing a task — committing already validates everything. Stage your changes and commit; if pre-commit rejects the commit, fix all reported warnings and errors (not just hard errors — warnings that caused a non-zero exit must also be resolved), then git commit --amend to fold the fixes into the original commit.

If you don't have a git pre-commit hook installed (fresh clone), copy this into .git/hooks/pre-commit and chmod +x it:

#!/bin/sh
if command -v pnpm >/dev/null 2>&1 && pnpm --version >/dev/null 2>&1; then
  pnpm pre-commit
else
  npm run pre-commit
fi

End-to-end tests (e2e/) — conditional in pre-push

e2e/ holds integration tests that drive the app's real git + Nostr libraries against a live [ngit-grasp][grasp] server (push, packed refs, GRASP purgatory/state). pnpm test / npm test and pre-commit do not run them; nix develop installs a .git/hooks/pre-push hook that runs them automatically when pushed commits changed git/GRASP/e2e-sensitive paths. They can also be run explicitly via pnpm test:e2e or npm run test:e2e (vitest.e2e.config.ts).

  • They run headless in the Node environment, but require the ngit-grasp binary and a Node runtime — they cannot run in a browser-only environment or anywhere the binary is unavailable. The Nix devShell provides a pinned binary (nix develop, sets $NGIT_GRASP_BIN); without a binary every suite skips cleanly rather than failing.
  • Run them (if your environment can) whenever you change git/relay integration code — especially src/lib/git-grasp-pool/, src/lib/git-*, or the merge flow (src/lib/git-grasp-pool/merge.ts / grasp-push.ts) — since those paths are not covered by the default unit run. The Nix-installed pre-push hook catches common pushes touching those paths, but run pnpm test:e2e manually if you are outside Nix or want earlier feedback.
  • See e2e/README.md for the harness, invariants (never import src/services/nostr.ts singletons), and the degrade-don't-stub rule for browser-only globals in Node.

[grasp]: https://github.com/ — see ../ngit-grasp

Benchmarks (benchmarks/) — manual only

Before performance optimisation, read the UX priorities and tradeoff guidance. Use these priorities to assess effects outside the measured scenario. Reuse the existing harness, keep measurement scope bounded, and explain likely sacrifices and unmeasured risks; a narrow benchmark win alone is not sufficient evidence.

pnpm bench runs the browser-driven relay query-budget benchmark. It drives a production build in headless Playwright Chromium, measures REQ frames / filter bytes / relay connections against the committed benchmarks/baseline.json (--compare), and is never part of pre-commit, pnpm test, or CI. The default devShell deliberately omits the ~1 GB browser bundle — run it via nix develop .#bench --command pnpm bench, or outside Nix provision a browser once with npx playwright-core install chromium. The playwright-core devDependency must stay pinned to the exact version of pkgs.playwright-driver in flake.nix; see benchmarks/README.md.

Nostr Protocol Integration

Maintainer Protocol

The cross-project implementation guide is maintained in the repository nostr://danconwaydev.com/relay.ngit.dev/ngit-docs at docs/protocol/nip-34/maintainers/ai-implementers.md. It is published as the maintainer protocol for AI implementers. Check it when changing maintainer-role parsing, graph resolution, authority, or repository membership workflows.

Choosing kinds, designing tags, content vs. tags

  1. Always review existing NIPs first. Use the NIP index tool, then read candidate NIPs in detail. Find the closest existing solution.
  2. Prefer extending existing NIPs over creating custom kinds, even with minor schema compromises. Custom kinds fragment the ecosystem.
  3. When existing NIPs are close but not perfect, use the existing kind as the base and add domain-specific tags. Document extensions in NIP.md.
  4. Only generate a new kind when no existing NIP fits or storage characteristics differ. If a tool to generate a new kind number is available, you MUST use it — don't pick an arbitrary number.
  5. Custom kinds MUST include a NIP-31 alt tag with a human-readable description.

Tag design:

  • Kind = schema, tags = semantics. Don't create new kinds just for a different category of the same data.
  • Relays only index single-letter tags. Use t for categories ('#t': ['farming']); multi-letter tags force inefficient client-side filtering.
  • Filter at the relay — pass tag filters in the query rather than fetching everything and filtering in JS.

Content vs. tags:

  • Use content for large freeform text or industry-standard JSON formats (kind 0 is the historical exception).
  • Use tags for queryable metadata. If you need to filter by a field, it must be a tag — relays don't index content.
  • Empty content is fine (content: "" is idiomatic for tag-only events).

Kind ranges: Regular (1000–9999) stored permanently; Replaceable (10000–19999) latest per pubkey+kind; Addressable (30000–39999) latest per pubkey+kind+d. Kinds below 1000 are legacy with per-kind storage rules (kind 1 is regular, kind 3 is replaceable).

NIP.md

NIP.md documents custom kinds and schema extensions this project defines. Whenever you generate a new kind or change a custom schema, update NIP.md.

Repository authorization model — non-negotiable

Nostr is permissionless: anyone can publish any event. A NIP-34 repository is not a single pubkey + identifier; it is an identifier plus a reciprocally confirmed component of kind:30617 announcements. Directional listings are invitations and grant no authority. Kind:30618 state and maintainer-only operations require a current confirmed maintainer. Status, label, subject, and cover-note events accept the root author or a maintainer/moderator confirmed by resolved role history at the event's publication time.

Rules:

  • Always filter by authors when fetching anything trust-bearing for a repo. Never trust an event because its #a / #d matches. One carve-out: kind:30617 announcement discovery fetches MAY be identifier-scoped ({kinds: [30617], "#d": [id]} with no authors) because announcement authority is never derived from the fetch filter — it is established exclusively by reciprocal resolution (resolveChain) rooted at the route's pubkey. Every other trust-bearing fetch keeps the authors-filter rule.
  • URLs for addressable events include the author: /:npub/:repoId/..., never /:repoId/.... (See §"Routing" — multi-segment repo routes must be declared above the /:nip19 catch-all.)
  • Don't roll your own author check or repository grouping. The pure resolver is surfaced through useResolvedRepository, while discovery surfaces use the shared repository-component index. Use repo.componentId for card/component identity; repo.confirmedMaintainers / repo.confirmedMaintainerCoordinates for state, merges, settings, releases, and CI controls; and repo.confirmedMembers / repo.confirmedMemberCoordinates for member actions and collaboration tags. repo.discoveryPubkeys, repo.discoveredAnnouncements, and invitations are never authority sets. Copy the pattern from src/hooks/useIssues.ts, src/hooks/usePRs.ts, or src/hooks/useRepositoryState.ts.
  • Background: see docs/matainership.md for the full multi-maintainer model (recursive maintainers, mutual listing = one repo, splits when the chain breaks).

For events that are intentionally open (kind:1 notes, kind:7 reactions, follower kind:10018 lists, public discovery feeds), filtering by author defeats the point — don't.

Querying Events from Relays

CRITICAL: never call pool.subscription(), pool.req(), pool.relay().subscription(), or pool.relay().request() directly for fetching events. Always use resilientSubscription / resilientRequest from @/lib/resilientSubscription. They provide smart reconnect with since: lastReceivedAt gap-fill, foreground-resume gap-fill, EOSE settle signal, optional backward pagination, rate-limit backoff, and per-relay error isolation.

Reading relay metadata observables (connected$, icon$) for UI display is fine without the wrappers — never for event fetching.

Patterns, in order of preference:

  1. Read from the EventStore (store.getByFilters(filters) / store.timeline(filters) / store.event(id) / store.model(...)). On RepoLayout, IssuePage, and PRPage the relay fetches are already wired upstream (see "Pre-wired loaders" below). Components inside those pages should read from the store rather than opening their own subscriptions.
  2. Two-layer hook (relay fetch + store read) — when the data isn't already pre-wired. This is the dominant pattern across src/hooks/ (useUserRepositories, useUserStarredRepos, useUserPinnedRepos, useUserActivity, useResolvedRepository, etc.). Use one use$ to fire resilientSubscription(pool, relays, filters).pipe(onlyEvents(), mapEventsToStore(store)) (return undefined to short-circuit when inputs are missing), then a second use$ to read the resulting events back via store.model(...) / store.timeline(...) / store.getByFilters(...). Copy src/hooks/useUserRepositories.ts as the canonical template.
  3. Direct resilientSubscription / resilientRequest — for one-off fetches, search flows, or anywhere you need pagination, custom reactivity, or a non-trivial pipeline outside a hook. See src/lib/searchForEvent.ts, src/services/userIdentitySubscription.ts.
  4. createPaginatedTagValueLoader from @/lib/tagValuePaginatedLoader — drop-in replacement for applesauce's createTagValueLoader that adds per-relay backward pagination, persistent live subscription, rate-limit-aware reconnect, and an EOSE settle signal. Use it for high-cardinality #e / #E / #a / #q fan-out (essentials, comments, threads, repo-level item streams). The NIP-34 singletons in src/services/nostr.ts (nip34EssentialsLoader, nip34CommentsLoader, the thread loaders) are all instances of this — calls within the buffer window are batched into one REQ per relay automatically, so always reuse the singleton rather than instantiating a new one.

For options, conditional/optional observables, tag-filter casting (#a, #E, #t), reactive counts, and mapEventsToTimeline() typing, load the resilient-subscriptions skill.

Pre-wired loaders — don't duplicate them

Relay fetching for the main collaboration surfaces is already invoked at the page boundary; new code below those pages should read from the EventStore rather than opening its own subscriptions:

  • RepoLayout (src/pages/repo/RepoLayout.tsx) — fires nip34RepoLoader once via useNip34RepoLoader (useIssues / usePRs are store-only) and, in outbox mode, nip34SupplementalRelayLoader. This loads every issue/PR root + their essentials (status, labels, deletions, cover notes, legacy replies) and NIP-22 comments for the whole repo. It also subscribes to repo meta (kind:7 stars, kind:10018 followers).
  • IssuePage / PRPage — go through useResolvedIssue / useResolvedPR → useNip34ItemDetailLoader, which fires nip34ListLoader + nip34ThreadItemLoader for the item. The thread loader recursively pulls every event referencing the root or any comment via #e / #E / #q (reactions, zaps, deletions, quotes, child comments) — no kind restriction.

Inside any component or hook on those pages, the right move is store.getByFilters(...) / store.timeline(...) / store.model(...) (see src/hooks/useInlineComments.ts for an example). Only reach for resilientSubscription or a new createPaginatedTagValueLoader instance when the data isn't already in scope of one of the pre-wired loaders.

Replaceable and Addressable Event Preflight

Before adding or changing a writer for a replaceable or addressable event, read docs/replaceable-preflight.md. Classify the writer by its ownership category and modifiers, reuse session- or page-owned warm evidence where the documented coverage semantics apply, and keep relay lifecycle facts separate from the category's sufficiency policy. An open relay connection alone is not query coverage. Adoption is deliberately staged; do not extend stable-filter coverage claims to additive filters without supplying the stronger per-revision semantics described there. Document new categories or exceptions in the same change.

Custom Event Kinds — Factory + Cast + Hook

For any project-specific kind, use the three-layer pattern: Factory in src/factories/ (builds + signs), Cast in src/casts/ (typed wrapper with Symbol.for(...)-cached getters), Hook in src/hooks/ (subscribes and casts via castTimelineStream). Never manually parse NostrEvent.tags in hooks or components.

Don't reinvent — copy the closest existing example and adapt: IssueFactory + Issue + useIssues, or PatchFactory + Patch + usePatchChain, or RepositoryFactory + Repository + useResolvedRepository. Look up additional applesauce-core/operations/... and EventCast / EventFactory API in the Applesauce MCP.

NIP-22 Comments (kind:1111)

Replies to non-kind-1 events (NIP-34 issues/patches, NIP-23 articles) use kind:1111 with uppercase E / P tags for the thread root and lowercase e / p for the immediate parent. Load the nip22-comments skill for the tag layout and queries.

NIP-19 Identifiers and Routing

Bech32 identifiers (npub1, nprofile1, note1, nevent1, naddr1) route at the URL root — /:nip19 is handled by src/pages/NIP19Page.tsx, which branches on nip19.decode().type. Never nest under /note/, /profile/, etc.

  • Filters only accept hex — always nip19.decode() before querying. For naddr1, decoded data is { kind, pubkey, identifier, relays? } — always include pubkey in authors (see §"Repository authorization model"). For nevent1, decoded data is { id, author?, kind?, relays? } — pass relays into your subscription as a hint.
  • Treat nsec1 and unknown prefixes as 404.
  • Build with nip19.npubEncode / noteEncode / neventEncode / nprofileEncode / naddrEncode.
  • Route ordering matters. Multi-segment routes (/:npub/:repoId, /:npub/:repoId/issues/:issueId) must appear above the catch-all /:nip19 route — React Router matches top-to-bottom and stops at the first match.

File Uploads

File uploads use Blossom via useBlossomUpload / useBlossomFallback.

Authentication

<LoginArea /> from @/components/auth/LoginArea provides the full login/signup UI (extension, nsec, NIP-46 bunker) and an account switcher when logged in. Drop it in your header. For programmatic flows use useLoginActions (extension(), nsec(), bunker(), logout()).

The active account is exposed via useAccount() (returns { pubkey, signer } | null). The signer implements NIP-07 (signEvent, optional nip04, optional nip44).

Git Operations via GRASP — git-grasp-pool

src/lib/git-grasp-pool/ is the only sanctioned way to do git HTTP in this app. It hand-rolls the smart-HTTP protocol on top of @fiatjaf/git-natural-api's low-level primitives so we can stream just the objects we need (commits, trees with blob:none, individual blobs by path) instead of cloning, race the announced clone URLs, fall back across mirrors, route through a CORS proxy when needed, and serve everything out of a content-addressed L1+L2 (Map + IndexedDB) cache. Treat it the same way as resilientSubscription for events: never roll your own.

  • React entrypoint: useGitPool(cloneUrls, { knownHeadCommit?, stateRefs?, stateCreatedAt? }) from src/hooks/useGitPool.ts. Returns { poolState, pool }. Multiple components on the same repo share one pool via the registry — pass the announced clone URLs straight in.
  • Imperative / outside React: getOrCreatePool({ cloneUrls, stateEvent$? }) from @/lib/git-grasp-pool. The same registry deduplicates pools and grows a pool's URL set when new announcements arrive.
  • Read APIs on the pool (all cache-first, all accept an optional fallbackUrls for one-off URLs like a PR author's fork): getSingleCommit, getCommitHistory, getTree, getFullTree, getBlob, getObjectByPath, findMergeBase, countCommitsBehind, findCommitBeforeTimestamp. For diffs, fetch two getFullTree results, walk them with diffTrees, fetch only the changed blobs, then generateUnifiedDiff (all exported from the barrel).
  • State event integration is automatic when you pass knownHeadCommit / stateRefs / stateCreatedAt — the pool computes state-behind-git / state-commit-unavailable warnings, per-URL UrlRefStatus, and crossRefDiscrepancies for the multi-server status UI; it also schedules backoff re-fetches when the signed Nostr state is ahead of every git server.
  • Don't: import from @fiatjaf/git-natural-api outside git-grasp-pool/git-http.ts, construct GitGraspPool yourself, add a parallel cache, or fan out Promise.any(cloneUrls.map(fetch...)) in a hook. The deep details (cache layout, packfile parsing, error classification, eviction) live in the source — read src/lib/git-grasp-pool/ when you need them.
  • Testing: this code is not exercised by the default unit run. If your environment can (Node + the ngit-grasp binary), run pnpm test:e2e or npm run test:e2e after changing anything here — see the "End-to-end tests" section above.

Routing

Routes live in AppRouter.tsx. To add one:

  1. Create the page component in src/pages/.
  2. Import it in AppRouter.tsx.
  3. Place it above the /:nip19 catch-all and the * 404 route.

The router auto-scrolls to top on navigation.

Error Recovery

Use the shared useErrorRetry / ErrorRetryAction pattern for recoverable errors. Read docs/error-recovery.md before adding retry behavior. Offer a visible manual retry; automatic retries require an explicitly audited read-only path that cannot request a signature. Keep the retry owner mounted during loading, use context-specific bounded delays, and cancel on navigation. Signing/authentication, mutations, and deterministic errors stay manual. Never add an independent error-component timer.

Loading and Empty States

Use skeletons for structured content (feeds, profiles, forms). Use spinners only for buttons or short operations.

<Card>
  <CardHeader>
    <div className="flex items-center space-x-3">
      <Skeleton className="h-10 w-10 rounded-full" />
      <div className="space-y-1">
        <Skeleton className="h-4 w-24" />
        <Skeleton className="h-3 w-16" />
      </div>
    </div>
  </CardHeader>
  <CardContent>
    <div className="space-y-2">
      <Skeleton className="h-4 w-full" />
      <Skeleton className="h-4 w-4/5" />
    </div>
  </CardContent>
</Card>

For empty results, show a minimalist border-dashed card:

<Card className="border-dashed">
  <CardContent className="py-12 px-8 text-center">
    <p className="text-muted-foreground max-w-sm mx-auto">
      No results found. Try checking your relay connections or wait a moment for
      content to load.
    </p>
  </CardContent>
</Card>

Design Standards

Designs should be polished and production-ready. Concrete rules:

  • Responsive down to ~360px; test mobile, tablet, desktop.
  • WCAG 2.1 AA: ≥ 4.5:1 contrast for body text, ≥ 3:1 for large text and UI elements. Full keyboard nav, ARIA labels, visible focus-visible rings.
  • 8px grid (Tailwind's 4-based scale). Avoid one-off p-[13px]-style values.
  • Typography hierarchy: ≥ 18px body, ≥ 40px primary headlines. Inter (already wired via @fontsource-variable/inter) is the default sans.
  • Depth: soft shadows, gentle gradients, rounded corners (rounded-lg / rounded-xl). Avoid heavy drop shadows.
  • Motion: lightweight, purposeful (hover, scroll reveals, transitions). Respect prefers-reduced-motion with motion-safe: / motion-reduce:.
  • Reusable components: consistent variants and feedback states (hover, focus-visible, active, disabled, aria-invalid). Use cn() for conditional classes and class-variance-authority for variants — copy an existing ui/ component as a template.
  • Custom over generic: avoid template-looking headers — use layered visuals, subtle motion, brand colors. Generate custom images before reaching for stock.

For font installation, color-scheme changes, light/dark theming, and the isolate + negative-z-index gotcha, load the theming skill.

Date Formatting

date-fns is already a project dependency. Nostr created_at is seconds — multiply by 1000 for Date.

import { formatDistanceToNow, format } from "date-fns";
formatDistanceToNow(new Date(event.created_at * 1000), { addSuffix: true });
format(new Date(event.created_at * 1000), "MMM d, yyyy 'at' h:mm a");

Writing Tests vs. Running Tests

Writing (creating new test files) — don't, unless asked. Only create new tests when:

  1. The user explicitly asks for tests.
  2. The user describes a specific bug and asks for tests to diagnose it.
  3. The user says a problem persists after you tried to fix it.

Never write tests because tool results show failures, because you think tests would be helpful, or because you added a feature.

Running validation — let pre-commit do it. The git pre-commit hook runs the full pre-commit script (tsc, eslint, prettier --write, vitest, build). Don't run those tools manually as part of "validating" your changes — commit and react to anything pre-commit rejects.

Test Setup

Vitest + jsdom, with React Testing Library and jest-dom matchers. Mocked browser APIs: matchMedia, scrollTo, IntersectionObserver, ResizeObserver. Wrap components in TestApp (from @/test/TestApp) when rendering — it provides all required providers.

import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import { TestApp } from "@/test/TestApp";
import { MyComponent } from "./MyComponent";

describe("MyComponent", () => {
  it("renders correctly", () => {
    render(
      <TestApp>
        <MyComponent />
      </TestApp>,
    );
    expect(screen.getByText("Expected text")).toBeInTheDocument();
  });
});

Validating Your Changes

Your task is finished when git commit succeeds — commit automatically without waiting to be asked. The pre-commit hook handles type-checking, linting, formatting, tests, and build. If pre-commit rejects the commit, fix all reported warnings and errors (warnings that cause a non-zero exit are just as blocking as hard errors), then git commit --amend to fold the fixes into the original commit.

Using Git

Use git status / git diff / git log to inspect state and learn project conventions. If you make a mistake, git checkout restores files. Always commit when you are finished — non-negotiable, every completed task ends with a successful commit.

Specialized Skills

Load via the skill tool when the task matches:

  • react-rxjs-observables — using use$ correctly: factory pattern, dependency arrays, conditional observables, common mistakes.
  • resilient-subscriptions — resilientSubscription / resilientRequest deep-dive: options, three query patterns, tag-filter casting, mapEventsToTimeline typing, reactive counts.
  • nip22-comments — kind:1111 comment trees on non-kind-1 events; uppercase E/P vs lowercase e/p.
  • theming — fonts (@fontsource), color schemes, light/dark, isolate + negative z-index.
  • ngit — workflows for nostr:// git remotes, ngit CLI, gitworkshop.dev PRs/issues. (Auto-loaded when working with nostr:// remotes.)

When the task is Applesauce API surface — looking up methods, models, casts, actions, loaders — prefer the Applesauce MCP over loading a skill.

Contributors

If you are a contributor (not DanConwayDev), you MUST read and comply with CONTRIBUTING.md before writing any code.