# Institutions

Institutions define organizations, groups, and systems -- entities that function like characters but represent collectives rather than individuals. Unlike locations (which model *where*), institutions model *what structures and organizations* operate in your world.

---

## Syntax

```bnf
<institution-decl> ::= "institution" <identifier> "{" <institution-body> "}"

<institution-body> ::= (<field> | <uses-behaviors> | <uses-schedule> | <prose-block>)*

<uses-behaviors>  ::= "uses" "behaviors" ":" "[" <behavior-link> ("," <behavior-link>)* "]"

<behavior-link>   ::= "{" "tree" ":" <path> ","?
                           ("when" ":" <expression> ","?)?
                           ("priority" ":" <priority-level> ","?)? "}"

<priority-level>  ::= "low" | "normal" | "high" | "critical"

<uses-schedule>   ::= "uses" "schedule" ":" <identifier>
                     | "uses" "schedules" ":" "[" <identifier> ("," <identifier>)* "]"
```

An institution declaration consists of:
- The `institution` keyword
- A unique name (identifier)
- A body block containing fields, resource links, and optional prose blocks

---

## Basic Institution

The simplest institution has a name and descriptive fields:

```storybook
institution BakersGuild {
    type: trade_guild
    members: 50
    founded: "1892"
    reputation: 0.85
}
```

---

## Fields

Institution fields describe properties of the organization:

```storybook
institution BakersGuild {
    type: trade_guild
    members: 50
    founded: "1892"
    reputation: 0.85
    dues_annual: 120
    meeting_frequency: "monthly"
    accepts_apprentices: true
    max_apprentices: 10
    location: BakersGuildHall
}
```

### Common Field Patterns

| Field | Type | Description |
|-------|------|-------------|
| `type` | enum/identifier | Category of organization |
| `members` | integer | Membership count |
| `founded` | string | Establishment date |
| `reputation` | float | Public standing (0.0-1.0) |
| `location` | identifier | Where the institution operates |
| `leader` | identifier | Who runs the institution |

These are conventions -- you define whatever fields make sense for your world.

---

## Prose Blocks

Institutions support prose blocks for rich narrative documentation:

```storybook
institution BakersGuild {
    type: trade_guild
    members: 50

    ---description
    The Bakers Guild has been the backbone of the town's bread trade
    since 1892. Members share recipes, arrange apprenticeships, and
    collectively negotiate flour prices with suppliers.
    ---

    ---charter
    Article I: All members shall maintain the highest standards of
    baking quality. Article II: Apprentices must complete a three-year
    training program. Article III: Monthly meetings are mandatory.
    ---

    ---traditions
    Every autumn, the Guild hosts the Great Bake-Off, a competition
    open to all members. The winner earns the title of Master Baker
    for the following year.
    ---
}
```

**Prose block rules:**
- Start with `---tag_name` on its own line
- Content is free-form text (Markdown supported)
- End with `---` on its own line
- Multiple prose blocks per institution are allowed
- Each tag must be unique within the institution

---

## Resource Linking: Behaviors

Institutions can link to [behavior trees](./11-behavior-trees.md) using the `uses behaviors` clause. This defines what actions the institution takes as a collective entity.

### Simple Behavior Linking

```storybook
institution BakersGuild {
    type: trade_guild
    members: 50

    uses behaviors: [
        { tree: ManageApprentices },
        { tree: NegotiateSuppliers },
        { tree: HostEvents }
    ]
}
```

Each behavior link is an object with a `tree` field referencing a behavior tree by name or path.

### Behavior Links with Priority

```storybook
institution BakersGuild {
    type: trade_guild

    uses behaviors: [
        { tree: ManageApprentices, priority: normal },
        { tree: NegotiateSuppliers, priority: high },
        { tree: HostEvents, priority: low }
    ]
}
```

Priority levels: `low`, `normal` (default), `high`, `critical`.

### Conditional Behavior Links

```storybook
institution BakersGuild {
    type: trade_guild

    uses behaviors: [
        { tree: ManageApprentices },
        { tree: NegotiateSuppliers, priority: high },
        { tree: EmergencyMeeting, when: reputation < 0.3, priority: critical }
    ]
}
```

The `when` clause takes an [expression](./17-expressions.md) that determines when the behavior activates.

### Behavior Link Fields

| Field | Required | Type | Description |
|-------|----------|------|-------------|
| `tree` | Yes | path | Reference to a behavior tree |
| `priority` | No | priority level | Execution priority (default: `normal`) |
| `when` | No | expression | Activation condition |

---

## Resource Linking: Schedules

Institutions can link to [schedules](./14-schedules.md) using the `uses schedule` or `uses schedules` clause.

### Single Schedule

```storybook
institution BakersGuild {
    type: trade_guild
    uses schedule: GuildOperatingHours
}
```

### Multiple Schedules

```storybook
institution BakersGuild {
    type: trade_guild
    uses schedules: [WeekdaySchedule, WeekendSchedule, HolidaySchedule]
}
```

---

## Complete Syntax Example

An institution using all available features:

