Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## What Is Pronghorn

Pronghorn is an AI-powered software development platform (MIT license, Government of Alberta). It transforms unstructured requirements into production-ready code with traceability. Live at https://pronghorn.red.

## Development Commands

```bash
npm install # Install dependencies
npm run dev # Start Vite dev server on port 8080
npm run build # Production build
npm run build:dev # Development build
npm run lint # ESLint
npm run preview # Preview production build
```

No `.env` file is needed for the frontend — Supabase config is embedded in `src/integrations/supabase/client.ts`.

Edge functions are Deno TypeScript in `supabase/functions/` and deploy automatically on push. They require Supabase secrets (GEMINI_API_KEY, ANTHROPIC_API_KEY, GROK_API_KEY, GITHUB_PAT, RENDER_API_KEY, RESEND_API_KEY).

## Architecture Overview

**Frontend-only React SPA** backed by Supabase (PostgreSQL + Edge Functions + Realtime + Storage).

### Provider Hierarchy (src/main.tsx)

```
ThemeProvider → QueryClientProvider → AuthProvider → AdminProvider → BrowserRouter → App
```

### Key Architectural Patterns

1. **Token-Based RBAC**: All data access goes through `SECURITY DEFINER` RPC functions (e.g., `get_canvas_nodes_with_token`) that validate access via `authorize_project_access(p_project_id, p_token)`. Never query tables directly — always use `*_with_token` RPCs.

2. **Share Token Flow**: Tokens appear in URL as `/project/:projectId/:page/t/:token`, get cached in memory + sessionStorage (`src/lib/tokenCache.ts`), then masked to `/t/masked` for security. The `useShareToken` hook (`src/hooks/useShareToken.ts`) manages this lifecycle and calls `set_share_token` RPC to configure the Postgres session.

3. **Realtime Subscriptions**: Two-layer model:
- `postgres_changes`: RLS-protected database events (secure, filtered server-side)
- `broadcast`: Public refresh signals with empty payloads (data still requires valid token via RPC)
- Pattern: `useRef` for channel storage, cleanup on unmount. See `src/hooks/useRealtimeCanvas.ts` as reference.

4. **Lazy Loading**: Heavy pages (Canvas, Build, Repository, etc.) use `React.lazy()` with `Suspense` + `PageLoader`. Lightweight pages (Landing, Auth, Terms) are eagerly loaded.

5. **Agent Configuration as JSON**: All AI agent behaviors are defined in `public/data/*.json` files — not hardcoded. Key files:
- `agents.json` — 13 specification agents
- `buildAgents.json` — 10 canvas design agents
- `auditAgentInstructions.json` — audit orchestrator spec
- `codingAgentInstructions.json` — coding agent tools & patterns
- `presentAgentInstructions.json` — presentation blackboard spec
- `connectionLogic.json` — canvas edge validation rules
- `presentationLayouts.json` — 15 slide layouts + themes

6. **Edge Function Pattern**: All edge functions follow the same structure — CORS headers, parse JSON body with `projectId` + `shareToken`, create Supabase client with auth header, validate access via `authorize_project_access` RPC, then perform operation. Streaming functions use SSE.

### Role Hierarchy

`owner` > `editor` > `viewer`. Owners can manage tokens and delete projects. Editors can create/update. Viewers are read-only. Role checked via `require_role(p_project_id, p_token, p_min_role)` in RPC functions.

### Admin Roles

Separate from project roles: `superadmin` > `admin` > `user`. Stored in `user_roles` table, exposed via `AdminContext`.

## Tech Stack

- **React 18** + TypeScript 5.8 + Vite 5.4 (SWC)
- **Tailwind CSS 3.4** + shadcn/ui (Radix primitives) — use `cn()` from `src/lib/utils.ts`
- **React Router DOM 6** — routes in `src/App.tsx`
- **TanStack React Query 5** — server state caching
- **React Flow 11** — interactive canvas diagrams
- **Monaco Editor** — code/SQL editing
- **Supabase JS v2** — client singleton at `src/integrations/supabase/client.ts`
- **LLM Providers**: Google Gemini, Anthropic Claude, xAI Grok

## Project Structure

```
src/
components/ # React components organized by feature domain
ui/ # shadcn/ui base components (do not edit manually — use shadcn CLI)
canvas/ # React Flow canvas editor
build/ # Coding agent interface
deploy/ # Database & deployment management
present/ # AI presentation generator
audit/ # Multi-agent audit system
collaboration/# Collaborative document editing
buildbook/ # Build Book management
gallery/ # Project gallery
artifacts/ # File/document management
repository/ # File tree, code editor, Git integration
requirements/ # Requirement tree management
specifications/# Spec generation
standards/ # Standards library UI
dashboard/ # Project cards & creation
layout/ # Navigation, sidebar, header
project/ # Project settings, token management
contexts/ # AuthContext (auth state), AdminContext (admin roles)
hooks/ # Custom hooks — realtime subscriptions, token management, data fetching
pages/ # Route pages (project/ subdirectory for project-scoped pages)
integrations/ # Supabase client & auto-generated types
lib/ # Utilities (tokenCache, connectionLogic, sqlParser, etc.)
styles/ # Global CSS

supabase/
functions/ # ~58 Deno edge functions
config.toml # Supabase project config (verify_jwt settings)

public/data/ # JSON configuration files for AI agents and UI behavior
```

