Skip to content
SaaS4Builders
Extending

Prompt Patterns

Reusable patterns for structuring AI agent context: workplan templates, code templates, agent personas, acceptance criteria conventions, and the reference-copy approach that keeps AI output consistent.

SaaS4Builders uses several structured patterns to keep AI agent output consistent and correct. These patterns are not specific to Claude Code — they work with any AI coding agent that supports context files. This page documents the patterns so you can extend them for your own features.


Pattern 1 — Workplan Templates

Workplans are structured documents that decompose a feature into executable Work Units. They are the primary artifact that drives development — both human and AI-assisted.

Structure

Every workplan follows this structure:

# W{id} — {Title} — Workplan

> **Phase:** W{id} — {Title}
> **Duration:** {estimated weeks}
> **Work Units Backend:** {count}
> **Work Units Frontend:** {count}
> **Prerequisites:** {list or "None"}

## Context & Objectives
### Problem
{Why this feature is needed}

### Objective
{What the feature delivers}

### Non-Goals
| Non-Goal | Reason |
|----------|--------|
| {Item} | {Why it's out of scope} |

## Architecture Notes
{Key design decisions and trade-offs}

## Existing Infrastructure
| Component | File | Role |
|-----------|------|------|
| {Reusable component} | {path} | {How it's used} |

## API Endpoints
| Method | Endpoint | Description | Auth |
|--------|----------|-------------|------|
| POST | `/api/v1/tenant/{tenant}/resource` | Create resource | Sanctum |

## Deliverables Summary
| Category | Count |
|----------|-------|
| Migrations | {n} |
| Models | {n} |
| Actions | {n} |
| Tests | ~{n} |

## Dependency Graph
{ASCII diagram showing WU dependencies by layer}

## Execution Order
| Period | Work Units | Focus |
|--------|------------|-------|
| Day 1-2 | WU-B01 | Domain primitives |

# BACKEND WORK UNITS
{WU-B01, WU-B02, ...}

# FRONTEND WORK UNITS
{WU-F01, WU-F02, ...}

## Validation Checklist
{Quality gates for the entire milestone}

## AI Agent Guardrails
{Feature-specific rules preventing common mistakes}

Non-Goals Section

The Non-Goals table is the most underrated section. Without it, AI agents (and developers) add features that seem related but are out of scope. Each non-goal should have a reason — "not in scope" is not a reason; "deferred to V2 because it requires a billing provider abstraction" is.

Dependency Graph

The ASCII dependency graph shows which Work Units can run in parallel and which must be sequential:

LAYER 1 — Domain Primitives
  WU-B01: Models, migrations, factories
          │
          ▼
LAYER 2 — Business Logic
  WU-B02: Actions     WU-B03: Queries  (parallelizable)
          │                    │
          └────────┬───────────┘
                   ▼
LAYER 3 — HTTP Layer
  WU-B04: Controllers, routes, resources
          │
          ▼
LAYER 4 — Integration Tests
  WU-B05: End-to-end API tests

Dependencies flow downward only. WUs within the same layer can run in parallel if they don't share files.


Pattern 2 — Work Unit Structure

Each Work Unit within a workplan follows a strict format. This format is designed to be machine-readable — the /implement-wu skill parses it to understand what to build.

## WU-B{nn}: {Descriptive Title}

**Objective:** {1-2 sentence goal — what this WU delivers and why}

**Files ({N})**

path/to/new/file.php (new) path/to/existing/file.php (modified)


**Dependencies:** {WU-B01, WU-B02 | None}

### Implementation Details
{Design guidance, patterns to follow, key decisions.
Include request/response shapes for API endpoints.
Include translation keys if user-facing strings.}

### Acceptance Criteria
- [ ] Migration creates `table` with columns: id, tenant_id, ...
- [ ] Action dispatches `Event` after creation
- [ ] 8 tests passing (24 assertions) covering happy path, validation, tenant isolation
- [ ] PHPStan level 9 passes on modified files

### Verification Commands
```bash
docker compose exec php vendor/bin/pint --dirty
docker compose exec php vendor/bin/phpstan analyse --memory-limit=1G
docker compose exec php php artisan test --compact --filter=RelevantTest

### Acceptance Criteria Rules

Acceptance criteria must be objectively verifiable. Compare:

| Bad (Subjective) | Good (Verifiable) |
|---|---|
| Code is clean | `pint --dirty` produces no output |
| Tests pass | 8 tests passing (24 assertions) |
| No errors | PHPStan level 9 passes on modified files |
| Well-tested | Covers happy path, 401, 403, 404, 422, tenant isolation |
| Properly formatted | ISO-8601 dates via `->toIso8601String()` |

Every criterion should be checkable by running a command, reading the code, or verifying a specific behavior. If you cannot describe how to verify it, rewrite it.

### File List Convention

The file list uses `(new)` and `(modified)` annotations so the agent knows whether to create or edit:

backend/database/migrations/2025_01_15_create_notifications_table.php (new) backend/app/Models/Notification.php (new) backend/app/Application/Notification/Actions/CreateNotification.php (new) backend/routes/api.php (modified)


This prevents the agent from accidentally overwriting existing files or trying to edit files that don't exist yet.

---

## Pattern 3 — Code Templates

Code templates provide copy-paste starting points for common file types. They live in `docs/architecture/backend/TEMPLATES.md` and `docs/architecture/frontend/TEMPLATES.md`.

### Backend Templates

The backend templates cover the four most common file types:

**Query template** — For read-only operations with filtering and pagination:

```php [backend template — Query]
final class ListX
{
    public function execute(ListXFilters $filters): LengthAwarePaginator
    {
        return QueryBuilder::for(Model::class)
            ->allowedFilters([/* explicit whitelist */])
            ->allowedSorts([/* explicit whitelist */])
            ->defaultSort('-created_at')
            ->paginate($filters->perPage);
    }
}

Action template — For mutations wrapped in a transaction:

backend template — Action
final class CreateX
{
    public function execute(CreateXData $data): Model
    {
        return DB::transaction(function () use ($data) {
            $model = Model::create([/* ... */]);
            // dispatch events, sync relations
            return $model;
        });
    }
}

Resource template — For API responses with snake_case keys:

backend template — Resource
final class XResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id'         => $this->uuid,
            'name'       => $this->name,
            'amount_cents' => $this->amount_cents,    // money: integer cents
            'currency'   => $this->currency,           // money: ISO 4217
            'created_at' => $this->created_at->toIso8601String(),  // dates: ISO-8601
        ];
    }
}

