AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Configuring .windsurfrules: Enforcing Architecture Patterns and Coding Standards for Cascade in Codeium Windsurf

Vanessa Morais · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

When developers deploy Cascade—the autonomous agent in Codeium Windsurf—across complex codebases, they quickly discover a fundamental tension between agentic autonomy and architectural discipline. Unlike traditional auto-complete plugins that react only to the current line, Cascade reasons across the entire repository, plans multi-step implementations, creates new files, modifies shared modules, and executes commands inside the IDE terminal shell.

Without explicit boundaries, this autonomy causes rapid codebase decay. Cascade defaults to generic LLM training data: it will spontaneously introduce deprecated framework APIs (such as Next.js Pages Router patterns inside App Router projects), violate internal directory structures by creating random helper folders, litter code with permissive any types, and run npm install for unapproved libraries when native primitives or project utilities already exist.

At 365Finds, our research and engineering assessment is clear: unconstrained agentic autonomy is technical debt by default. A single developer relying on unstructured chat prompts cannot maintain repository integrity. To make Cascade a dependable full-stack contributor, engineering teams must configure .windsurfrules (and its modular evolution under .windsurf/rules/) as an executable architectural contract.

This guide details the core instruction paradigms, syntax structures, negative constraint patterns, and modular scoping strategies required to govern Cascade strictly and reliably.


1. Architectural Blueprint: The Core Structure of .windsurfrules

The legacy single-file .windsurfrules lives at the root of the workspace. Cascade automatically ingests this file as persistent context before executing planning, file modifications, or terminal operations.

While .windsurfrules is written in standard Markdown, 365Finds strongly advises against authoring rules in loose, narrative prose. Large language models (such as Claude 3.5/3.7 Sonnet and GPT-4o, which power Cascade workflows) parse structured blocks with substantially higher fidelity when instructions are segregated using XML pseudo-tags.

Below is a production-grade blueprint for full-stack TypeScript projects:

# Project Architectural Rules & Cascade Directives

<project_context>
Repository: E-Commerce & Subscription Core
Monorepo Structure: Turborepo with Next.js 14 (App Router) and Node.js microservices.
Primary Runtime: Node.js 20 LTS, pnpm package manager.
</project_context>

<tech_stack>
- Framework: Next.js 14.2+ (strictly App Router; no `pages/` directory conventions)
- Language: TypeScript 5.4+ (configured with `strict: true`, `noImplicitAny: true`)
- Styling: Tailwind CSS v3.4 with Shadcn UI (Radix primitives)
- Database & ORM: PostgreSQL with Prisma ORM 5.x
- State & Data Fetching: Server Components by default; TanStack Query v5 for client cache
- Validation: Zod schemas for all runtime input/output boundaries
</tech_stack>

<directory_conventions>
- `src/app/`: Routing layer only. Keep route handlers and page components thin.
- `src/features/[feature_name]/`: Feature-driven domain modules.
  - `components/`: UI components exclusive to this feature.
  - `server/`: Server actions, database queries, and service mutations.
  - `schemas/`: Zod validation contracts.
  - `types/`: Domain-specific TypeScript interfaces.
- `src/components/ui/`: Shared, headless/presentational UI primitives.
- `src/lib/`: Cross-cutting clients (Prisma client, Redis client, analytics).
- NEVER place ad-hoc helper files in the repository root or random nested directories.
</directory_conventions>

<coding_standards>
- Component Architecture:
  - Default to React Server Components (RSC).
  - Add `"use client"` directive only at leaf nodes requiring DOM events or hooks.
  - Maximum component size: 150 lines. Decompose larger components into sub-units.
- Type Safety:
  - Explicit return types are required on all exported functions and Server Actions.
  - Zero tolerance for `any` or loose casting (`as unknown as T`).
- Imports & Path Aliases:
  - Always use configured path aliases (`@/features/...`, `@/components/...`).
  - Never use relative imports exceeding two parent traversals (`../../`).
  - Prefer named exports over default exports for components and domain functions.