## Conventions

- Path alias: `@/*` maps to `./src/*`
- TypeScript strict mode is OFF (`noImplicitAny: false`, `strictNullChecks: false`)
- ESLint: `@typescript-eslint/no-unused-vars` is disabled
- All edge functions set `verify_jwt = false` in `supabase/config.toml` (access validated via RPC instead)
- Dark mode: class-based (`tailwind.config.ts`)
- Colors use HSL CSS variables (e.g., `hsl(var(--primary))`)
- Vite splits vendor chunks: react, monaco, pdf, reactflow, charts, office, radix
- PWA support via `vite-plugin-pwa` with workbox caching strategies

## URL Routing Pattern

```
/project/:projectId/:page # Authenticated users
/project/:projectId/:page/t/:token # Token-based shared access
/viewer/:artifactId # Public artifact viewer (no auth)
```

All project routes are duplicated for both patterns in `src/App.tsx`.
22 changes: 22 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Pronghorn Documentation

## Table of Contents

| Document | Description |
|----------|-------------|
| [Architecture](./architecture.md) | System architecture, provider hierarchy, data flow, state management, security overview |
| [Authentication](./authentication.md) | Auth methods, token-based RBAC, role hierarchy, authorization functions, token caching |
| [AI Agents](./ai-agents.md) | Multi-agent systems, orchestration patterns, LLM providers, agent configuration files |
| [Edge Functions](./edge-functions.md) | All ~58 Deno edge functions, common patterns, streaming (SSE), secrets reference |
| [Realtime](./realtime.md) | WebSocket subscriptions, two-layer security model, hook pattern, available hooks |
| [Components](./components.md) | Component organization by feature domain, key components per domain, shared patterns |
| [Hooks](./hooks.md) | All custom hooks — token management, realtime, data fetching, state management |
| [Database Schema](./database-schema.md) | Key tables, access patterns, RPC conventions, authorization functions, custom types |
| [Development Guide](./development-guide.md) | Setup, scripts, configuration, working with Supabase/Realtime/Canvas, utility libraries |

## Quick Links

- **Live Application**: https://pronghorn.red
- **Repository**: https://github.com/pronghorn-red/pronghorn
- **CLAUDE.md** (Claude Code guidance): [../CLAUDE.md](../CLAUDE.md)
- **README.md** (Project README): [../README.md](../README.md)
160 changes: 160 additions & 0 deletions docs/ai-agents.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# AI Agents & Orchestration

Pronghorn uses multi-agent AI systems across several features. Agent behaviors are defined in JSON configuration files (`public/data/*.json`) rather than being hardcoded.

## Agent Types

### 1. Canvas Design Agents (Multi-Agent Orchestration)

**Config**: `public/data/buildAgents.json`
**Edge Function**: `orchestrate-agents`

10 specialized agents collaborate on canvas architecture design using a blackboard pattern:

| Agent | Focus |
|-------|-------|
| Architect | System structure and component hierarchy |
| Developer | Implementation details and code patterns |
| DBA | Database schemas and data modeling |
| Security | Vulnerability assessment and secure patterns |
| QA | Test coverage and validation strategies |
| DevOps | Deployment and infrastructure |
| UX | User experience and interface design |
| API | API design and integration patterns |
| Performance | Optimization and scalability |
| Documentation | Technical documentation |

**How it works**:
1. User configures which agents to include and how many iterations (epochs)
2. Each epoch, agents take turns reading the current canvas state and proposing changes
3. A critic agent reviews proposed changes after each epoch
4. Canvas nodes and edges are created/modified via the canvas RPC functions
5. Results are streamed back via SSE

### 2. Specification Agents

**Config**: `public/data/agents.json`
**Edge Function**: `generate-specification`

13 agents generate comprehensive project documents:

| Agent | Output |
|-------|--------|
| Overview | Executive summary and project scope |
| Technical Specification | Detailed technical documentation |
| Cloud Architecture | AWS/Azure/GCP infrastructure design |
| API Specification | OpenAPI/REST endpoint documentation |
| Security Analysis | Threat modeling and security controls |
| Data Requirements | Data models and storage requirements |
| Accessibility | WCAG compliance and accessibility audit |
| Internationalization | i18n/l10n requirements |
| DevOps | CI/CD and deployment strategies |
| Testing | Test strategy and coverage plans |
| Standards Compliance | Regulatory compliance mapping |
| Executive Summary | Business-focused project overview |
| Project Charter | Governance and stakeholder documentation |