Frontend Templates

The frontend templates cover the vertical-slice module structure:

Zod schema template — For runtime API response validation:

frontend template — schemas.ts
import { z } from 'zod'

export const itemSchema = z.object({
  id: z.string().uuid(),
  // fields matching the backend Resource (camelCase)
  createdAt: z.string().datetime(),
  updatedAt: z.string().datetime(),
})

export const itemListSchema = z.array(itemSchema)

export type Item = z.infer<typeof itemSchema>

API module template — For tenant-scoped API calls:

frontend template — api.ts
export function useItemApi() {
  const client = useApiClient()
  const { tenantPath } = useCurrentTenant()

  return {
    async list(): Promise<Item[]> {
      const response = await client.get(tenantPath('/items'))
      return itemListSchema.parse(response.data).data
    },

    async create(input: CreateItemInput): Promise<Item> {
      const response = await client.post(tenantPath('/items'), input)
      return itemSchema.parse(response.data)
    },
  }
}

How Templates Work with Skills

Templates and skills are complementary:

  • Templates provide the starting code structure (the "what")
  • Skills provide the domain rules and workflow (the "how" and "why")

When the /new-feature skill runs, it tells the agent to create Actions, Queries, Resources, and schemas. The agent looks at the template files to understand the structural pattern, then fills in the domain-specific details guided by the skill's mental model and rules.