</coding_standards>

<negative_constraints>
- DO NOT execute `npm install`, `pnpm add`, or `yarn add` autonomously. If a missing dependency is needed, document it and request developer authorization.
- DO NOT use deprecated React lifecycles or legacy Next.js patterns (`getStaticProps`, `getServerSideProps`).
- DO NOT create custom CSS stylesheets or inline styles; use Tailwind utility classes.
- DO NOT access environment variables via raw `process.env` in domain logic; use the validated schema in `@/lib/env`.
- DO NOT execute destructive bash operations (`rm -rf`, `git reset --hard`, `git push --force`, or unapproved migration rollbacks).
</negative_constraints>

<terminal_execution_policy>
- Cascade may autonomously execute verification commands: `pnpm lint`, `pnpm test`, `pnpm typecheck`.
- Cascade must pause and request explicit user confirmation before executing database migrations (`prisma migrate dev`) or build commands that mutate system state.
</terminal_execution_policy>

2. Enforcing Directory Conventions and Domain Boundaries

Cascade excels at multi-file refactoring, but left unguided, its file-creation logic mimics a greenfield hobby project. It will place utility functions in whatever folder is closest to its active context window, leading to circular dependencies and architectural drift.

To enforce boundaries:

Structural Directory Binding

Explicitly map domain logic to designated directories. When Cascade is instructed:

<directory_conventions>
- All database mutation logic must reside in `src/features/[feature]/server/*.actions.ts`.
- Components in `src/components/ui/` must remain completely stateless and free of business logic.
</directory_conventions>

Cascade checks these paths during its planning phase. If a user asks Cascade to "add an update password function," the agent places the backend mutation inside src/features/auth/server/updatePassword.ts rather than embedding Prisma queries directly inside a React component.

Strict Path Aliasing