### 3. Audit Agents (Multi-Perspective Analysis)

**Config**: `public/data/auditAgentInstructions.json`
**Edge Functions**: `audit-orchestrator`, `audit-extract-concepts`, `audit-merge-concepts`, `audit-merge-concepts-v2`, `audit-generate-venn`, `audit-build-tesseract`, `audit-enhanced-sort`

5 agents provide multi-perspective cross-comparison:

| Agent | Perspective |
|-------|-------------|
| Security Analyst | Vulnerability and risk assessment |
| Business Analyst | Business value and ROI analysis |
| Developer | Implementation feasibility |
| End User | Usability and user experience |
| Architect | System design and patterns |

**Audit Pipeline** (runs locally until explicit save):

```
1. Extract Concepts (D1) → Extract concepts from dataset 1 elements
2. Extract Concepts (D2) → Extract concepts from dataset 2 elements
3. Merge Concepts → Find alignments between D1 and D2 concepts
4. Enhanced Sort → Smart sorting of merged results
5. Build Tesseract → Construct 3D evidence grid
6. Generate Venn → Synthesize Venn diagram (Unique to D1 | Aligned | Unique to D2)
```

**Key**: All audit processing runs locally in the browser (`useAuditPipeline` hook, `src/hooks/useAuditPipeline.ts`). No database writes occur until the user explicitly saves results.

### 4. Coding Agent

**Config**: `public/data/codingAgentInstructions.json`, `public/data/codingAgentToolsManifest.json`, `public/data/codingAgentPromptTemplate.json`
**Edge Function**: `coding-agent-orchestrator`

Autonomous file operations with full Git workflow:
- Read, edit, create, delete, rename files
- Stage → Commit → Push workflow
- Real-time progress monitoring via SSE
- Pause/resume and abort operations
- Raw LLM logs viewer for debugging

**Components**: `src/components/build/` (UnifiedAgentInterface, AgentProgressMonitor, StagingPanel, RawLLMLogsViewer)

### 5. Presentation Agent

**Config**: `public/data/presentAgentInstructions.json`, `public/data/presentationLayouts.json`
**Edge Function**: `presentation-agent`

Uses the **Blackboard Memory Pattern**:
1. Agent reads project data sequentially (requirements, canvas, standards, etc.)
2. Accumulates insights on an append-only blackboard
3. Generates slides based on accumulated context
4. Supports 15+ slide layouts and multiple themes

### 6. Collaboration Agent

**Config**: `public/data/collaborationAgentInstructions.json`
**Edge Function**: `collaboration-agent-orchestrator`

AI partner for document editing:
- Line-level `edit_lines` operations for surgical changes
- Respects human edits (never replaces entire documents)
- Change tracking with diff visualization
- Project context attachment (requirements, canvas, artifacts)

### 7. Database Agent

**Config**: `public/data/databaseAgentPromptTemplate.json`, `public/data/databaseAgentToolsManifest.json`
**Edge Function**: `database-agent-orchestrator`

AI-powered database operations:
- Schema inference from imported data
- SQL generation and execution
- Data import wizard with type detection

## LLM Providers

| Provider | Models | Used For |
|----------|--------|----------|
| Google Gemini | gemini-2.5-flash, gemini-2.5-pro | Primary: chat, agents, image generation |
| Anthropic Claude | claude-opus-4-5 | Alternative chat provider |
| xAI Grok | grok-4-1-fast-reasoning, grok-4-1-fast-non-reasoning | Alternative chat provider |

Image generation uses Gemini models: `gemini-2.5-flash-image`, `gemini-3-pro-image-preview`.

## Agent Configuration Files

All agent behaviors are defined in `public/data/`:

| File | Purpose |
|------|---------|
| `agents.json` | 13 specification agent definitions (name, prompt, capabilities) |
| `buildAgents.json` | 10 canvas design agent definitions |
| `auditAgentInstructions.json` | Audit orchestrator and agent specifications |
| `codingAgentInstructions.json` | Coding agent system prompt and tool definitions |
| `codingAgentToolsManifest.json` | Available tools for the coding agent |
| `codingAgentPromptTemplate.json` | Prompt template for coding agent |
| `presentAgentInstructions.json` | Presentation agent blackboard specification |
| `presentationLayouts.json` | 15+ slide layout definitions with themes |
| `collaborationAgentInstructions.json` | Collaboration agent behavior specification |
| `databaseAgentPromptTemplate.json` | Database agent prompt template |
| `databaseAgentToolsManifest.json` | Database agent tool definitions |
| `graphicStyles.json` | 6 image generation style categories |
| `connectionLogic.json` | Canvas edge validation rules and flow hierarchy |
| `deploymentSettings.json` | Multi-runtime deployment configurations |
Loading