.rules file for agent grounding

I think this was brought up a few months ago but now that other solutions (Cline, Cursor) have a rules file I think it’s worth revisiting. Especially with newer LLM’s becoming more ambitious and doing more than desired at times. Are there plans for a .rules type file to help the Agent stay grounded into a set of rules?

The Cline rules bank is an interesting approach though I’m still unsure how well LLM’s are adhering to complex rule sets on larger code bases. About half way down this link is the rules bank visual.

Thanks!

6 Likes

I think I agree with you (if I understand the suggestion). There are a set of coding preferences I have (e.g., never using memory storage, creating columns as nullable, adding unit tests, asking before adding an SDK or integrating an API) that I need to type every time.

Commenting for reach. I’d like to see a way to add per project or global system prompt(s) to ensure agents code within a predefined set of guardrails.

i use an agents.md per project. I think it helps, but never sure if it’s my file that helps, or replit improving thigs their side.

AI IDE Development Guide (agents.md) - Node.js Backend

IMPORTANT: This guide provides principles and patterns, NOT prescriptive code. Agents should adapt these concepts to specific needs rather than copying code examples exactly.

:warning: CRITICAL IMPORT RULES :warning:

Node.js Backend - NEVER use require() - ES Modules Only

// ❌ WRONG - Will break in Vite/modern environments
const express = require('express');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');

// ✅ CORRECT - Always use ES6 imports
import express from 'express';
import jwt from 'jsonwebtoken';
import crypto from 'crypto';
import { readFileSync } from 'fs';

Frontend - NEVER use require() - ES Modules Only

// ❌ WRONG - Will break the application
const jwt = require('jsonwebtoken');

// ✅ CORRECT - Always use ES6 imports
import jwt from 'jsonwebtoken';

Stack Overview

  • Package Manager: npm only (no yarn/pnpm)
  • Database: Neon PostgreSQL (offsite)
  • Backend: Node.js + Express.js (ES Modules only)
  • Frontend: React (ES Modules only)
  • UI Framework: TailwindCSS + shadcn/ui (prefer standard Card components)
  • Build: Vite (dev only, disabled for production)
  • Deployment: Railway (auto-scaling)
  • Storage: Replit Object Storage SDK (never local fs)
  • Config: Replit Secrets (never .env files)
  • Dependencies: Allow auto-upgrades to non-breaking stable versions

Core Principles

Naming Consistency (CRITICAL)

  • Database fields, form names, and variables must ALWAYS match exactly
  • Use snake_case everywhere: user_id, email_address, created_at
  • Never convert between camelCase and snake_case

Database Standards

  • Always construct raw SQL - you know SQL well, use it directly
  • Always use native snake_case field names - no camelCase conversion
  • No ORM - use raw SQL with pg (node-postgres)
  • Use parameterized queries for safety

File Organization Principles

  • Monorepo structure - keep frontend and backend together
  • Group routes thematically from day one - avoid refactoring pain later
  • Separate concerns clearly: /api/auth/, /api/users/, /api/billing/
  • Modular route files - don’t put all routes in one file

Deployment Constraints

  • Never use local filesystem - files don’t persist in Railway
  • Use Replit Object Storage SDK for all file operations
  • All config via Replit Secrets - no .env files anywhere

Architecture Decisions

  • REST APIs - keep it simple and standard
  • Multi-method Authentication - Support Passport.js + JWT + Replit Auth for maximum compatibility
  • TailwindCSS + shadcn/ui - consistent design system with accessible components
  • Rich dev logging, error-only production - use middleware to filter
  • Minimal caching strategy - reduce server/DB load for multi-user scenarios

Critical Port & Environment Rules

Port Binding (CRITICAL for Railway)

  • Development: Can use localhost or 127.0.0.1
  • Production: MUST use 0.0.0.0 to bind to all interfaces
  • This prevents deployment failures on Railway

Environment Detection Principles

  • Use app.get('env') for Express environment checking
  • Check NODE_ENV, ENVIRONMENT, REPLIT_DEPLOYMENT_ID
  • Prevent Vite HMR from running in production
  • Serve static files in production, let Vite handle development

Express.js Environment Patterns

// Environment detection for static file serving
if (app.get('env') === 'production') {
  // Serve built React app from dist/
  app.use(express.static('frontend/dist'));
} else {
  // Development: Vite handles frontend
  // Backend only serves API routes
}

Authentication Strategy

Multi-Method Support Principle

Support multiple authentication methods with graceful fallbacks:

  1. Passport.js sessions (primary for web apps)
  2. JWT tokens (for APIs and autoscale compatibility)
  3. Replit Auth (development convenience)