LLMs frequently fall back to chaotic relative imports such as import { db } from "../../../../lib/prisma". This breaks instantly when files are relocated. Mandating @/* path aliases in .windsurfrules ensures every file generated by Cascade aligns with your tsconfig.json paths:

- Always import internal modules using `@/lib/*`, `@/features/*`, or `@/components/*`.
- Flag and refactor any multi-level relative path (`../../`) encountered during edits.

3. The Supremacy of Negative Constraints (Anti-Patterns)

In prompt engineering for autonomous code agents, positive instructions ("write clean code", "use best practices") have near-zero marginal utility. Cascade already possesses broad pre-trained representations of modern syntax.

The primary failure mode of agents is path-of-least-resistance generation: reaching for outdated code snippets, introducing quick-fix packages, or using type bypasses to satisfy immediate linter complaints.

At 365Finds, our testing demonstrates that negative constraints (<negative_constraints> / <do_not>) deliver triple the compliance impact of positive suggestions. Explicitly pruning the model's solution space prevents bad code from ever entering your Git working tree.

High-Impact Negative Constraints Every Project Needs

Engineering HazardCascade Default TendencyEnforced Negative Constraint in .windsurfrules
Dependency SprawlInstalls axios, moment, or lodash to solve a minor taskDO NOT install external libraries. Utilize native fetch, date-fns, or web standards already installed.
Type InvalidationUses as any or @ts-ignore to silence compilation errorsDO NOT use 'any', 'unknown' casting, or '@ts-ignore' without prior written user justification in chat.
Architecture BleedInlines database queries inside UI componentsDO NOT import PrismaClient or run database queries inside files lacking the '.server.ts' suffix.
Obsolete Framework APIsMixes Next.js Pages router APIs into App router directoriesDO NOT use 'next/router'. Exclusively use 'next/navigation' ('useRouter', 'usePathname').
Destructive Shell ExecutionRuns cleanup commands that wipe untracked files or branchesDO NOT execute 'rm -rf', 'git clean', or 'git checkout --' inside the integrated terminal.

4. Scaling Beyond Single Files: The Modern .windsurf/rules/ Directory

While a single root .windsurfrules file is straightforward, it suffers from hard limitations in enterprise applications:

  1. Character Budget Limits: In Codeium Windsurf, single workspace rule files are capped at 12,000 characters (and global rules at 6,000 characters).
  2. Context Window Dilution: Forcing Cascade to ingest 200 lines of frontend Tailwind and React guidelines when it is debugging a backend SQL migration wastes prompt tokens and dilutes the model's focus.

To solve this, Codeium Windsurf supports modular workspace rules under .windsurf/rules/ (and .devin/rules/). Each rule is a distinct Markdown file utilizing YAML frontmatter to define its activation mode.

The Four Activation Modes

flowchart TD
    Rule[Rule in .windsurf/rules/*.md] --> Trigger{trigger: mode}
    Trigger -->|always_on| A[Injected into every Cascade message prompt]
    Trigger -->|glob| B[Injected only when matching files are opened or edited]
    Trigger -->|model_decision| C[Description checked; full file loaded only when relevant]
    Trigger -->|manual| D[Loaded only when explicitly tagged via @rule-name]
  1. always_on: Loaded into Cascade's context on every message. Reserved for global architectural fundamentals, core tech stack versions, and security policies.
  2. glob: Dynamically attached only when Cascade reads, edits, or references files matching defined file glob patterns. This is the gold standard for separating frontend from backend rules.
  3. model_decision: Only the rule's description is exposed in the base prompt. If Cascade determines that the task requires this rule, it pulls the complete text on demand.
  4. manual: Excluded from autonomous injection. Activated only when the developer types @rule-name in the Cascade chat prompt.

Example: Modular Glob-Scoped Rules

File: .windsurf/rules/frontend-components.md

---
trigger: glob
globs: src/components/**/*.tsx,src/features/**/components/*.tsx
description: Component creation standards, React Server Component constraints, and accessibility rules.
---

# Frontend Component Standards

- Every interactive component must have an accessible ARIA label.
- Client components must declare `"use client"` at line 1.
- Use Tailwind utility classes; do not write custom CSS modules.
- Ensure all interactive button states include `:hover`, `:focus-visible`, and `:disabled` styling.

File: .windsurf/rules/backend-database.md

---
trigger: glob
globs: prisma/**/*,src/server/**/*.ts,src/features/**/server/*.ts
description: Database access rules, Prisma ORM standards, and transaction handling.
---

# Backend & Database Standards

- Never write raw SQL strings unless wrapped in `prisma.$queryRaw` with typed parameterization.
- Multi-table writes must always be executed within a `prisma.$transaction([])` block.
- All database mutation errors must be caught and mapped to standard domain error classes (`NotFoundError`, `ValidationError`, `UnauthorizedError`).

By leveraging glob triggers, a monorepo containing frontend, backend, and documentation can maintain 50,000 characters of detailed engineering rules without overloading Cascade's context budget on any individual prompt.


5. Architectural Hierarchy: Rules vs. Memories vs. Workflows

A frequent source of confusion in Codeium Windsurf is how .windsurfrules interacts with Cascade's other context mechanisms:

flowchart LR
    subgraph Persistent & Version-Controlled
        Rules[".windsurfrules / .windsurf/rules/"]
        Agents["AGENTS.md (Root & Subdirs)"]
        Workflows[".windsurf/workflows/*.md"]
    end
    subgraph Machine-Local & Ephemeral
        Memories["Cascade Auto-Memories (~/.codeium/windsurf/memories/)"]
    end

    Rules -->|Enforces Coding Standards| Cascade[Cascade AI Agent]
    Agents -->|Zero-Config Directory Scoping| Cascade
    Workflows -->|Manual Slash Commands /task| Cascade
    Memories -->|Learned Personal Patterns| Cascade

The Governance Distinction

  1. Rules (.windsurfrules and .windsurf/rules/*.md):

    • Explicit, developer-authored, version-controlled via Git.
    • Team-wide consistency: Every developer checking out the repo shares the exact same guardrails.
    • 365Finds Verdict: Rules are the authoritative source of truth for repository architecture.
  2. Memories (Automated Memories):

    • Introduced in Windsurf Wave 2. Cascade autonomously observes how you work and records observations locally in ~/.codeium/windsurf/memories/.
    • Critical Warning: Memories are machine-local and uncommitted. They do not transfer between machines or team members. 365Finds strongly cautions against relying on automated memories for team architecture. If Cascade learns a useful team pattern, immediately codify it into a version-controlled rule file.
  3. Workflows (.windsurf/workflows/*.md):

    • Reusable prompt procedures triggered manually via slash commands (e.g., /run-e2e, /deploy-staging). Workflows are operational runbooks, whereas rules are continuous constraints.
  4. AGENTS.md:

    • Location-scoped conventions. Devin Desktop and modern Windsurf runtimes treat a root-level AGENTS.md as always-on, and subdirectory AGENTS.md files as automatic globs for their respective folders.

6. Controlling Cascade's Autonomous Terminal Execution

Cascade is equipped with an integrated terminal shell tool. It can inspect compiler output, execute test suites, and attempt automatic bug remediation. In Windsurf Wave 1 and Wave 2, Codeium expanded Cascade's capability to run terminal commands autonomously without requiring manual click approval for every command.

To prevent uncontrolled shell behavior, engineering leads must configure terminal safety policies:

  1. Native Allow/Deny Lists: Configure IDE settings (settings.json) to classify commands:
    • Safe (Auto-execute): ls, git status, git diff, pnpm test, pnpm lint.
    • Ambiguous (Require approval or strict confirmation): pnpm install, tar, python script.py.
    • Dangerous (Strict manual approval): rm, git reset, prisma migrate reset, dropdb.
  2. Rule-Level Shell Directives: Explicitly state shell restrictions in .windsurfrules:
    <terminal_policies>
    - Cascade must run `pnpm typecheck` after completing multi-file modifications.
    - Cascade is forbidden from running migration scripts against remote staging or production databases.
    - Cascade must never run background daemon processes (`pnpm dev`, `docker compose up -d`) that hijack the terminal session.
    </terminal_policies>
    

When Cascade detects compiler or type-checker errors via the terminal, its internal planning agent systematically reads the problem stack, locates cross-file references, and applies patches that respect the rules file.


7. 365Finds Operational Implementation Strategy

To implement .windsurfrules successfully across engineering teams, 365Finds recommends the following five-step rollout:

  1. Audit Common Agent Regressions: Review recent Git commits where developers used Cascade. Identify the top three recurring errors (e.g., wrong import paths, missing Zod schemas, unapproved packages).
  2. Draft a Concise Core Rule File: Begin with a focused .windsurfrules file of fewer than 150 lines. Focus exclusively on the tech stack, directory layout, and 5 to 7 high-priority negative constraints.
  3. Migrate to Modular Scoping Early: Once the rule file approaches 5,000 characters, break it into .windsurf/rules/ with glob triggers. Keep the root file strictly for baseline architecture.
  4. Treat Rules as Code in CI/CD: Commit all rule files to Git. Any architectural shift (e.g., migrating from Prisma to Drizzle, or updating Next.js versions) must include a corresponding PR updating .windsurf/rules/.
  5. Practice Chat Reset Discipline: When working on large features, long conversation threads accumulate context noise. If Cascade begins to deviate from .windsurfrules, wipe the chat session and start a fresh prompt. Cascade will re-read the clean rule files on cold start without conversational baggage.

By treating .windsurfrules not as an afterthought, but as an executable architectural constitution, development teams transform Codeium Windsurf's Cascade from an erratic code generator into a disciplined, high-velocity engineering partner.


References