Templates are living documents. As the project evolves, update the templates to reflect current patterns. Skills reference templates by file path, so the agent always uses the latest version.

Pattern 4 — Agent Personas

Agent personas are pre-configured AI agents with specific roles, tool access, and pre-loaded skills. They live in .claude/agents/ as Markdown files with YAML frontmatter.

Anatomy

.claude/agents/backend-dev.md
---
name: backend-dev
description: "Laravel backend developer for SaaS4Builders.
  Use for API endpoints, Actions, Queries, DTOs, migrations,
  models, policies, billing, tenancy, and all backend PHP work."
tools: Read, Write, Edit, Bash, Grep, Glob
model: sonnet
skills:
  - billing
  - api-contracts
  - domain-model
  - multi-tenancy
memory: project
---

# Backend Developer — SaaS4Builders

You are a senior Laravel 13 developer working on the SaaS4Builders backend API.

## Scope Restriction
- You ONLY modify files under `backend/`, `docs/`, and root config files.
- You NEVER modify files under `frontend/`.

## Before Writing Code
1. Read backend conventions
2. Read API contract format
3. Verify the endpoint exists in the endpoint catalog
4. If NOT documented: propose the shape and stop

## Architecture Rules
{Layer rules, code style, multi-tenancy, i18n}

## Quality Gate (Before Finishing)
- [ ] Formatting check passes
- [ ] Static analysis passes
- [ ] Tests pass (targeted filter)
- [ ] Tenant isolation tested
- [ ] i18n strings in all 4 locales

Key Design Decisions

Scope restriction: The backend-dev agent is explicitly told it cannot modify frontend files. This prevents cross-stack contamination — a backend agent should not edit Vue components. If a task requires frontend changes, the agent reports what the frontend needs and stops.

Pre-loaded skills: The skills field loads domain context automatically. The backend-dev agent always has billing, API contracts, domain model, and multi-tenancy context — the four areas where backend mistakes are most costly.

Quality gate: Every agent persona ends with a quality checklist. This ensures the agent runs formatting, static analysis, and tests before considering the task complete.

Creating a Custom Agent

To create a new agent persona:

  1. Create a file at .claude/agents/your-agent.md
  2. Define the YAML frontmatter with name, tools, model, skills
  3. Write the system prompt with scope restrictions, rules, and quality gates
  4. Reference the agent from tasks or sessions

Example — a frontend agent:

.claude/agents/frontend-dev.md
---
name: frontend-dev
description: "Nuxt 4 / Vue frontend developer for SaaS4Builders."
tools: Read, Write, Edit, Bash, Grep, Glob
model: sonnet
skills:
  - api-contracts
  - domain-model
memory: project
---

# Frontend Developer — SaaS4Builders

You are a senior Nuxt 4 / Vue developer.

## Scope Restriction
- You ONLY modify files under `frontend/`.
- You NEVER modify files under `backend/`.

## Architecture Rules
- Vertical slices in `features/core/<feature>/`
- API calls via `useXxxApi()` composables
- Validate responses with Zod `.parse()`
- Use `useAuthenticatedAsyncData()` for authenticated data
- i18n strings in all 4 locales (en, fr, es, it)

## Quality Gate
- [ ] `pnpm typecheck` passes
- [ ] `pnpm lint` passes
- [ ] `pnpm test -- --run` passes

Read-Only Agents

The reviewer agent demonstrates a read-only pattern:

.claude/agents/reviewer.md
---
name: reviewer
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit, NotebookEdit
---

The disallowedTools field prevents the agent from modifying any files. The Bash tool is allowed but restricted to read-only commands (git log, git diff, static analysis). This creates a safe code review agent that analyzes code quality without risk of accidental changes.


Pattern 5 — Convention Files as Guardrails