Implementation Approach

  • Use Express.js middleware for authentication
  • Passport.js for session management and strategies
  • JWT for stateless API authentication
  • Redis sessions for production, memory store for development

Session Management Strategy

  • Development: MemoryStore is acceptable
  • Production: Use connect-redis for session persistence
  • Fallback: Graceful degradation if Redis unavailable
  • Security: Proper cookie settings for production

LiteLLM Integration Principles

Cost Tracking (CRITICAL)

  • Always track costs for any LLM operation
  • Include user attribution, operation type, model used
  • Provide cost visibility to users and admins
  • Store cost data in database with proper indexing

Error Handling Strategy

  • Don’t break chat functionality when handling errors
  • Use global event system for error notifications
  • Provide helpful error messages with model and version info
  • Implement toast notifications for user feedback

Version Management

  • Execute Python scripts from Node.js for LiteLLM version detection
  • Include version in error messages for debugging
  • Support version endpoint for health checks

Express.js Best Practices

Middleware Organization

  • Authentication middleware first
  • Error handling middleware last
  • Route-specific middleware in route files
  • Global middleware in main app file

Route Organization Principles

  • Separate route files by feature (auth.js, users.js, costs.js)
  • Use Express Router for modular routes
  • Mount routers in main app file only
  • Keep individual route handlers focused

Error Handling Strategy

  • Global error handling middleware
  • Consistent error response format
  • Proper HTTP status codes
  • Development vs production error details

React Best Practices

Component Anti-Patterns to Avoid

  • Never use React.memo with () => true - this freezes components
  • Always include proper dependencies in useEffect/useCallback
  • Use refs for WebSocket handlers to avoid stale state closures
  • Implement error boundaries for graceful failure handling

State Management Principles

  • Use React Query for server state
  • Global events for cross-component communication
  • Context for auth state
  • Local state for UI interactions

Error Handling Strategy

  • Global error events that React components can listen to
  • Fallback error display when React isn’t ready
  • Hybrid toast system (React + DOM fallback)

TailwindCSS + shadcn/ui Principles

Design System Approach

  • Use design tokens, not hardcoded colors (bg-primary not bg-blue-500)
  • Prefer standard shadcn/ui Card components over custom implementations
  • Use theme-aware classes for dark/light mode support
  • Don’t mix CSS approaches - pure Tailwind utility classes

Component Strategy

  • Leverage shadcn/ui for accessibility and consistency
  • Extend shadcn/ui components rather than rebuilding
  • Use Radix UI primitives through shadcn/ui
  • Implement proper theme provider for dark mode

Database Patterns

Node.js Database Connection

  • Use pg (node-postgres) for PostgreSQL connections
  • Implement connection pooling for performance
  • Use environment variables for connection strings
  • Handle connection errors gracefully

Query Principles

  • Write explicit SQL queries with specific field selection
  • Use proper indexing for performance
  • Always use parameterized queries for security ($1, $2, etc.)
  • Keep queries readable and well-commented

Performance Approach

  • Select only needed fields (SELECT user_id, email not SELECT *)
  • Use appropriate indexes on frequently queried fields
  • Monitor query performance
  • Implement query timeout handling

Error Handling & Logging Standards

Logging Strategy

  • Use structured logging (winston, pino, or similar)
  • Rich, detailed logging in development
  • Error-only logging in production (use middleware filtering)
  • Include context: user ID, operation, timestamp
  • Use consistent log prefixes for easy filtering

Express.js Error Middleware

  • Implement global error handling middleware
  • Catch async errors properly
  • Return consistent JSON error format
  • Log errors with full context

Session & Storage Management

Express.js Session Strategy

  • Development: express-session with MemoryStore
  • Production: connect-redis for session persistence
  • Configuration: Proper cookie settings for security
  • Secrets: Use strong session secrets from environment

File Storage Approach

  • Never use local filesystem in production
  • Always use Replit Object Storage for persistence
  • Generate safe file paths for temporary operations
  • Clean up temporary files after use

Node.js Specific Patterns

ES Module Configuration

  • Use "type": "module" in package.json
  • Update all import statements to ES6 syntax
  • Handle dynamic imports for Node.js built-ins when needed
  • Ensure all dependencies support ES modules

Process Management

  • Handle process signals gracefully (SIGTERM, SIGINT)
  • Implement proper shutdown procedures
  • Clean up resources (database connections, file handles)
  • Use process.env for environment variables

Child Process Execution

  • Use child_process for executing external scripts
  • Handle stdout/stderr properly
  • Implement timeouts for external processes
  • Proper error handling for failed executions

