> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getnao.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Rules

> Define how your agent should behave and respond

Rules guide your agent's behavior, ensuring it responds appropriately and follows your organization's standards.

## RULES.md File

When you initialize a nao project with `nao init`, a `RULES.md` file is automatically created in your project root. It is loaded with **every** message to the agent, so keep it lean.

`RULES.md` has two jobs:

1. **Orchestrator**: point the agent to the right context fast - which metric maps to which definition, which topic maps to which file, which question type maps to which table or skill.
2. **Broad rules**: how to query and how to answer (tone, SQL conventions, data access).

Everything else - per-table schemas, full metric semantics, domain-specific rules - belongs in a referenced file. **`RULES.md` should never duplicate context that already lives elsewhere in your repo.** It points to it.

<Tip>
  Since `RULES.md` is included with every message, keeping it concise optimizes performance and cost. When `nao sync` has already populated per-table docs, a semantic layer, or `docs/`, point to those instead of restating them.
</Tip>

## Recommended structure

`nao init` scaffolds `RULES.md` with the sections below. Keep the ones that fit your project and drop any already covered by synced context.

| Section                    | Purpose                                                                                                                                                            |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `## Business overview`     | What the company does and how it makes money.                                                                                                                      |
| `## Data architecture`     | Warehouse, data stack, layers, and data sources.                                                                                                                   |
| `## Context map`           | The index of where context lives: per-table files, key repo files, `docs/`, and the semantic layer. The orchestrator's routing table.                              |
| `## Core data models`      | `Most Used Tables` (one-line pointers, always) plus `Tables detail` (only when no richer table docs exist elsewhere).                                              |
| `## Key Metrics Reference` | Canonical metric definitions, **only if** no semantic layer or metric docs already define them. Otherwise a one-line pointer to where they live.                   |
| `## Date filtering`        | A few example SQL formulas (last X weeks, last X days, current month) the agent extrapolates from.                                                                 |
| `## Analysis Process`      | The steps the agent follows: resolve the metric definition, read relevant docs, select tables, check column values before filtering, query, validate, add context. |

### Point to context, don't copy it

The `## Context map` section is what keeps `RULES.md` lean. Instead of restating column lists or metric formulas, route the agent to where they already live:

