diff --git a/.agents/skills/backend-fastify/SKILL.md b/.agents/skills/backend-fastify/SKILL.md deleted file mode 100644 index f74eaa8a..00000000 --- a/.agents/skills/backend-fastify/SKILL.md +++ /dev/null @@ -1,171 +0,0 @@ ---- -name: backend-fastify -description: Backend development using Fastify + TypeScript. Use when creating new backend APIs, adding routes, implementing services, working with plugins, or configuring environment variables. ---- - -# Backend Fastify Stack - -High-performance Node.js backend stack: - -- **Fastify 5.x** - Web framework -- **TypeScript** - Type safety -- **tsx** - Development with watch mode -- **pino-pretty** - Pretty logging for development -- **@fastify/env** - Environment variable validation with JSON Schema -- **@fastify/cors** - CORS support -- **fastify-plugin** - Plugin system - -## Environment Setup - -Use [asdf](https://asdf-vm.com/) to manage Node.js versions: - -```bash -# Install Node.js plugin (one-time) -asdf plugin add nodejs - -# Set project Node.js version -asdf set nodejs latest:22 -``` - -This creates a `.tool-versions` file in the project root that ensures consistent Node.js versions across the team. - -## Reference Files - -| File | When to Use | -|------|-------------| -| [setup-guide.md](references/setup-guide.md) | Starting a new backend project from scratch | -| [patterns.md](references/patterns.md) | Implementing routes, services, schema validation | -| [authentication.md](references/authentication.md) | Adding JWT auth, authorization, protected routes | -| [api-design.md](references/api-design.md) | Swagger/OpenAPI integration, response format, errors | -| [mcp-integration.md](references/mcp-integration.md) | Integrating MCP server for AI agent access | -| [gotchas.md](references/gotchas.md) | Debugging issues, common mistakes and fixes | - -## Quick Reference - -### Commands - -```bash -# Dev server with watch mode -npm run dev - -# Build for production -npm run build - -# Run production build -npm start - -# Type check -npm run type-check -``` - -### Key Imports - -```typescript -// Fastify types -import Fastify, { FastifyInstance, FastifyPluginAsync } from 'fastify' -import fp from 'fastify-plugin' - -// Common plugins -import fastifyEnv from '@fastify/env' -import cors from '@fastify/cors' -``` - -### Configuration Access - -Always access configuration through `fastify.config`, never `process.env` directly: - -```typescript -// CORRECT - type-safe, validated at startup -const port = fastify.config.PORT -const apiKey = fastify.config.API_KEY - -// WRONG - no validation, no type safety -const port = process.env.PORT // Don't do this -``` - -### Response Format - -```typescript -// Standard response structure -{ - success: boolean - data?: T - error?: string - metadata?: { timestamp: Date } -} -``` - -### Plugin Pattern - -```typescript -import fp from 'fastify-plugin' - -export default fp(async (fastify, opts) => { - // Plugin logic here - fastify.decorate('something', value) -}, '5.x') -``` - -### Route Pattern - -```typescript -import { FastifyPluginAsync } from 'fastify' - -const routes: FastifyPluginAsync = async (fastify, opts) => { - fastify.get('/', async (request, reply) => { - return { success: true, data: 'example' } - }) -} - -export default routes -``` - -### Service Pattern - -```typescript -// 1. Create service class -export class MyService { - constructor(private fastify: FastifyInstance) {} - - async doWork() { - // Access config through fastify instance - const apiKey = this.fastify.config.API_KEY - this.fastify.log.info('Service method called') - } -} - -// 2. Declare module augmentation -declare module 'fastify' { - interface FastifyInstance { - myService: MyService - } -} - -// 3. Initialize and decorate in app.ts -fastify.decorate('myService', new MyService(fastify)) -``` - -### Project Structure - -``` -backend/ -├── src/ -│ ├── plugins/ # Fastify plugins (env, auth, etc.) -│ ├── routes/ # HTTP route handlers -│ ├── services/ # Business logic classes -│ ├── utils/ # Shared utilities -│ ├── app.ts # Plugin registration & setup -│ └── index.ts # Server entry point -├── package.json -├── tsconfig.json -├── .env.example -└── .gitignore -``` - -### Common Gotchas - -- **Plugin order matters**: Register env plugin first, then services, then routes -- **Config access**: Use `fastify.config.VAR` not `process.env.VAR` -- **Server ready**: Call `await server.ready()` before accessing config in index.ts -- **Path normalization**: Centralize path utilities, handle root '/' as special case -- **Package management**: Use `npm install ` not manual `package.json` edits diff --git a/.agents/skills/backend-fastify/references/authentication.md b/.agents/skills/backend-fastify/references/authentication.md deleted file mode 100644 index 4ed408ca..00000000 --- a/.agents/skills/backend-fastify/references/authentication.md +++ /dev/null @@ -1,377 +0,0 @@ -# Authentication Patterns - -Patterns for implementing JWT authentication and authorization in Fastify backends. - -## Dependencies - -```bash -npm install jsonwebtoken -npm install -D @types/jsonwebtoken -``` - -## Environment Configuration - -Add auth-related config to your env plugin: - -```typescript -// src/plugins/env.ts -const schema = { - type: 'object', - required: ['JWT_SECRET'], - properties: { - JWT_SECRET: { - type: 'string', - minLength: 32, - description: 'Secret key for JWT signing' - }, - JWT_ISSUER: { - type: 'string', - default: 'my-app' - }, - JWT_AUDIENCE: { - type: 'string', - default: 'my-app-users' - }, - JWT_EXPIRES_IN: { - type: 'string', - default: '24h' - } - } -} - -declare module 'fastify' { - interface FastifyInstance { - config: { - JWT_SECRET: string - JWT_ISSUER: string - JWT_AUDIENCE: string - JWT_EXPIRES_IN: string - // ... other config - } - } -} -``` - -## Auth Middleware - -### Bearer Token Extraction - -```typescript -// src/middleware/auth.ts -import { FastifyRequest } from 'fastify' - -function extractBearerToken(request: FastifyRequest): string | null { - const authHeader = request.headers.authorization - if (!authHeader) return null - - const parts = authHeader.split(' ') - if (parts.length !== 2 || parts[0].toLowerCase() !== 'bearer') { - return null - } - return parts[1] -} -``` - -### JWT Payload Type - -```typescript -export interface JWTPayload { - sub: string // User ID - email: string - groups: string[] // Roles/permissions - iat: number // Issued at - exp: number // Expiration -} - -// Extend FastifyRequest to include user -declare module 'fastify' { - interface FastifyRequest { - user?: JWTPayload - } -} -``` - -### Required Authentication - -Use when endpoint requires a valid token: - -```typescript -import jwt from 'jsonwebtoken' -import { FastifyRequest, FastifyReply } from 'fastify' - -export async function verifyJWT( - request: FastifyRequest, - reply: FastifyReply -): Promise { - const token = extractBearerToken(request) - - if (!token) { - reply.code(401).send({ - success: false, - error: 'Authentication required' - }) - return - } - - try { - // Access config through request.server, not process.env - const config = request.server.config - const decoded = jwt.verify(token, config.JWT_SECRET, { - issuer: config.JWT_ISSUER, - audience: config.JWT_AUDIENCE - }) as JWTPayload - - request.user = decoded - } catch (error) { - request.log.debug({ error }, 'JWT verification failed') - reply.code(401).send({ - success: false, - error: 'Invalid or expired token' - }) - } -} -``` - -### Optional Authentication - -Use when endpoint works with or without authentication: - -```typescript -export async function optionalAuth( - request: FastifyRequest, - reply: FastifyReply -): Promise { - const token = extractBearerToken(request) - - if (!token) { - // No token is fine, continue without user - return - } - - try { - const config = request.server.config - const decoded = jwt.verify(token, config.JWT_SECRET, { - issuer: config.JWT_ISSUER, - audience: config.JWT_AUDIENCE - }) as JWTPayload - - request.user = decoded - } catch (error) { - // Invalid token with optional auth - log but continue - request.log.debug({ error }, 'Optional auth token invalid, continuing without user') - } -} -``` - -### Group-Based Authorization - -Require specific groups/roles: - -```typescript -export function requireGroups(requiredGroups: string[]) { - return async function ( - request: FastifyRequest, - reply: FastifyReply - ): Promise { - // First verify the JWT - await verifyJWT(request, reply) - - // If verifyJWT sent a response, stop - if (reply.sent) return - - // Check if user has at least one required group - const hasRequiredGroup = requiredGroups.some( - group => request.user!.groups.includes(group) - ) - - if (!hasRequiredGroup) { - reply.code(403).send({ - success: false, - error: 'Insufficient permissions', - required: requiredGroups, - actual: request.user!.groups - }) - return - } - } -} -``` - -## Using Auth in Routes - -### Protected Route - -```typescript -import { verifyJWT } from '../middleware/auth' - -const routes: FastifyPluginAsync = async (fastify, opts) => { - // Single route protection - fastify.get('/profile', { - preHandler: verifyJWT - }, async (request, reply) => { - // request.user is guaranteed to exist - const userId = request.user!.sub - return { success: true, data: { userId } } - }) -} -``` - -### Route with Role Requirement - -```typescript -import { requireGroups } from '../middleware/auth' - -const adminRoutes: FastifyPluginAsync = async (fastify, opts) => { - fastify.delete<{ Params: { id: string } }>('/users/:id', { - preHandler: requireGroups(['admin']) - }, async (request, reply) => { - // Only admins can reach here - const { id } = request.params - await fastify.userService.delete(id) - return { success: true } - }) -} -``` - -### Optional Auth Route - -```typescript -import { optionalAuth } from '../middleware/auth' - -const routes: FastifyPluginAsync = async (fastify, opts) => { - fastify.get('/items', { - preHandler: optionalAuth - }, async (request, reply) => { - const items = await fastify.itemService.findAll() - - // Customize response based on auth status - if (request.user) { - // Authenticated users see more details - return { success: true, data: items } - } else { - // Anonymous users see limited data - return { success: true, data: items.map(i => ({ id: i.id, name: i.name })) } - } - }) -} -``` - -## Global Auth Hook - -Apply optional auth globally, then require it on specific routes: - -```typescript -// In app.ts -export const app: FastifyPluginAsync = async (fastify, opts) => { - await fastify.register(envPlugin) - - // Global optional auth (skips health checks) - fastify.addHook('onRequest', async (request, reply) => { - if (request.raw.url?.startsWith('/api/health')) { - return - } - await optionalAuth(request, reply) - }) - - // Register routes - they can check request.user or use preHandler for required auth - await fastify.register(publicRoutes, { prefix: '/api' }) - await fastify.register(protectedRoutes, { prefix: '/api' }) -} -``` - -## Token Generation - -Service for creating tokens: - -```typescript -// src/services/auth-service.ts -import jwt from 'jsonwebtoken' -import bcrypt from 'bcrypt' -import { FastifyInstance } from 'fastify' -import { JWTPayload } from '../middleware/auth' - -export class AuthService { - constructor(private fastify: FastifyInstance) {} - - generateToken(user: { id: string; email: string; groups: string[] }): string { - const config = this.fastify.config - - const payload: Omit = { - sub: user.id, - email: user.email, - groups: user.groups - } - - return jwt.sign(payload, config.JWT_SECRET, { - issuer: config.JWT_ISSUER, - audience: config.JWT_AUDIENCE, - expiresIn: config.JWT_EXPIRES_IN - }) - } - - async validateCredentials(email: string, password: string): Promise { - // Note: Requires userService to be decorated on fastify instance before AuthService is used - const user = await this.fastify.userService.findByEmail(email) - if (!user) return null - - const valid = await this.comparePassword(password, user.passwordHash) - if (!valid) return null - - return user - } - - private async comparePassword(plain: string, hash: string): Promise { - return bcrypt.compare(plain, hash) - } -} -``` - -## Login Route - -```typescript -const authRoutes: FastifyPluginAsync = async (fastify, opts) => { - fastify.post<{ Body: { email: string; password: string } }>('/login', { - schema: { - body: { - type: 'object', - required: ['email', 'password'], - properties: { - email: { type: 'string', format: 'email' }, - password: { type: 'string', minLength: 1 } - } - } - } - }, async (request, reply) => { - const { email, password } = request.body - - const user = await fastify.authService.validateCredentials(email, password) - - if (!user) { - reply.code(401) - return { success: false, error: 'Invalid credentials' } - } - - const token = fastify.authService.generateToken({ - id: user.id, - email: user.email, - groups: user.groups - }) - - return { - success: true, - data: { - token, - user: { id: user.id, email: user.email } - } - } - }) -} -``` - -## Security Considerations - -1. **Never log tokens**: Ensure JWT tokens are not logged in request/response hooks -2. **Use strong secrets**: JWT_SECRET should be at least 32 characters, randomly generated -3. **Set appropriate expiration**: Balance security vs user experience -4. **Validate issuer/audience**: Prevents token reuse across different applications -5. **Use HTTPS**: Always require HTTPS in production to protect tokens in transit diff --git a/.agents/skills/frontend-shadcn/README.md b/.agents/skills/frontend-shadcn/README.md deleted file mode 100644 index 91a56f46..00000000 --- a/.agents/skills/frontend-shadcn/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# frontend-shadcn - -The Jarvus convention set for building frontends with **Vite + React 19 + shadcn/ui + Tailwind CSS -v4 + React Router v7** — project setup, adding UI components, routing, and styling, the way Jarvus -builds React apps. - -## When you'd want it - -Any project with this React frontend stack — scaffolding a new app, adding shadcn/ui components, -implementing routing, or styling with Tailwind. Install it on a repo so an agent working on the UI -follows the house conventions (New York style components, the `@tailwindcss/vite` plugin, etc.). - -## Install - -**Recommended scope: per-project.** This encodes the stack *this* project uses, so installing it in -the repo means every developer (and their agents) gets the same guidance — version-controlled with -the code and updated alongside it. - -```bash -npx skills add JarvusInnovations/agent-skills --skill frontend-shadcn -``` - -(Add `--global` if you'd rather have it available everywhere.) See `SKILL.md` for the stack and patterns -and `references/` for the setup guide and component details. diff --git a/.agents/skills/frontend-shadcn/SKILL.md b/.agents/skills/frontend-shadcn/SKILL.md deleted file mode 100644 index 072755b9..00000000 --- a/.agents/skills/frontend-shadcn/SKILL.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -name: frontend-shadcn -description: Frontend development using Vite + React + shadcn/ui + Tailwind CSS + React Router v7. Use when creating new frontend projects, adding UI components, implementing routing, styling with Tailwind, or working with shadcn/ui component library. ---- - -# Frontend ShadCN Stack - -Modern React frontend stack: - -- **Vite** - Build tooling -- **React 19** - UI framework -- **TypeScript** - Type safety -- **Tailwind CSS v4** - Utility-first styling (`@tailwindcss/vite` plugin) -- **shadcn/ui** - Component library (New York style) -- **React Router v7** - Client-side routing - -## Environment Setup - -Use [asdf](https://asdf-vm.com/) to manage Node.js versions: - -```bash -# Install Node.js plugin (one-time) -asdf plugin add nodejs - -# Set project Node.js version -asdf set nodejs latest:22 -``` - -This creates a `.tool-versions` file in the project root that ensures consistent Node.js versions across the team. - -## Reference Files - -| File | When to Use | -|------|-------------| -| [setup-guide.md](references/setup-guide.md) | Starting a new project from scratch | -| [patterns.md](references/patterns.md) | Implementing features, understanding architecture | -| [maplibre.md](references/maplibre.md) | Working with MapLibre GL JS maps | -| [mcp-tools.md](references/mcp-tools.md) | Looking up docs, adding components via MCP | - -## Quick Reference - -### Commands - -```bash -# Add shadcn component -npx shadcn@latest add -y - -# Dev server -npm run dev - -# Type check -npm run type-check -``` - -### Key Imports - -```typescript -// React Router v7 - use 'react-router' NOT 'react-router-dom' -import { Routes, Route, Link, useLocation, useSearchParams } from 'react-router' - -// Path alias - @/ maps to src/ -import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' -``` - -### Conditional Classes - -```typescript -import { cn } from '@/lib/utils' - -
-``` - -### Common Components - -```bash -# Layout -npx shadcn@latest add sidebar card separator -y - -# Forms -npx shadcn@latest add button input form select checkbox -y - -# Feedback -npx shadcn@latest add dialog alert toast -y - -# Navigation -npx shadcn@latest add dropdown-menu tabs tooltip -y -``` - -### Project Structure - -``` -src/ -├── components/ -│ ├── ui/ # shadcn/ui components (auto-generated) -│ ├── AppShell.tsx # Main layout with header -│ └── AppSidebar.tsx -├── pages/ # Route page components -├── hooks/ # Custom hooks -├── lib/ -│ └── utils.ts # cn() helper -├── App.tsx # Route definitions -├── main.tsx # Entry point with BrowserRouter -└── index.css # Tailwind + shadcn theme -``` - -### Tailwind Patterns - -```typescript -// Common utility patterns -"flex items-center gap-4" // Flexbox with gap -"bg-muted text-muted-foreground" // Muted backgrounds -"border-b bg-background" // Borders and backgrounds -"h-screen overflow-auto" // Full height scrolling -"space-y-4" // Vertical spacing -``` - -### Common Gotchas - -- **Package management**: Use `npm install ` not manual `package.json` edits -- **shadcn components**: Use `npx shadcn@latest add -y` -- **React Router imports**: Use `react-router` NOT `react-router-dom` diff --git a/.agents/skills/frontend-shadcn/references/mcp-tools.md b/.agents/skills/frontend-shadcn/references/mcp-tools.md deleted file mode 100644 index ec315a26..00000000 --- a/.agents/skills/frontend-shadcn/references/mcp-tools.md +++ /dev/null @@ -1,113 +0,0 @@ -# MCP Tools for Frontend Development - -Two MCP servers enhance frontend development workflows: **shadcn** for UI components and **context7** for library documentation. - -> **Note:** These MCP servers are bundled with this plugin via `.claude-plugin/marketplace.json`. They will be automatically available when using Claude Code with this plugin installed. - -## Research Workflow - -Before implementing new features or installing unfamiliar libraries: - -1. **Research** with context7 MCP - Get up-to-date documentation -2. **Understand** with shadcn MCP - Find component examples -3. **Install** with npm/npx - Add the dependency -4. **Implement** - Build the feature - -## shadcn MCP Server - -Use for discovering, understanding, and installing shadcn/ui components. - -### Search for Components - -``` -mcp__shadcn__search_items_in_registries(registries: ["@shadcn"], query: "sidebar") -``` - -Common searches: `sidebar`, `card`, `dialog`, `dropdown`, `table`, `form`, `button` - -### Get Component Examples - -``` -mcp__shadcn__get_item_examples_from_registries(registries: ["@shadcn"], query: "button-demo") -``` - -Pattern: Use `{component}-demo` to find usage examples. - -### Get Install Command - -``` -mcp__shadcn__get_add_command_for_items(items: ["@shadcn/sidebar"]) -``` - -Returns the exact `npx shadcn@latest add ...` command. - -### Workflow Example - -``` -1. mcp__shadcn__search_items_in_registries(registries: ["@shadcn"], query: "data table") -2. mcp__shadcn__get_item_examples_from_registries(registries: ["@shadcn"], query: "data-table-demo") -3. mcp__shadcn__get_add_command_for_items(items: ["@shadcn/table"]) -4. Run: npx shadcn@latest add table -y -``` - -### After Adding Components - -Use `mcp__shadcn__get_audit_checklist` to verify the component was added correctly and understand any additional setup needed. - -## context7 MCP Server - -Use for accessing up-to-date documentation for React, TypeScript, and other libraries. - -### Resolve Library ID - -First, get the context7 library ID: - -``` -mcp__context7__resolve-library-id(libraryName: "react-router", query: "routing") -``` - -Returns: `/remix-run/react-router` - -### Query Library Docs - -Then fetch specific documentation: - -``` -mcp__context7__query-docs( - libraryId: "/remix-run/react-router", - query: "useSearchParams hook usage" -) -``` - -### Common Libraries - -| Library | context7 ID | Common Topics | -|---------|-------------|---------------| -| React Router v7 | `/remix-run/react-router` | BrowserRouter, useLocation, useSearchParams | -| React | `/facebook/react` | hooks, context, suspense | -| Tailwind CSS | `/tailwindlabs/tailwindcss` | utilities, configuration | -| MapLibre GL | `/maplibre/maplibre-gl-js` | Map, markers, layers | - -### Workflow Example - -``` -1. mcp__context7__resolve-library-id(libraryName: "react-router", query: "routing") - → Returns: /remix-run/react-router - -2. mcp__context7__query-docs( - libraryId: "/remix-run/react-router", - query: "nested routes configuration" - ) - → Returns: Documentation on nested routing patterns -``` - -## When to Use Each - -| Scenario | Tool | -|----------|------| -| Adding a new UI component | shadcn MCP | -| Understanding component API | shadcn MCP (examples) | -| Learning React Router patterns | context7 MCP | -| Checking latest library syntax | context7 MCP | -| Finding component install command | shadcn MCP | -| Debugging library behavior | context7 MCP (mode: "info") | diff --git a/.agents/skills/frontend-shadcn/references/patterns.md b/.agents/skills/frontend-shadcn/references/patterns.md deleted file mode 100644 index 9421e921..00000000 --- a/.agents/skills/frontend-shadcn/references/patterns.md +++ /dev/null @@ -1,309 +0,0 @@ -# Development Patterns - -Patterns for building features in Vite + React + shadcn/ui + Tailwind + React Router v7 projects. - -## Project Structure - -``` -src/ -├── components/ -│ ├── ui/ # shadcn/ui components (auto-generated) -│ ├── AppShell.tsx # Main layout with header and outlet -│ └── AppSidebar.tsx # Navigation sidebar -├── pages/ # Route page components (organized by feature) -│ ├── dashboard/ -│ └── settings/ -├── hooks/ # Custom React hooks -├── lib/ -│ └── utils.ts # cn() helper and shared utilities -├── App.tsx # Route definitions -├── main.tsx # Entry point with BrowserRouter -└── index.css # Tailwind + shadcn theme variables -``` - -**Conventions:** - -- Use `pages/` directory for page components organized by feature area -- Use shadcn/ui components from `components/ui/` for consistent styling -- Utility functions go in `lib/` directory -- Path alias `@/*` maps to `./src/*` - -## Routing Architecture - -### React Router v7 Setup - -```typescript -// main.tsx - Entry point -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import { BrowserRouter } from 'react-router' -import './index.css' -import App from './App' - -createRoot(document.getElementById('root')!).render( - - - - - , -) -``` - -```typescript -// App.tsx - Route definitions -import { Routes, Route } from 'react-router' -import { SidebarProvider } from '@/components/ui/sidebar' -import { AppSidebar } from '@/components/AppSidebar' -import { AppShell } from '@/components/AppShell' - -function App() { - return ( - - - - - - }> - } /> - } /> - - - ) -} -``` - -### Key Imports - -All routing imports come from `react-router` (NOT `react-router-dom`): - -```typescript -import { - BrowserRouter, // Wrap app in main.tsx - Routes, Route, // Define routes in App.tsx - Link, // Navigation links - Outlet, // Render child routes - useLocation, // Get current path - useParams, // Get route params - useSearchParams, // Get/set query params -} from 'react-router' -``` - -### Nested Routes with Outlet - -```typescript -// Parent route renders layout + Outlet -}> - {/* Child routes render into Outlet */} - } /> - } /> - -``` - -## State Management - -### URL-Based State - -Use `useSearchParams` for state that should persist in the URL: - -```typescript -const [searchParams, setSearchParams] = useSearchParams() - -// Read value -const environment = searchParams.get('env') - -// Update value -setSearchParams({ env: 'production' }) -``` - -### Route-Based Logic - -Use `useLocation` for determining active states: - -```typescript -const location = useLocation() -const isActive = location.pathname === '/dashboard' -``` - -### Query Parameter Preservation - -Create a helper to preserve query params across navigation: - -```typescript -function createNavLink(path: string, searchParams: URLSearchParams) { - const params = searchParams.toString() - return params ? `${path}?${params}` : path -} -``` - -## Component Patterns - -### Layout System - -**AppShell** - Main content wrapper with header: - -```typescript -import { Outlet } from 'react-router' -import { SidebarTrigger } from '@/components/ui/sidebar' - -export function AppShell() { - return ( -
-
- -
-
-
- -
-
- ) -} -``` - -**AppSidebar** - Navigation with active states: - -```typescript -import { useLocation, Link } from 'react-router' -import { - Sidebar, SidebarContent, SidebarGroup, - SidebarGroupContent, SidebarGroupLabel, SidebarHeader, - SidebarMenu, SidebarMenuButton, SidebarMenuItem, -} from '@/components/ui/sidebar' - -export function AppSidebar() { - const location = useLocation() - - return ( - - - App Name - - - - Navigation - - - - - - - Dashboard - - - - - - - - - ) -} -``` - -### Page Components - -Consistent structure with header and content sections: - -```typescript -export function DashboardPage() { - return ( -
-
-

Dashboard

-

Overview of your data

-
- -
- {/* Content cards */} -
-
- ) -} -``` - -### Collapsible Sidebar Sections - -```typescript -import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible' -import { ChevronDown } from 'lucide-react' - - - - - - - Section - - - - - - {/* Sub items */} - - - - -``` - -## UI Patterns - -### Common Layouts - -- **Two-column layouts** for complex forms -- **Card-based layouts** for dashboards and listings -- **Consistent navigation** with back links and breadcrumbs - -### Design Conventions - -**shadcn/ui components:** - -- Button, Input, Badge, Card, Tabs -- Sidebar, Dialog, Command, Table -- Tooltip, Dropdown Menu, Select - -**Tailwind patterns:** - -- `bg-muted`, `text-muted-foreground` - Muted backgrounds/text -- `space-y-4`, `gap-4` - Consistent spacing -- `flex-1` - Flexible sizing -- `border-b`, `border-r` - Borders - -### Color-Coded Status - -```typescript -// Status badges with semantic colors -Active // Primary color -Pending // Muted -Error // Red -Draft // Outlined -``` - -## Development Workflow - -### Before Starting Dev Server - -Check if a dev server is already running on port 5173: - -```bash -lsof -i :5173 -``` - -### Testing Changes - -1. Run the dev server and verify navigation works -2. Ensure query parameter preservation across route transitions -3. Verify active states for all sidebar menu items -4. Check conditional rendering for context-dependent sections - -### Package Management - -- Always use `npm install ` to add dependencies -- Never manually edit `package.json` to add packages -- Use `npx shadcn@latest add -y` for shadcn components - -### Theming Considerations - -- Project typically uses light theme only (configure dark mode if needed) -- CSS variables defined in `index.css` control theme colors -- Avoid adding `dark:` classes unless dark mode is implemented diff --git a/.agents/skills/frontend-shadcn/references/setup-guide.md b/.agents/skills/frontend-shadcn/references/setup-guide.md deleted file mode 100644 index 5c2349f1..00000000 --- a/.agents/skills/frontend-shadcn/references/setup-guide.md +++ /dev/null @@ -1,572 +0,0 @@ -# Vite + React + Tailwind + shadcn/ui + React Router v7 Stack Setup Guide - -This guide documents the complete process for bootstrapping a modern React application with this stack. Based on actual implementation experience and reference patterns. - -## Prerequisites - -- Node.js 22.x -- npm - -### Node.js Version Management with asdf - -Use [asdf](https://asdf-vm.com/) to manage Node.js versions consistently across the team: - -```bash -# Install Node.js plugin (one-time setup) -asdf plugin add nodejs - -# Set project Node.js version (creates .tool-versions file) -asdf set nodejs latest:22 -``` - -The `.tool-versions` file created by `asdf set` ensures all team members use the same Node.js version. - -## Step-by-Step Setup - -### 1. Initialize Vite Project - -```bash -npm create vite@latest . -- --template react-ts -npm install -``` - -**Commit:** `feat: initialize Vite project with React + TypeScript` - -This creates the base React 19 + TypeScript project with Vite 7.x. - ---- - -### 2. Install Tailwind CSS - -```bash -npm install tailwindcss @tailwindcss/vite -``` - -**Note:** Tailwind v4 uses `@tailwindcss/vite` plugin instead of PostCSS config. - -**Commit:** `build: install Tailwind CSS with @tailwindcss/vite plugin` - ---- - -### 3. Configure Tailwind and Path Aliases - -**Install @types/node for path resolution:** - -```bash -npm install -D @types/node -``` - -**Update `vite.config.ts`:** - -```typescript -import path from "path" -import tailwindcss from "@tailwindcss/vite" -import react from "@vitejs/plugin-react" -import { defineConfig } from "vite" - -export default defineConfig({ - plugins: [react(), tailwindcss()], - resolve: { - alias: { - "@": path.resolve(__dirname, "./src"), - }, - }, -}) -``` - -**Update `src/index.css`** (replace all content): - -```css -@import "tailwindcss"; -``` - -**Update `tsconfig.json`** (add compilerOptions): - -```json -{ - "files": [], - "references": [ - { "path": "./tsconfig.app.json" }, - { "path": "./tsconfig.node.json" } - ], - "compilerOptions": { - "baseUrl": ".", - "paths": { - "@/*": ["./src/*"] - } - } -} -``` - -**Update `tsconfig.app.json`** (add to compilerOptions): - -```json -{ - "compilerOptions": { - // ... existing options ... - "baseUrl": ".", - "paths": { - "@/*": ["./src/*"] - } - } -} -``` - -**Commit:** `config: configure Tailwind CSS and TypeScript path aliases` - ---- - -### 4. Initialize shadcn/ui - -```bash -npx shadcn@latest init --base-color neutral -``` - -This will: - -- Create `components.json` -- Update `src/index.css` with CSS variables and theme -- Create `src/lib/utils.ts` with `cn()` helper -- Install required dependencies (clsx, tailwind-merge, etc.) - -**Interactive prompts (if not using --base-color):** - -- Style: New York -- Base color: Neutral (or your preference) -- CSS variables: Yes - -**Commit:** `feat: initialize shadcn/ui with Neutral color scheme` - ---- - -### 5. Install React Router v7 - -**IMPORTANT:** React Router v7 uses the package name `react-router`, NOT `react-router-dom`. - -```bash -npm install react-router -``` - -**Commit:** `build: install React Router v7` - ---- - -### 6. Set Up React Router - -**Update `src/main.tsx`:** - -```tsx -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import { BrowserRouter } from 'react-router' -import './index.css' -import App from './App.tsx' - -createRoot(document.getElementById('root')!).render( - - - - - , -) -``` - -**Update `src/App.tsx`:** - -```tsx -import { Routes, Route } from 'react-router' - -function App() { - return ( - - Home
} /> - - ) -} - -export default App -``` - -**Key imports from `react-router`:** - -- `BrowserRouter` - Wrap app in main.tsx -- `Routes`, `Route` - Define routes in App.tsx -- `Link` - Navigation links -- `useLocation` - Get current path -- `useParams` - Get route params -- `useSearchParams` - Get/set query params -- `Outlet` - Render child routes - ---- - -### 7. Add shadcn/ui Components - -Add components as needed: - -```bash -npx shadcn@latest add sidebar -y -npx shadcn@latest add card -y -npx shadcn@latest add button -y -npx shadcn@latest add collapsible -y -# etc. -``` - -The sidebar component includes many dependencies automatically: - -- button, separator, sheet, tooltip, input, skeleton - -**Commit each component addition separately or batch related ones.** - ---- - -### 8. Create App Shell Structure - -**Create `src/components/AppShell.tsx`:** - -```tsx -import { Outlet } from 'react-router' -import { SidebarTrigger } from '@/components/ui/sidebar' - -export function AppShell() { - return ( -
-
- -
-
-
- -
-
- ) -} -``` - -**Create `src/components/AppSidebar.tsx`:** - -```tsx -import { useLocation, Link } from "react-router"; -import { - Sidebar, - SidebarContent, - SidebarGroup, - SidebarGroupContent, - SidebarGroupLabel, - SidebarHeader, - SidebarMenu, - SidebarMenuButton, - SidebarMenuItem, -} from "@/components/ui/sidebar"; -import { Home } from "lucide-react"; - -export function AppSidebar() { - const location = useLocation(); - - return ( - - - App Name - - - - - Navigation - - - - - - - Home - - - - - - - - - ); -} -``` - -**Update `src/App.tsx` with layout:** - -```tsx -import { Routes, Route } from 'react-router' -import { SidebarProvider } from '@/components/ui/sidebar' -import { AppSidebar } from '@/components/AppSidebar' -import { AppShell } from '@/components/AppShell' - -function App() { - return ( - - - - - - }> - } /> - } /> - - - ) -} -``` - ---- - -### 9. Optional: Add MapLibre GL JS - -```bash -npm install maplibre-gl -``` - -**Commit:** `build: install MapLibre GL JS` - -**Basic map component:** - -```tsx -import { useEffect, useRef } from 'react'; -import maplibregl from 'maplibre-gl'; -import 'maplibre-gl/dist/maplibre-gl.css'; - -export function Map() { - const mapContainer = useRef(null); - const map = useRef(null); - - useEffect(() => { - if (!mapContainer.current || map.current) return; - - map.current = new maplibregl.Map({ - container: mapContainer.current, - style: { - version: 8, - sources: { - osm: { - type: 'raster', - tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'], - tileSize: 256, - }, - }, - layers: [{ id: 'osm', type: 'raster', source: 'osm' }], - }, - center: [-104.99, 39.74], - zoom: 10, - }); - - return () => { - map.current?.remove(); - map.current = null; - }; - }, []); - - return
; -} -``` - -**Important:** Import the CSS file for proper map styling. - ---- - -## File Structure After Setup - -``` -├── .claude/ -│ └── CLAUDE.md # Project documentation -├── src/ -│ ├── components/ -│ │ ├── ui/ # shadcn/ui components (auto-generated) -│ │ ├── AppShell.tsx -│ │ └── AppSidebar.tsx -│ ├── hooks/ -│ │ └── use-mobile.ts # From shadcn sidebar -│ ├── lib/ -│ │ └── utils.ts # cn() helper -│ ├── pages/ # Route components -│ ├── App.tsx -│ ├── main.tsx -│ └── index.css # Tailwind + shadcn theme -├── components.json # shadcn/ui config -├── tsconfig.json -├── tsconfig.app.json -├── vite.config.ts -└── package.json -``` - ---- - -## Key Patterns - -### Sidebar Navigation with Active State - -```tsx - - - - Label - - -``` - -### Collapsible Sidebar Sections - -```tsx -import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; - - - - - - - Section - - - - - - {/* Sub items */} - - - - -``` - -### Nested Routes with Outlet - -```tsx -// Parent route renders layout + Outlet -}> - {/* Child routes render into Outlet */} - } /> - } /> - -``` - ---- - -## VSCode Debugging - -Configure VSCode to debug the Vite dev server and React application. - -### Launch Configuration - -**Create `.vscode/launch.json`:** - -```json -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Debug Dev Server", - "type": "node", - "request": "launch", - "cwd": "${workspaceFolder}", - "runtimeExecutable": "npx", - "runtimeArgs": ["vite"], - "skipFiles": ["/**", "**/node_modules/**"], - "console": "integratedTerminal" - }, - { - "name": "Debug in Chrome", - "type": "chrome", - "request": "launch", - "url": "http://localhost:5173", - "webRoot": "${workspaceFolder}/src", - "sourceMaps": true - } - ] -} -``` - -**Key patterns:** - -- "Debug Dev Server" runs Vite with Node.js debugging for server-side breakpoints -- "Debug in Chrome" launches Chrome with DevTools protocol for client-side React debugging -- `webRoot` maps to `src/` for accurate source map resolution -- Default Vite port is `5173` - -### Using the Debugger - -**For client-side React debugging:** - -1. Start the dev server: `npm run dev` -2. Select "Debug in Chrome" and press `F5` -3. Set breakpoints in React components (`.tsx` files) -4. Breakpoints pause execution in Chrome with VSCode controls - -**Commit:** `config: add VSCode debugging configuration` - ---- - -## Commit Message Format - -``` -: - -[Command: ] -[- Additional context bullet points] -``` - -**Types:** - -- `feat` - New feature -- `fix` - Bug fix -- `build` - Dependency changes -- `config` - Configuration changes -- `docs` - Documentation -- `chore` - Maintenance - -**Examples:** - -``` -feat: initialize Vite project with React + TypeScript - -Command: npm create vite@latest . -- --template react-ts && npm install -``` - -``` -config: configure Tailwind CSS and TypeScript path aliases - -Command: npm install -D @types/node -- Updated src/index.css with Tailwind import -- Added baseUrl and paths to tsconfig.json and tsconfig.app.json -- Updated vite.config.ts with tailwindcss plugin and path aliases -``` - ---- - -## Common Issues - -### TypeScript Path Alias Errors - -Ensure `baseUrl` and `paths` are in BOTH `tsconfig.json` and `tsconfig.app.json`. - -### Unused Variable Errors - -TypeScript is strict by default. Use `_varName` prefix for intentionally unused variables. - -### React Router Import Errors - -Use `react-router` not `react-router-dom` for v7. - -### Tailwind Classes Not Working - -Ensure `@import "tailwindcss";` is at the top of `index.css`. - -### shadcn Components Not Styled - -The `index.css` must have the CSS variables that `npx shadcn init` adds. - ---- - -## shadcn/ui Component Reference - -Common components to add: - -```bash -npx shadcn@latest add button card sidebar collapsible dropdown-menu avatar separator sheet tooltip input skeleton badge tabs dialog alert -``` - -Search for components and get examples using the bundled MCP tools. See [mcp-tools.md](mcp-tools.md) for usage details. diff --git a/.agents/skills/gitsheets/SKILL.md b/.agents/skills/gitsheets/SKILL.md new file mode 100644 index 00000000..a6f76c80 --- /dev/null +++ b/.agents/skills/gitsheets/SKILL.md @@ -0,0 +1,87 @@ +--- +name: gitsheets +description: Use this skill whenever the user is working with `gitsheets` — the git-backed document store on npm. Trigger on mentions of `gitsheets`, `.gitsheets/.toml` configs, sheet path templates with `${{ field }}` syntax, content-typed records (markdown with TOML frontmatter), the `git sheet` / `gitsheets` CLI, `openRepo` / `openSheet` / `openStore` / `repo.transact` API calls, or push-daemon setup. Also trigger when the user shows a TOML record file, asks about validating records with JSON Schema layered with Zod/Valibot, mentions canonical TOML normalization, or asks how to model document-style records (blog posts, knowledge bases) in a git repo. Reach for this skill *before* improvising — gitsheets has a specific API shape and config grammar that's easy to get subtly wrong. +--- + +# gitsheets + +`gitsheets` is a git-backed document store for low-volume, high-touch, human-scale data. Records are TOML files in a git repo (one record per file); the library provides typed reads/writes, validation, transactions, and async push-to-remote. Records can also be **content-typed** (markdown with TOML frontmatter) for documents-as-records. + +This skill helps you assist a developer who consumes the published `gitsheets` package — writing TypeScript that calls the library, authoring `.gitsheets/.toml` configs, using the `gitsheets` CLI. + +## Routing + +Four reference files cover the surface. Read the relevant one(s) for the user's question: + +| User is asking about… | Read | +| --- | --- | +| The `gitsheets` / `git sheet` CLI (commands, flags, exit codes) | `references/cli.md` | +| The TypeScript API (`openRepo`, `Sheet`, `Transaction`, `Store`, push daemon, errors) | `references/api.md` | +| Authoring `.gitsheets/.toml` configs (path template, **date-bucket partitioning**, schema, fields, format, indices) | `references/sheet-config.md` | +| The **agent-facing** `gitsheets-axi` CLI (TOON output, idempotent mutations, session hooks) | `references/axi.md` | + +If unsure or the question spans multiple surfaces, read all four. They're sized to fit comfortably in context together. + +If the user is working *inside an agent session* and wants to read/mutate gitsheets data via shell, prefer `gitsheets-axi` (`references/axi.md`). If they're writing application code, prefer the library API. If they're authoring configs or asking conceptual questions, sheet-config or api references are right. + +**Bootstrapping the CLI.** `gitsheets-axi` may not be on `PATH` in a fresh environment where only this skill is installed — that's fine. Run it with no install via `npx -y gitsheets-axi ` (e.g. `npx -y gitsheets-axi query users`), or `npm install -g gitsheets-axi` once for a persistent command. Check with `command -v gitsheets-axi`. The human `gitsheets` CLI bootstraps the same way (`npx -y gitsheets …`). So "just install the skill" is a complete starting point — the tools are one `npx` away. + +## Always-true facts + +These don't change between releases and are worth keeping in mind regardless of the user's question: + +- **TypeScript, ESM-only.** `import { ... } from 'gitsheets'` — no CJS `require`. Targets Node ≥ 20 or Bun ≥ 1. +- **Rust-core engine (v2+).** Since v2.0.0 the engine (TOML, normalization, path templates, validation, query, markdown, the whole state machine) is a shared Rust core, shipped as a prebuilt addon (`@gitsheets/core-napi`) for Linux/macOS/Windows — a plain `npm install gitsheets` needs no Rust toolchain. The same core backs a Python binding, so writes are byte-identical across languages. The JS API is unchanged from v1; the one migration is a one-time canonical re-baseline of on-disk bytes (re-normalize with `git sheet normalize`). +- **One record = one file.** Records are individual TOML (or markdown-with-frontmatter) files; the sheet's `path` template renders the filename from record fields. The whole sheet's set of records lives under a per-sheet `root`. +- **Validation is on writes only.** Reads return whatever's on disk. If a schema was tightened after some records were written, those reads can return records that wouldn't pass current validation. +- **Canonical normalization is deterministic.** Object keys are deep-sorted on write; array fields can declare a `sort` rule. Logically-equal records produce byte-identical TOML, so git diffs are meaningful. +- **Mutations go through transactions.** `repo.transact(opts, async tx => …)` is the explicit path. Outside a transaction, standalone Sheet methods (`upsert`, `delete`, `patch`) auto-open one — unless the consumer called `repo.requireExplicitTransactions()`, in which case they throw. +- **Writes land in the git ref, not the working tree — so keep records off the checked-out branch.** gitsheets commits records via git plumbing directly to a ref; it never updates checked-out files. When the records sit on the branch you check out, every write leaves the working tree behind (`git status` shows them *deleted* or *modified* — not data loss). The fix is a **headless layout**: an orphan data branch (`git config gitsheets.branch data`, or `--branch` / `openRepo({ branch })`; start it with `git sheet init --commit --branch data`), a bare data clone (`gitDir`), or a **data submodule** (`git sheet submodule init data --url …`, then `gitsheets.submodule` / `--submodule` / `openRepo({ submodule })`) whose `HEAD` is the code repo's pointer to a data snapshot — each write shows up as `modified: data (new commits)` and the user commits the pointer with their code. Only for records that must stay on the code branch, `git checkout HEAD -- .` refreshes the files after a write. See `docs/recipes/headless-data.md`. +- **Sheet configs are read from the committed tree.** A freshly-authored `.gitsheets/.toml` is invisible to record commands until it's committed. Commit the config first, then upsert/query. +- **The push daemon is push-only; `repo.sync()` is the explicit reverse path.** The daemon (`repo.startPushDaemon`) pushes new commits with retry/backoff and never pulls. To take in commits other writers pushed, call `repo.sync()` (v2.8+) when *you* decide — boot, webhook, timer: it fetches, then fast-forwards / replays your commits / escapes a conflict to a `conflicts/` branch, under the write lock. +- **A record carries every field needed to render its path.** Every static path-template field is a `required` schema field (v2.8+ enforces this at `openSheet`; there is no exemption list). Never suggest injecting or stripping path fields in consumer code — put them on the record and in the schema; a child keyed by its parent's handle references the parent through that field. +- **A sheet can be opened read-only at any ref** (`openSheet(name, { ref })`, `openStore(repo, { ref })`, v2.8+) for operator reads of another branch; it never auto-refreshes and rejects writes. Two branches of a data repo merge **record by record** with `repo.merge` / `git sheet merge` (or the `git sheet merge-driver` behind a plain `git merge`), never with a bare `git merge` of TOML text. +- **All gitsheets errors extend `GitsheetsError`** and carry a stable `code` field. Consumers switch on `instanceof` or `err.code`, never on `err.message`. The error classes are: `ConfigError`, `ValidationError`, `TransactionError`, `IndexError`, `RefError`, `PathTemplateError`, `NotFoundError`. + +## Common patterns to recommend + +When the user is building something, these idioms are usually the right shape: + +- **Typed sheets**: combine `openStore(repo, { validators: { users: UserSchema } })` (Standard Schema — Zod / Valibot / ArkType) with a `[gitsheet.schema]` block in the sheet config. The Zod schema flows TS types; the persisted JSON Schema is the on-repo contract. +- **Per-request transactions** in HTTP handlers: open one `repo.transact` per request with the user's identity in `author` + structured `trailers`. Errors thrown from the handler discard the transaction. +- **Date-partitioned sheets**: anything time-series-ish (posts, events, logs, daily rollups) should partition by a declarative **date bucket** in the path template — `path = '${{ publishedAt: YYYY/MM/DD }}/${{ slug }}'` (also `YYYY/MM`, `YYYY`, `YYYY/WW`). It's UTC-safe by construction, and it's what makes **range queries** cheap: `queryAll({ publishedAt: { $gte: '2026-01-01', $lt: '2026-04-01' } })` (or `gitsheets-axi query posts --filter 'publishedAt>=2026-01-01'`) walks only the partitions inside the bounds. See `references/sheet-config.md` → "Date-bucket partitioning" and `references/api.md` → "Range filters". +- **Bulk reads + lazy bodies**: on content-typed (markdown) sheets, pass `{ withBody: false }` to `query` for listing/filtering, then `await sheet.loadBody(record)` when the body is actually needed. +- **Secondary indices**: `sheet.defineIndex('byEmail', { unique: true }, r => r.email.toLowerCase())`. Built lazily on first `findByIndex` call; rebuilt when the underlying tree hash changes. For markdown sheets, index builds always use body-less reads — don't index on body content (returns `undefined` → record excluded). +- **CSV import**: `gitsheets upsert records.csv --format=csv` — first row is the header, each subsequent row becomes one record. Cell values stay strings; type coercion belongs in the schema. +- **Bulk ingest a databank**: build a JSON array or NDJSON stream with `jq` (never hand-serialize TOML), then pipe it into **one** `upsert` — `jq -c '.[]' raw.json | gitsheets-axi upsert repos`. The whole batch commits once. To reshape existing data, `gitsheets-axi query --ndjson-out`, transform the file, and pipe it back in (exports round-trip verbatim). See `references/axi.md` → "Bulk data engineering". +- **Classify / update in bulk**: use bulk `gitsheets-axi patch` (array/NDJSON of `{, }` → one commit, merge-not-replace), not `upsert` (which replaces whole records). `--on-missing skip|insert` tolerates or inserts stale rows; `--dry-run` previews; `--delete-missing` makes the sheet exactly match a source. +- **Review / audit without `jq`**: `gitsheets-axi count --filter …` for totals, `query --group-by ` for distributions, `distinct ` for the value set, `aggregate --agg total=sum:f --agg lo=min:f [--group-by g]` for sums / extremes / averages. In code, `sheet.aggregate(filter, { total: { sum: 'f' }, … })` folds in the core instead of `queryAll` + a JS reduce (see `references/api.md` → "Aggregation"). The `--filter` DSL does comparison / `!=` / `in()` / regex / `:present` / `:empty`, not just equality — and comparisons on a date-bucket path field prune the walk instead of scanning. +- **Totals asked over and over** (a monthly sum on every dashboard load, totals you want in `git diff`): declare a **rollup sheet** (`[gitsheet.rollup]`, see `references/sheet-config.md`) instead of re-aggregating — gitsheets commits per-partition aggregates alongside the records, stamped so reads stay correct. Rollup sheets are read-only; repair after a plain `git merge` with `git sheet rollup ` (`--check` in CI). + +## Anti-patterns to redirect + +If the user is heading toward one of these, gently steer them back: + +- **Treating `Sheet` like a SQL table.** Records are *files* with structured filenames. Path templates uniquely identify a record by its fields; there's no surrogate primary key. If the user wants a stable identifier, design it into the path template. +- **Hand-rolling date partitions with expressions** (`${{ publishedAt.getUTCFullYear() }}/${{ String(publishedAt.getUTCMonth() + 1).padStart(2, '0') }}/…`). Use `${{ publishedAt: YYYY/MM }}` instead: shorter, timezone-safe, and the only form whose range queries prune. Likewise, don't fetch `queryAll({})` and filter dates in consumer code on a partitioned sheet — pass a `{ $gte, $lt }` range so the walk skips the other partitions. +- **Stuffing huge text bodies into a TOML field** when they actually want a markdown document. Switch to content-typed records (`[gitsheet.format] type = 'markdown'`) so the body is a proper file with editor affordances. +- **Indexing on body content.** Indexes always build with body-less reads on markdown sheets — `keyFn(record).body` is `undefined`. Index on frontmatter fields. +- **Shelling out to `git pull` / `fetch` + `update-ref` around gitsheets** to take in another writer's commits. Use `repo.sync({ onConflict })` (v2.8+): it runs under gitsheets' own write lock, replays without a working tree, rebinds live sheets, and reports a structured outcome instead of leaving a half-moved ref. +- **Using `Sheet.upsert(partial)` to update a single field.** `upsert` is a full-record replace. To mutate fields without overwriting the rest, use `sheet.patch(query, partial)` (RFC 7396 — `null` deletes a field, arrays replace). +- **Updating existing records with `upsert` in bulk.** `upsert` replaces the whole record, so a bulk update must re-send every field or silently drop the rest. For updating fields across many records (classifying, tagging, backfilling), use **bulk `gitsheets-axi patch`** (array / NDJSON of combined records → one commit, merge semantics) — emit only the fields you're setting. +- **Looping `upsert` (or `patch`) once per record for a bulk job.** That produces one commit per record (hundreds of junk commits). Both `upsert` and `patch` autodetect a JSON array or NDJSON and process the whole batch in a single commit — pass the stream, don't loop. +- **Merging data branches with a plain `git merge`** (or resolving thousands of delete/modify conflicts by hand with `checkout --theirs`). Line-wise merges leave a mix of serializations; use `git sheet merge [--prefer ours|theirs]` / `repo.merge()` (v2.8+), or install the merge driver so `git merge` does it. +- **"Injecting" a path field in the service right before upsert** (a tenant key, a parent slug the record "doesn't need"). The field belongs on the record and in the schema's `required` — gitsheets refuses to open a sheet whose template names a non-required field, and there is no exemption list (`injectedFields` was removed in 2.9.0). +- **Hand-serializing TOML to write records.** Never build TOML strings (or reach for a TOML library) to produce records. gitsheets owns serialization, key-sorting, canonical form, and validation. Produce JSON and let `upsert` write the bytes. + +## Editing record files directly (post-edit hook) + +If you're going to edit gitsheets record files (`.toml` or `.md`) directly on disk rather than through the API, install a post-edit hook that runs `gitsheets-axi check $FILE --fix` after each edit. This re-canonicalizes the file (deep-sorted keys, normalized markdown body) and validates against the sheet's schema, catching mistakes immediately rather than at the next git commit. Hook examples in `references/axi.md`. + +`gitsheets-axi` is preferred for hook use because its output is TOON on stdout with stable error codes (`VALIDATION_FAILED`, `CONFIG_INVALID`, `NOT_CANONICAL`, etc.) — an agent reading the hook's stdout can switch on the outcome. If it isn't installed, install it (`npm install -g gitsheets-axi`) — a `npx -y` prefix isn't a good fit inside a per-edit hook that fires constantly, so a real install is worth it here. The human `gitsheets check` (`references/cli.md`) is an equivalent fallback when a global install isn't possible. + +For CI / pre-commit verification, drop the `--fix`: `gitsheets-axi check $FILE` exits non-zero if the file isn't already canonical, without touching it. + +## When you genuinely don't know + +If the user asks something this skill doesn't cover (an obscure edge case, a behavior across releases, internal mechanics), say so and recommend they check [the gitsheets specs](https://github.com/JarvusInnovations/gitsheets/tree/develop/specs) or [docs site](https://jarvusinnovations.github.io/gitsheets/). Don't guess at API shapes. diff --git a/.agents/skills/gitsheets/evals/evals.json b/.agents/skills/gitsheets/evals/evals.json new file mode 100644 index 00000000..5f4eed98 --- /dev/null +++ b/.agents/skills/gitsheets/evals/evals.json @@ -0,0 +1,53 @@ +{ + "skill_name": "gitsheets", + "evals": [ + { + "id": 1, + "name": "design-a-blog-cms-sheet-config", + "prompt": "I'm building a small blog with gitsheets. Posts have a slug, title, publish date, tags array, and a long markdown body. Slugs are kebab-case, tags should be deduplicated and alphabetized on save, and the publish date should validate as ISO-8601. Write me the `.gitsheets/posts.toml` config. Also: I want the files on disk to be `.md` with frontmatter so I can edit them in VS Code with the markdown preview, and I want listing pages (which only show the title + date) to be fast \u2014 don't load the body unless needed.\n\nAlongside the config, write a short TypeScript snippet showing: (a) opening the sheet via `openStore` with a Zod validator, (b) the listing-page query (no body), and (c) loading a single post for the article page (with body).", + "expected_output": "A working .gitsheets/posts.toml (with [gitsheet.format] type='markdown' body='body', [gitsheet.fields.tags.sort], [gitsheet.schema] requiring slug/title/publishedAt with format='date-time') plus a TypeScript snippet using openStore + Zod, query({}, {withBody:false}) for listing, and loadBody() or default-withBody query for single article.", + "files": [] + }, + { + "id": 2, + "name": "fastify-handler-with-validation", + "prompt": "I have a Fastify HTTP handler that needs to create a new user in gitsheets and return the new user's slug. The user is validated against a Zod schema. The commit message should include the request ID as a trailer, and use the authenticated user's email as the author. If validation fails, return 422 with the issues; if anything else fails, return 500.\n\nWrite the handler. Assume `repo` is already opened via `openRepo`, `UserSchema` is already imported, and `request.user` and `request.id` are available. Don't write the Fastify boilerplate \u2014 just the handler body.", + "expected_output": "A handler that calls openStore (or assumes store is available) with the Zod validator threaded in, uses store.transact (or repo.transact + tx.sheet) with author + trailers from the request, catches ValidationError (instanceof or by err.code === 'validation_failed') to return 422 with err.issues, lets other errors bubble. Should NOT use repo.transact then a separate sheet.upsert outside the transaction.", + "files": [] + }, + { + "id": 3, + "name": "post-edit-hook-setup", + "prompt": "I'm letting an AI agent (Claude Code) edit gitsheets record files directly in my repo. The agent edits .md files under `content/posts/` (a markdown sheet) and .toml files under `data/users/` (a TOML sheet). I want a post-edit hook that runs after each agent edit and either auto-fixes the canonical form or flags a validation error. How do I wire that up? What command(s) do I run, and how do I structure the hook so it knows which sheet a given file belongs to?", + "expected_output": "Should recommend `gitsheets check $FILE --fix` as the post-edit command, explain that the sheet name has to be known per path prefix (sheets are addressed by name, not auto-detected), give a settings.json or hook-script example that maps a path glob to the right sheet name, and note that exit 22 indicates ValidationError, exit 64 indicates parse failure. Should also distinguish --fix mode (auto-rewrite) from no-fix CI verification mode.", + "files": [] + }, + { + "id": 4, + "name": "diff-from-feature-branch", + "prompt": "I want to write a TypeScript function that takes two commit hashes and produces a human-readable change summary for one sheet \u2014 showing which records were added, modified, deleted, and (for modified ones) which fields changed. I want this for a code review tool that shows what changed in a feature branch's data updates. The sheet is called 'users'.", + "expected_output": "Should use sheet.diffFrom(srcCommitHash, {records: true, patches: true}), iterate over the async generator, group by change.status, and for 'modified' entries use change.patch (RFC 6902 ops) to enumerate field-level changes. Should NOT try to manually compare two sets of records.", + "files": [] + }, + { + "id": 5, + "name": "upsert-vs-patch-confusion", + "prompt": "I have a record like `{slug: 'jane', email: 'jane@x.org', team: 'eng', joined: '2024-01-01'}`. I want to update just the team to 'design' without touching the other fields. I tried `await sheet.upsert({slug: 'jane', team: 'design'})` and it wiped out email and joined! What am I doing wrong?", + "expected_output": "Should explain that upsert is a full-record replace by design \u2014 it's not a partial update. The fix is sheet.patch({slug: 'jane'}, {team: 'design'}) which uses RFC 7396 merge semantics: only the keys in the partial override; other fields are preserved. Should also note that null in the partial deletes that field (RFC 7396 semantics).", + "files": [] + }, + { + "id": 6, + "name": "partition-events-by-date-and-range-query", + "prompt": "We have an `events` sheet with a few thousand records: each has an `id`, an `occurredAt` datetime, a `kind`, and a short `summary`. Queries like \"everything from the last 30 days\" and \"all events in March 2026\" currently load the whole sheet and filter in JS, which is slow. Rewrite the `.gitsheets/events.toml` config so the records are partitioned by day on disk, then show (a) the TypeScript query for a date range that only reads the partitions it needs, (b) the equivalent `gitsheets-axi` one-liner an agent would run, and (c) a `count` of events since the start of the year. Call out any gotchas with timezones.", + "expected_output": "Config uses the declarative date-bucket path form (e.g. `path = '${{ occurredAt: YYYY/MM/DD }}/${{ id }}'`) rather than a JS expression, with a date-time schema on occurredAt. (a) uses a range filter object (`{ occurredAt: { $gte: '...', $lt: '...' } }` with ISO strings or Dates) on queryAll; (b) uses `gitsheets-axi query events --filter 'occurredAt>=YYYY-MM-DD' --filter 'occurredAt`; `at` with no pointer is `RefError(ref_not_found)`, and writes on an `at`-bound repo are `TransactionError(transaction_required)`. A `stagePointer` index update that fails after the commit landed is `TransactionError(pointer_stage_failed)` with `err.commitHash` — stage with `git add `, never retry the write. + +Backed by the Rust core's git repository discovery (gix). Fresh-but-initialized repositories (no commits yet) are supported. + +## Repository + +| Method | Purpose | +| --- | --- | +| `repo.openSheet(name, opts?)` | Sheet handle; `opts.validator` (Standard Schema), `opts.root`, `opts.prefix`, `opts.ref` (v2.8+: pin reads to a branch/tag/commit — read-only, never auto-refreshed; `sheet.refresh()` re-resolves the ref; writes throw `TransactionError(transaction_required)` — write via `repo.transact({ parent: ref })`) | +| `repo.openSheets(opts?)` | `Record` of every sheet declared under `.gitsheets/`; `opts.ref` pins them all | +| `repo.transact(opts, handler)` | Single-commit transaction; see below | +| `repo.requireExplicitTransactions()` | One-way strict-mode switch — standalone Sheet writes throw | +| `repo.startPushDaemon(opts)` | Start async push to a remote (returns `PushDaemon`) | +| `repo.resolveRef(ref)` | `Promise` — resolve a ref or commit hash | +| `repo.readBlob(ref, path)` | `Promise` (v2.8+) — the blob at `:` resolved now: `hash`, `size`, `read()`, `stream()`; `RefError` / `NotFoundError` | +| `repo.readBlobStream(ref, path)` | `Promise` — `readBlob(…).stream()` | +| `repo.sync(opts?)` | `Promise` (v2.8+) — fetch + fast-forward / replay / preserve-on-conflict under the write lock; see PushDaemon section | +| `repo.fetch(opts?)` | (v2.11+) sync's fetch step alone, outside any lock → `{ ok: true, remoteRef, remoteCommit }` or `{ ok: false, remoteRef, error }`; pair with `sync({ fetch: false })` | +| `repo.isAncestor(a, b)` | `Promise` (v2.8+) — is commit `a` reachable from `b` | +| `repo.tag(name, target?, { force? })` | (v2.11+) lightweight tag in-core; existing tag refused unless `force` — use instead of shelling out to `git tag -f` | +| `repo.listTree(ref, path?)` | (v2.11+) direct entries `{ name, type, mode, hash }` at `:` or `null` — use instead of `git ls-tree` | +| `repo.merge({ theirs, ours?, prefer?, commit?, message? })` | `Promise` (v2.8+) — sheet-aware merge: records changed on both sides are field-merged and written canonically; `prefer: 'fail'` (default) reports conflicts in `result.conflicts` with nothing written, `'ours'` / `'theirs'` resolves field, delete/modify and blob conflicts; `commit: false` = dry run. Outcomes `up-to-date` · `fast-forward` · `merged` · `conflict` · `dry-run` | + +### `repo.transact` + +```typescript +const result = await repo.transact( + { + parent: 'main', // ref or commit hash; default HEAD + author: { name: 'Jane', email: 'jane@x.org' }, + committer: { name: 'Jane', email: 'jane@x.org' }, // default: author + message: 'janedoe: POST /api/users', + trailers: { 'X-Request-Id': 'req-123' }, // appended per git-interpret-trailers + branch: 'refs/heads/main', // ref to advance on success + }, + async (tx: Transaction) => { + await tx.sheet('users').upsert({ slug: 'janedoe', email: 'jane@x.org' }); + return { ok: true }; + } +); +// result: { value: { ok: true }, commitHash, treeHash, ref, parentCommitHash } +``` + +**Commit-on-success-only.** If the handler stages no mutations, the transaction does *not* commit — `commitHash`, `treeHash`, `ref` are `null` and the parent ref is unchanged. Throws from the handler discard the staged tree. + +Trailer keys follow HTTP-style casing (`Some-Header`). + +## Sheet + +`Sheet`. With a validator (via `openSheet({ validator })` or `openStore`), `T` flows through every method signature. + +### Reading + +```typescript +for await (const user of sheet.query({ accountLevel: 'staff' })) { … } +const jane = await sheet.queryFirst({ slug: 'jane' }); +const all = await sheet.queryAll(); +``` + +| Method | Returns | Notes | +| --- | --- | --- | +| `sheet.query(filter?, opts?)` | `AsyncGenerator` | `opts.signal` (AbortSignal), `opts.withBody` (content-typed sheets) | +| `sheet.queryFirst(filter?, opts?)` | `Promise` | Same opts | +| `sheet.queryAll(filter?, opts?)` | `Promise` | Same opts | +| `sheet.count(filter?)` | `Promise` | Cheap count (walks candidate paths, no parse) when unfiltered; a filter falls back to a body-less scan | +| `sheet.get(path, opts?)` | `Promise` | One record by its rendered path — one blob read, no scan; `opts.withBody`; tx-bound reads the private tree. The primitive behind "read one record" | +| `sheet.loadBody(record)` | `Promise` | Hydrate a body-less record (markdown sheets); no-op on TOML sheets | +| `sheet.pathForRecord(record)` | `Promise` | Render the path template; doesn't write | +| `sheet.normalizeRecord(record)` | `Promise` | Canonical form (deep-sort keys, array sort rules); doesn't write/validate | + +**Filters.** A filter is a plain object; every entry must hold (AND). Per field, the value is one of: + +| Entry | Meaning | +| --- | --- | +| literal (`'staff'`, `42`, `true`, a `Date`) | strict equality (`Date`s compare by instant) | +| `(value, record) => boolean` | predicate — opaque to pruning | +| plain object | nested-table filter, descends recursively | +| `{ $gt?, $gte?, $lt?, $lte? }` | **range** — see below (v2.7+) | + +Filters that reference path-template fields prune the tree walk (see `sheet-config.md` → "How queries use the template"); predicates and most other entries filter record-level after the walk. + +**Range filters** (`RangeFilter`): any combination of the four bounds, at least one. Comparison is by kind — numbers numerically (int and float interchangeably), strings lexicographically, `Date`s as instants — and a `Date` field also accepts an **ISO 8601 string bound** (`'2026-01-01'`, `'2026-01-01T00:00:00Z'`), so you rarely need to construct a `Date`. Mismatched kinds (a string bound against a number field, an absent field) never match. A `$`-keyed object outside this vocabulary, or mixing `$gte` with ordinary keys, or giving both `$gt` and `$gte`, throws `TypeError` at query start. `$in` / `$or` don't exist — use a predicate or filter in consumer code. + +```typescript +// template '${{ publishedAt: YYYY/MM/DD }}/${{ slug }}' — walks only the 2025/11/20 … 2026/02/03 partitions +const q1 = await posts.queryAll({ publishedAt: { $gte: '2025-11-20', $lt: '2026-02-03' } }); +const recent = await posts.queryAll({ publishedAt: { $gt: new Date('2026-01-01T00:00:00Z') } }); // one-sided +const adults = await users.queryAll({ age: { $gte: 18, $lt: 65 } }); // numeric, record-level +const n = await posts.count({ publishedAt: { $gte: '2026-01-01' } }); // count honors it too +``` + +On a **date-bucket** path field (`${{ field: YYYY/MM/DD }}` etc.) a range prunes the walk to the bounded span of partitions — pruning is inclusive at the day/month/year level and the record-level comparison applies the exact `$gt` / `$lt` cutoff, so results equal a full scan, just far cheaper. On any other field a range is record-level only. Typed sheets: `RangeFilter` admits string bounds, `RangeFilter` doesn't. + +AbortSignal: throws `signal.reason` on the next yield boundary. Filters that reference the body field under `withBody: false` throw `TypeError` at query start. + +### Writing + +```typescript +await sheet.upsert({ slug: 'jane', email: 'jane@x.org' }); +await sheet.delete({ slug: 'jane' }); // by record +await sheet.delete('users/jane'); // by path +await sheet.patch({ slug: 'jane' }, { email: 'new@x.org', bio: null }); +await sheet.clear(); // remove all records +const cloned = await sheet.clone(); // staging copy +``` + +| Method | Purpose | +| --- | --- | +| `sheet.upsert(record, opts?)` | Insert or replace; returns `{ blob, path }`. `opts.allowMissingBody` for markdown sheets — only for an absent/`undefined` body; an explicit `null` body is accepted as-is and written empty (v2.8+). | +| `sheet.delete(recordOrPath)` | Remove a record + cascade attachment directory | +| `sheet.patch(query, partial)` | RFC 7396 merge: `null` deletes a field, arrays replace, objects merge | +| `sheet.clear()` | Wipe the sheet's tree | +| `sheet.clone()` | Deep-clone the Sheet handle (for staged comparisons) | + +**Important:** `upsert` is a full-record replace. Use `patch` for partial updates. + +All writes route through the current transaction (auto-opened in permissive mode; required-explicit in strict mode). + +### Attachments + +Binary blobs colocated with a record at `/`. + +```typescript +const blob = await repo.writeBlobFromFile('/path/to/avatar.jpg'); +await sheet.setAttachment(record, 'avatar.jpg', blob); +await sheet.setAttachments(record, { 'avatar.jpg': blob, 'cover.png': otherBlob }); + +const blob = await sheet.getAttachment(record, 'avatar.jpg'); +const map = await sheet.getAttachments(record); // Map of name → BlobHandle { hash, size, read(), stream() } (size + stream() v2.8+) + +await sheet.deleteAttachment(record, 'avatar.jpg'); // throws if missing +await sheet.deleteAttachments(record); // no-op if no attachment dir + +for await (const { name, mimeType, blob } of sheet.attachments(record)) { + const buf = await blob.read(); // Buffer + // or pipe blob.stream() — Readable backed by `git cat-file blob ` +} +``` + +`AttachmentEntry.mimeType` is inferred from the extension; defaults to `application/octet-stream`. + +Cascade-on-delete: `sheet.delete(record)` removes the record's attachment directory in the same operation. + +### Indexing + +In-memory secondary indices. + +```typescript +sheet.defineIndex( + 'byEmail', + { unique: true, eager: false }, // opts: defaults shown + (record) => record.email.toLowerCase() +); + +sheet.defineIndex( + 'byProjectStatus', + (record) => `${record.projectId}:${record.status}`, // non-unique by default +); + +await sheet.defineIndex('byTag', { eager: true }, fn); // returns Promise + +const jane = await sheet.findByIndex('byEmail', 'jane@x.org'); // T | undefined (unique) +const open = await sheet.findByIndex('byProjectStatus', 'p1:open'); // T[] (non-unique) +``` + +- `keyFn` returns `undefined`/`null` → exclude from index +- `eager: true` builds at definition time (returns Promise); `false` (default) builds lazily on first `findByIndex` +- Indexes rebuild when the underlying tree hash changes +- **For markdown sheets**: index builds always use body-less reads. A `keyFn` referencing `record.body` sees `undefined`. Don't index on body content; index on frontmatter fields. `findByIndex` returns body-less records — `sheet.loadBody(record)` to hydrate. + +### Diff + +```typescript +for await (const change of sheet.diffFrom('HEAD~1', { records: true, patches: true })) { + // change.path — relative to sheet root, no extension + // change.status — 'added' | 'modified' | 'deleted' | 'renamed' + // change.srcMode / dstMode — git modes (null on add/delete) + // change.srcHash / dstHash — blob hashes (null on add/delete) + // change.src / dst — parsed records (records: true) + // change.patch — RFC 6902 ops (patches: true) + // change.srcBlob / dstBlob — gitsheets BlobHandle handles (blobs: true) +} +``` + +`srcCommitHash` accepts a commit hash, tree hash, or ref name. Omitted → defaults to the empty tree (every current record yields `status: 'added'`). + +Scope: matches the sheet's storage format (`.toml` for TOML sheets, `.md` for markdown). Attachment-blob diffs are out of scope. + +Throws `RefError(ref_not_found)` if `srcCommitHash` doesn't resolve. + +### Aggregation + +`sheet.aggregate(filter, aggregates, opts?)` → `Promise>`. Reach for it instead of `queryAll` + a JS reduce: the fold runs in the core (identical across Node and Python), reads body-less, and folds in canonical path order. + +```typescript +const r = await sheet.aggregate( + { postedAt: { $gte: '2026-01-01' } }, // any query filter (functions allowed); undefined or {} = all + { + n: { count: true }, + total: { sum: 'amountCents' }, // integer when every value is; else the float fold + mean: { avg: 'amountCents' }, // float + range: { min: 'postedAt' }, // number / string / datetime, one kind per field + teams: { distinct: 'team' }, // sorted unique scalars + byStatus: { count: true, groupBy: 'status' }, // → { posted: 1390, pending: 12 } + refunds: { sum: 'amountCents', where: { kind: 'refund' } }, + ids: { reduce: 'acc.push(record.id); return acc;', initial: [], finalize: 'return acc.length;' }, + }, +); +``` + +- `where` takes values and ranges only (no functions). `groupBy` keys by the field's string form (string / integer / boolean values only); a grouped result is always an object. +- Nothing to fold → the aggregate is omitted, except `count` / `sum` (`0`). +- `reduce` / `finalize` are JS **bodies** (use `return`), run in the core's embedded engine — pure by construction: `Math.random()`, `Date.now()`, and argument-less `new Date()` / `Date()` throw → `AggregationError` (`new Date(ms)`, `Date.UTC`, `Date.parse` work; local-time methods read UTC); runaway loops hit runtime limits → `AggregationError`. `acc` starts at `initial` (required). Integral numbers come back as integers (`1.0` → `1`). +- Throws `TypeError` for a malformed spec or a body-field reference (markdown sheets); `AggregationError` (`aggregation_failed`, `.sheet`, `.aggregate`) for mixed kinds under `min`/`max`/`distinct`, a throwing `reduce`, or a non-TOML result. + +### Rollup sheets + +A sheet config with `[gitsheet.rollup]` is a **rollup sheet**: one record per partition of a source sheet, regenerated by every gitsheets commit that touches the partition (same commit), stamped `sourceTree = ` + `configTree = <.gitsheets/ tree id>` (fresh only while both match). + +```toml +[gitsheet] +root = 'transactions-monthly' +path = '${{ postedAt: YYYY/MM }}' # proper prefix of the source path; 'all' = whole sheet + +[gitsheet.rollup] +from = 'transactions' + +[gitsheet.rollup.aggregates] +count = { count = true } +total = { sum = 'amountCents' } +``` + +```typescript +const monthly = await repo.openSheet('transactions-monthly'); +await monthly.queryAll({ postedAt: { $gte: '2026-01-01' } }); // read-through: stale partitions recomputed, nothing written +await monthly.get('2026/03', { stale: 'serve' }); // the stored record as committed +await monthly.materialize(); // → { recomputed, deleted }; one commit, none when fresh +``` + +- Records carry the key fields (a bucket → the period's first day as a TOML local date; equality accepts `'2026-03-01'` or a midnight-UTC `Date`), `sourceTree`, `configTree`, and one field per aggregate. `aggregate()` on a rollup sheet folds the read-through. Prefixed sources → per-prefix rollups at `//…`. +- Writes (`upsert`/`delete`/`patch`/`clear`/attachments) → `TransactionError('sheet_derived')`. Bad config (not a prefix, expression component, overlapping roots, a chain, …) → `ConfigError('config_invalid')` at open. +- An aggregate failure aborts the commit: `AggregationError` with `.sheet`, `.aggregate`, `.partition`. +- `repo.merge` and `repo.sync` regenerate them; a plain `git merge` leaves stale stamps → `git sheet rollup [--check]`. + +## Transaction + +The handler argument of `repo.transact`. Don't construct directly. + +```typescript +tx.sheet(name, opts?) // sheet bound to the tx's tree (opts: validator, prefix) +tx.parentCommitHash // may be null on fresh repos and orphan commits +tx.parentRef // ref the tx is reading from +tx.branchRef // ref the tx will advance on commit +tx.writeFile(path, content) // raw file (string → UTF-8, or Buffer/Uint8Array) at a repo-root-relative path → BlobHandle (v2.8+) +tx.deleteFile(path) // → boolean: did a blob exist there (v2.8+) +``` + +Writes inside the handler are atomic; throws from the handler discard the staged tree. Nested `repo.transact` throws `TransactionError(transaction_in_progress)`. + +`writeFile` / `deleteFile` are for non-record files that belong in the same commit — a `.gitsheets/.toml`, a vendored contract, a fixture, a README. Nothing is validated or normalized; use `tx.sheet(name)` for records. + +**Orphan commits and new branches (v2.8+).** `repo.transact({ parent: null, branch: 'snapshot' }, …)` starts from the empty tree and commits with no parents (always, even if the handler stages nothing); the branch is created and must not already exist (`TransactionError(commit_failed)` at open). Without `branch` the result is a detached root (`ref: null`). Separately, `branch` may name a branch that does not exist yet: `transact({ parent: 'main', branch: 'review/x' }, …)` forks it from `main` in one call. + +## openStore + Store + +Typed wrapper over `Repository.openSheets()` that binds per-sheet Standard Schema validators. + +```typescript +import { openStore } from 'gitsheets'; +import { z } from 'zod'; + +const UserSchema = z.object({ slug: z.string(), email: z.string().email() }); +const ProjectSchema = z.object({ id: z.string(), name: z.string() }); + +const store = await openStore(repo, { + validators: { users: UserSchema, projects: ProjectSchema }, + // ref: 'published', // v2.8+: read-only store pinned at a ref; store.refresh() re-resolves it +}); + +// Each named sheet is Sheet>: +const jane = await store.users.queryFirst({ slug: 'jane' }); +// jane is typed as z.infer | undefined + +// Single-commit multi-sheet writes: +await store.transact( + { message: 'janedoe: register' }, + async (tx) => { + const user = await tx.users.upsert({ slug: 'janedoe', email: 'jane@x.org' }); + await tx.projects.upsert({ id: 'p1', name: `${user.path}'s project` }); + } +); +``` + +Sheets not in `validators` aren't on the typed `Store` surface; access them via `repo.openSheet(name)` for one-off un-typed reads. + +`Store` is a mapped type — `store.` is `Sheet>` for every named validator, plus a `store.transact` that mirrors `repo.transact` with typed `tx.` aliases. + +## PushDaemon + +```typescript +const daemon = await repo.startPushDaemon({ + remote: 'origin', + branch: 'main', // default: HEAD's branch + backoff: 'exponential', // or { base, multiplier, cap } + maxRetries: Infinity, // default +}); + +daemon.on('push', ({ commit, durationMs }) => log.info({ commit, durationMs })); +daemon.on('retry', ({ commit, attempt, nextDelayMs, reason }) => log.info({ … })); +daemon.on('error', ({ commit, err, attempt, reason }) => { + if (reason === 'non-fast-forward') alerts.page({ message: 'remote diverged' }); + else log.warn({ err: String(err), attempt }, 'push failed'); +}); +daemon.on('stopped', () => log.info('daemon stopped')); + +daemon.status(); // snapshot — see below +await daemon.stop({ timeoutMs: 30_000 }); // graceful drain +``` + +**Status snapshot:** + +```typescript +{ + running: boolean, + lastPushAt: ISO-8601 | null, + lastError: { message, at, attempt, reason: 'non-fast-forward' | 'unknown' } | null, + pendingCommits: number, + currentBackoffMs: number | null, + currentAttempt: number | null, +} +``` + +`reason: 'non-fast-forward'` is **terminal** — the daemon doesn't retry that batch. Page on-call. + +On `startPushDaemon` the daemon runs a startup-backlog check (fetch + `rev-list --count /..`) and queues any commits ahead of the remote — useful for catching up after a restart. + +**Push-only.** Never pulls. The consumer process is the single writer — the reverse direction is `repo.sync()`: + +```typescript +const r = await repo.sync({ remote: 'origin', branch: 'main', onConflict: 'preserve-branch' }); // v2.8+ +// r.outcome: 'in-sync' | 'fast-forwarded' | 'ahead' | 'rebased' | 'conflict' | 'conflict-escaped' | 'fetch-failed' +// r.oldCommit, r.newCommit, r.ahead, r.behind, r.conflictBranch?, r.conflictCommit?, r.fetchError? +``` + +Fetch happens outside the write lock; classification and ref movement happen under it (no transaction can interleave); live sheets are rebound when HEAD's branch moved; `ahead` / `rebased` tips are handed to a running push daemon. `onConflict: 'fail'` (default) leaves everything in place and names the commit that would not replay; `'preserve-branch'` keeps the local history on `conflicts/` (pushed best-effort) and adopts the remote. `repo.isAncestor(a, b)` is the "do I already have this commit?" short-circuit. **Hot reload:** pass `afterMove: async (r) => { await store.refresh(); rebuildCaches(); }` (v2.11+) — it runs under the write lock after the move and rebind, so no transaction can land between the ref move and your rebuild (inside it, `transact` is `lock_held`). Don't hold `withLock` and call `sync()` on a second `Repository` handle. + +## Errors + +All exceptions extend `GitsheetsError` and carry a stable `code` field. + +```typescript +class GitsheetsError extends Error { + readonly code: string; // stable identifier + readonly status: number; // HTTP-style hint + readonly cause?: unknown; +} +``` + +Subclasses + codes: + +| Class | Codes | +| --- | --- | +| `ConfigError` | `config_missing`, `config_invalid` | +| `ValidationError` | `validation_failed` (carries `issues: ValidationIssue[]`) | +| `TransactionError` | `transaction_in_progress`, `transaction_required`, `parent_moved`, `commit_failed`, `push_daemon_running`, `transaction_closed` | +| `IndexError` | `index_unique_conflict`, `index_not_defined` (carries `conflictingPaths`) | +| `RefError` | `ref_not_found`, `not_an_ancestor` | +| `PathTemplateError` | `path_render_failed`, `path_invalid_chars` | +| `NotFoundError` | `record_not_found` | +| `AggregationError` | `aggregation_failed` (carries `sheet`, `aggregate`, `partition?`) | + +Consumers switch on `instanceof` or `err.code` — never on `err.message`. + +`ValidationError.issues[]` shape: `{ path: string[], message: string, source: 'json-schema' | 'standard-schema', schemaPath?, code? }`. + +## validateRecord + +The same validation pipeline `Sheet.upsert` uses, exposed for pre-flight checks (UI form submission, CSV ingest audits). + +```typescript +import { validateRecord } from 'gitsheets'; + +const validated = await validateRecord({ + record, + schema, // JSONSchema | null + schemaSourcePath, // for error messages + validator, // optional Standard Schema +}); +// returns the possibly-transformed record on success; throws ValidationError on failure +``` + +## Template + +`Template.fromString(s)` — parse + cache. Most consumers don't construct `Template` directly; it's exposed for advanced use (path-template diagnostics, custom `queryTree` integrations). + +```typescript +const tpl = Template.fromString('${{ domain }}/${{ username }}'); +tpl.render({ domain: 'af.mil', username: 'jane' }); // → 'af.mil/jane' +tpl.getFieldNames(); // → ['domain', 'username'] +``` + +## Record annotations + +Records read from a Sheet carry two symbol-keyed annotations: + +```typescript +import { RECORD_SHEET_KEY, RECORD_PATH_KEY } from 'gitsheets'; + +const jane = await sheet.queryFirst({ slug: 'jane' }); +const sheetName = (jane as Record)[RECORD_SHEET_KEY]; // 'users' +const recordPath = (jane as Record)[RECORD_PATH_KEY]; // 'jane' +``` + +These annotations let `Sheet.upsert` detect renames: if the rendered path differs from `RECORD_PATH_KEY`, the old file is deleted **and the record's attachment directory moves to the new path** (v2.8+). Symbols are stripped before writing to disk. + +So the rename idiom is "load, change the key, upsert the same object" — `await sheet.upsert({ ...person, slug: 'new' })` (spread keeps symbol keys). Do **not** `delete` then `upsert`: `delete` cascades to the attachment directory first, so the attachments are lost. A validator that drops symbol keys (Zod `.parse`) needs the annotation re-applied — `parsed[RECORD_PATH_KEY] = person[RECORD_PATH_KEY]` — or pass the validator via `openSheet({ validator })` so the sheet carries it across itself. diff --git a/.agents/skills/gitsheets/references/axi.md b/.agents/skills/gitsheets/references/axi.md new file mode 100644 index 00000000..2ee87a5a --- /dev/null +++ b/.agents/skills/gitsheets/references/axi.md @@ -0,0 +1,437 @@ +# gitsheets-axi reference + +`gitsheets-axi` is the **agent-facing** companion to `gitsheets`. Same underlying library, different ergonomics: TOON output by default, errors on stdout, idempotent mutations, format-aware schemas, and opt-in session hooks installed via `gitsheets-axi setup hooks`. + +**Use `gitsheets-axi` when an agent is reading or mutating gitsheets data via shell execution.** Use the `gitsheets` library (TypeScript imports) when authoring code that runs inside an application. + +**Getting the tool.** If `gitsheets-axi` isn't already on `PATH`, don't stop — you don't need to install anything to start: + +```bash +gitsheets-axi query users # if it's already installed +npx -y gitsheets-axi query users # zero-install: runs the published package on demand +npm install -g gitsheets-axi # optional: install once for a persistent global command +``` + +`npx -y gitsheets-axi ` runs the latest published package with no install step, so a fresh environment that has **only this skill** can use every command below by prefixing `npx -y`. For repeated use in a session, `npm install -g gitsheets-axi` once (then drop the prefix). To check availability: `command -v gitsheets-axi`. Every example in this reference writes the bare `gitsheets-axi` — prefix `npx -y` when it isn't installed. + +`gitsheets-axi` shares the gitsheets minor version (1.3.x ↔ 1.3.x). Major and minor stay in lockstep; patch versions are independent. Run `gitsheets-axi setup hooks` once to install opt-in `SessionStart` hooks for Claude Code, Codex, and OpenCode — once installed, every new agent session sees a TOON home view of the current repo's sheets. + +## Output: TOON + +[TOON](https://toonformat.dev/) is a compact JSON-like format that's ~40% cheaper in tokens. A `gitsheets-axi query users` invocation looks like: + +``` +count: 2 of 2 total +records[2]{slug,email,name,path}: + bob,bob@x.org,Bob Smith,bob + jane,jane@x.org,Jane Doe,jane +help[1]: Run `gitsheets-axi read users ` to view a single record +``` + +The leading row in a list (`records[2]{slug,email,...}`) declares the column schema; subsequent lines are the rows. Object detail views use `key: value` shape. Help suggestions arrive as `help[N]: ...` lists, one per useful next command. + +## Idempotency + +Every mutation runs a pre-flight check against the current on-disk state. When the resulting bytes would be identical to what's already there, the command exits 0 with `result: "no-op"` and **no commit is produced**. Re-running the same `upsert` ten times produces one commit (or zero, if the record already exists with those bytes). + +This makes agent workflows safe to retry without bookkeeping. An agent that wrote a record, lost connection, and reconnected to re-run the same upsert won't double-commit. + +## Errors + +All errors go to **stdout** (not stderr — agents typically don't read stderr). Format: + +``` +error: +code: +help[N]: +``` + +The exit code is `0` for success and `(no-op)`, `2` for `VALIDATION_ERROR` (a usage error: unknown command or flag, missing argument, malformed `--filter` / `--agg` or global flag), `1` for everything else. Stable codes include `VALIDATION_ERROR`, `VALIDATION_FAILED` (a record failed its schema — a data error, exit 1), `NOT_FOUND`, `CONFIG_MISSING`, `CONFIG_INVALID`, `CONFIG_EXISTS`, `NOT_CANONICAL`, `INDEX_CONFLICT`, `NOT_A_REPOSITORY`, `INVALID_JSON`, `NO_RECORDS`, `PATH_TEMPLATE_ERROR`, `REF_ERROR`, `SHEET_DERIVED`, `TRANSACTION_ERROR`, `ROLLUP_STALE`, `AGGREGATION_FAILED`, `CONTRACT_MISSING` / `CONTRACT_INVALID` / `CONTRACT_UNSATISFIED`, `WRITE_ERROR`, `NON_FAST_FORWARD`, `PUSH_FAILED`, `HOOK_INSTALL_FAILED`, `UNKNOWN_ERROR`. + +## Command surface + +### `gitsheets-axi` (bare) + +Home view. Repo path + table of sheets (name, format, record count, root) + 2-3 suggested next commands. Runs as the SessionStart hook so this state is in agent context from turn 1. + +### `gitsheets-axi sheets [list]` + +List sheets configured in the current repo. Same data as the home view, separated command for explicit invocation. + +### `gitsheets-axi sheets view ` + +Single-sheet detail: config summary (root, format, path template), schema property types, record count. Surfaces `body_field` for content-typed sheets. Each schema field renders as `type [required] enum: a|b|c`, so you see allowed enum values (and which fields are required) **before** writing rather than from a rejected upsert. + +### `gitsheets-axi query [flags]` + +List records. + +| Flag | Notes | +| --- | --- | +| `--filter ` | Filter clause; repeatable, clauses AND. See the filter DSL below. | +| `--fields ` | Extra columns beyond the default schema | +| `--sort ` | Sort records by a field (missing values sort last) | +| `--desc` | Sort descending (with `--sort`) | +| `--group-by ` | Emit `{value,count}` facets instead of a record list | +| `--limit ` | Caps the **stdout preview**. Default 100, max 10000 | +| `--prefix

` | Tenant sub-tree scope (matches the library's `prefix` option) | +| `--json-out[=path]` | Also write the **full** result set to a JSON array file | +| `--ndjson-out[=path]` | Also write the full result set to an NDJSON file | +| `--csv-out[=path]` | Also write the full result set to a CSV file (flat, lossy) | + +**Filter DSL** (`--filter`, repeatable, AND-combined) — shared by `query`, `count`, `distinct`, and bulk `delete`: + +| Form | Meaning | +| --- | --- | +| `k=v` / `k!=v` | equality / inequality | +| `kv` `k<=v` `k>=v` | comparison (numeric for number fields, time for dates, else lexical — ISO dates sort right). **On a date-bucket path field** (`${{ k: YYYY/MM/DD }}` etc.) these are pushed down to the core, which walks only the partitions inside the bounds instead of scanning the sheet — the fast path for "last 30 days" on a big partitioned sheet. Use a date-only (`2026-01-01`) or `Z`/offset-qualified bound; an offset-less `T…` datetime stays host-side. | +| `k~regex` | `String(value)` matches the JS regex | +| `"k in (a,b,c)"` | value is one of the listed strings | +| `k:present` / `k:empty` | field exists and is non-empty / is absent, null, `""`, or `[]` | + +`--group-by ` aggregates over the **filtered** set (ignores `--limit`), biggest bucket first: `groups[K]{value,count}:`. Any value kind groups (Dates as ISO strings); records missing the field count under the empty value. For sums, extremes, or averages per group, use `aggregate … --group-by`. + +**Default schema is format-aware:** + +- **TOML sheets** — path-template fields + first scalar schema properties, capped at 4 columns. +- **Markdown/MDX sheets** — path-template fields + `title` (if in schema) + `body_size` (byte count). Body content itself never appears in lists — that belongs in `read`. Reads are **body-less by default** on these sheets (`query` / `count` / `distinct` parse only frontmatter) unless a `--filter` targets the body field, `--fields` names it, or an export flag is set — so listing a few thousand markdown records is a sub-second read, not a scan of every body. + +The summary line `count: N of M total` is always present so agents know when results are paginated. + +**Bulk export — the round-trip out of gitsheets.** The `--*-out` flags are a side-channel: stdout stays the token-cheap TOON preview, and the file carries **every matched record** (ignoring `--limit`). A bare flag auto-writes an owner-only (`0600`) file under `$TMPDIR/gitsheets-axi/`; `=path` persists it wherever you point it. At most one export flag per invocation. On write, stdout gains `wrote:` / `columns:` / a `jq` hint so you can compose the follow-up without opening the file: + +``` +wrote: /tmp/gitsheets-axi/repos-….ndjson +rows: 463 +cols: 12 +columns[12]: name,visibility,archived,... +help[1]: Run `jq '.name' /tmp/gitsheets-axi/repos-….ndjson` to process all 463 rows +``` + +`--json-out` and `--ndjson-out` are written **verbatim** (record fields only, no injected keys), so they pipe straight back into `gitsheets-axi upsert` — export → transform → re-import is a clean loop. `--csv-out` is flat (nested values JSON-encoded into their cell): a lossy reporting view, not a round-trip format. + +### `gitsheets-axi count [--filter expr ...]` + +Record count. With no `--filter`, counts candidate tree paths **without parsing** (cheap — the fast path for totals). A filter scans body-less records and reports `count: ` + `of: ` (the total stays the cheap full-sheet count). Same filter DSL as `query`, including the date-bucket range pushdown — `count posts --filter 'publishedAt>=2026-01-01'` opens only the 2026 partitions. Use this instead of `query … --limit 1 | grep count`. + +### `gitsheets-axi distinct [--filter expr ...]` + +Unique values of `` with counts, sorted alphabetically (`values[K]{value,count}:`). `query --group-by ` is the same facets ordered by count. Kills the `--ndjson-out | jq 'group_by'` loop for "what values does this field take?". + +### `gitsheets-axi aggregate --agg =

[:] ... [flags]` + +Named aggregates computed in the gitsheets core — the same fold as the library's `sheet.aggregate` — over the filtered records (body-less, canonical path order). One call answers "how many / how much / what range / which values". + +| Flag | Notes | +| --- | --- | +| `--agg =[:]` | Repeatable, at least one: `n=count`, `total=sum:amountCents`, `lo=min:f`, `hi=max:f`, `mean=avg:f`, `vals=distinct:f` | +| `--group-by ` | Group every aggregate: each result becomes a table keyed by the field's string form | +| `--filter ` | Same DSL as `query` (the clauses pick the records, date-bucket ranges also prune; the core folds over the picked records). A body-field clause on a markdown sheet → `VALIDATION_ERROR` | +| `--prefix

` | Tenant sub-tree scope | + +``` +$ gitsheets-axi aggregate tx --agg n=count --agg total=sum:amountCents --group-by status +sheet: tx +results: + n: + pending: 12 + posted: 1390 + total: + pending: -500 + posted: 98231600 +``` + +`sum` stays an integer when every value is one (store money as integer cents). An aggregate with nothing to fold is omitted, except `count` and `sum` (`0`). Mixed kinds in one field under `min`/`max`/`distinct` → `AGGREGATION_FAILED`. Custom folds (`reduce`) are library-only. + +### `gitsheets-axi rollup [--check] [--prefix p] [--message m]` + +Maintains a rollup sheet (`[gitsheet.rollup]` — stored per-partition aggregates). Reads of a rollup sheet are always correct (stale partitions recompute on read); this persists the repair after a plain `git merge` or an outside writer. + +```text +$ gitsheets-axi rollup transactions-monthly --check +error: 1 partition(s) of transactions-monthly are not fresh: stale 2026/03 +code: ROLLUP_STALE +$ gitsheets-axi rollup transactions-monthly +result: committed +partitions[1]{path,status}: + 2026/03,recomputed +``` + +Fresh → `result: no-op`, no commit. Writing a rollup sheet → `SHEET_DERIVED`; a non-rollup sheet → `VALIDATION_ERROR`. + +### `gitsheets-axi read [--full]` + +Single-record detail. For markdown/mdx sheets, the body field is truncated to ~500 chars with `(truncated, N chars total)` and a `--full` hint. Surfaces `_path` and `_sheet` as plain fields (the `RECORD_PATH_KEY` / `RECORD_SHEET_KEY` Symbol annotations). + +### `gitsheets-axi upsert [--data ] [flags]` + +Create or replace one **or many** records. + +| Flag | Notes | +| --- | --- | +| `--data ` | Record JSON inline. If omitted, reads stdin. | +| `--delete-missing` | After the batch, delete existing records **not** in the input set (exact re-sync). One commit. | +| `--dry-run` | Preview `{willChange, noOp, invalid, willDelete}` (+ invalid rows) — no commit. | +| `--allow-missing-body` | Content-typed sheets only — opt in to upserting without body field | +| `--prefix

` | Tenant scope | +| `--message ` | Commit message (default: ` upsert `) | + +**Bulk import — this is the path for loading a databank.** The input shape is autodetected, no flag needed: + +- a single JSON object → one record +- a **JSON array** of objects → batch +- **NDJSON** (one compact object per line) → batch + +A batch upserts every record in **one transaction that produces ONE commit** — not one commit per record. Feed it a file or a pipe: + +```bash +cat repos.array.json | gitsheets-axi upsert repos # JSON array → one commit +jq -c '.[]' repos.json | gitsheets-axi upsert repos # NDJSON → one commit +``` + +**Idempotent, per record.** Each record's canonical bytes are compared against what's on disk; unchanged records are skipped. A batch where nothing changed exits 0 with `result: "no-op"` and no commit. In a batch, a **single invalid record aborts the whole transaction** (nothing committed) and the error names the offending row. + +Single-record output on commit: + +``` +result: committed +sheet: users +path: jane +hash: 4d3f... +commit: a1b2c3... +help[1]: records live on the checked-out branch, so your working tree now lags the commit — keep them off it with `--branch data` or `--submodule data` (docs/recipes/headless-data.md), or run `git checkout HEAD -- .` to refresh the files +``` + +Batch output: + +``` +result: committed +sheet: repos +upserted: 5 +unchanged: 458 +commit: a1b2c3... +help[1]: records live on the checked-out branch, so your working tree now lags the commit — keep them off it with `--branch data` or `--submodule data` (docs/recipes/headless-data.md), or run `git checkout HEAD -- .` to refresh the files +``` + +Output on no-op mirrors the shape with `result: no-op` and no `commit`. + +**`--delete-missing`** makes the sheet exactly match the input set (upsert the batch, delete anything else) — the primitive for a periodic re-sync from a source. **`--dry-run`** validates a whole batch up front and reports `willChange` / `noOp` / `invalid` (with the offending rows) / `willDelete` without committing — use it before a big import instead of finding out about a bad row mid-batch. + +> **Working-tree gotcha.** gitsheets writes to the git **ref** via plumbing; it never touches your working tree. When records live on the checked-out branch, `git status` shows them *deleted* or *modified* right after a commit — not data loss. The `help` line above appears only in that case. **Prefer a headless layout** so there is no working tree of records to lag: a data branch (`--branch data`, `GITSHEETS_BRANCH`, or `git config gitsheets.branch data`) or a data submodule (`--submodule data`, `GITSHEETS_SUBMODULE`, or `git config gitsheets.submodule data`; set up with `git sheet submodule init data --url …`). Writes there print no hint. Only if records must stay on the code branch, run `git checkout HEAD -- .` to refresh the files. + +### `gitsheets-axi patch [] [flags]` + +RFC 7396 JSON Merge Patch — update fields without replacing the whole record. `null` deletes a field, arrays replace, objects merge recursively. Two modes: + +| Flag | Notes | +| --- | --- | +| `--patch ` | **Single mode**: partial JSON for the record matched by ``. If omitted, reads stdin. | +| `--data ` | **Bulk mode**: a JSON array / NDJSON of combined records. If omitted, reads stdin. | +| `--on-missing ` | Bulk: when a record's query matches nothing — `abort` (default) \| `skip` \| `insert` (upsert it as new). | +| `--delete-missing` | Bulk: delete existing records **not** targeted by the batch (exact re-sync). One commit. | +| `--dry-run` | Bulk: preview `{willChange, insert, noOp, missing, invalid, willDelete}` — no commit. | +| `--prefix

` | Tenant scope | +| `--message ` | Commit message | + +**Single** — explicit query + partial: + +```bash +gitsheets-axi patch users '{"slug":"jane"}' --patch '{"name":"Jane O. Doe"}' +``` + +**Bulk — this is the classification primitive.** Drop the `` positional and pass an array / NDJSON of **combined** records. In each record the sheet's **path-template fields** form the query (which record to patch); the **remaining fields** are the merge patch. Every patch runs in **one transaction → one commit** — the per-row preflight (resolve + will-change) runs *inside* that same transaction as pruned reads of the private tree, so a 3,000-row batch costs seconds, not a sheet scan per row; batches over 200 rows print `preflight: N/total` / `apply: N/total` progress on stderr, and `--dry-run` discards the transaction without committing: + +```bash +# classify many repos at once — one commit, merge-not-replace +jq -c '.[] | {name, target_team, status}' decisions.json | gitsheets-axi patch repos +``` + +Prefer bulk `patch` over bulk `upsert` for updates: `upsert` is a full-record *replace* (you must carry every existing field or lose it), while `patch` merges — you emit only the fields you're setting, and untouched fields are safe. + +**Idempotent.** Unchanged records are skipped; a batch where nothing changed is a `no-op` with no commit. By default a record whose query matches nothing **aborts the whole transaction** (nothing committed) and names the offending row — but `--on-missing skip` tolerates stale rows (handy re-running a classification pass after new records were ingested) and `--on-missing insert` upserts them as new. Output mirrors bulk `upsert` (`patched:` / `unchanged:` / `skipped:` / the materialize hint). + +Single mode throws `NOT_FOUND` if the query matches no record. + +### `gitsheets-axi rename ` + +Re-key a record: read it, write it at `` with rename semantics (the old file goes and the record's attachments move with it, v2.8+) — atomically in **one commit**. Supported for a bare single-field path template (`path = '${{ field }}'`), where `` maps directly onto the field's value; refuses to overwrite an existing target, errors on a missing source. For decorated/multi-field templates, use `patch` to change the path fields (or `upsert --delete-missing`). This reads as intent in git history vs. a manual write-new + delete-old. + +### `gitsheets-axi delete [flags]` · bulk: `delete --filter … | --stdin` + +Delete the record at ``, or many records at once. + +| Flag | Notes | +| --- | --- | +| `--filter ` | Bulk: delete every record matching the filter DSL (repeatable). No ``. | +| `--stdin` | Bulk: delete records named one-per-line on stdin. No ``. | +| `--dry-run` | Bulk: report `willDelete` (of total) — no commit. | +| `--prefix

` | Tenant scope | +| `--message ` | Commit message | + +**Idempotent on already-missing.** Agents can call `delete` without checking existence; an already-absent record exits 0 with `result: "no-op"`. **Bulk delete** removes every matching record in **one commit** (absent ids skipped) — e.g. `delete repos --filter disposition=delete-candidate`. Always `--dry-run` first to confirm the count. + +### `gitsheets-axi check [--fix]` + +Verify a record file in the working tree is parseable, valid against the sheet's schema, and in canonical form. Reads from the working tree (not git). **Never commits.** + +| Flag | Notes | +| --- | --- | +| `--fix` | Rewrite the file in canonical form if not already canonical | +| `--prefix

` | Tenant scope | + +Designed as a post-edit hook for agents that wrote a record directly: + +- With `--fix` (post-edit): `gitsheets-axi check users users/jane.toml --fix` lands the file in canonical form +- Without `--fix` (pre-commit): non-zero exit blocks the commit when the file isn't canonical + +Outputs: + +- `result: ok` — already canonical +- `result: fixed` — rewritten by --fix +- `NOT_CANONICAL` error (exit 1) when not canonical and --fix wasn't passed +- `VALIDATION_FAILED` (exit 1) when the record fails schema validation +- `CONFIG_INVALID` (exit 1) when the file fails to parse as the sheet's format +- `NOT_FOUND` when the target file doesn't exist + +#### Claude Code post-edit hook + +Add to `.claude/settings.json` (project) or `~/.claude/settings.json` (user-wide): + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "command": "gitsheets-axi check ${SHEET} \"$FILE\" --fix" + } + ] + } +} +``` + +Substitute `${SHEET}` with the sheet name. For multi-sheet repos, point the hook at a wrapper script that infers the sheet from `$FILE`'s path (e.g. `users/jane.toml` → `users`). + +#### Pre-commit verification + +Drop `--fix` for a non-destructive verification — exits non-zero (with structured `NOT_CANONICAL` / `VALIDATION_FAILED` on stdout) when the file isn't already canonical. Suitable for a git pre-commit hook or a CI step that runs over staged record files. + +### `gitsheets-axi diff [] [--patches]` + +TOON change summary between a source ref and the current tree. With no ``, compares against the empty tree — every current record shows as `added`, useful for one-shot snapshots. + +Default columns: `status` (added/modified/deleted/renamed), `path`, `src_hash`, `dst_hash`. `--patches` adds an RFC 6902 patch column with the per-change ops as JSON-encoded TOON. + +### `gitsheets-axi normalize ` + +Bulk re-canonicalize every record in a sheet. Per-record idempotency via `sheet.willChange` means only records whose canonical bytes differ from disk get rewritten; if every record is already canonical, exits with `result: "no-op"` and no commit. + +Use this when migrating sheets to a new schema or after a normalization-rule change in the sheet config. For single-file fixes, `check --fix` is cheaper. + +### `gitsheets-axi init [--path