Critical Anti-Patterns (NEVER DO THESE)

Import Issues

  • :cross_mark: Using require() anywhere in the codebase
  • :cross_mark: Mixing CommonJS and ES modules
  • :cross_mark: Not setting "type": "module" in package.json

Express.js Issues

  • :cross_mark: Putting all routes in main app file
  • :cross_mark: Missing error handling middleware
  • :cross_mark: Not using parameterized queries
  • :cross_mark: Synchronous operations blocking the event loop

Environment Issues

  • :cross_mark: Using 127.0.0.1 binding in Railway production
  • :cross_mark: Running Vite dev server in production
  • :cross_mark: Hardcoded environment paths
  • :cross_mark: Not checking app.get('env') for Express environment

Authentication Issues

  • :cross_mark: Custom auth logic instead of Passport.js middleware
  • :cross_mark: Single auth method without fallbacks
  • :cross_mark: Insecure session configuration
  • :cross_mark: Not handling session store failures

Database Issues

  • :cross_mark: SQL injection from non-parameterized queries
  • :cross_mark: Not using connection pooling
  • :cross_mark: Blocking the event loop with synchronous database operations
  • :cross_mark: Not handling database connection errors

LiteLLM Issues

  • :cross_mark: Missing cost tracking for operations
  • :cross_mark: Breaking chat during error handling
  • :cross_mark: Ignoring version information in errors
  • :cross_mark: Not handling LiteLLM service unavailability

Key Dependencies (Auto-Upgrading Versions)

Node.js Backend

{
  "type": "module",
  "dependencies": {
    "express": "^4.18.0",
    "pg": "^8.11.0",
    "passport": "^0.7.0",
    "passport-local": "^1.0.0",
    "passport-jwt": "^4.0.0",
    "express-session": "^1.17.0",
    "connect-redis": "^7.1.0",
    "redis": "^4.6.0",
    "jsonwebtoken": "^9.0.0",
    "bcrypt": "^5.1.0",
    "winston": "^3.10.0"
  },
  "devDependencies": {
    "nodemon": "^3.0.0",
    "@types/express": "^4.17.0",
    "@types/passport": "^1.0.0"
  }
}

Frontend

{
  "dependencies": {
    "react": "^18.0.0",
    "tailwindcss": "^3.3.0",
    "class-variance-authority": "^0.7.0",
    "lucide-react": "^0.300.0",
    "@radix-ui/react-*": "^1.0.0"
  }
}

Development Setup

Server Configuration

  • Use nodemon for development auto-restart
  • Configure proper environment variable loading
  • Set up hot reload for development
  • Implement graceful shutdown handling

Development vs Production

  • Different database connection strings
  • Different session store configuration
  • Different logging levels
  • Different static file serving strategies

Debug Approaches

Systematic Debugging

  1. Verify ES module setup - check package.json type and imports
  2. Check environment detection - ensure proper prod/dev handling
  3. Test authentication flow - verify all auth methods work
  4. Validate error handling - ensure errors don’t break functionality
  5. Check cost tracking - verify LiteLLM operations are tracked
  6. Test database connections - verify pooling and error handling

Common Investigation Steps

  • Check server logs for import/module errors
  • Verify Express.js middleware order
  • Test auth endpoints with different methods
  • Validate database queries with proper parameterization
  • Check environment variables are properly loaded
  • Monitor connection pool usage

Node.js Specific Debugging

  • Check event loop blocking with --trace-warnings
  • Monitor memory usage for leaks
  • Verify async/await error handling
  • Test graceful shutdown procedures

Guidelines for AI Agents:

  1. These are principles, not rigid rules - adapt to specific project needs
  2. Focus on the “why” behind patterns rather than copying code exactly
  3. Prioritize working solutions over perfect adherence to examples
  4. Don’t force patterns that don’t fit the specific use case
  5. Always implement critical safety measures: ES modules, cost tracking, error handling
  6. Feel free to modify approaches as long as core principles are maintained

Critical Success Factors:

  • ES module consistency prevents import errors
  • Proper environment detection prevents deployment failures
  • Multi-method auth provides maximum compatibility
  • Cost tracking prevents unexpected bills
  • Error handling maintains user experience
  • Design system consistency improves maintainability

This guide prioritizes preventing common time-wasting mistakes while maintaining flexibility for AI agents to adapt patterns to specific Node.js project requirements.

2 Likes

Very useful. Thanks for sharing. How do we make the agent persist and follow the rules. I also previously used a rules files but it does not follow the rules continuously and misses the context.