Convention files are standalone documents that define rules for a specific concern. They serve as both human documentation and AI agent guardrails.

The Pattern

Each convention file follows this structure:

  1. Purpose statement — What this file governs
  2. Rules — Stated as invariants with MUST/NEVER/ALWAYS
  3. Examples — Correct and incorrect usage
  4. Quick reference — Decision tables for common choices

Key Convention Files in the Project

FileGovernsKey Rules
CONTRACTS.mdAPI response formatsnake_case keys, ISO-8601 dates, amount_cents + currency for money
TEMPLATES.mdCode structureStandard file templates for Actions, Queries, Resources, schemas
QUERY-BUILDER.mdFiltering and sortingSpatie QueryBuilder conventions, explicit whitelists, default sorts
DOMAIN-GLOSSARY.mdBusiness terminologyCanonical names for entities, states, and concepts

Writing Your Own Convention File

When you add a new domain, consider creating a convention file if:

  • The domain has non-obvious rules that developers (or AI agents) would violate
  • Multiple files must follow the same pattern consistently
  • The rules are cross-cutting (affect multiple layers or features)

Template:

# {DOMAIN} Convention Rules

## Purpose
This file defines the conventions for {domain}. AI agents and developers
MUST follow these rules when working in this area.

## Rules

### Rule 1 — {Name}
{Description}

**MUST:** {what to do}
**NEVER:** {what to avoid}

**Correct:**
```code
{correct example}

Incorrect:

{incorrect example}

Rule 2 — {Name}

...

Quick Reference

DecisionRule
{situation}{what to do}

### How Convention Files Feed Into Skills

Skills reference convention files in their References section:

```markdown
## References
- API response format convention file — Source of truth for response shapes
- Query builder convention file — Filtering and sorting patterns
- Domain glossary — Canonical entity and state names

When the agent needs deeper context during a task, it reads the referenced convention file. This creates a two-tier context system:

  1. Skill — Provides the mental model and workflow (always loaded)
  2. Convention files — Provide the detailed rules (loaded on demand)

Pattern 6 — Progress Tracking

The /implement-wu skill maintains a tracking file that records completed Work Units. This file serves as both progress documentation and a dependency checker.

Tracking File Structure

# Current Work Unit Progress — W{id}

**Workplan:** W{id} — {Title}
**Last Updated:** 2025-06-15 (WU-B03 completed — Subscription queries)

---

## WU-B01: Domain Primitives
**Status:** Completed

### Overview
Created the notification model, migration, and factory.

### Files Created
| File | Purpose |
|------|---------|
| `backend/database/migrations/...` | Notifications table |
| `backend/app/Models/Notification.php` | Eloquent model with BelongsToTenant |

### Acceptance Criteria
- [x] Migration creates `notifications` table with all columns
- [x] Model uses `BelongsToTenant` trait
- [x] Factory generates realistic data
- [x] PHPStan passes on new files

Why Tracking Matters for AI Agents

When the agent starts a new WU via /implement-wu, it reads the tracking file to:

  1. Check dependencies — If WU-B03 depends on WU-B01, the agent verifies WU-B01 is marked as completed
  2. Understand context — The Files Created tables show what was built in previous WUs, helping the agent understand what already exists
  3. Avoid rework — If a WU is already completed, the agent reports it and stops instead of re-implementing

This is the mechanism that makes multi-session development reliable. Each session picks up exactly where the last one left off.


Putting It All Together

The patterns work as a system. A typical feature development flow uses them in this order:

  1. Workplan template — Structure the feature into Work Units
  2. Convention files — Define any new domain rules
  3. Code templates — Provide the structural starting points
  4. Skill — Create a domain skill if the area has non-obvious rules
  5. Agent persona — Add the skill to relevant agents
  6. Progress tracking — Record completed WUs for multi-session continuity

Each pattern solves a specific problem. Together, they create a development workflow where AI agents produce consistent, correct code — and where every session builds on the last without losing context.


What's Next