pgconsole
CLAUDE.md154 starsChanged 5 months agoApache-2.0View on GitHub
pgconsole is a PostgreSQL management console with a React frontend and Express backend using ConnectRPC for API communication. When using plan mode, create the plan under plans/ directory. Don't assume. Don't hide confusion. Surface tradeoffs. Before implementing: - State your assumptions explicitly. If uncertain, ask. - If multiple interpretations exist, present them - don't pick silently. - If a simpler approach exists, say so. Push back when warranted. - If something is unclear, stop. Name what's confusing. Ask. Minimum code…
- Deletes or force-pushes
In this repository3 other files it gives its agents.
- pr-bot-reviewsSkill
- refactor-passSkill
- take-doc-screenshotsSkill
The file
Show its rules and text
We split this claude.md into the rules it gives an agent
30 rules. About 0 are common, 19 are distinctive, and 11 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈19
Distinctive · estimate
This author's own choices. Worth a look.
11
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 11
When using plan mode, create the plan under plans/ directory.
- Distinctive: line 19
If multiple interpretations exist, present them - don't pick silently.
- Distinctive: line 20
If a simpler approach exists, say so.
- Distinctive: line 21
If something is unclear, stop.
- Distinctive: line 27
No features beyond what was asked.
- Distinctive: line 28
No abstractions for single-use code.
- Distinctive: line 30
No error handling for impossible scenarios.
- Distinctive: line 31
If you write 200 lines and it could be 50, rewrite it.
- Distinctive: line 33
Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
- Distinctive: line 39
When editing existing code:
- Distinctive: line 40
Don't "improve" adjacent code, comments, or formatting.
- Distinctive: line 41
Don't refactor things that aren't broken.
- Distinctive: line 43
If you notice unrelated dead code, mention it - don't delete it.
- Distinctive: line 45
When your changes create orphans:
- Very specific: line 46
Remove imports/variables/functions that YOUR changes made unused.
- Distinctive: line 47
Don't remove pre-existing dead code unless asked.
- Very specific: line 119
All configuration is done via pgconsole.toml (no environment variables required).
- Very specific: line 148
Access: Use getAuthProvider(type) to look up an auth provider by type.
- Distinctive: line 152
When adding or updating config fields:
- Very specific: line 157
Required column: Only mark Yes for required fields.
- Distinctive: line 158
Inline details: Put formats/options in table descriptions, not separate subsections (e.g., SSL modes, timeout format)
- Very specific: line 160
Config reference links: When other docs reference config fields, link to docs/configuration/config.mdx with the specific anchor (e.g., …
- Very specific: line 168
Tool: Use /take-doc-screenshots skill to capture screenshots from the running app
- Very specific: line 217
Use useConnectionPermissions hook to check permissions in components:
- Distinctive: line 288
When adding features that modify data:
- Very specific: line 290
Use useConnectionPermissions in the component
- Distinctive: line 293
Consider context (e.g., EXPLAIN results should be read-only)
- Distinctive: line 503
Keep components focused and composable
- Very specific: line 504
Use existing UI components from src/components/ui/
- Very specific: line 505
Use clsx and tailwind-merge for conditional classes
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Project Guidelines
Overview
pgconsole is a PostgreSQL management console with a React frontend and Express backend using ConnectRPC for API communication.
Working Guidelines
Plan Mode
When using plan mode, create the plan under plans/ directory.
Think Before Coding
Don't assume. Don't hide confusion. Surface tradeoffs.
Before implementing:
- State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
- If something is unclear, stop. Name what's confusing. Ask.
Simplicity First
Minimum code that solves the problem. Nothing speculative.
- No features beyond what was asked.
- No abstractions for single-use code.
- No "flexibility" or "configurability" that wasn't requested.
- No error handling for impossible scenarios.
- If you write 200 lines and it could be 50, rewrite it.
Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
Surgical Changes
Touch only what you must. Clean up only your own mess.
When editing existing code:
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it.
When your changes create orphans:
- Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked.
The test: Every changed line should trace directly to the user's request.
Goal-Driven Execution
Define success criteria. Loop until verified.
Transform tasks into verifiable goals:
- "Add validation" → "Write tests for invalid inputs, then make them pass"
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
- "Refactor X" → "Ensure tests pass before and after"
For multi-step tasks, state a brief plan:
1. [Step] → verify: [check]
2. [Step] → verify: [check]
3. [Step] → verify: [check]SQL Analysis: Use the Parser, Not Regex
NEVER use regex to parse or analyze SQL. Always use @libpg-query/parser.
The codebase has a full SQL parser in src/lib/sql/:
core.ts-parseSql()returns typed AST with statement kinds and expressionsserver/lib/sql-permissions.ts- Example of proper parser usage
// ❌ WRONG - Don't do this
const isSelect = sql.trim().toUpperCase().startsWith('SELECT')
const hasFunction = /pg_terminate_backend/i.test(sql)
// ✅ CORRECT - Use the parser
import { parseSql } from 'src/lib/sql/core'
const parsed = await parseSql(sql)
const stmt = parsed.statements[0]
if (stmt.kind === 'select') { /* ... */ }The parser handles:
- Comments, string literals, quoted identifiers
- Multi-statement SQL
- Nested expressions and subqueries
- All PostgreSQL syntax
Project Structure
/server - Express backend with ConnectRPC services
/lib - Config, auth utilities
/services - RPC service implementations
/src - React frontend application
/components - React components
/ui - Reusable UI primitives (95+ components)
/sql-editor - SQL editor feature components
/hooks - Custom React hooks
/lib - Shared utilities
/sql - SQL parsing, formatting, autocomplete
/autocomplete - Autocomplete pipeline (8 modules)
/gen - Generated protobuf code
/pages - Page components
/proto - Protocol buffer definitions
/scripts - Build scripts
/tests - Test suite (SQL parser, autocomplete, API)
/docs - Documentation and design plans
/dist/client - Built frontend (Vite output)
/dist/server.mjs - Built server (esbuild output)Configuration
All configuration is done via pgconsole.toml (no environment variables required). See docs/configuration/config.mdx for the full reference. Source of truth for config fields: server/lib/config.ts.
Provider Config Pattern
Both auth and AI providers use [[array]] of tables with a type/vendor discriminator:
# Auth providers — type discriminator, issuer_url required for keycloak/okta
[[auth.providers]]
type = "google"
client_id = "..."
client_secret = "..."
[[auth.providers]]
type = "keycloak"
client_id = "..."
client_secret = "..."
issuer_url = "https://keycloak.example.com/realms/myrealm"
# AI providers — vendor discriminator
[[ai.providers]]
id = "gpt4"
vendor = "openai"
model = "gpt-4o"
api_key = "sk-..."Types: AuthProviderConfig (with type field) and AIProviderConfig (with vendor field) in server/lib/config.ts.
Access: Use getAuthProvider(type) to look up an auth provider by type. In OAuth route files, import getAuthProvider (not getAuthConfig).
Config Docs Convention (docs/configuration/config.mdx)
When adding or updating config fields:
- Section titles: Human-readable (e.g., "Connections" not "
[[connections]]") - Section order: General → Labels → Connections → Authentication → Users → Groups → Access Control (IAM) → AI Providers
- Each section: Description → field table → TOML code example
- Complete example at top must follow the same section order
- Required column: Only mark
Yesfor required fields; leave cell empty for optional - Inline details: Put formats/options in table descriptions, not separate subsections (e.g., SSL modes, timeout format)
- Cross-reference: Link to related docs pages and external references (e.g., PostgreSQL docs)
- Config reference links: When other docs reference config fields, link to
docs/configuration/config.mdxwith the specific anchor (e.g.,/configuration/config#users,/configuration/config#oauth-providers), not a generic link to the whole page - Verify against source:
server/lib/config.tsis the canonical SSOT for all config fields. Always check it (loadConfig) for field names, types, and whether they're optional
Docs Screenshot Convention
- Format: WebP (
.webp), quality 90, dimensions 1440x900 (1x) - Location:
docs/images/mirroring thedocs/structure (e.g.,docs/images/features/sql-editor/) - Reference:
 - Tool: Use
/take-doc-screenshotsskill to capture screenshots from the running app - Prerequisites:
pnpm devrunning,shot-scraper+cwebpinstalled
Permission System (IAM)
Permission Levels
Seven permission levels control what users can do per connection:
| Permission | Operations | Use Case |
explain | EXPLAIN | View query plans |
read | SELECT, SHOW | Query execution |
execute | CALL | Stored procedure execution |
export | CSV export button | Client-side data export |
write | INSERT, UPDATE, DELETE, COPY | Data modification |
ddl | CREATE, ALTER, DROP | Schema changes |
admin | Role/database management, dangerous functions | Database administration |
Permissions are disjoint (not hierarchical). A query like SELECT pg_terminate_backend(123) requires both read AND admin.
Backend SQL Permission Detection
The server uses @libpg-query/parser to detect required permissions from SQL:
server/lib/sql-permissions.ts
├── getRequiredPermission(kind) → Maps statement type to permission
├── extractFunctionsFromStatement() → Extracts function calls from AST
├── getFunctionPermission(name) → Looks up function permission
└── detectRequiredPermissions(sql) → Returns Set<Permission>Statement → Permission mapping:
explain: EXPLAINread: SELECT, SHOW, SET, BEGIN/COMMITexecute: CALLwrite: INSERT, UPDATE, DELETE, COPYddl: CREATE/ALTER/DROP TABLE/VIEW/INDEX/FUNCTION, GRANT, REVOKEadmin: CREATE/DROP ROLE, CREATE/DROP DATABASE, ALTER SYSTEM
Function permissions are defined in src/lib/sql/pg-system-functions.ts:
- Most functions:
read pg_cancel_backend,pg_terminate_backend:admin
Safety: Unparseable SQL defaults to admin permission.
Frontend Permission Hook
Use useConnectionPermissions hook to check permissions in components:
import { useConnectionPermissions } from '@/hooks/usePermissions'
function MyComponent({ connectionId }: { connectionId: string }) {
const { hasWrite, hasDdl, hasAdmin, hasExplain, hasExport } = useConnectionPermissions(connectionId)
return (
<>
{hasExplain && <Button onClick={handleExplain}>Explain</Button>}
{hasExport && <Button onClick={handleExport}>Export</Button>}
{hasWrite && <Button onClick={handleEdit}>Edit</Button>}
{hasDdl && <Button onClick={handleAlter}>Alter Table</Button>}
{hasAdmin && <Button onClick={handleTerminate}>Terminate</Button>}
</>
)
}Permission Gating Patterns
Pattern 1: Direct gating in initiating components
// Gate buttons/actions that start write operations
{hasWrite && <Button onClick={handleDelete}>Delete</Button>}Pattern 2: Callback-based gating for child components
// Parent passes callbacks only when permitted
<ChildComponent
onEdit={hasWrite ? handleEdit : undefined}
onDelete={hasWrite ? handleDelete : undefined}
/>
// Child renders based on callback presence
{onEdit && <Button onClick={onEdit}>Edit</Button>}Pattern 3: Context-aware gating
// Disable features for read-only result types (e.g., EXPLAIN)
const isExplainResult = sql?.trim().toUpperCase().startsWith('EXPLAIN')
{hasWrite && !isExplainResult && <Button>Edit</Button>}Currently Gated Operations
Backend (server-side enforcement):
| Endpoint | Permission Detection |
ExecuteSQL | Parsed from SQL (statement + functions) |
TerminateSession | admin |
Frontend (UI gating):
| Component | Operation | Permission |
| QueryResults.tsx | Add/Edit/Delete/Duplicate rows | hasWrite |
| QueryResults.tsx | Context menu actions | hasWrite |
| QueryResults.tsx | Double-click to edit | hasWrite |
| QueryResults.tsx | JSON modal save | hasWrite |
| FunctionSchemaContent.tsx | Edit function definition | hasDdl |
| ProcessesModal.tsx | Terminate process | hasAdmin |
| EditorArea.tsx | Explain button and context menu | hasExplain |
| QueryResults.tsx | Export to CSV button | hasExport |
Adding New Gated Features
When adding features that modify data:
- Identify the permission level needed (write/ddl/admin)
- Use
useConnectionPermissionsin the component - Gate UI elements with the appropriate permission
- For child components, pass callbacks conditionally
- Consider context (e.g., EXPLAIN results should be read-only)
Technology Stack
Frontend
- Framework: React 19 with TypeScript
- Build: Vite (rolldown-vite)
- Styling: Tailwind CSS v4
- UI Base: @base-ui/react
- Icons: lucide-react
- Routing: react-router-dom v7
- Data Fetching: TanStack React Query
- Editor: CodeMirror 6
- SQL Parsing: @libpg-query/parser (WASM)
Backend
- Framework: Express 5
- RPC: ConnectRPC
- Database: postgres.js (postgres), pg
- Auth: jose (JWT)
- Config: smol-toml
Frontend Architecture
Key Directories
src/components/sql-editor/- Main editor featureSQLEditorLayout.tsx- Main container with resizable panelsQueryEditor.tsx- CodeMirror-based SQL editorQueryResults.tsx- Results grid with inline editingContextPanel.tsx- Right panel for object detailshooks/useEditorTabs.ts- Tab state managementschema/- Schema display components (tables, views, functions)
src/lib/- Shared utilitiesconnect-client.ts- ConnectRPC client setupschema-store.ts- In-memory schema cache (Map-based)staged-changes.ts- DML change tracking for inline editing
src/lib/sql/- SQL toolingautocomplete/- 8-module autocomplete pipelinepg-highlight.ts- Syntax highlightingpg-lint.ts- Error detectionpg-signature-help.ts- Function signature tooltipsformat.ts- SQL formatting
State Management
Server State: TanStack React Query with query keys pattern [resource, id, params]
Local State: Custom hooks with localStorage persistence
- Tab content/state →
pgconsole-editor-{connectionId} - Layout (panel sizes) →
pgconsole-layout-{connectionId}
Schema Cache: Non-React schemaStore object (connection-scoped Map)
Editor Tab System
type EditorTab = QueryTab | SchemaTab
interface QueryTab {
type: 'query'
id: string
name: string
content: string
}
interface SchemaTab {
type: 'schema'
id: string
name: string
schema: string
table: string
objectType?: 'table' | 'view' | 'materialized_view' | 'function' | 'procedure'
}UI Component Library
Located in src/components/ui/. Always use these instead of plain HTML elements.
Form Controls
input.tsx,textarea.tsx,select.tsxcheckbox.tsx,checkbox-group.tsx,radio-group.tsxswitch.tsx,slider.tsx,number-field.tsx
Buttons & Interactive
button.tsx,toggle.tsx,toggle-group.tsx
Layout
card.tsx,separator.tsx,sheet.tsx,sidebar.tsxscroll-area.tsx,tabs.tsx,accordion.tsx,collapsible.tsx
Dialogs & Overlays
dialog.tsx,alert-dialog.tsx,popover.tsx,tooltip.tsx
Feedback
alert.tsx,toast.tsx,progress.tsx,spinner.tsx,skeleton.tsx
Data Display
table.tsx,badge.tsx,avatar.tsx,kbd.tsx
Advanced
combobox.tsx,autocomplete.tsx,command.tsx
Usage:
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select'Server Architecture
Auth Routes (/server/auth-routes.ts)
POST /api/auth/login- Basic authGET /api/auth/session- Current sessionPOST /api/auth/logout- LogoutGET /api/auth/providers- List providers- OAuth:
/api/auth/google,/api/auth/keycloak+ callbacks
ConnectRPC Services
ConnectionService (/server/services/connection-service.ts)
ListConnections- List all configured connectionsGetConnection- Get connection details by IDTestConnection- Test connection with latency measurement
QueryService (/server/services/query-service.ts)
ExecuteSQL- Execute SQL (streaming response with PID, returns affected rows for DML)CancelQuery- Cancel running query by PIDGetSchemas- List schemasGetTables- List tables in schemaGetColumns- Get columns for table (with metadata)GetTableInfo- Full table metadata (size, row count, etc.)GetIndexes,GetConstraints,GetTriggers- Table structureGetPolicies,GetGrants- Security infoGetMaterializedViews,GetFunctions,GetProcedures- Object listsGetFunctionInfo- Function/procedure details with definition
AIService (/server/services/ai-service.ts)
ListAIProviders- List configured AI providersGenerateSQL- Generate SQL from natural languageExplainSQL- Explain SQL query in plain languageFixSQL- Fix SQL syntax errorsRewriteSQL- Rewrite and optimize SQLRefreshSchemaCache- Refresh cached schema info
Schema Caching for AI (/server/lib/schema-cache.ts)
AI features use a backend schema cache to avoid expensive database queries on every request. Schema cache includes:
- Tables, views, materialized views (name, type, comments)
- Columns (name, type, nullable, defaults, comments)
- Constraints (primary keys, foreign keys, unique, check)
- Indexes (name, columns, unique flag)
Cache behavior:
- Automatically populated on first AI request
- Stored in-memory per connection
- Frontend can trigger refresh via
RefreshSchemaCacheRPC - Shared across all AI operations (GenerateSQL, ExplainSQL, etc.)
Config (/server/lib/config.ts)
loadConfig(path?)- Load and validate TOMLgetConnections(),getConnectionById(id)getAuthConfig(),isAuthEnabled()getAuthProvider(type)- Find auth provider by type ('google','keycloak','okta')getExternalUrl()
SQL Autocomplete Pipeline
Located in src/lib/sql/autocomplete/. Eight modular components:
tokenizer.ts- Lexical analysis of SQLparser.ts- Error-tolerant SQL parsingsection-detector.ts- Context detection (SELECT_COLUMNS, FROM, WHERE, etc.)scope-analyzer.ts- Table aliases, CTEs, available columnscandidate-generator.ts- Generate completions based on contextranker.ts- Rank by relevance and match typepipeline.ts- Orchestrate the pipelinetypes.ts- Shared type definitions
Development
pnpm dev # Full dev (gen + server + vite)
pnpm build # Production build
pnpm build:server # Server only
pnpm test # All tests
pnpm test:parser # SQL parser tests
pnpm test:format # SQL formatter tests
pnpm test:autocomplete # Autocomplete pipeline tests
pnpm test:api # API tests with HurlDev Mode
- Frontend: Vite dev server (port 5173) with proxy to backend
- Backend: esbuild watch + Node.js watch (port 9876)
- Proxy routes:
/api/*,/connection.v1.*,/query.v1.*→:9876
Production
- Server serves frontend from
dist/client - Single process on PORT (default 9876)
Code Style
- Functional components with hooks
- Type imports:
import type { ... } - Tailwind utility classes for styling
- Keep components focused and composable
- Use existing UI components from
src/components/ui/ - Use
clsxandtailwind-mergefor conditional classes
Key Files
Configuration
pgconsole.toml- Application configurationvite.config.ts- Frontend build configscripts/build-server.mjs- Server build config
Backend
server/index.ts- Server entry pointserver/lib/config.ts- Config parsing and validationserver/lib/iam.ts- Permission checking (requirePermission, getUserPermissions)server/lib/sql-permissions.ts- SQL permission detection using parserserver/lib/schema-cache.ts- Backend schema cache for AI featuresserver/auth-routes.ts- Auth endpointsserver/services/query-service.ts- Core query executionserver/services/connection-service.ts- Connection managementserver/services/ai-service.ts- AI-powered SQL features
Frontend
src/App.tsx- Route setup and auth redirectsrc/components/sql-editor/SQLEditorLayout.tsx- Main editor containersrc/components/sql-editor/hooks/useEditorTabs.ts- Tab state machinesrc/lib/connect-client.ts- RPC client setupsrc/lib/schema-store.ts- Schema cachingsrc/lib/sql/autocomplete/pipeline.ts- Autocomplete orchestration
Protocol Buffers
proto/connection.proto- Connection service definitionproto/query.proto- Query service definition (13 RPCs)proto/ai.proto- AI service definition (6 RPCs)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