```markdown theme={null}
## Context map

**Per-table context** - each `databases/.../table=<name>/` folder contains:
- `columns.md` - column names, types, descriptions
- `profiling.md` - distinct counts, min/max, and `top_values`. Read before filtering on any column value.

**Repos:**
- `repos/dbt/` - dbt project. Column docs: `models/silver.yml`. Domain decisions: `models/silver/*_ANALYTICS_DECISIONS.md`. Semantic layer (metrics): `models/silver_semantic_layer.yml`.

**Docs:**
- `docs/crm.md` - CRM funnel statuses and opportunity stages. Read before any sales question.

**Semantic layer:** metrics are defined in `repos/dbt/models/silver_semantic_layer.yml`. Query through it, don't recompute from raw tables.
```

### Conditional sections

Two sections are conditional. Include them only when that context does not already exist elsewhere:

* **`Tables detail`**: skip it when per-table docs (`how_to_use.md`, `ai_summary.md`) or dbt `schema.yml` column docs already describe your tables - the `Most Used Tables` pointers and the Context map route there already. Reserve it for cross-table pitfalls documented nowhere else.
* **`Key Metrics Reference`**: skip it when a semantic layer or metric docs define your metrics. Replace it with a one-line pointer so each metric keeps a single canonical definition.

<Tip>
  Each metric should have exactly one canonical definition across all your context. Duplicating it in `RULES.md` and a semantic layer is the most common cause of inconsistent answers.
</Tip>

## Broad rules example

Beyond routing, `RULES.md` holds the broad rules for how the agent queries and answers. Here's an example of that portion:

```markdown theme={null}
# Agent Rules

## Tone of Voice
- Be professional, concise, and friendly
- Always explain your reasoning
- If you make assumptions, state them clearly
- Suggest follow-up questions when relevant

## Interacting with Business Users

### Clarify Before Analyzing
Before running analysis, ask clarifying questions if any of these are unclear:

- **Time scope**: "What time period?" (last 7 days, MTD, YTD, specific dates)
- **Geographical scope**: "Which regions/countries?" (all, specific markets)
- **Segmentation**: "Which customer segments?" (all, B2B, B2C, enterprise)
- **Metric definition**: "Which definition of [metric]?" (if multiple exist)
- **Granularity**: "Daily, weekly, or monthly view?"

### Response Structure
For every analysis, follow this structure:

1. **Answer first**: State the key finding upfront
2. **Supporting data**: Show the numbers/visualization
3. **Context**: Add relevant comparisons (vs last period, vs target)
4. **Sanity checks**: Validate against known benchmarks
5. **Caveats**: Mention any data quality issues or limitations

### Sanity Check Guidelines
Before presenting results, verify:

- Numbers align with order-of-magnitude expectations
- Totals match when aggregated different ways
- Check against reference tables (e.g., monthly_kpi_summary)
- Flag if results differ significantly from historical trends

### Follow-Up Suggestions
After answering, suggest relevant next questions:

- Drill-downs (e.g., "Want to see this by region?")
- Related metrics (e.g., "Should we look at retention too?")
- Trend analysis (e.g., "Want to see how this changed over time?")

## SQL Code Style
- Use explicit JOIN syntax
- Add meaningful table aliases (e.g., u for users, o for orders)
- Format SQL for readability (indentation, line breaks)
- Always use LIMIT clauses for queries
- Prefer CTEs over nested subqueries

## Data Access
- Only query production tables (exclude *_test, *_staging)
- Default to last 30 days of data unless specified
- Maximum 10,000 rows per query

## Privacy & Security
- Never display full email addresses or phone numbers
- Flag queries accessing PII
- Aggregate personal data when possible

## Orchestration - Domain-Specific Context

For detailed information on specific topics, read the appropriate file:

- **Marketing questions**: Read `agent/semantics/marketing.md`
- **Finance questions**: Read `agent/semantics/finance.md`
- **Product questions**: Read `agent/semantics/product.md`

These files contain:
- Detailed business definitions
- Metric calculations
- Data quality considerations
- Domain-specific rules
```

## Sub Rules Files

For detailed, domain-specific information, create additional `.md` files in your context. The agent will read these files only when needed.

**File Structure Example**

```
context/
├── RULES.md                    # Core rules (always sent)
└── agent/
    └── semantics/
        ├── marketing.md        # Marketing-specific context
        ├── finance.md          # Finance-specific context
        └── product.md          # Product-specific context
```

You can use sub-rules files for this kind of context:

* **Business Context**: Context on your company and products.
* **Business Glossary**: Glossary on your business key concepts and terms.
* **Domain-Specific Context**: Specific knowledge on a domain (Business definitions, key metrics, key tables)
* **Data Quality Information**: Context on specific data issues or specificity to add explainability to the agent.
* **Events Information**: Context on specific events that happened and can help explain data.

<Tip>
  Organize your rules modularly to keep token costs low and maintain agent focus. Each metric should have only one canonical definition across all your rules files.
</Tip>

<Card title="Context Engineering Principles" icon="lightbulb" href="/nao-agent/context-engineering/principles">
  Learn how to organize rules effectively using MECE principles and modular structure
</Card>

**Example: Specialized File (marketing.md)**

Here's an example of a specialized context file:

````markdown theme={null}
# Marketing Context

## Business Definitions

### Customer Lifecycle
- **Lead**: Contact with valid email, no account created
- **Prospect**: Account created, no purchase
- **Customer**: At least one purchase completed
- **Active Customer**: Purchase within last 90 days
- **Churned Customer**: No activity for 180+ days AND no active subscription

### Campaign Types
- **Acquisition**: Targeting new leads/prospects
- **Retention**: Targeting existing customers
- **Winback**: Targeting churned customers
- **Upsell**: Targeting customers with expansion opportunities

## SQL Metrics Definitions

### Customer Acquisition Cost (CAC)
```sql
-- Definition
SELECT 
  SUM(marketing_spend) / COUNT(DISTINCT customer_id) AS cac
FROM campaigns c
LEFT JOIN customers cu ON c.campaign_id = cu.acquisition_campaign_id
WHERE c.campaign_type = 'acquisition'
  AND cu.created_at BETWEEN c.start_date AND c.end_date + INTERVAL '30 days'
````