```storybook
institution BakersGuild {
    type: trade_guild
    members: 50
    founded: "1892"
    reputation: 0.85
    dues_annual: 120
    location: BakersGuildHall
    leader: Martha
    accepts_apprentices: true

    uses behaviors: [
        { tree: ManageApprentices, priority: normal },
        { tree: NegotiateSuppliers, priority: high },
        { tree: HostAnnualBakeOff, when: month is october, priority: high },
        { tree: EmergencyMeeting, when: reputation < 0.3, priority: critical }
    ]

    uses schedule: GuildOperatingHours

    ---description
    The Bakers Guild has been the backbone of the town's bread trade
    since 1892. Martha Baker currently serves as Guild Master.
    ---

    ---membership_rules
    New members must be nominated by an existing member and pass
    a baking trial. Apprentices are accepted from age 16.
    ---
}
```

---

## Membership Modeling

Institutions themselves don't have a built-in membership list. Instead, model membership through character fields or relationships:

### Via Character Fields

```storybook
character Martha {
    age: 45
    guild_member: true
    guild_role: guild_master
    guild: BakersGuild
}

character Jane {
    age: 19
    guild_member: true
    guild_role: apprentice
    guild: BakersGuild
}
```

### Via Relationships

```storybook
relationship GuildMembership {
    Martha as guild_master { }
    BakersGuild as organization { }
    bond: 0.95
    years_active: 20
}

relationship Apprenticeship {
    Jane as apprentice { }
    BakersGuild as guild { }
    Martha as mentor { }
    years_completed: 1
    years_remaining: 2
}
```

---

## Institutions vs. Characters

Both institutions and characters can use behaviors and schedules, but they serve different purposes:

| Aspect | Institutions | Characters |
|--------|-------------|------------|
| Represents | Organizations, collectives | Individuals |
| Species | No | Yes (optional) |
| Templates | No | Yes (optional) |
| `uses behaviors` | Yes | Yes |
| `uses schedule` | Yes | Yes |
| Prose blocks | Yes | Yes |
| Participation in relationships | Yes (via name) | Yes (via name) |

Use institutions when you need an entity that acts collectively: a guild votes, a government issues decrees, a school enrolls students.

---

## Use Cases

- **Organizations**: Guilds, companies, governments, religions
- **Social structures**: Families, tribes, castes, classes
- **Systems**: Economic systems, magical systems, legal frameworks
- **Abstract entities**: Dream logic, fate, cultural norms
- **Collectives**: Military units, sports teams, musical ensembles

---

## Complete Example: Baker Family World

```storybook
use schema::enums::{GuildRole, InstitutionType};

institution BakersGuild {
    type: trade_guild
    members: 50
    founded: "1892"
    reputation: 0.85
    location: BakersGuildHall
    leader: Martha
    annual_dues: 120
    accepts_apprentices: true
    max_apprentices_per_mentor: 2

    uses behaviors: [
        { tree: ManageApprentices, priority: normal },
        { tree: NegotiateSuppliers, priority: high },
        { tree: HostAnnualBakeOff, when: month is october, priority: high }
    ]

    uses schedule: GuildOperatingHours

    ---description
    The Bakers Guild has served the town since 1892, ensuring quality
    standards and fair pricing across all bakeries. Monthly meetings
    are held at the Guild Hall, and the annual Bake-Off is the
    highlight of the autumn calendar.
    ---
}

institution TownCouncil {
    type: government
    members: 12
    meets: "first Monday of each month"
    location: TownHall
    jurisdiction: "town limits"

    uses behaviors: [
        { tree: ReviewPetitions },
        { tree: AllocateBudget, priority: high }
    ]

    ---description
    The elected body governing the town. Martha Baker has been
    lobbying them for years about flour import tariffs.
    ---
}

institution BakersBakeryBusiness {
    type: business
    owner: Martha
    employees: 4
    location: BakersBakery
    annual_revenue: 180000
    established: "2011"

    uses behaviors: [
        { tree: DailyBakingOps, priority: high },
        { tree: InventoryManagement },
        { tree: CustomerService }
    ]

    uses schedule: BakeryOperatingHours

    ---description
    The business entity behind Baker's Bakery. Martha runs the
    operation with help from her daughter Jane (apprentice baker),
    two full-time bakers, and a part-time cashier.
    ---
}
```

---

## Validation Rules

1. **Unique names**: Institution names must be unique within their scope
2. **Valid field values**: All fields must have values conforming to [value types](./18-value-types.md)
3. **Unique field names**: No duplicate field names within an institution
4. **Unique prose tags**: No duplicate prose block tags within an institution
5. **Valid behavior links**: Each behavior link must have a `tree` field
6. **Valid priority levels**: Priority must be `low`, `normal`, `high`, or `critical`
7. **Valid schedule references**: Schedule names in `uses schedule`/`uses schedules` must be valid identifiers
8. **Valid identifiers**: Institution names must follow identifier rules (`[a-zA-Z_][a-zA-Z0-9_]*`)

---

## Cross-References

- [Characters](./10-characters.md) -- Characters can be members of institutions
- [Locations](./16a-locations.md) -- Institutions can be associated with locations
- [Behavior Trees](./11-behavior-trees.md) -- Institutions can use behaviors
- [Schedules](./14-schedules.md) -- Institutions can use schedules
- [Relationships](./15-relationships.md) -- Model membership via relationships
- [Expressions](./17-expressions.md) -- Conditional behavior activation
- [Value Types](./18-value-types.md) -- All field value types
- [Other Declarations](./16-other-declarations.md) -- Overview of all utility declarations
- [Validation Rules](./19-validation.md) -- Complete validation reference
