release: Storybook v0.2.0 - Major syntax and features update

BREAKING CHANGES:
- Relationship syntax now requires blocks for all participants
- Removed self/other perspective blocks from relationships
- Replaced 'guard' keyword with 'if' for behavior tree decorators

Language Features:
- Add tree-sitter grammar with improved if/condition disambiguation
- Add comprehensive tutorial and reference documentation
- Add SBIR v0.2.0 binary format specification
- Add resource linking system for behaviors and schedules
- Add year-long schedule patterns (day, season, recurrence)
- Add behavior tree enhancements (named nodes, decorators)

Documentation:
- Complete tutorial series (9 chapters) with baker family examples
- Complete reference documentation for all language features
- SBIR v0.2.0 specification with binary format details
- Added locations and institutions documentation

Examples:
- Convert all examples to baker family scenario
- Add comprehensive working examples

Tooling:
- Zed extension with LSP integration
- Tree-sitter grammar for syntax highlighting
- Build scripts and development tools

Version Updates:
- Main package: 0.1.0 → 0.2.0
- Tree-sitter grammar: 0.1.0 → 0.2.0
- Zed extension: 0.1.0 → 0.2.0
- Storybook editor: 0.1.0 → 0.2.0
This commit is contained in:
2026-02-13 21:52:03 +00:00
parent 80332971b8
commit 16deb5d237
290 changed files with 90316 additions and 5827 deletions

View File

@@ -0,0 +1,213 @@
# Language Overview
> **The Storybook language enables narrative simulation through structured declarations of characters, behaviors, relationships, and events.**
## Philosophy
Storybook is a domain-specific language for narrative simulation, influenced by:
- **Rust**: Strong typing, explicit declarations, and clear ownership semantics
- **C#**: Object-oriented patterns with declarative syntax
- **Python**: Readable, accessible syntax that prioritizes clarity
The language balances **technical precision** with **narrative expressiveness**, making it accessible to storytellers while maintaining the rigor developers need.
## Design Principles
### 1. Code as Narrative
Named nodes and prose blocks let code read like stories:
```storybook
behavior Baker_MorningRoutine {
choose daily_priority {
then prepare_sourdough { ... }
then serve_customers { ... }
then restock_display { ... }
}
}
```
### 2. Explicit is Better Than Implicit
Every declaration is self-documenting:
- Character fields show what defines them
- Behavior trees show decision structures
- Relationships name their participants
### 3. Progressive Disclosure
Simple cases are simple, complex cases are possible:
- Basic characters need just a name and fields
- Templates enable inheritance and reuse
- Advanced features (state machines, decorators) available when needed
### 4. Semantic Validation
The compiler catches narrative errors:
- Bond values must be 0.0..1.0
- Schedule blocks can't overlap
- Life arc transitions must reference valid states
## Language Structure
### Declaration Types
Storybook has 10 top-level declaration types:
| Declaration | Purpose | Example |
|-------------|---------|---------|
| `character` | Define entities with traits and behaviors | A baker with skills and schedule |
| `template` | Reusable patterns with ranges | A generic NPC template |
| `behavior` | Decision trees for actions | How a character responds to events |
| `life_arc` | State machines for life stages | Apprentice → Baker → Master |
| `schedule` | Time-based activities | Daily routine from 6am to 10pm |
| `relationship` | Connections between entities | Parent-child with bond values |
| `institution` | Organizations and groups | A bakery with employees |
| `location` | Places with properties | The town square |
| `species` | Type definitions with traits | Human vs Cat vs Rabbit |
| `enum` | Named value sets | EmotionalState options |
### Value Types
Fields can contain:
- **Primitives**: `42`, `3.14`, `"text"`, `true`
- **Time**: `08:30:00`, `14:15`
- **Duration**: `2h30m`, `45s`
- **Ranges**: `20..40` (for templates)
- **Identifiers**: `OtherCharacter`, `path::to::Thing`
- **Lists**: `[1, 2, 3]`
- **Objects**: `{ field: value }`
- **Prose blocks**: ` ---tag\nMulti-line\ntext\n---`
### Expression Language
Conditions and queries use:
- **Comparisons**: `age > 18`, `energy <= 0.5`
- **Equality**: `status is active`, `ready is true`
- **Logic**: `tired and hungry`, `rich or lucky`, `not ready`
- **Field access**: `self.health`, `other.bond`
- **Quantifiers**: `forall x in children: x.happy`
## Compilation Model
### Source → AST → SBIR → Runtime
```
.sb files → Parser → Abstract Syntax Tree → Resolver → SBIR Binary
```
**SBIR** (Storybook Intermediate Representation) is a compact binary format that:
- Resolves all cross-file references
- Validates semantic constraints
- Optimizes for simulation runtime
### Validation Layers
1. **Lexical**: Valid tokens and syntax
2. **Syntactic**: Correct grammar structure
3. **Semantic**: Type checking, reference resolution
4. **Domain**: Narrative constraints (bond ranges, schedule overlaps)
## File Organization
### Project Structure
```
my-storybook/
├── characters/
│ ├── baker.sb
│ └── family.sb
├── behaviors/
│ └── daily_routine.sb
├── world/
│ ├── locations.sb
│ └── institutions.sb
└── schema/
├── species.sb
└── templates.sb
```
### Import System
Use `use` statements to reference definitions from other files:
```storybook
use schema::species::Human;
use schema::templates::Adult;
character Baker: Human from Adult {
// ...
}
```
**Resolution order:**
1. Same file
2. Explicitly imported
3. Error if not found
## Quick Reference
### Character Declaration
```storybook
character Name: Species from Template {
field: value
field: value
---prose_tag
Text content
---
}
```
### Behavior Tree
```storybook
behavior Name {
choose label { // Selector
then label { ... } // Sequence
if (condition) // Condition
ActionName // Action
include path // Subtree
}
}
```
### Life Arc
```storybook
life_arc Name {
state StateName {
on condition -> NextState
}
}
```
### Schedule
```storybook
schedule Name {
08:00 -> 12:00: activity { }
12:00 -> 13:00: lunch { }
}
```
### Relationship
```storybook
relationship Name {
Person1 as role
Person2 as role
bond: 0.85
}
```
## Next Steps
Dive deeper into each declaration type:
- [Characters](10-characters.md) - Detailed character syntax
- [Behavior Trees](11-behavior-trees.md) - Complete behavior node reference
- [Decorators](12-decorators.md) - All decorator types
- [Life Arcs](13-life-arcs.md) - State machine semantics
- [Schedules](14-schedules.md) - Time-based planning
- [Relationships](15-relationships.md) - Connection modeling
- [Other Declarations](16-other-declarations.md) - Templates, institutions, etc.
- [Expressions](17-expressions.md) - Full expression language
- [Value Types](18-value-types.md) - All field value types
- [Validation](19-validation.md) - Error checking rules
---
**Philosophy Note**: Storybook treats narrative as data. Characters aren't objects with methods - they're **declarations** of traits, connected by **behaviors** and **relationships**. This separation enables rich analysis, modification, and simulation of narrative worlds.

View File

@@ -0,0 +1,429 @@
# Characters
Characters are the primary entities in Storybook—the people, creatures, and beings that inhabit your world. Each character has a set of attributes that define who they are, what they can do, and how they relate to the world around them.
## Syntax
```bnf
<character-decl> ::= "character" <identifier> <species-clause>? <template-clause>? <body>
<species-clause> ::= ":" <qualified-path>
<template-clause> ::= "from" <qualified-path> ("," <qualified-path>)*
<body> ::= "{" <body-item>* "}"
<body-item> ::= <field>
| <uses-behaviors>
| <uses-schedule>
<uses-behaviors> ::= "uses" "behaviors" ":" <behavior-link-list>
<uses-schedule> ::= "uses" ("schedule" | "schedules") ":" (<qualified-path> | <schedule-list>)
<behavior-link-list> ::= "[" <behavior-link> ("," <behavior-link>)* "]"
<behavior-link> ::= "{" <behavior-link-field>* "}"
<behavior-link-field> ::= "tree" ":" <qualified-path>
| "when" ":" <expression>
| "priority" ":" ("low" | "normal" | "high" | "critical")
<schedule-list> ::= "[" <qualified-path> ("," <qualified-path>)* "]"
<field> ::= <identifier> ":" <value>
<value> ::= <literal>
| <qualified-path>
| <list>
| <object>
| <prose-block>
| <override>
<prose-block> ::= "---" <identifier> <content> "---"
```
## Components
### Name
The character's identifier. Must be unique within its scope and follow standard identifier rules (alphanumeric + underscore, cannot start with digit).
### Species (Optional)
The species clause (`: SpeciesName`) defines what the character fundamentally *is*. This is distinct from templates, which define what attributes they *have*.
- **Purpose**: Ontological typing—what kind of being this is
- **Validation**: Must reference a defined `species` declaration
- **Single inheritance**: A character can only have one species
- **Default behavior**: Species fields are inherited automatically
Example:
```storybook
character Martha: Human {
age: 34
}
```
### Template Inheritance (Optional)
The template clause (`from Template1, Template2`) specifies templates from which the character inherits fields. Templates provide reusable attribute sets.
- **Purpose**: Compositional inheritance—mix-and-match capabilities and traits
- **Multiple inheritance**: Characters can inherit from multiple templates
- **Merge semantics**: Fields from later templates override earlier ones
- **Override allowed**: Character fields override all inherited fields
Example:
```storybook
character Martha: Human from Baker, BusinessOwner {
specialty: "sourdough"
}
```
### Fields
Fields define the character's attributes using the standard field syntax. All [value types](./18-value-types.md) are supported.
**Common field categories:**
- **Physical traits**: `height`, `weight`, `age`, `eye_color`
- **Personality**: `confidence`, `patience`, `dedication`
- **Professional**: `skill_level`, `specialty`, `recipes_mastered`
- **State tracking**: `energy`, `mood`, `orders_today`
- **Capabilities**: `can_teach`, `can_work_independently`
### Prose Blocks
Characters can contain multiple prose blocks for narrative content. Common tags:
- `---backstory`: Character history and origin
- `---appearance`: Physical description
- `---personality`: Behavioral traits and quirks
- `---motivation`: Goals and desires
- `---secrets`: Hidden information
Prose blocks are narrative-only and do not affect simulation logic.
### Behavior Integration
Characters can link to [behavior trees](./14-behavior-trees.md) using the `uses behaviors` clause.
```storybook
character Guard {
uses behaviors: [
{
tree: combat::patrol_route
priority: normal
},
{
tree: combat::engage_intruder
when: threat_detected
priority: high
}
]
}
```
Each behavior link includes:
- **`tree`**: Qualified path to the behavior tree (required)
- **`when`**: Condition expression for activation (optional)
- **`priority`**: Execution priority (optional, default: `normal`)
See [Behavior Trees](./11-behavior-trees.md) for details on behavior tree syntax and semantics.
### Schedule Integration
Characters can follow [schedules](./16-schedules.md) using the `uses schedule` or `uses schedules` clause.
```storybook
character Baker {
uses schedule: BakerySchedule
}
character Innkeeper {
uses schedules: [WeekdaySchedule, WeekendSchedule]
}
```
- Single schedule: `uses schedule: ScheduleName`
- Multiple schedules: `uses schedules: [Schedule1, Schedule2]`
The runtime selects the appropriate schedule based on temporal constraints. See [Schedules](./14-schedules.md) for composition and selection semantics.
## Species vs. Templates
The distinction between species (`:`) and templates (`from`) reflects ontological vs. compositional typing:
| Feature | Species (`:`) | Templates (`from`) |
|---------|--------------|-------------------|
| **Semantics** | What the character *is* | What the character *has* |
| **Cardinality** | Exactly one | Zero or more |
| **Example** | `: Human`, `: Dragon` | `from Warrior, Mage` |
| **Purpose** | Fundamental nature | Reusable trait sets |
| **Override** | Can override species fields | Can override template fields |
Example showing both:
```storybook
species Dragon {
max_lifespan: 1000
can_fly: true
}
template Hoarder {
treasure_value: 0..1000000
greed_level: 0.0..1.0
}
template Ancient {
age: 500..1000
wisdom: 0.8..1.0
}
character Smaug: Dragon from Hoarder, Ancient {
age: 850
treasure_value: 500000
greed_level: 0.95
}
```
## Field Resolution Order
When a character inherits from species and templates, fields are resolved in this order (later overrides earlier):
1. **Species fields** (base ontology)
2. **Template fields** (left to right in `from` clause)
3. **Character fields** (highest priority)
Example:
```storybook
species Human {
lifespan: 80
speed: 1.0
}
template Warrior {
speed: 1.5
strength: 10
}
template Berserker {
speed: 2.0
strength: 15
}
character Conan: Human from Warrior, Berserker {
strength: 20
}
// Resolved fields:
// lifespan: 80 (from Human)
// speed: 2.0 (Berserker overrides Warrior overrides Human)
// strength: 20 (character overrides Berserker)
```
## Validation Rules
The Storybook compiler enforces these validation rules:
1. **Unique names**: Character names must be unique within their module
2. **Species exists**: If specified, the species must reference a defined `species` declaration
3. **Templates exist**: All templates in the `from` clause must reference defined `template` declarations
4. **No circular inheritance**: Templates cannot form circular dependency chains
5. **Field type consistency**: Field values must match expected types from species/templates
6. **Reserved fields**: Cannot use reserved keywords as field names
7. **Behavior trees exist**: All behavior tree references must resolve to defined `behavior` declarations
8. **Schedules exist**: All schedule references must resolve to defined `schedule` declarations
9. **Prose tag uniqueness**: Each prose tag can appear at most once per character
## Examples
### Basic Character
```storybook
character SimpleMerchant {
name: "Gregor"
occupation: "Fish Merchant"
wealth: 50
---personality
A straightforward fish seller at the market. Honest, hardworking,
and always smells faintly of mackerel.
---
}
```
### Character with Species
```storybook
character Martha: Human {
age: 34
skill_level: 0.95
specialty: "sourdough"
---backstory
Martha learned to bake from her grandmother, starting at age
twelve. She now runs the most popular bakery in town.
---
}
```
### Character with Template Inheritance
```storybook
character Jane: Human from Baker, PastrySpecialist {
age: 36
specialty: "pastries"
recipes_mastered: 120
years_experience: 18
can_teach: true
---appearance
A focused woman with flour-dusted apron and steady hands.
Known for her intricate pastry decorations and precise
temperature control.
---
}
```
### Character with All Features
```storybook
character CityGuard: Human from CombatTraining, LawEnforcement {
age: 30
rank: "Sergeant"
// Physical traits
height: 175
strength: 12
// Equipment
has_weapon: true
armor_level: 2
// Behavior integration
uses behaviors: [
{
tree: guards::patrol_route
priority: normal
},
{
tree: guards::engage_hostile
when: threat_detected
priority: high
},
{
tree: guards::sound_alarm
when: emergency
priority: critical
}
]
// Schedule integration
uses schedules: [guards::day_shift, guards::night_shift]
---backstory
A veteran of the city watch, now responsible for training new recruits
while maintaining order in the merchant district.
---
---personality
Gruff exterior with a hidden soft spot for street children. Follows
the rules but knows when to look the other way.
---
}
```
### Character with Overrides
```storybook
template WeaponUser {
damage: 5..15
accuracy: 0.7
}
character MasterSwordsman: Human from WeaponUser {
// Override template range with specific value
damage: 15
accuracy: 0.95
// Add character-specific fields
signature_move: "Whirlwind Strike"
}
```
## Use Cases
### Protagonist Definition
Define rich, dynamic protagonists with complex attributes:
```storybook
character Elena: Human from Scholar, Diplomat {
age: 28
intelligence: 18
charisma: 16
languages_known: ["Common", "Elvish", "Draconic"]
books_read: 347
current_quest: "Broker peace between warring kingdoms"
---backstory
Raised in the Grand Library, Elena discovered ancient texts that
hinted at a forgotten alliance between humans and dragons. She now
seeks to revive that alliance to end the current war.
---
}
```
### NPC Templates
Create diverse NPCs from templates:
```storybook
template Villager {
occupation: "Farmer"
wealth: 10..50
disposition: 0.0..1.0 // 0=hostile, 1=friendly
}
character Oswald: Human from Villager {
occupation: "Blacksmith"
wealth: 45
disposition: 0.8
}
character Mildred: Human from Villager {
occupation: "Baker"
wealth: 35
disposition: 0.95
}
```
### Ensemble Casts
Define multiple related characters:
```storybook
template BakeryStaff {
punctuality: 0.5..1.0
teamwork: 0.5..1.0
}
template Apprentice {
skill_level: 0.0..0.5
dedication: 0.5..1.0
}
character Elena: Human from BakeryStaff, Apprentice {
age: 16
natural_talent: 0.8
dedication: 0.9
---backstory
Elena comes from a family of farmers who could never afford to
buy bread from the bakery. When Martha offered her an apprenticeship,
she jumped at the chance to learn a trade.
---
}
```
## Cross-References
- [Species](./16-other-declarations.md#species) - Species declarations
- [Templates](./16-other-declarations.md#templates) - Template definitions and strict mode
- [Value Types](./18-value-types.md) - All supported value types
- [Behavior Trees](./11-behavior-trees.md) - Character behavior integration
- [Schedules](./14-schedules.md) - Character schedule integration
- [Relationships](./15-relationships.md) - Relationships between characters
- [Life Arcs](./13-life-arcs.md) - Character state machines over time
## Related Concepts
- **Instantiation**: Characters are concrete instances; they cannot be instantiated further
- **Composition**: Prefer template composition over deep species hierarchies
- **Modularity**: Characters can reference behaviors and schedules from other modules
- **Narrative-driven**: Use prose blocks to embed storytelling directly with data

View File

@@ -0,0 +1,765 @@
# Behavior Trees
Behavior trees define the decision-making logic for characters, institutions, and other entities. They model how an entity chooses actions, responds to conditions, and adapts to its environment. Storybook uses behavior trees for character AI, NPC routines, and complex reactive behavior.
## What is a Behavior Tree?
A behavior tree is a hierarchical structure that executes from root to leaves, making decisions based on success/failure of child nodes:
- **Composite nodes** (choose, then) have multiple children and control flow
- **Condition nodes** (if, when) test predicates
- **Action nodes** execute concrete behaviors
- **Decorator nodes** (repeat, invert, timeout, etc.) modify child behavior
- **Subtree nodes** (include) reference other behavior trees
Behavior trees are evaluated every tick (frame), flowing through the tree from root to leaves until a node returns success or failure.
## Syntax
```bnf
<behavior-decl> ::= "behavior" <identifier> <body>
<body> ::= "{" <prose-blocks>* <behavior-node> "}"
<behavior-node> ::= <selector>
| <sequence>
| <condition>
| <action>
| <decorator>
| <subtree>
<selector> ::= "choose" <label>? "{" <behavior-node>+ "}"
<sequence> ::= "then" <label>? "{" <behavior-node>+ "}"
<condition> ::= ("if" | "when") "(" <expression> ")"
<action> ::= <identifier> ( "(" <param-list> ")" )?
<param-list> ::= <field> ("," <field>)*
<decorator> ::= <decorator-type> ("(" <params> ")")? "{" <behavior-node> "}"
<subtree> ::= "include" <qualified-path>
<label> ::= <identifier>
```
## Composite Nodes
### Selector: `choose`
A selector tries its children in order until one succeeds. Returns success if any child succeeds, failure if all fail.
**Execution:**
1. Try first child
2. If succeeds -> return success
3. If fails -> try next child
4. If all fail -> return failure
**Use case:** "Try A, if that fails try B, if that fails try C..."
```storybook
behavior GuardBehavior {
choose guard_actions {
AttackIntruder // Try first
SoundAlarm // If attack fails, sound alarm
FleeInPanic // If alarm fails, flee
}
}
```
**Named selectors:**
```storybook
choose service_options {
then serve_regular {
CustomerIsWaiting
TakeOrder
}
then restock_display {
DisplayIsLow
FetchFromKitchen
}
}
```
Labels are optional but recommended for complex trees--they improve readability and debugging.
### Sequence: `then`
A sequence runs its children in order until one fails. Returns success only if all children succeed, failure if any fails.
**Execution:**
1. Run first child
2. If fails -> return failure
3. If succeeds -> run next child
4. If all succeed -> return success
**Use case:** "Do A, then B, then C... all must succeed"
```storybook
behavior BrewingSequence {
then brew_potion {
GatherIngredients // Must succeed
MixIngredients // Then this must succeed
Boil // Then this must succeed
BottlePotion // Finally this
}
}
```
**Named sequences:**
```storybook
then prepare_sourdough {
MixDough
KneadDough
ShapeLoaves
}
```
### Nesting Composites
Composite nodes can nest arbitrarily deep:
```storybook
behavior ComplexAI {
choose root_decision {
// Combat branch
then engage_combat {
if(enemy_nearby)
choose combat_tactics {
AttackWithSword
AttackWithMagic
DefendAndWait
}
}
// Exploration branch
then explore_area {
if(safe)
choose exploration_mode {
SearchForTreasure
MapTerritory
Rest
}
}
// Default: Idle
Idle
}
}
```
## Condition Nodes
Conditions test expressions and return success/failure based on the result.
### `if` vs. `when`
Both are semantically identical--use whichever reads better in context:
```storybook
behavior Example {
choose options {
// "if" for state checks
then branch_a {
if(player_nearby)
Attack
}
// "when" for event-like conditions
then branch_b {
when(alarm_triggered)
Flee
}
}
}
```
### Condition Syntax
```storybook
if(health < 20) // Comparison
when(is_hostile) // Boolean field
if(distance > 10 and has_weapon) // Logical AND
when(not is_stunned or is_enraged) // Logical OR with NOT
```
See [Expression Language](./17-expressions.md) for complete expression syntax.
## Action Nodes
Actions are leaf nodes that execute concrete behaviors. They reference action implementations in the runtime.
### Basic Actions
```storybook
behavior SimpleActions {
then do_things {
MoveForward
TurnLeft
Attack
}
}
```
### Actions with Parameters
Actions can have named parameters using parenthesis syntax:
```storybook
behavior ParameterizedActions {
then patrol {
MoveTo(destination: "Waypoint1", speed: 1.5)
WaitFor(duration: 5s)
MoveTo(destination: "Waypoint2", speed: 1.5)
}
}
```
**Parameter passing:**
- Parameters are passed as fields (name: value)
- All [value types](./18-value-types.md) supported
- Runtime validates parameter types
```storybook
behavior RichParameters {
then complex_action {
CastSpell(spell: "Fireball", target: enemy_position, power: 75, multicast: false)
Heal(amount: 50, target: self)
}
}
```
## Decorator Nodes
Decorators wrap a single child node and modify its behavior. See [Decorators](./12-decorators.md) for complete reference.
### Common Decorators
```storybook
behavior DecoratorExamples {
choose {
// Repeat infinitely
repeat {
PatrolRoute
}
// Repeat exactly 3 times
repeat(3) {
CheckDoor
}
// Repeat 2 to 5 times
repeat(2..5) {
SearchArea
}
// Invert success/failure
invert {
IsEnemyNearby // Returns success if enemy NOT nearby
}
// Retry up to 5 times on failure
retry(5) {
OpenLockedDoor
}
// Timeout after 10 seconds
timeout(10s) {
SolveComplexPuzzle
}
// Cooldown: only run once per 30 seconds
cooldown(30s) {
FireCannon
}
// If: only run if condition true
if(health > 50) {
AggressiveAttack
}
// Always succeed regardless of child result
succeed_always {
AttemptOptionalTask
}
// Always fail regardless of child result
fail_always {
ImpossipleTask
}
}
}
```
## Subtree References
The `include` keyword references another behavior tree, enabling modularity and reuse.
### Basic Subtree
```storybook
behavior PatrolRoute {
then patrol {
MoveTo(destination: "Waypoint1")
MoveTo(destination: "Waypoint2")
MoveTo(destination: "Waypoint3")
}
}
behavior GuardBehavior {
choose guard_ai {
then combat {
if(enemy_nearby)
include combat::engage
}
include PatrolRoute // Reuse patrol behavior
}
}
```
### Qualified Subtree References
```storybook
behavior ComplexAI {
choose ai_modes {
include behaviors::combat::melee
include behaviors::combat::ranged
include behaviors::exploration::search
include behaviors::social::greet
}
}
```
## Named Nodes
Both composite nodes (`choose`, `then`) can have optional labels:
```storybook
behavior NamedNodeExample {
choose daily_priority { // Named selector
then handle_special_orders { // Named sequence
CheckOrderQueue
PrepareSpecialIngredients
BakeSpecialItem
}
choose regular_work { // Named selector
then morning_bread { // Named sequence
MixSourdough
BakeLoaves
}
}
}
}
```
**Benefits:**
- **Readability**: Tree structure is self-documenting
- **Debugging**: Named nodes appear in execution traces
- **Narrative**: Labels can be narrative ("handle_special_orders" vs. anonymous node)
**Guidelines:**
- Use labels for important structural nodes
- Use descriptive, narrative names
- Omit labels for trivial nodes
## Complete Examples
### Simple Guard AI
```storybook
behavior GuardPatrol {
choose guard_logic {
// Combat if enemy nearby
then combat_mode {
if(enemy_nearby and has_weapon)
Attack
}
// Sound alarm if see intruder
then alarm_mode {
if(intruder_detected)
SoundAlarm
}
// Default: Patrol
then patrol_mode {
include PatrolRoute
}
}
}
```
### Complex NPC Behavior
```storybook
behavior Innkeeper_DailyRoutine {
---description
The innkeeper's behavior throughout the day. Uses selectors for
decision-making and sequences for multi-step actions.
---
choose daily_activity {
// Morning: Prepare for opening
then morning_prep {
when(time_is_morning)
then prep_sequence {
UnlockDoor
LightFireplace
PrepareBreakfast
WaitForGuests
}
}
// Day: Serve customers
then day_service {
when(time_is_daytime)
choose service_mode {
// Serve customer if present
then serve {
if(customer_waiting)
GreetCustomer
TakeOrder
ServeMeal
CollectPayment
}
// Restock if needed
then restock {
if(inventory_low)
ReplenishInventory
}
// Default: Clean
CleanTables
}
}
// Night: Close up
then evening_close {
when(time_is_evening)
then close_sequence {
DismissRemainingGuests
LockDoor
CountMoney
GoToBed
}
}
}
}
```
### Morning Baking Routine
```storybook
behavior Baker_MorningRoutine {
---description
Martha's morning routine: prepare dough step by step,
from mixing to shaping to baking.
---
then morning_baking {
// Start with sourdough
then prepare_starter {
CheckStarter
FeedStarter
WaitForActivity
}
// Mix the dough
then mix_dough {
MeasureFlour
AddWater
IncorporateStarter
}
// Knead and shape
then shape_loaves {
KneadDough
FirstRise
ShapeLoaves
}
// Bake
then bake {
PreHeatOven
LoadLoaves
MonitorBaking
}
}
}
```
### Repeating Behavior
```storybook
behavior Bakery_CustomerServiceLoop {
---description
The bakery's continuous customer service loop. Uses infinite
repeat decorator to serve customers throughout the day.
---
repeat {
then service_cycle {
// Check for customers
choose service_mode {
then serve_waiting {
if(customer_waiting)
GreetCustomer
TakeOrder
}
then restock_display {
if(display_low)
FetchFromKitchen
ArrangeOnShelves
}
}
// Process payment
CollectPayment
ThankCustomer
// Brief pause between customers
timeout(5s) {
CleanCounter
}
PrepareForNextCustomer
}
}
}
```
### Retry Logic for Delicate Recipes
```storybook
behavior Baker_DelicatePastry {
---description
Elena attempting a delicate pastry recipe that requires
precise technique. Uses retry decorator for persistence.
---
choose baking_strategy {
// Try when conditions are right
then attempt_pastry {
if(oven_at_temperature)
// Try up to 3 times
retry(3) {
then make_pastry {
RollDoughThin
ApplyFilling
FoldAndSeal
CheckForLeaks
}
}
}
// If oven not ready, prepare meanwhile
then prepare_meanwhile {
if(not oven_at_temperature)
then prep_sequence {
PrepareIngredients
MixFilling
ChillDough
}
}
}
}
```
## Integration with Characters
Characters link to behaviors using the `uses behaviors` clause:
```storybook
character Guard {
uses behaviors: [
{
tree: guards::patrol_route
priority: normal
},
{
tree: guards::engage_hostile
when: threat_detected
priority: high
},
{
tree: guards::sound_alarm
when: emergency
priority: critical
}
]
}
```
**Behavior selection:**
- Multiple behaviors evaluated by priority (critical > high > normal > low)
- Conditions (`when` clause) gate behavior activation
- Higher-priority behaviors preempt lower-priority ones
See [Characters](./10-characters.md#behavior-integration) for complete behavior linking syntax.
## Execution Semantics
### Tick-Based Evaluation
Behavior trees execute every "tick" (typically once per frame):
1. **Start at root** node
2. **Traverse** down to leaves based on composite logic
3. **Execute** leaf nodes (conditions, actions)
4. **Return** success/failure up the tree
5. **Repeat** next tick
### Node Return Values
Every node returns one of:
- **Success**: Node completed successfully
- **Failure**: Node failed
- **Running**: Node still executing (async action)
### Stateful vs. Stateless
- **Stateless nodes**: Evaluate fresh every tick (conditions, simple actions)
- **Stateful nodes**: Maintain state across ticks (decorators, long actions)
Example of stateful behavior:
```storybook
behavior LongAction {
timeout(30s) { // Stateful: tracks elapsed time
ComplexCalculation // May take multiple ticks
}
}
```
## Validation Rules
1. **At least one node**: Behavior body must contain at least one node
2. **Composite children**: `choose` and `then` require at least one child
3. **Decorator child**: Decorators require exactly one child
4. **Action exists**: Action names must reference registered actions in runtime
5. **Subtree exists**: `include` must reference a defined `behavior` declaration
6. **Expression validity**: Condition expressions must be well-formed
7. **Duration format**: Decorator durations must be valid (e.g., `5s`, `10m`)
8. **Unique labels**: Node labels (if used) should be unique within their parent
9. **Parameter types**: Action parameters must match expected types
## Best Practices
### 1. Prefer Shallow Trees
**Avoid:**
```storybook
choose {
then { then { then { then { Action } } } } // Too deep!
}
```
**Prefer:**
```storybook
choose root {
include combat_tree
include exploration_tree
include social_tree
}
```
### 2. Use Named Nodes for Clarity
**Avoid:**
```storybook
choose {
then {
IsHungry
FindFood
Eat
}
Wander
}
```
**Prefer:**
```storybook
choose survival {
then eat_if_hungry {
IsHungry
FindFood
Eat
}
Wander
}
```
### 3. Subtrees for Reusability
**Avoid:** Duplicating logic across behaviors
**Prefer:**
```storybook
behavior Combat_Common {
then attack_sequence {
DrawWeapon
Approach
Strike
}
}
behavior Warrior {
include Combat_Common
}
behavior Guard {
include Combat_Common
}
```
### 4. Decorators for Timing
**Avoid:** Manual timing in actions
**Prefer:**
```storybook
timeout(10s) {
ComplexTask
}
cooldown(30s) {
SpecialAbility
}
```
### 5. Guard for Preconditions
**Avoid:**
```storybook
then problematic {
ExpensiveAction // Always runs even if inappropriate
}
```
**Prefer:**
```storybook
if(can_afford_action) {
ExpensiveAction // Only runs when condition passes
}
```
## Cross-References
- [Decorators](./12-decorators.md) - Complete decorator reference
- [Characters](./10-characters.md) - Linking behaviors to characters
- [Expression Language](./17-expressions.md) - Condition expression syntax
- [Value Types](./18-value-types.md) - Parameter value types
- [Design Patterns](../advanced/20-patterns.md) - Common behavior tree patterns
## Related Concepts
- **Reactive AI**: Behavior trees continuously react to changing conditions
- **Hierarchical decision-making**: Composite nodes create decision hierarchies
- **Modularity**: Subtrees enable behavior reuse and composition
- **Narrative-driven design**: Named nodes make behavior trees readable as stories

View File

@@ -0,0 +1,492 @@
# Species
Species define the fundamental ontological categories of beings in your world. A species represents what a character or entity *is* at its core—human, dragon, sentient tree, animated playing card. Unlike templates (which provide compositional trait sets), species provide singular, essential identity.
## Syntax
```bnf
<species-decl> ::= "species" <identifier> <includes-clause>? <body>
<includes-clause> ::= "includes" <qualified-path> ("," <qualified-path>)*
<body> ::= "{" <species-body-item>* "}"
<species-body-item> ::= <field>
| <prose-block>
<field> ::= <identifier> ":" <value>
<prose-block> ::= "---" <identifier> <content> "---"
```
## Components
### Name
The species identifier. Must be unique within its module and follow standard identifier rules.
**Naming conventions:**
- Use PascalCase: `Human`, `Dragon`, `PlayingCardPerson`
- Be specific: `BakeryCat` vs. generic `Cat` if varieties exist
- Avoid abbreviations: `ElderDragon` not `EldDrgn`
### Includes Clause (Optional)
Species can include other species to inherit their fields. This enables species composition without deep hierarchies.
```storybook
species Mammal {
warm_blooded: true
has_fur: true
}
species Carnivore includes Mammal {
diet: "meat"
has_claws: true
}
species Feline includes Carnivore {
retractable_claws: true
purrs: true
}
```
**Semantics:**
- **Multiple includes**: `species X includes A, B, C`
- **Resolution order**: Left-to-right (later overrides earlier)
- **Transitive**: Including `Feline` also brings in `Carnivore` and `Mammal`
- **No circular includes**: Compiler rejects circular dependencies
### Fields
Species fields define the default attributes shared by all members of that species.
**Common field categories:**
- **Biological**: `lifespan`, `reproductive_cycle`, `diet`
- **Physical**: `has_fur`, `warm_blooded`, `can_fly`
- **Cognitive**: `sapience_level`, `intelligence_range`
- **Special abilities**: `can_vanish`, `breathes_fire`, `regenerates`
All [value types](./18-value-types.md) are supported. Unlike templates, species fields should use concrete values rather than ranges (templates handle variation).
### Prose Blocks
Species can include narrative descriptions. Common tags:
- `---description`: What this species is and how it behaves
- `---ecology`: Habitat, diet, lifecycle
- `---culture`: Social structures (if sapient)
- `---notes`: Design notes or inspirations
## Species vs. Templates
Understanding the distinction is crucial for effective modeling:
| Aspect | Species (`:`) | Templates (`from`) |
|--------|--------------|-------------------|
| **Question** | "What *is* it?" | "What *traits* does it have?" |
| **Cardinality** | One per character | Zero or more |
| **Inheritance** | `includes` (species from species) | Characters inherit from templates |
| **Variation** | Concrete defaults | Ranges allowed |
| **Example** | `species Human` | `template Warrior` |
| **Override** | Characters can override | Characters can override |
**When to use species:**
```storybook
species Dragon {
lifespan: 1000
can_fly: true
breathes_fire: true
}
character Smaug: Dragon {
// Smaug IS a Dragon
age: 850
}
```
**When to use templates:**
```storybook
template Hoarder {
treasure_value: 0..1000000
greed_level: 0.5..1.0
}
character Smaug: Dragon from Hoarder {
// Smaug HAS hoarder traits
greed_level: 0.95
}
```
## Field Resolution with Includes
When a species includes other species, fields are merged in declaration order:
1. **Base species** (leftmost in `includes`)
2. **Middle species** (middle in `includes`)
3. **Rightmost species** (rightmost in `includes`)
4. **Current species fields** (highest priority)
Example:
```storybook
species Aquatic {
breathes_underwater: true
speed_in_water: 2.0
}
species Reptile {
cold_blooded: true
speed_in_water: 1.0
}
species SeaTurtle includes Aquatic, Reptile {
has_shell: true
speed_in_water: 1.5 // Overrides both Aquatic and Reptile
}
// Resolved fields:
// breathes_underwater: true (from Aquatic)
// cold_blooded: true (from Reptile)
// speed_in_water: 1.5 (SeaTurtle overrides Reptile overrides Aquatic)
// has_shell: true (from SeaTurtle)
```
## Validation Rules
1. **Unique names**: Species names must be unique within their module
2. **No circular includes**: Cannot form include cycles (compile-time error)
3. **Includes exist**: All included species must be defined
4. **Field type consistency**: Field values must be well-typed
5. **Reserved keywords**: Cannot use reserved keywords as field names
6. **Prose tag uniqueness**: Each prose tag can appear at most once per species
## Examples
### Simple Species
```storybook
species Human {
lifespan: 70
---description
Bipedal mammals with complex language and tool use.
Highly variable in cultures and capabilities.
---
}
```
### Species with Includes
```storybook
species Mammal {
warm_blooded: true
has_fur: true
reproductive_cycle: "live_birth"
}
species Primate includes Mammal {
opposable_thumbs: true
sapience_potential: 0.5..1.0
}
species Human includes Primate {
sapience_potential: 1.0
language_complexity: "high"
---description
Highly intelligent primates with advanced tool use,
complex social structures, and symbolic communication.
---
}
```
### Domestic Species
```storybook
species Cat {
lifespan: 15
---description
Domestic cats often found in bakeries and shops for pest
control and companionship. Independent and territorial.
---
}
species Dog {
lifespan: 12
---description
Loyal companion animals. Some breeds are working dogs
found on farms and in family households.
---
}
```
### Fantasy Species Hierarchy
```storybook
species Draconic {
lifespan: 1000
magic_affinity: true
scales: true
---description
Ancient lineage of magical reptilian beings.
---
}
species Dragon includes Draconic {
can_fly: true
breathes_fire: true
hoard_instinct: 0.8
---description
The apex predators of the sky. Territorial, intelligent,
and obsessed with collecting treasure.
---
}
species Drake includes Draconic {
can_fly: false
breathes_fire: false
pack_hunting: true
---description
Smaller, land-bound cousins of true dragons. Hunt in packs
and lack the fire breath of their larger kin.
---
}
species Wyrm includes Draconic {
can_fly: false
breathes_fire: true
burrows_underground: true
---description
Serpentine dragons without legs or wings. Burrow through
earth and stone with ease.
---
}
```
### Composed Species
```storybook
species ElementalBeing {
physical_form: false
elemental_affinity: "none"
lifespan: 500
}
species FireElemental includes ElementalBeing {
elemental_affinity: "fire"
temperature: 1500 // Celsius
---ecology
Born from volcanic eruptions and wildfires. Feed on combustion
and heat. Hostile to water and ice.
---
}
species WaterElemental includes ElementalBeing {
elemental_affinity: "water"
fluidity: 1.0
---ecology
Manifest in rivers, lakes, and oceans. Can assume any liquid
form. Vulnerable to extreme heat.
---
}
```
### Species with Rich Metadata
```storybook
species Elf {
lifespan: 1000
aging_rate: 0.1 // Relative to humans
magic_sensitivity: 0.9
height_range: 160..190 // cm
---description
Long-lived humanoids with innate magical abilities and
connection to ancient forests.
---
---culture
Elven societies value art, music, and the preservation of
knowledge. They see the rise and fall of human kingdoms as
fleeting moments in the great tapestry of time.
---
---ecology
Elves are closely tied to the health of forests. When
woodlands are destroyed, nearby elven communities weaken
and may fade entirely.
---
---notes
Inspired by Tolkien's concept of immortal sadness—the burden
of watching all mortal things pass away.
---
}
```
## Use Cases
### Taxonomy Systems
Build biological hierarchies:
```storybook
species Vertebrate {
has_spine: true
bilateral_symmetry: true
}
species Fish includes Vertebrate {
breathes_underwater: true
fins: true
}
species Amphibian includes Vertebrate {
metamorphosis: true
moist_skin: true
}
species Reptile includes Vertebrate {
cold_blooded: true
scales: true
}
species Bird includes Vertebrate {
feathers: true
lays_eggs: true
}
species Mammal includes Vertebrate {
warm_blooded: true
mammary_glands: true
}
```
### Fantasy Races
Define playable races or NPC types:
```storybook
species Dwarf {
lifespan: 300
height_range: 120..150
darkvision: true
stone_affinity: 0.9
---culture
Master craftsmen who live in underground mountain halls.
Value honor, loyalty, and fine metalwork.
---
}
species Orc {
lifespan: 60
height_range: 180..220
strength_bonus: 2
darkvision: true
---culture
Tribal warriors with strong oral traditions. Misunderstood
by outsiders as brutal savages; actually have complex honor
codes and shamanistic practices.
---
}
```
### Sci-Fi Species
Model alien life:
```storybook
species Crystalline {
silicon_based: true
communicates_via: "resonance"
reproduction: "budding"
lifespan: 10000
---ecology
Crystalline beings grow slowly in high-pressure environments.
They communicate through harmonic vibrations and perceive
electromagnetic spectra invisible to carbon-based life.
---
}
```
### Surreal Species
For absurdist or dreamlike worlds:
```storybook
species SentientColor {
has_physical_form: false
wavelength: 400..700 // nanometers
emotional_resonance: true
---description
Living colors that exist as pure wavelengths of light.
They experience emotions as shifts in frequency and can
paint themselves onto surfaces to communicate.
---
}
```
## Design Patterns
### Prefer Composition Over Deep Hierarchies
**Avoid:**
```storybook
species Being { ... }
species LivingBeing includes Being { ... }
species Animal includes LivingBeing { ... }
species Vertebrate includes Animal { ... }
species Mammal includes Vertebrate { ... }
species Primate includes Mammal { ... }
species Human includes Primate { ... } // Too deep!
```
**Prefer:**
```storybook
species Mammal {
warm_blooded: true
live_birth: true
}
species Human includes Mammal {
sapient: true
language: true
}
// Use templates for capabilities
template Climber { ... }
template SocialCreature { ... }
character Jane: Human from Climber, SocialCreature { ... }
```
### Use Species for Ontology, Templates for Variation
```storybook
// Species: What they are
species Wolf {
pack_animal: true
carnivore: true
}
// Templates: Different wolf types
template AlphaWolf {
dominance: 0.9..1.0
pack_size: 5..15
}
template LoneWolf {
dominance: 0.3..0.5
pack_size: 0..2
}
character Fenrir: Wolf from AlphaWolf { ... }
character Outcast: Wolf from LoneWolf { ... }
```
## Cross-References
- [Characters](./10-characters.md) - How characters use species with `:` syntax
- [Templates](./16-other-declarations.md#templates) - Compositional alternative to species
- [Value Types](./18-value-types.md) - All supported field value types
- [Use Statements](./16-other-declarations.md#use-statements) - Importing species from other modules
- [Enums](./16-other-declarations.md#enums) - Defining controlled vocabularies for species fields
## Related Concepts
- **Taxonomic thinking**: Species form natural hierarchies mirroring biological classification
- **Essence vs. Traits**: Species capture essence (what something *is*); templates capture traits (what it *has*)
- **Single inheritance for identity**: A character can only be one species (you can't be both Human and Dragon)
- **Multiple inheritance for capabilities**: A character can have many templates (a Human can be both Warrior and Mage)

View File

@@ -0,0 +1,687 @@
# Decorators
Decorators are special nodes that wrap a single child and modify its execution behavior. They enable timing control, retry logic, conditional execution, and result inversion without modifying the child node itself.
## What Are Decorators?
Decorators sit between a parent and child node, transforming the child's behavior:
```
Parent
└─ Decorator
└─ Child
```
The decorator intercepts the child's execution, potentially:
- Repeating it multiple times
- Timing it out
- Inverting its result
- Guarding its execution
- Forcing a specific result
## Decorator Types
Storybook provides 10 decorator types:
| Decorator | Purpose | Example |
|-----------|---------|---------|
| `repeat` | Loop infinitely | `repeat { Patrol }` |
| `repeat(N)` | Loop N times | `repeat(3) { Check }` |
| `repeat(min..max)` | Loop min to max times | `repeat(2..5) { Search }` |
| `invert` | Flip success/failure | `invert { IsEnemy }` |
| `retry(N)` | Retry on failure (max N times) | `retry(5) { Open }` |
| `timeout(duration)` | Fail after duration | `timeout(10s) { Solve }` |
| `cooldown(duration)` | Run at most once per duration | `cooldown(30s) { Fire }` |
| `if(condition)` | Only run if condition true | `if(health > 50) { Attack }` |
| `succeed_always` | Always return success | `succeed_always { Try }` |
| `fail_always` | Always return failure | `fail_always { Test }` |
## Syntax
```bnf
<decorator> ::= <repeat-decorator>
| <invert-decorator>
| <retry-decorator>
| <timeout-decorator>
| <cooldown-decorator>
| <if-decorator>
| <force-result-decorator>
<repeat-decorator> ::= "repeat" <repeat-spec>? "{" <behavior-node> "}"
<repeat-spec> ::= "(" <number> ")"
| "(" <number> ".." <number> ")"
<invert-decorator> ::= "invert" "{" <behavior-node> "}"
<retry-decorator> ::= "retry" "(" <number> ")" "{" <behavior-node> "}"
<timeout-decorator> ::= "timeout" "(" <duration-literal> ")" "{" <behavior-node> "}"
<cooldown-decorator> ::= "cooldown" "(" <duration-literal> ")" "{" <behavior-node> "}"
<if-decorator> ::= "if" "(" <expression> ")" "{" <behavior-node> "}"
<force-result-decorator> ::= ("succeed_always" | "fail_always") "{" <behavior-node> "}"
<duration-literal> ::= <number> ("s" | "m" | "h" | "d")
```
## Repeat Decorators
### Infinite Repeat: `repeat`
Loops the child infinitely. The child is re-executed immediately after completing (success or failure).
```storybook
behavior InfinitePatrol {
repeat {
PatrolRoute
}
}
```
**Execution:**
1. Run child
2. Child completes (success or failure)
3. Immediately run child again
4. Go to step 2 (forever)
**Use cases:**
- Perpetual patrols
- Endless background processes
- Continuous monitoring
**Warning:** Infinite loops never return to parent. Ensure they're appropriate for your use case.
### Repeat N Times: `repeat N`
Repeats the child exactly N times, then returns success.
```storybook
behavior CheckThreeTimes {
repeat(3) {
CheckDoor
}
}
```
**Execution:**
1. Counter = 0
2. Run child
3. Counter++
4. If counter < N, go to step 2
5. Return success
**Use cases:**
- Fixed iteration counts
- "Try three times then give up"
- Deterministic looping
### Repeat Range: `repeat min..max`
Repeats the child between min and max times. At runtime, a specific count is selected within the range.
```storybook
behavior SearchRandomly {
repeat(2..5) {
SearchArea
}
}
```
**Execution:**
1. Select count C randomly from [min, max]
2. Repeat child C times (as in `repeat N`)
**Use cases:**
- Variable behavior
- Procedural variation
- Non-deterministic actions
**Validation:**
- min ≥ 0
- max ≥ min
- Both must be integers
## Invert Decorator
Inverts the child's return value: success becomes failure, failure becomes success.
```storybook
behavior AvoidEnemies {
invert {
IsEnemyNearby // Success if NOT nearby
}
}
```
**Truth table:**
| Child returns | Decorator returns |
|---------------|------------------|
| Success | Failure |
| Failure | Success |
| Running | Running (unchanged) |
**Use cases:**
- Negating conditions ("if NOT X")
- Inverting success criteria
- Converting "found" to "not found"
**Example:**
```storybook
behavior SafeExploration {
choose safe_actions {
// Only explore if NOT dangerous
then explore {
invert { IsDangerous }
ExploreArea
}
// Default: Stay put
Wait
}
}
```
## Retry Decorator
Retries the child up to N times on failure. Returns success if any attempt succeeds, failure if all N attempts fail.
```storybook
behavior PersistentDoor {
retry(5) {
OpenLockedDoor
}
}
```
**Execution:**
1. Attempts = 0
2. Run child
3. If child succeeds → return success
4. If child fails:
- Attempts++
- If attempts < N, go to step 2
- Else return failure
**Use cases:**
- Unreliable actions (lockpicking, persuasion)
- Network/resource operations
- Probabilistic success
**Example with context:**
```storybook
behavior Thief_PickLock {
then attempt_entry {
// Try to pick lock (may fail)
retry(3) {
PickLock
}
// If succeeded, enter
EnterBuilding
// If failed after 3 tries, give up
}
}
```
**Validation:**
- N must be ≥ 1
## Timeout Decorator
Fails the child if it doesn't complete within the specified duration.
```storybook
behavior TimeLimitedPuzzle {
timeout(30s) {
SolvePuzzle
}
}
```
**Execution:**
1. Start timer
2. Run child each tick
3. If child completes before timeout → return child's result
4. If timer expires → return failure (interrupt child)
**Use cases:**
- Time-limited actions
- Preventing infinite loops
- Enforcing deadlines
**Duration formats:**
- `5s` - 5 seconds
- `10m` - 10 minutes
- `2h` - 2 hours
- `3d` - 3 days
**Example:**
```storybook
behavior QuickDecision {
choose timed_choice {
// Give AI 5 seconds to find optimal move
timeout(5s) {
CalculateOptimalStrategy
}
// Fallback: Use simple heuristic
UseQuickHeuristic
}
}
```
**Notes:**
- Timer starts when decorator is first entered
- Timer resets if decorator exits and re-enters
- Child node should handle interruption gracefully
## Cooldown Decorator
Prevents the child from running more than once per cooldown period. Fails immediately if called within cooldown.
```storybook
behavior SpecialAbility {
cooldown(30s) {
FireCannon
}
}
```
**Execution:**
1. Check last execution time
2. If (current_time - last_time) < cooldown → return failure
3. Else:
- Run child
- Record current_time as last_time
- Return child's result
**Use cases:**
- Rate-limiting abilities
- Resource cooldowns (spells, items)
- Preventing spam
**Example:**
```storybook
behavior Mage_SpellCasting {
choose spells {
// Fireball: 10 second cooldown
cooldown(10s) {
CastFireball
}
// Lightning: 5 second cooldown
cooldown(5s) {
CastLightning
}
// Basic attack: No cooldown
MeleeAttack
}
}
```
**State management:**
- Cooldown state persists across behavior tree ticks
- Each cooldown decorator instance has independent state
- Cooldown timers are per-entity (not global)
## If Decorator
Only runs the child if the condition is true. Fails immediately if condition is false.
```storybook
behavior ConditionalAttack {
if(health > 50) {
AggressiveAttack
}
}
```
**Execution:**
1. Evaluate condition expression
2. If true → run child and return its result
3. If false → return failure (do not run child)
**Use cases:**
- Preconditions ("only if X")
- Resource checks ("only if have mana")
- Safety checks ("only if safe")
**Expression syntax:**
See [Expression Language](./17-expressions.md) for complete syntax.
**Examples:**
```storybook
behavior GuardedActions {
choose options {
// Only attack if have weapon and enemy close
if(has_weapon and distance < 10) {
Attack
}
// Only heal if health below 50%
if(health < (max_health * 0.5)) {
Heal
}
// Only flee if outnumbered
if(enemy_count > ally_count) {
Flee
}
}
}
```
**Comparison with bare `if` conditions:**
```storybook
// Using bare 'if' condition (checks every tick, no body)
then approach_and_attack {
if(enemy_nearby)
Approach
Attack
}
// Using 'if' decorator with body (precondition check, fails fast)
if(enemy_nearby) {
then do_attack {
Approach
Attack
}
}
```
The `if` decorator with a body is more efficient for gating expensive subtrees.
## Force Result Decorators
### `succeed_always`
Always returns success, regardless of child's actual result.
```storybook
behavior TryOptionalTask {
succeed_always {
AttemptBonus // Even if fails, we don't care
}
}
```
**Use cases:**
- Optional tasks that shouldn't block progress
- Logging/monitoring actions
- Best-effort operations
**Example:**
```storybook
behavior QuestSequence {
then main_quest {
TalkToNPC
// Try to find secret, but don't fail quest if not found
succeed_always {
SearchForSecretDoor
}
ReturnToQuestGiver
}
}
```
### `fail_always`
Always returns failure, regardless of child's actual result.
```storybook
behavior TestFailure {
fail_always {
AlwaysSucceedsAction // But we force it to fail
}
}
```
**Use cases:**
- Testing/debugging
- Forcing alternative paths
- Disabling branches temporarily
**Example:**
```storybook
behavior UnderConstruction {
choose abilities {
// Temporarily disabled feature
fail_always {
NewExperimentalAbility
}
// Fallback to old ability
ClassicAbility
}
}
```
## Combining Decorators
Decorators can nest to create complex behaviors:
```storybook
behavior ComplexPattern {
// Repeat 3 times, each with 10 second timeout
repeat(3) {
timeout(10s) {
SolveSubproblem
}
}
}
```
**More complex nesting:**
```storybook
behavior ResilientAction {
// If: Only if health > 30
if(health > 30) {
// Timeout: Must complete in 20 seconds
timeout(20s) {
// Retry: Try up to 5 times
retry(5) {
// Cooldown: Can only run once per minute
cooldown(1m) {
PerformComplexAction
}
}
}
}
}
```
**Execution order:** Outside → Inside
1. If checks condition
2. Timeout starts timer
3. Retry begins first attempt
4. Cooldown checks last execution time
5. Child action runs
## Duration Syntax
Timeout and cooldown decorators use duration literals:
```bnf
<duration-literal> ::= <number> <unit>
<unit> ::= "s" // seconds
| "m" // minutes
| "h" // hours
| "d" // days
<number> ::= <digit>+
```
**Examples:**
- `5s` - 5 seconds
- `30s` - 30 seconds
- `2m` - 2 minutes
- `10m` - 10 minutes
- `1h` - 1 hour
- `24h` - 24 hours
- `7d` - 7 days
**Validation:**
- Number must be positive integer
- No compound durations (use `120s` not `2m` if runtime expects seconds)
- No fractional units (`1.5m` not allowed; use `90s`)
## Comparison Table
| Decorator | Affects Success | Affects Failure | Affects Running | Stateful |
|-----------|----------------|----------------|----------------|----------|
| `repeat` | Repeat | Repeat | Wait | Yes (counter) |
| `repeat N` | Repeat | Repeat | Wait | Yes (counter) |
| `repeat min..max` | Repeat | Repeat | Wait | Yes (counter) |
| `invert` | → Failure | → Success | Unchanged | No |
| `retry N` | → Success | Retry or fail | Wait | Yes (attempts) |
| `timeout dur` | → Success | → Success | → Failure if expired | Yes (timer) |
| `cooldown dur` | → Success | → Success | → Success | Yes (last time) |
| `if(expr)` | → Success | → Success | → Success | No |
| `succeed_always` | → Success | → Success | → Success | No |
| `fail_always` | → Failure | → Failure | → Failure | No |
**Stateful decorators** maintain state across ticks. **Stateless decorators** evaluate fresh every tick.
## Validation Rules
1. **Child required**: All decorators must have exactly one child node
2. **Repeat count**: `repeat N` requires N ≥ 0
3. **Repeat range**: `repeat min..max` requires 0 ≤ min ≤ max
4. **Retry count**: `retry N` requires N ≥ 1
5. **Duration positive**: Timeout/cooldown durations must be > 0
6. **Duration format**: Must match `<number><unit>` (e.g., `10s`, `5m`)
7. **Guard expression**: Guard condition must be valid expression
8. **No empty decorators**: `repeat { }` is invalid (missing child)
## Use Cases by Category
### Timing Control
- **timeout**: Prevent infinite loops, enforce time limits
- **cooldown**: Rate-limit abilities, prevent spam
- **repeat**: Continuous processes, patrols
### Reliability
- **retry**: Handle unreliable actions, probabilistic success
- **if**: Precondition checks, resource validation
- **succeed_always**: Optional tasks, best-effort
### Logic Control
- **invert**: Negate conditions, flip results
- **fail_always**: Disable branches, testing
### Iteration
- **repeat N**: Fixed loops, deterministic behavior
- **repeat min..max**: Variable loops, procedural variation
## Best Practices
### 1. Use Guards for Expensive Checks
**Avoid:**
```storybook
then expensive {
if(complex_condition)
ExpensiveOperation
}
```
**Prefer:**
```storybook
if(complex_condition) {
ExpensiveOperation // Only runs if condition passes
}
```
### 2. Combine Timeout with Retry
**Avoid:** Infinite retry loops
**Prefer:**
```storybook
timeout(30s) {
retry(5) {
UnreliableAction
}
}
```
### 3. Use Cooldowns for Rate Limiting
**Avoid:** Manual timing in actions
**Prefer:**
```storybook
cooldown(10s) {
FireCannon
}
```
### 4. Invert for Readable Conditions
**Avoid:**
```storybook
choose options {
then branch_a {
if(not is_dangerous)
Explore
}
}
```
**Prefer:**
```storybook
choose options {
then branch_a {
invert { IsDangerous }
Explore
}
}
```
### 5. succeed_always for Optional Tasks
**Avoid:**
```storybook
then quest {
MainTask
choose optional {
BonusTask
DoNothing // Awkward fallback
}
NextTask
}
```
**Prefer:**
```storybook
then quest {
MainTask
succeed_always { BonusTask } // Try bonus, don't fail quest
NextTask
}
```
## Cross-References
- [Behavior Trees](./11-behavior-trees.md) - Using decorators in behavior trees
- [Expression Language](./17-expressions.md) - Guard condition syntax
- [Value Types](./18-value-types.md) - Duration literals
- [Design Patterns](../advanced/20-patterns.md) - Common decorator patterns
## Related Concepts
- **Composability**: Decorators can nest for complex control flow
- **Separation of concerns**: Decorators handle control flow, children handle logic
- **State management**: Stateful decorators (repeat, retry, timeout, cooldown) persist across ticks
- **Performance**: Guards prevent unnecessary child execution

View File

@@ -0,0 +1,738 @@
# Life Arcs
Life arcs are state machines that model how characters or other entities evolve over time. They define discrete states and the conditions under which an entity transitions between states. Life arcs capture character development, quest progress, relationship phases, and any other finite-state processes.
## What is a Life Arc?
A life arc is a finite state machine (FSM) composed of:
- **States**: Discrete phases or modes (e.g., "happy", "angry", "sleeping")
- **Transitions**: Conditional edges between states (e.g., "when health < 20, go to 'fleeing'")
- **On-enter actions**: Field updates that occur when entering a state
```
[State A] --condition--> [State B] --condition--> [State C]
| | |
on enter on enter on enter
(set fields) (set fields) (set fields)
```
Life arcs run continuously, evaluating transitions every tick and moving between states as conditions become true.
## Syntax
```bnf
<life-arc-decl> ::= "life_arc" <identifier> <body>
<body> ::= "{" <prose-blocks>* <state>+ "}"
<state> ::= "state" <identifier> "{" <state-body>* "}"
<state-body> ::= <on-enter-block>
| <transition>
| <prose-block>
<on-enter-block> ::= "on" "enter" "{" <field>+ "}"
<transition> ::= "on" <expression> "->" <identifier>
<prose-block> ::= "---" <identifier> <content> "---"
```
## States
A state represents a discrete phase in an entity's lifecycle.
### Basic State
```storybook
life_arc SimpleArc {
state idle {
---narrative
The character is doing nothing, waiting for something to happen.
---
}
state active {
---narrative
The character is engaged in their primary activity.
---
}
}
```
### State Names
State names are identifiers that must be unique within the life arc. Use descriptive names:
- **Good**: `idle`, `combat`, `sleeping`, `enlightened`
- **Avoid**: `state1`, `s`, `temp`
## On-Enter Actions
When entering a state, the `on enter` block updates entity fields.
### Syntax
```storybook
state state_name {
on enter {
EntityName.field_name: value
EntityName.other_field: other_value
}
}
```
### Examples
```storybook
life_arc CharacterMood {
state happy {
on enter {
Martha.emotional_state: "happy"
Martha.energy: 100
}
}
state tired {
on enter {
Martha.emotional_state: "exhausted"
Martha.energy: 20
}
}
}
```
### Field Update Semantics
- **Target**: `EntityName.field_name` must reference an existing character/entity
- **Value**: Any valid [value type](./18-value-types.md)
- **Effect**: Field is set to the specified value when state is entered
- **Timing**: Happens immediately upon transition to the state
### Multiple Field Updates
```storybook
state exhausted_baker {
on enter {
Martha.energy: 0.1
Martha.mood: "stressed"
Martha.quality_output: 0.7
Martha.needs_break: true
}
---narrative
After a sixteen-hour shift during the harvest festival,
Martha's hands are shaking. She knows her bread quality is
suffering and reluctantly steps away from the oven.
---
}
```
## Transitions
Transitions define conditional edges between states. When a transition's condition becomes true, the state machine moves to the target state.
### Syntax
```storybook
state source_state {
on condition_expression -> target_state
on another_condition -> another_target
}
```
### Basic Transitions
```storybook
life_arc Combat {
state fighting {
on health < 20 -> fleeing
on enemy_defeated -> victorious
}
state fleeing {
on safe_distance_reached -> idle
}
state victorious {
on celebration_complete -> idle
}
state idle {}
}
```
### Expression Conditions
Transitions use the full [expression language](./17-expressions.md):
**Comparisons:**
```storybook
on health < 20 -> low_health
on distance > 100 -> far_away
on count == 0 -> empty
```
**Boolean fields:**
```storybook
on is_hostile -> combat
on completed -> done
on not ready -> waiting
```
**Logical operators:**
```storybook
on health < 20 and not has_potion -> desperate
on is_day or is_lit -> visible
```
**Complex conditions:**
```storybook
on (health < 50 and enemy_count > 3) or surrounded -> retreat
on forall e in enemies: e.defeated -> victory
```
### Multiple Transitions
A state can have multiple outgoing transitions:
```storybook
state monitoring {
on status is "active" -> active_state
on status is "inactive" -> inactive_state
on status is "error" -> error_state
on shutdown_requested -> shutting_down
}
```
**Evaluation order:**
- Transitions are evaluated in declaration order (top to bottom)
- First transition with a true condition is taken
- If no conditions are true, state remains unchanged
### Self-Transitions
A state can transition to itself:
```storybook
state patrolling {
on enemy_spotted -> combat
on checkpoint_reached -> patrolling // Reset patrol state
}
```
## Complete Examples
### Elena's Career Journey
```storybook
life_arc ElenaCareer {
---description
Tracks Elena's progression from nervous apprentice to confident
master baker. Each state represents a key phase of her career.
---
state early_apprentice {
on enter {
Elena.skill_level: novice
Elena.confidence: timid
}
on recipes_mastered > 5 -> growing_apprentice
---narrative
Elena's hands shake as she measures flour. She checks the
recipe three times before adding each ingredient. Martha
patiently corrects her technique.
---
}
state growing_apprentice {
on enter {
Elena.skill_level: beginner
Elena.confidence: uncertain
}
on recipes_mastered > 15 -> journeyman
---narrative
The shaking stops. Elena can make basic breads without
looking at the recipe. She still doubts herself but
Martha's encouragement is taking root.
---
}
state journeyman {
on enter {
Elena.skill_level: intermediate
Elena.confidence: growing
Elena.can_work_independently: true
}
on recipes_mastered > 30 -> senior_journeyman
---narrative
Elena runs the morning shift alone while Martha handles
special orders. Customers start asking for "Elena's rolls."
She begins experimenting with her own recipes.
---
}
state senior_journeyman {
on enter {
Elena.skill_level: advanced
Elena.confidence: steady
}
on recipes_mastered > 50 -> master
---narrative
Elena develops her signature recipe: rosemary olive bread
that becomes the bakery's bestseller. She handles difficult
customers with grace and trains new helpers.
---
}
state master {
on enter {
Elena.skill_level: master
Elena.confidence: commanding
Elena.can_teach: true
}
---narrative
Master Baker Elena. She has earned it. The guild acknowledges
her mastery, and Martha beams with pride. Elena begins
mentoring her own apprentice.
---
}
}
```
### Quest Progress
```storybook
life_arc HeroQuest {
state not_started {
on talked_to_elder -> received_quest
}
state received_quest {
on enter {
Hero.quest_active: true
Hero.quest_step: 0
}
on found_first_artifact -> collecting
}
state collecting {
on enter {
Hero.quest_step: 1
}
on artifact_count == 3 -> returning
on failed_trial -> failed
}
state returning {
on enter {
Hero.quest_step: 2
}
on reached_elder -> completed
}
state completed {
on enter {
Hero.quest_active: false
Hero.quest_completed: true
Hero.reputation: 100
}
---narrative
The hero returns triumphant, artifacts in hand. The elder
bestows great rewards and the village celebrates.
---
}
state failed {
on enter {
Hero.quest_active: false
Hero.quest_failed: true
}
on retry_accepted -> received_quest
}
}
```
### Name Checker (Equality Examples)
```storybook
life_arc NameCheck {
state checking {
on name is "Martha" -> found_martha
on name is "Jane" -> found_jane
}
state found_martha {
on ready -> checking
}
state found_jane {
on ready -> checking
}
}
```
### Status Monitor
```storybook
life_arc StatusMonitor {
state monitoring {
on status is active -> active_state
on status is inactive -> inactive_state
on status is error -> error_state
}
state active_state {
on enter {
System.led_color: "green"
}
on status is inactive -> inactive_state
on status is error -> error_state
}
state inactive_state {
on enter {
System.led_color: "yellow"
}
on status is active -> active_state
on status is error -> error_state
}
state error_state {
on enter {
System.led_color: "red"
System.alarm: true
}
on error_cleared -> monitoring
}
}
```
### Character Mood Swings
```storybook
life_arc MoodSwings {
state neutral {
on provoked -> angry
on complimented -> happy
on tired -> sleepy
}
state angry {
on enter {
Character.aggression: 0.9
Character.willingness_to_talk: 0.1
}
on calmed_down -> neutral
on escalated -> furious
}
state furious {
on enter {
Character.aggression: 1.0
Character.will_attack: true
}
on timeout_elapsed -> angry
on apologized_to -> neutral
}
state happy {
on enter {
Character.aggression: 0.0
Character.willingness_to_talk: 1.0
Character.gives_discounts: true
}
on insulted -> neutral
on bored -> neutral
}
state sleepy {
on enter {
Character.responsiveness: 0.2
}
on woke_up -> neutral
on fell_asleep -> sleeping
}
state sleeping {
on enter {
Character.responsiveness: 0.0
Character.is_vulnerable: true
}
on woke_up -> neutral
}
}
```
## Execution Semantics
### Tick-Based Evaluation
Life arcs evaluate transitions every "tick" (typically once per frame):
1. **Current state**: Start in the current state
2. **Evaluate transitions**: Check each outgoing transition's condition (in order)
3. **First true transition**: Take the first transition with a true condition
4. **Enter new state**: Execute the new state's `on enter` block
5. **Repeat next tick**
### Transition Priority
When multiple transitions could fire, the **first one in declaration order** is taken:
```storybook
state combat {
on health < 10 -> desperate // Checked first
on health < 50 -> defensive // Checked second
on surrounded -> retreat // Checked third
}
```
If health is 5, only `desperate` transition fires (even though `defensive` condition is also true).
### State Persistence
The current state persists across ticks until a transition fires.
```storybook
state waiting {
on signal_received -> active
}
```
The entity remains in `waiting` state indefinitely until `signal_received` becomes true.
### On-Enter Execution
`on enter` blocks execute **once** when entering the state, not every tick:
```storybook
state combat {
on enter {
Character.weapon_drawn: true // Runs once when entering combat
}
}
```
## Validation Rules
1. **At least one state**: Life arc must contain at least one state
2. **Unique state names**: State names must be unique within the life arc
3. **Valid transitions**: Transition targets must reference defined states
4. **No orphan states**: All states should be reachable (warning, not error)
5. **Expression validity**: Transition conditions must be well-formed expressions
6. **Field targets**: On-enter field updates must reference valid entities/fields
7. **No cyclic immediate transitions**: Avoid transitions that fire immediately in a loop
## Design Patterns
### 1. Hub-and-Spoke
A central "hub" state with transitions to specialized states:
```storybook
life_arc HubPattern {
state idle {
on combat_triggered -> combat
on quest_accepted -> questing
on entered_shop -> shopping
}
state combat {
on combat_ended -> idle
}
state questing {
on quest_completed -> idle
}
state shopping {
on left_shop -> idle
}
}
```
### 2. Linear Progression
States form a linear sequence (quests, tutorials):
```storybook
life_arc Tutorial {
state intro {
on clicked_start -> movement
}
state movement {
on moved_forward -> combat
}
state combat {
on defeated_enemy -> inventory
}
state inventory {
on opened_inventory -> complete
}
state complete {}
}
```
### 3. Cyclic States
States form a cycle (day/night, seasons):
```storybook
life_arc DayNightCycle {
state dawn {
on hour >= 8 -> day
}
state day {
on hour >= 18 -> dusk
}
state dusk {
on hour >= 20 -> night
}
state night {
on hour >= 6 -> dawn
}
}
```
### 4. Hierarchical (Simulated)
Use multiple life arcs for hierarchical state:
```storybook
// Top-level life arc
life_arc CharacterState {
state alive {
on health <= 0 -> dead
}
state dead {}
}
// Nested life arc (only active when alive)
life_arc CombatState {
state idle {
on enemy_nearby -> combat
}
state combat {
on enemy_defeated -> idle
}
}
```
## Best Practices
### 1. Use Descriptive State Names
**Avoid:**
```storybook
state s1 { ... }
state s2 { ... }
```
**Prefer:**
```storybook
state waiting_for_player { ... }
state engaged_in_combat { ... }
```
### 2. Add Narrative Prose Blocks
```storybook
state master_baker {
---narrative
Master Baker Elena. She has earned it. The guild acknowledges
her mastery, and Martha beams with pride. Elena begins
mentoring her own apprentice.
---
}
```
### 3. Order Transitions by Priority
```storybook
state health_check {
on health <= 0 -> dead // Most urgent
on health < 20 -> critical // Very urgent
on health < 50 -> wounded // Moderate
}
```
### 4. Avoid Orphan States
Ensure all states are reachable from the initial state.
**Avoid:**
```storybook
life_arc Broken {
state start {
on ready -> middle
}
state middle {
on done -> end
}
state unreachable {} // No transition leads here!
state end {}
}
```
### 5. Use On-Enter for State Initialization
```storybook
state combat {
on enter {
Character.weapon_drawn: true
Character.combat_stance: "aggressive"
Character.target: nearest_enemy
}
}
```
## Cross-References
- [Characters](./10-characters.md) - Characters can have associated life arcs
- [Expression Language](./17-expressions.md) - Transition condition syntax
- [Value Types](./18-value-types.md) - On-enter field value types
- [Validation Rules](./19-validation.md) - Life arc validation constraints
## Related Concepts
- **Finite State Machines (FSM)**: Life arcs are FSMs
- **Character development**: Track character growth over time
- **Quest states**: Model quest progression
- **Mood systems**: Model emotional states
- **Lifecycle modeling**: Birth, growth, aging, death

View File

@@ -0,0 +1,776 @@
# Schedules
Schedules define time-based routines for characters and institutions. They specify what activities occur during specific time ranges, support seasonal variations, recurring events, and template composition. Schedules enable rich temporal behavior from simple daily routines to complex year-long patterns.
## What is a Schedule?
A schedule is a collection of time blocks that define activities throughout a day, week, season, or year:
- **Blocks**: Time ranges (e.g., `06:00 - 14:00`) with associated activities/behaviors
- **Temporal constraints**: When blocks apply (season, day of week, month)
- **Recurrence patterns**: Repeating events (e.g., "Market Day every Earthday")
- **Composition**: Schedules can extend and override other schedules
```
Schedule: BakerySchedule
├─ Block: 06:00 - 08:00 → prepare_dough
├─ Block: 08:00 - 14:00 → serve_customers
├─ Recurrence: Market Day (on Earthday) → special_market_hours
└─ Extends: BaseBusiness (inherits closing hours)
```
## Syntax
```bnf
<schedule-decl> ::= "schedule" <identifier> <extends-clause>? <body>
<extends-clause> ::= "extends" <identifier>
<body> ::= "{" <schedule-item>* "}"
<schedule-item> ::= <schedule-block>
| <recurrence-pattern>
<schedule-block> ::= "block" <block-name>? "{" <block-content>+ "}"
<block-name> ::= <identifier>
<block-content> ::= <time-range>
| "action" ":" <qualified-path>
| <temporal-constraint>
| <field>
<time-range> ::= <time> "-" <time>
<temporal-constraint> ::= "on" <temporal-spec>
<temporal-spec> ::= "season" <identifier>
| "day" <identifier>
| "month" <identifier>
| "dates" <string> ".." <string>
<recurrence-pattern> ::= "recurs" <identifier> <temporal-constraint> "{" <schedule-block>+ "}"
```
## Schedule Blocks
A schedule block defines an activity during a specific time range.
### Basic Block
```storybook
schedule SimpleBaker {
block {
06:00 - 14:00
action: baking::prepare_and_sell
}
}
```
### Named Block
Named blocks support the override system:
```storybook
schedule BakeryBase {
block work {
09:00 - 17:00
action: baking::standard_work
}
}
schedule EarlyBaker extends BakeryBase {
block work { // Override by name
05:00 - 13:00
action: baking::early_shift
}
}
```
### Block Content
Blocks can contain:
1. **Time range** (required): `HH:MM - HH:MM`
2. **Action** (optional): Behavior tree reference
3. **Temporal constraint** (optional): When the block applies
4. **Fields** (optional): Additional metadata
```storybook
schedule CompleteBlock {
block morning_work {
06:00 - 12:00
action: work::morning_routine
on season summer
location: "Outdoor Market"
}
}
```
## Time Ranges
Time ranges use 24-hour clock format.
### Syntax
```storybook
HH:MM - HH:MM
```
- **HH**: Hour (00-23)
- **MM**: Minute (00-59)
- Optional seconds: `HH:MM:SS - HH:MM:SS`
### Examples
```storybook
schedule Examples {
block early { 05:00 - 08:00, action: prep }
block midday { 12:00 - 13:00, action: lunch }
block late { 20:00 - 23:59, action: closing }
}
```
### Overnight Ranges
Blocks can span midnight:
```storybook
schedule NightShift {
block night_work {
22:00 - 06:00 // 10 PM to 6 AM next day
action: security::patrol
}
}
```
The system interprets this as 22:00-24:00 (day 1) + 00:00-06:00 (day 2).
## Actions
The `action` field links a schedule block to a behavior tree.
### Syntax
```storybook
action: <qualified-path>
```
### Examples
```storybook
schedule BakerSchedule {
block morning {
05:00 - 08:00
action: baking::prepare_dough
}
block sales {
08:00 - 14:00
action: baking::serve_customers
}
block cleanup {
14:00 - 15:00
action: baking::close_shop
}
}
```
### Qualified Paths
Actions can reference behaviors from other modules:
```storybook
schedule GuardSchedule {
block patrol {
08:00 - 16:00
action: behaviors::guards::patrol_route
}
block training {
16:00 - 18:00
action: combat::training::drills
}
}
```
## Temporal Constraints
Temporal constraints specify when a block applies (season, day of week, month, date range).
### Season Constraint
```storybook
schedule SeasonalHours {
block summer_hours {
06:00 - 20:00
action: work::long_day
on season summer
}
block winter_hours {
07:00 - 18:00
action: work::short_day
on season winter
}
}
```
**Season values** are defined by enums in your storybook:
```storybook
enum Season {
spring
summer
fall
winter
}
```
### Day of Week Constraint
```storybook
schedule WeeklyPattern {
block weekday_work {
09:00 - 17:00
action: work::standard
on day monday // Also: tuesday, wednesday, thursday, friday, saturday, sunday
}
block weekend_rest {
10:00 - 16:00
action: leisure::relax
on day saturday
}
}
```
**Day values** are typically defined by a `DayOfWeek` enum:
```storybook
enum DayOfWeek {
monday
tuesday
wednesday
thursday
friday
saturday
sunday
}
```
### Month Constraint
```storybook
schedule AnnualPattern {
block harvest {
06:00 - 20:00
action: farming::harvest_crops
on month october
}
block spring_planting {
07:00 - 19:00
action: farming::plant_seeds
on month april
}
}
```
### Date Range Constraint
```storybook
schedule TouristSeason {
block high_season {
08:00 - 22:00
action: tourism::busy_service
on dates "Jun 1" .. "Sep 1"
}
}
```
**Note**: Date format is implementation-specific. Check your runtime for supported formats.
## Recurrence Patterns
Recurrence patterns define recurring events that modify the schedule.
### Syntax
```storybook
recurs EventName on <temporal-constraint> {
<schedule-block>+
}
```
### Examples
#### Weekly Recurring Event
```storybook
schedule MarketSchedule {
// Regular daily hours
block work {
08:00 - 17:00
action: shop::regular_sales
}
// Market day every saturday
recurs MarketDay on day saturday {
block setup {
06:00 - 08:00
action: market::setup_stall
}
block busy_market {
08:00 - 18:00
action: market::busy_sales
}
block teardown {
18:00 - 20:00
action: market::pack_up
}
}
}
```
#### Monthly Recurring Event
```storybook
schedule TownSchedule {
recurs CouncilMeeting on month first_monday {
block meeting {
18:00 - 21:00
action: governance::council_session
}
}
}
```
#### Seasonal Recurring Event
```storybook
schedule FarmSchedule {
recurs SpringPlanting on season spring {
block planting {
06:00 - 18:00
action: farming::plant_all_fields
}
}
recurs FallHarvest on season fall {
block harvest {
06:00 - 20:00
action: farming::harvest_all_crops
}
}
}
```
## Schedule Composition
Schedules can extend other schedules using `extends`, inheriting and overriding blocks.
### Extends Clause
```storybook
schedule Base {
block work {
09:00 - 17:00
action: work::standard
}
}
schedule Extended extends Base {
block work { // Override inherited block
05:00 - 13:00
action: work::early_shift
}
}
```
### Override Semantics
When extending a schedule:
1. **Named blocks** with matching names override base blocks
2. **Unnamed blocks** are appended
3. **Time range** can change
4. **Action** can change
5. **Constraints** can be added/changed
### Multiple Levels
```storybook
schedule BaseWork {
block work {
09:00 - 17:00
action: work::standard
}
}
schedule BakerWork extends BaseWork {
block work {
05:00 - 13:00 // Earlier hours
action: baking::work
}
}
schedule MasterBaker extends BakerWork {
block work {
03:00 - 11:00 // Even earlier!
action: baking::master_work
}
block teaching {
14:00 - 16:00
action: baking::teach_apprentice
}
}
```
**Resolution:**
- `work` block: 03:00-11:00 with `baking::master_work` (MasterBaker overrides BakerWork overrides BaseWork)
- `teaching` block: 14:00-16:00 with `baking::teach_apprentice` (from MasterBaker)
## Complete Examples
### Simple Daily Schedule
```storybook
schedule SimpleFarmer {
block sleep {
22:00 - 05:00
action: rest::sleep
}
block morning_chores {
05:00 - 08:00
action: farming::feed_animals
}
block fieldwork {
08:00 - 17:00
action: farming::tend_crops
}
block evening_chores {
17:00 - 19:00
action: farming::evening_tasks
}
block leisure {
19:00 - 22:00
action: social::family_time
}
}
```
### Seasonal Variation
```storybook
schedule SeasonalBaker {
block summer_work {
06:00 - 20:00
action: baking::long_shift
on season summer
}
block winter_work {
07:00 - 18:00
action: baking::short_shift
on season winter
}
block spring_work {
06:30 - 19:00
action: baking::medium_shift
on season spring
}
block fall_work {
06:30 - 19:00
action: baking::medium_shift
on season fall
}
}
```
### Weekly Pattern with Recurrence
```storybook
schedule InnkeeperSchedule {
// Weekday routine
block weekday_service {
08:00 - 22:00
action: inn::regular_service
on day monday // Repeat for each weekday
}
block weekday_service {
08:00 - 22:00
action: inn::regular_service
on day tuesday
}
// ... (wednesday, thursday, friday)
// Weekend hours
block weekend_service {
10:00 - 24:00
action: inn::busy_service
on day saturday
}
block weekend_service {
10:00 - 24:00
action: inn::busy_service
on day sunday
}
// Weekly market day
recurs MarketDay on day wednesday {
block market_prep {
06:00 - 08:00
action: inn::prepare_market_goods
}
block market_rush {
08:00 - 16:00
action: inn::market_day_chaos
}
}
}
```
### Extended Schedule
```storybook
schedule BaseShopkeeper {
block open {
09:00 - 17:00
action: shop::standard_hours
}
}
schedule BlacksmithSchedule extends BaseShopkeeper {
block open { // Override
06:00 - 18:00 // Longer hours
action: smithing::work
}
block forge_heat { // New block
05:00 - 06:00
action: smithing::heat_forge
}
}
```
### Complex Year-Round Schedule
```storybook
schedule MasterBakerYear {
// Daily base pattern
block prep {
04:00 - 06:00
action: baking::prepare
}
block baking {
06:00 - 10:00
action: baking::bake
}
block sales {
10:00 - 16:00
action: baking::serve
}
block cleanup {
16:00 - 17:00
action: baking::clean
}
// Seasonal variations
block summer_hours {
10:00 - 20:00 // Extended sales
action: baking::busy_summer
on season summer
}
// Weekly market
recurs MarketDay on day saturday {
block market_prep {
02:00 - 04:00
action: baking::market_prep
}
block market_sales {
08:00 - 18:00
action: baking::market_rush
}
}
// Annual events
recurs HarvestFestival on dates "Sep 20" .. "Sep 25" {
block festival {
06:00 - 23:00
action: baking::festival_mode
}
}
}
```
## Integration with Characters
Characters link to schedules using the `uses schedule` clause:
```storybook
character Martha {
uses schedule: BakerySchedule
}
```
**Multiple schedules:**
```storybook
character Innkeeper {
uses schedules: [WeekdaySchedule, WeekendSchedule]
}
```
See [Characters](./10-characters.md#schedule-integration) for complete integration syntax.
## Execution Semantics
### Time-Based Selection
At any given time, the runtime:
1. **Evaluates temporal constraints**: Which blocks apply right now?
2. **Selects matching block**: First block whose time range and constraint match
3. **Executes action**: Runs the associated behavior tree
4. **Repeats next tick**
### Priority Order
When multiple blocks could apply:
1. **Recurrences** take priority over regular blocks
2. **Constraints** filter blocks (season, day, month)
3. **Time ranges** must overlap current time
4. **First match** wins (declaration order)
### Block Overlap
Blocks can overlap in time. The runtime selects the first matching block.
**Example:**
```storybook
schedule Overlapping {
block general {
08:00 - 17:00
action: work::general
}
block specialized {
10:00 - 12:00 // Overlaps with general
action: work::specialized
on day wednesday
}
}
```
On Wednesday at 11:00, `specialized` block is selected (more specific constraint).
## Validation Rules
1. **Time format**: Times must be valid HH:MM or HH:MM:SS (24-hour)
2. **Time order**: Start time must be before end time (unless spanning midnight)
3. **Extends exists**: If using `extends`, base schedule must be defined
4. **No circular extends**: Cannot form circular dependency chains
5. **Named blocks unique**: Block names must be unique within a schedule
6. **Action exists**: Action references must resolve to defined behaviors
7. **Constraint values**: Temporal constraint values must reference defined enums
8. **Recurrence names unique**: Recurrence names must be unique within a schedule
## Best Practices
### 1. Use Named Blocks for Overrides
**Avoid:**
```storybook
schedule Extended extends Base {
block { 05:00 - 13:00, action: work } // Appends instead of overriding
}
```
**Prefer:**
```storybook
schedule Extended extends Base {
block work { 05:00 - 13:00, action: early_work } // Overrides by name
}
```
### 2. Group Related Blocks
```storybook
schedule DailyRoutine {
// Sleep blocks
block night_sleep { 22:00 - 05:00, action: sleep }
// Morning blocks
block wake_up { 05:00 - 06:00, action: morning_routine }
block breakfast { 06:00 - 07:00, action: eat_breakfast }
// Work blocks
block commute { 07:00 - 08:00, action: travel_to_work }
block work { 08:00 - 17:00, action: work }
}
```
### 3. Use Recurrences for Special Events
**Avoid:** Duplicating blocks manually
**Prefer:**
```storybook
recurs MarketDay on day saturday {
block market { 08:00 - 16:00, action: market_work }
}
```
### 4. Extend for Variations
**Avoid:** Duplicating entire schedules
**Prefer:**
```storybook
schedule WorkerBase { ... }
schedule EarlyWorker extends WorkerBase { ... }
schedule NightWorker extends WorkerBase { ... }
```
### 5. Use Temporal Constraints for Clarity
```storybook
block summer_hours {
06:00 - 20:00
action: long_shift
on season summer // Explicit and readable
}
```
## Cross-References
- [Characters](./10-characters.md) - Linking schedules to characters
- [Behavior Trees](./11-behavior-trees.md) - Actions reference behavior trees
- [Value Types](./18-value-types.md) - Time and duration literals
- [Enums](../reference/16-other-declarations.md#enums) - Defining seasons, days, months
## Related Concepts
- **Time-based AI**: Schedules drive time-dependent behavior
- **Template inheritance**: `extends` enables schedule reuse
- **Temporal constraints**: Filter blocks by season, day, month
- **Recurrence patterns**: Define repeating events
- **Composition**: Build complex schedules from simple parts

View File

@@ -0,0 +1,723 @@
# Relationships
Relationships define connections between characters, institutions, and other entities. They capture social bonds, power dynamics, emotional ties, and interactive patterns. Relationships can be symmetric (friendship) or asymmetric (parent-child), and support bidirectional perspectives where each participant has different fields.
## What is a Relationship?
A relationship connects two or more participants and describes:
- **Participants**: The entities involved (characters, institutions)
- **Roles**: Optional labels (parent, employer, spouse)
- **Shared fields**: Properties of the relationship itself (bond strength, duration)
- **Perspective fields**: How each participant views the relationship (`self`/`other` blocks)
```
Relationship: ParentChild
├─ Participant: Martha (as parent)
│ ├─ self: { responsibility: 1.0, protective: 0.9 }
│ └─ other: { dependent: 0.8 }
├─ Participant: Tommy (as child)
└─ Shared: { bond: 0.9, years_together: 8 }
```
## Syntax
```bnf
<relationship-decl> ::= "relationship" <identifier> <body>
<body> ::= "{" <participant>+ <field>* "}"
<participant> ::= <qualified-path> <role-clause>? <perspective-blocks>?
<role-clause> ::= "as" <identifier>
<perspective-blocks> ::= "self" "{" <field>* "}" "other" "{" <field>* "}"
| "self" "{" <field>* "}"
| "other" "{" <field>* "}"
<field> ::= <identifier> ":" <value>
```
## Basic Relationships
### Simple Two-Party Relationship
```storybook
relationship Friendship {
Martha
Gregory
bond: 0.8
years_known: 15
}
```
**Semantics:**
- Two participants: Martha and Gregory
- Shared field: `bond` (strength of friendship)
- Shared field: `years_known` (duration)
### Multi-Party Relationship
```storybook
relationship Family {
Martha
David
Tommy
Elena
household: "Baker Residence"
family_bond: 0.95
}
```
Relationships can have any number of participants.
## Roles
Roles label a participant's function in the relationship.
### Syntax
```storybook
ParticipantName as role_name
```
### Examples
```storybook
relationship Marriage {
Martha as spouse
David as spouse
bond: 0.9
anniversary: "2015-06-20"
}
```
```storybook
relationship ParentChild {
Martha as parent
Tommy as child
bond: 0.95
guardianship: true
}
```
```storybook
relationship EmployerEmployee {
Martha as employer
Elena as employee
workplace: "Martha's Bakery"
salary: 45000
}
```
### Role Semantics
- **Labels**: Roles are descriptive labels, not types
- **Multiple roles**: Same person can have different roles in different relationships
- **Optional**: Roles are optional—participants can be unnamed
- **Flexibility**: No predefined role vocabulary—use what makes sense
## Perspective Fields (Self/Other Blocks)
Perspective fields specify how each participant views the relationship. They enable asymmetric, bidirectional relationships.
### Syntax
```storybook
ParticipantName as role self {
// Fields describing this participant's perspective
} other {
// Fields describing how this participant views others
}
```
### Self Block
The `self` block contains fields about how the participant experiences the relationship:
```storybook
relationship ParentChild {
Martha as parent self {
responsibility: 1.0
protective: 0.9
anxiety_level: 0.6
}
Tommy as child
}
```
**Martha's perspective:**
- `responsibility`: She feels 100% responsible
- `protective`: She's highly protective (90%)
- `anxiety_level`: Moderate anxiety about parenting
### Other Block
The `other` block contains fields about how the participant views the other participants:
```storybook
relationship ParentChild {
Martha as parent self {
responsibility: 1.0
} other {
dependent: 0.8 // She sees Tommy as 80% dependent
mature_for_age: 0.7 // She thinks he's fairly mature
}
Tommy as child
}
```
### Both Blocks
```storybook
relationship EmployerEmployee {
Martha as employer self {
authority: 0.9
stress: 0.6
} other {
respect: 0.8
trust: 0.85
}
Elena as employee
}
```
**Martha's perspective:**
- **Self**: She has high authority (90%), moderate stress (60%)
- **Other**: She respects Elena (80%), trusts her (85%)
### Asymmetric Relationships
Different participants can have different perspective fields:
```storybook
relationship TeacherStudent {
Gandalf as teacher self {
patience: 0.8
wisdom_to_impart: 1.0
} other {
potential: 0.9
ready_to_learn: 0.6
}
Frodo as student self {
eager_to_learn: 0.7
overwhelmed: 0.5
} other {
admiration: 0.95
intimidated: 0.4
}
bond: 0.85
}
```
**Gandalf's view:**
- He's patient (80%), has much wisdom to share
- Sees Frodo as having high potential but only moderately ready
**Frodo's view:**
- He's eager but overwhelmed
- Deeply admires Gandalf, slightly intimidated
## Shared Fields
Fields declared at the relationship level (not in `self`/`other` blocks) are **shared** among all participants.
```storybook
relationship Friendship {
Martha
Gregory
bond: 0.8 // Shared: mutual bond strength
years_known: 15 // Shared: how long they've known each other
shared_routines: 3 // Shared: number of daily routines
}
```
**Common shared fields:**
- `bond`: Relationship strength (0.0 to 1.0)
- `years_known`: Duration of relationship
- `trust`: Mutual trust level
- `commitment`: Commitment to the relationship
- `compatibility`: How well they get along
## Prose Blocks
Relationships can include prose blocks for narrative context.
```storybook
relationship MarthaAndGregory {
Martha {
role: shopkeeper
values_loyalty: 0.9
---perspective
Martha appreciates Gregory's unwavering loyalty. He has
been buying her sourdough loaf every morning for fifteen
years. Their brief daily exchanges about the weather and
local gossip are a comforting routine.
---
}
Gregory {
role: regular_customer
always_orders: "sourdough_loaf"
---perspective
Gregory considers Martha's bakery a cornerstone of his
daily routine. The bread is excellent, but it is the brief
human connection that keeps him coming back.
---
}
}
```
**Common prose tags:**
- `---perspective`: How a participant views the relationship
- `---history`: Background of the relationship
- `---dynamics`: How the relationship functions
- `---notes`: Design or development notes
Note: In this syntax, perspective fields are inside participant blocks (not separate `self`/`other` blocks).
## Complete Examples
### Simple Friendship
```storybook
relationship Friendship {
Martha
NeighborBaker
bond: 0.6
years_known: 10
}
```
### Marriage with Roles
```storybook
relationship Marriage {
Martha as spouse
David as spouse
bond: 0.9
anniversary: "2015-06-20"
children: 2
}
```
### Parent-Child with Perspectives
```storybook
relationship ParentChild {
Martha as parent self {
responsibility: 1.0
protective: 0.9
anxiety_level: 0.6
} other {
dependent: 0.8
mature_for_age: 0.7
}
Tommy as child self {
seeks_independence: 0.7
appreciates_parent: 0.9
} other {
feels_understood: 0.6
wants_more_freedom: 0.8
}
bond: 0.95
years_together: 8
}
```
### Employer-Employee
```storybook
relationship EmployerEmployee {
Martha as employer self {
authority: 0.9
satisfaction_with_employee: 0.85
} other {
respect: 0.8
trust: 0.85
}
Elena as employee self {
job_satisfaction: 0.8
career_growth: 0.7
} other {
respects_boss: 0.9
appreciates_flexibility: 0.95
}
workplace: "Martha's Bakery"
salary: 45000
employment_start: "2023-01-15"
}
```
### Complex Multi-Perspective
```storybook
relationship MentorApprentice {
Martha {
role: mentor
teaching_style: "patient"
investment: 0.9
---perspective
Martha sees Elena as the daughter she might have had in
the trade. She recognizes the same passion she felt at
that age and pushes Elena harder because she knows the
talent is there. Every correction comes from love.
---
}
Elena {
role: apprentice
dedication: 0.9
anxiety: 0.4
---perspective
Elena idolizes Martha's skill but fears disappointing
her. Every morning she arrives thirty minutes early to
practice techniques before Martha gets in. She keeps a
notebook of every correction, reviewing them each night.
"I want to be half as good as her someday" -- this quiet
ambition drives everything Elena does.
---
}
bond: 0.85
}
```
### Business Rivalry
```storybook
relationship BakeryRivalry {
Martha {
role: established_baker
aware_of_competition: true
respects_rival: 0.6
---perspective
Martha views the new bakery across town as healthy
competition. She respects their pastry work but knows
her sourdough is unmatched. The rivalry pushes her to
keep innovating.
---
}
RivalBaker {
role: newcomer
wants_to_surpass: true
studies_martha: 0.8
---perspective
The rival baker moved to town specifically because of
Martha's reputation. They study her techniques, buy her
bread to analyze it, and dream of the day a customer
chooses their loaf over Martha's sourdough.
---
}
bond: 0.3
}
```
### Multi-Party Family
```storybook
relationship BakerFamily {
Martha as parent
David as parent
Tommy as child
Elena as child
household: "Baker Residence"
family_bond: 0.95
dinner_time: 18:00
---dynamics
A loving queer family running a bakery together. Martha and
David met at culinary school, married, and adopted Tommy and
Elena. The whole family works at the bakery on weekends.
---
}
```
### Co-Owners Partnership
```storybook
relationship BakeryPartnership {
Martha {
role: co_owner
specialty: "bread"
handles_finances: true
---perspective
Martha and Jane complement each other perfectly. Martha
handles the bread and business side while Jane creates
the pastries that draw customers in. Together they have
built something neither could alone.
---
}
Jane {
role: co_owner
specialty: "pastries"
handles_creativity: true
---perspective
Jane considers Martha the steady foundation of their
partnership. While Jane experiments and creates, Martha
ensures the bakery runs like clockwork. Their different
strengths make the bakery stronger.
---
}
bond: 0.9
}
```
## Participant Types
Participants can be:
1. **Characters**: Most common
2. **Institutions**: Organizations in relationships
3. **Locations**: Less common, but valid (e.g., "GuardianOfPlace")
```storybook
relationship GuildMembership {
Elena as member
BakersGuild as organization
membership_since: "2023-01-01"
standing: "good"
dues_paid: true
}
```
## Field Resolution
When a relationship is resolved, fields are merged:
1. **Relationship shared fields** apply to all participants
2. **Participant `self` blocks** apply to that participant
3. **Participant `other` blocks** describe how that participant views others
**Example:**
```storybook
relationship Example {
Martha as friend self {
loyalty: 0.9
} other {
trust: 0.8
}
Gregory as friend
bond: 0.85
}
```
**Resolution:**
- Martha gets: `loyalty: 0.9` (from self), `trust: 0.8` (towards Gregory, from other), `bond: 0.85` (shared)
- Gregory gets: `bond: 0.85` (shared)
- Relationship gets: `bond: 0.85`
## Validation Rules
1. **At least two participants**: Relationships require ≥2 participants
2. **Participants exist**: All participant names must reference defined entities
3. **Unique participant names**: Each participant appears at most once
4. **Field type consistency**: Fields must have valid value types
5. **No circular relationships**: Avoid infinite relationship chains (warning)
6. **Self/other completeness**: If using `self`/`other`, both blocks should be present (best practice)
## Use Cases
### Social Networks
```storybook
relationship BakerFriendship {
Martha
Gregory
bond: 0.8
}
relationship SupplierPartnership {
Martha
Farmer_Jenkins
bond: 0.7
}
relationship BakeryRivalry {
Martha
RivalBaker
bond: 0.2
competitive: true
}
```
### Family Structures
```storybook
relationship ParentChild {
Martha as parent
Tommy as child
bond: 0.95
}
relationship Siblings {
Tommy as older_sibling
Elena as younger_sibling
bond: 0.85
rivalry: 0.3
}
```
### Power Dynamics
```storybook
relationship Vassalage {
King as lord self {
grants: "protection"
expects: "loyalty"
} other {
trusts: 0.6
}
Knight as vassal self {
swears: "fealty"
expects: "land"
} other {
respects: 0.9
}
oath_date: "1205-03-15"
}
```
### Asymmetric Awareness
```storybook
relationship StalkingVictim {
Stalker as pursuer self {
obsession: 0.95
distance_maintained: 50 // meters
} other {
believes_unnoticed: true
}
Victim as unaware_target self {
awareness: 0.0
}
danger_level: 0.8
}
```
## Best Practices
### 1. Use Descriptive Relationship Names
**Avoid:**
```storybook
relationship R1 { ... }
relationship MarthaGregory { ... }
```
**Prefer:**
```storybook
relationship Friendship { ... }
relationship ParentChild { ... }
relationship MentorApprentice { ... }
```
### 2. Use Roles for Clarity
```storybook
relationship Marriage {
Martha as spouse
David as spouse
}
```
Better than:
```storybook
relationship Marriage {
Martha
David
}
```
### 3. Shared Fields for Mutual Properties
```storybook
relationship Partnership {
Martha
Jane
bond: 0.9 // Mutual bond
years_together: 5 // Shared history
}
```
### 4. Self/Other for Perspectives
```storybook
relationship TeacherStudent {
Teacher as mentor self {
patience: 0.8
} other {
potential: 0.9
}
Student as learner self {
motivation: 0.7
} other {
admiration: 0.95
}
}
```
### 5. Prose Blocks for Rich Context
```storybook
relationship ComplexDynamic {
Martha { ... }
Jane { ... }
---dynamics
Their relationship is characterized by mutual respect but
divergent goals. Martha focuses on traditional bread while Jane
pushes for experimental pastries, creating creative tension.
---
}
```
## Cross-References
- [Characters](./10-characters.md) - Participants are typically characters
- [Institutions](./16-other-declarations.md#institutions) - Institutions can participate
- [Value Types](./18-value-types.md) - Field value types
- [Expression Language](./17-expressions.md) - Querying relationships
## Related Concepts
- **Bidirectional modeling**: `self`/`other` blocks enable asymmetric perspectives
- **Social simulation**: Relationships drive character interactions
- **Narrative depth**: Prose blocks embed storytelling in relationship data
- **Power dynamics**: Roles and perspective fields model hierarchies
- **Emotional bonds**: Bond strength and trust metrics quantify connections

View File

@@ -0,0 +1,950 @@
# Other Declarations
This chapter covers six utility declaration types that complete the Storybook language: Templates, Institutions, Locations, Species, Enums, and Use statements. These declarations enable code reuse, organizational modeling, world-building, type safety, and modular file organization.
---
## Templates
Templates are reusable field sets that characters inherit using the `from` keyword. Unlike [species](./10-characters.md#species-optional) (which define what an entity *is*), templates define what an entity *has*—capabilities, traits, and characteristics.
### Syntax
```bnf
<template-decl> ::= "template" <identifier> <strict-clause>? <resource-links>? <includes-clause>? <body>
<strict-clause> ::= "strict"
<resource-links> ::= "uses" "behaviors" ":" <behavior-list>
| "uses" "schedule" ":" <schedule-ref>
| "uses" "schedules" ":" <schedule-list>
<includes-clause> ::= "include" <identifier> ("," <identifier>)*
<body> ::= "{" <field>* "}"
<field> ::= <identifier> ":" <value>
```
### Basic Template
```storybook
template Warrior {
strength: 10..20
dexterity: 8..15
weapon_proficiency: 0.7..1.0
}
```
Characters inheriting this template get these fields with values selected from the specified ranges.
### Template Includes
Templates can include other templates to compose functionality:
```storybook
template SkilledWorker {
skill_level: SkillLevel
confidence: Confidence
years_experience: 0..50
can_work_independently: false
}
template Baker {
include SkilledWorker
specialty: Specialty
recipes_mastered: 0..200
sourdough_starter_health: 0.0..1.0
}
```
**Semantics:**
- `include SkilledWorker` brings in all fields from that template
- Fields are merged left-to-right (later overrides earlier)
- Transitive includes supported
- Multiple includes allowed: `include A, B, C`
### Range Values
Templates can specify ranges for procedural variation:
```storybook
template Villager {
age: 18..65
wealth: 10..100
height: 150.0..190.0
disposition: 0.0..1.0
}
```
**Range syntax:**
- Integer ranges: `min..max` (inclusive)
- Float ranges: `min..max` (inclusive)
- Both bounds must be same type
- min ≤ max required
When a character uses this template, the runtime selects specific values within each range.
### Strict Mode
Strict templates enforce that characters using them can only have fields defined in the template:
```storybook
template RecipeCard strict {
include SkilledWorker
recipe_name: string
difficulty: Difficulty
prep_time_minutes: 10..180
requires_starter: false
}
```
**Strict semantics:**
- Characters using strict templates cannot add extra fields
- All template fields must be present in the character
- Enables type safety for well-defined schemas
- Use for controlled domains (game cards, rigid categories)
**Non-strict (default):**
```storybook
template Flexible {
base_stat: 10
}
character Custom from Flexible {
base_stat: 15 // Override
extra_field: 42 // Allowed in non-strict
}
```
**Strict:**
```storybook
template Rigid strict {
required_stat: 10
}
character Constrained from Rigid {
required_stat: 15 // OK: Override
extra_field: 42 // ERROR: Not allowed in strict template
}
```
### Resource Linking in Templates
Templates can link to behaviors and schedules (v0.2.0+):
```storybook
template BakeryStaffMember
uses behaviors: DailyBakingRoutine, CustomerService
uses schedule: BakerySchedule
{
include SkilledWorker
on_shift: true
orders_completed: 0..1000
current_station: 0..4
}
```
Characters inheriting this template automatically get the linked behaviors and schedule.
### Templates vs. Species
| Aspect | Templates (`from`) | Species (`:`) |
|--------|-------------------|---------------|
| Semantics | What entity *has* | What entity *is* |
| Cardinality | Multiple inheritance | Single inheritance |
| Ranges | Allowed | Not allowed |
| Strict mode | Supported | Not supported |
| Use case | Compositional traits | Ontological identity |
**Example combining both:**
```storybook
species Dragon {
lifespan: 1000
can_fly: true
}
template Hoarder {
treasure_value: 0..1000000
greed_level: 0.5..1.0
}
character Smaug: Dragon from Hoarder {
age: 850
greed_level: 0.95
}
```
### Validation Rules
1. **Includes exist**: All included templates must be defined
2. **No circular includes**: Cannot form cycles
3. **Range validity**: min ≤ max for all ranges
4. **Strict enforcement**: Strict templates reject extra fields in characters
5. **Resource links valid**: Behavior/schedule references must resolve
---
## Institutions
Institutions define organizations, groups, and systems—entities that function like characters but represent collectives rather than individuals.
### Syntax
```bnf
<institution-decl> ::= "institution" <identifier> <resource-links>? <body>
<resource-links> ::= "uses" "behaviors" ":" <behavior-list>
| "uses" "schedule" ":" <schedule-ref>
| "uses" "schedules" ":" <schedule-list>
<body> ::= "{" <field>* <prose-block>* "}"
```
### Basic Institution
```storybook
institution BakersGuild {
type: trade_guild
members: 50
founded: "1450-03-15"
reputation: 0.85
}
```
### Institutions with Fields
```storybook
institution BakersGuild {
type: professional_guild
government_style: elected_board
hierarchy: flat
standards_enforcement: true
// Leadership
board_chair: Martha
vice_chair: Henri
board_temperament: collegial
// Membership
master_bakers: 12
journeymen: 25
apprentices: 8
honorary_members: 3
// Standards
certification_process: "practical exam and peer review"
quality_standard: "excellence"
annual_competition: true
scholarships_offered: 2
---description
The local bakers' guild that sets quality standards, organizes
competitions, and mentors apprentices. Martha has been a board
member for three years.
---
}
```
### Resource Linking
Institutions can use behaviors and schedules:
```storybook
institution MarthasBakery
uses behaviors: DailyBakingRoutine, CustomerService
uses schedule: BakerySchedule
{
type: small_business
purpose: bread_and_pastry_production
family_owned: true
established: 2018
permanent_staff: 4
seasonal_helpers: 0..3
---description
A beloved neighborhood bakery run by Martha and Jane,
known for its sourdough bread and artisan pastries.
---
}
```
### Prose Blocks
Institutions support rich narrative documentation:
```storybook
institution TownCulinaryScene {
type: cultural_ecosystem
governs: "local food culture"
// Characteristics
farm_to_table: true
artisan_focus: strong
seasonal_menus: true
community_events: monthly
---description
The overarching culinary culture of the town -- a network
of bakeries, farms, and food artisans that sustain each other.
---
---philosophy
The town's food scene operates on relationships: farmers
supply bakers, bakers feed families, families support farms.
Quality and trust are the currency of this ecosystem.
---
}
```
### Use Cases
- **Organizations**: Guilds, companies, governments
- **Systems**: Magical systems, physical laws, economies
- **Social structures**: Families, tribes, castes
- **Abstract entities**: Dream logic, fate, chaos
### Validation Rules
1. **Unique names**: Institution names must be unique
2. **Resource links valid**: Behaviors/schedules must exist
3. **Field types**: All fields must have valid values
---
## Locations
Locations define places in your world—rooms, buildings, cities, landscapes, or abstract spaces.
### Syntax
```bnf
<location-decl> ::= "location" <identifier> <body>
<body> ::= "{" <field>* <prose-block>* "}"
```
### Basic Location
```storybook
location MarthasBakery {
square_feet: 1200
type: commercial
established: "2018"
has_storefront: true
---description
A warm, inviting bakery on Main Street. The aroma of fresh
bread wafts out the door every morning. Exposed brick walls,
a glass display case, and a view into the open kitchen.
---
}
```
### Location with Structure
```storybook
location BakeryKitchen {
type: "commercial kitchen"
ovens: 3
prep_stations: 4
walk_in_cooler: true
// Equipment
has_proofing_cabinet: true
mixer_capacity_kg: 20
starter_shelf: true
// Storage
flour_bins: 6
ingredient_shelves: 12
cold_storage: true
---description
The heart of the bakery. Three professional ovens line the
back wall. The sourdough starter sits on a shelf near the
warmest oven, bubbling contentedly in its ceramic crock.
---
}
```
### Geographic Hierarchy
Locations can reference other locations:
```storybook
location MainStreet {
type: commercial_district
shops: 15
foot_traffic: high
}
location BakeryStorefront {
part_of: MainStreet
seating_capacity: 12
display_case: true
---description
The customer-facing area with a glass display case full
of fresh bread, pastries, and seasonal specials.
---
}
location FarmersMarket {
part_of: MainStreet
operates_on: saturday
stalls: 30
---description
The weekly Saturday market where Martha sells bread directly
to the community. Her stall is always the first to sell out.
---
}
```
### Location with State
```storybook
location BakeryWarehouse {
temperature: controlled
square_feet: 400
humidity_controlled: true
shelving_units: 8
// Storage state
flour_stock_kg: 200
yeast_supply_days: 14
packaging_materials: true
---description
The storage area behind the kitchen. Climate-controlled to
keep flour dry and ingredients fresh. Martha takes inventory
every Monday morning.
---
---logistics
Deliveries arrive Tuesday and Friday mornings. The walk-in
cooler holds butter, eggs, and cream. Dry goods are rotated
on a first-in-first-out basis.
---
}
```
### Use Cases
- **Physical places**: Cities, buildings, rooms
- **Geographic features**: Mountains, rivers, forests
- **Abstract spaces**: Dream realms, pocket dimensions
- **Game boards**: Arenas, dungeons, maps
### Validation Rules
1. **Unique names**: Location names must be unique
2. **Field types**: All fields must have valid values
3. **References valid**: Location references (like `part_of`) should resolve
---
## Species
Species define the fundamental ontological categories of beings. A species represents what an entity *is* at its core—human, dragon, sentient tree, animated playing card.
### Syntax
```bnf
<species-decl> ::= "species" <identifier> <includes-clause>? <body>
<includes-clause> ::= "includes" <identifier> ("," <identifier>)*
<body> ::= "{" <field>* <prose-block>* "}"
```
### Basic Species
```storybook
species Human {
lifespan: 70
---description
Bipedal mammals with complex language and tool use.
Highly variable in cultures and capabilities.
---
}
```
### Species with Includes
Species can include other species for composition:
```storybook
species Mammal {
warm_blooded: true
has_fur: true
}
species Primate includes Mammal {
opposable_thumbs: true
sapience_potential: 0.5..1.0
}
species Human includes Primate {
sapience_potential: 1.0
language_complexity: "high"
---description
Highly intelligent primates with advanced tool use.
---
}
```
### Field Resolution with Includes
When a species includes others, fields are merged in declaration order:
1. **Base species** (leftmost in `includes`)
2. **Middle species**
3. **Rightmost species**
4. **Current species** (highest priority)
Example:
```storybook
species Aquatic {
breathes_underwater: true
speed_in_water: 2.0
}
species Reptile {
cold_blooded: true
speed_in_water: 1.0
}
species SeaTurtle includes Aquatic, Reptile {
has_shell: true
speed_in_water: 1.5 // Overrides both
}
// Resolved:
// breathes_underwater: true (from Aquatic)
// cold_blooded: true (from Reptile)
// speed_in_water: 1.5 (SeaTurtle overrides Reptile overrides Aquatic)
// has_shell: true (from SeaTurtle)
```
### Species vs. Templates
| Aspect | Species (`:`) | Templates (`from`) |
|--------|--------------|-------------------|
| Question | "What *is* it?" | "What *traits* does it have?" |
| Cardinality | One per character | Zero or more |
| Inheritance | `includes` (species → species) | Characters inherit from templates |
| Variation | Concrete defaults | Ranges allowed |
| Example | `species Human` | `template Warrior` |
**When to use species:**
```storybook
species Dragon {
lifespan: 1000
can_fly: true
breathes_fire: true
}
character Smaug: Dragon {
age: 850 // Smaug IS a Dragon
}
```
**When to use templates:**
```storybook
template Hoarder {
treasure_value: 0..1000000
greed_level: 0.5..1.0
}
character Smaug: Dragon from Hoarder {
greed_level: 0.95 // Smaug HAS hoarder traits
}
```
### Design Pattern: Prefer Composition Over Deep Hierarchies
**Avoid:**
```storybook
species Being { ... }
species LivingBeing includes Being { ... }
species Animal includes LivingBeing { ... }
species Vertebrate includes Animal { ... }
species Mammal includes Vertebrate { ... }
species Primate includes Mammal { ... }
species Human includes Primate { ... } // Too deep!
```
**Prefer:**
```storybook
species Mammal {
warm_blooded: true
live_birth: true
}
species Human includes Mammal {
sapient: true
}
// Use templates for capabilities
template Climber { ... }
template SocialCreature { ... }
character Jane: Human from Climber, SocialCreature { ... }
```
### Validation Rules
1. **Unique names**: Species names must be unique
2. **No circular includes**: Cannot form cycles
3. **Includes exist**: All included species must be defined
4. **Field types**: All fields must have valid values
---
## Enums
Enums define controlled vocabularies—fixed sets of named values. They enable type-safe categorization and validation.
### Syntax
```bnf
<enum-decl> ::= "enum" <identifier> "{" <variant>+ "}"
<variant> ::= <identifier> ","?
```
### Basic Enum
```storybook
enum Size {
tiny,
small,
normal,
large,
huge
}
```
### Using Enums
Enums are used as field values throughout the system:
```storybook
character Martha: Human {
skill_level: master // References SkillLevel enum
specialty: sourdough // References Specialty enum
}
```
### Common Enum Patterns
**Emotional States:**
```storybook
enum EmotionalState {
curious,
frightened,
confused,
brave,
angry,
melancholy,
amused
}
```
**Card Suits:**
```storybook
enum CardSuit {
hearts,
diamonds,
clubs,
spades
}
enum CardRank {
two, three, four, five, six, seven, eight, nine, ten,
knave, queen, king
}
```
**Time States:**
```storybook
enum TimeState {
normal,
frozen,
reversed,
accelerated
}
```
**Government Types:**
```storybook
enum GovernmentType {
monarchy,
democracy,
anarchy,
tyranny,
oligarchy
}
enum GovernmentStyle {
absolute_tyranny,
benevolent_dictatorship,
constitutional_monarchy,
direct_democracy,
representative_democracy
}
```
### Calendar Enums (Configurable)
Define custom calendars for your world:
```storybook
enum Season {
spring,
summer,
fall,
winter
}
enum DayOfWeek {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday
}
enum Month {
january, february, march, april,
may, june, july, august,
september, october, november, december
}
```
**Custom calendars:**
```storybook
enum EightSeasons {
deep_winter,
late_winter,
early_spring,
late_spring,
early_summer,
late_summer,
early_fall,
late_fall
}
```
### Validation Integration
Enums enable compile-time validation:
```storybook
enum Size {
tiny, small, normal, large, huge
}
character Martha {
skill_level: medium // ERROR: 'medium' not in SkillLevel enum
}
```
### Use Cases
- **Controlled vocabularies**: Prevent typos and invalid values
- **Schema constraints**: Temporal systems, card decks, status types
- **Type safety**: Catch errors at compile time
- **Documentation**: Enumerate all valid options
### Validation Rules
1. **Unique enum names**: Enum names must be unique
2. **Unique variants**: Variant names must be unique within the enum
3. **Non-empty**: Enums must have at least one variant
4. **Valid identifiers**: Variants must follow identifier rules
---
## Use Statements
Use statements import definitions from other files, enabling modular organization and code reuse.
### Syntax
```bnf
<use-decl> ::= "use" <use-path> <use-kind>
<use-path> ::= <identifier> ("::" <identifier>)*
<use-kind> ::= ";" // Single import
| "::{" <identifier> ("," <identifier>)* "}" ";" // Grouped import
| "::*" ";" // Wildcard import
```
### Single Import
```storybook
use schema::beings::Human;
```
Imports the `Human` species from `schema/beings.sb`.
### Grouped Import
```storybook
use schema::core_enums::{Size, EmotionalState};
```
Imports multiple items from the same module.
### Wildcard Import
```storybook
use schema::beings::*;
```
Imports all public items from `schema/beings.sb`.
### Qualified Paths
**Module structure:**
```
examples/alice-in-wonderland/
├─ schema/
│ ├─ core_enums.sb
│ ├─ templates.sb
│ └─ beings.sb
└─ world/
├─ characters/
│ └─ alice.sb
└─ locations/
└─ wonderland_places.sb
```
**In `martha.sb`:**
```storybook
use schema::core_enums::{SkillLevel, Specialty};
use schema::templates::Baker;
use schema::beings::Human;
character Martha: Human from Baker {
skill_level: master
specialty: sourdough
}
```
### Path Resolution
1. **Relative to file's module path**: Imports are resolved relative to the current file's location
2. **Module hierarchy**: `schema::beings` maps to `schema/beings.sb`
3. **Transitive imports**: Imported modules can themselves import others
### Common Patterns
**Schema organization:**
```storybook
// In schema/core_enums.sb
enum SkillLevel { novice, beginner, intermediate, advanced, master }
enum Specialty { sourdough, pastries, cakes, general }
// In world/characters/martha.sb
use schema::core_enums::{SkillLevel, Specialty};
```
**Template composition:**
```storybook
// In schema/templates.sb
template SkilledWorker { ... }
template Baker {
include SkilledWorker
...
}
// In world/characters/martha.sb
use schema::templates::Baker;
```
**Cross-file references:**
```storybook
// In world/characters/martha.sb
character Martha { ... }
// In world/relationships/bakery.sb
use world::characters::Martha;
relationship MarthaAndJane {
Martha
Jane
}
```
### Validation Rules
1. **Path exists**: Imported paths must reference defined modules/items
2. **No circular imports**: Modules cannot form circular dependency chains
3. **Valid identifiers**: All path segments must be valid identifiers
4. **Grouped import validity**: All items in `{}` must exist
### Best Practices
**1. Group related imports:**
```storybook
use schema::core_enums::{SkillLevel, Specialty, Confidence};
use schema::beings::{Human, Cat};
```
**2. Explicit over wildcard:**
```storybook
// Prefer:
use schema::core_enums::{SkillLevel, Specialty};
// Over:
use schema::core_enums::*; // Imports everything
```
**3. Organize by hierarchy:**
```storybook
// Schema imports first
use schema::core_enums::SkillLevel;
use schema::templates::Baker;
// Then world imports
use world::characters::Martha;
```
**4. Use qualified paths for clarity:**
```storybook
character Elena: Human from Baker, Apprentice {
// Human is species (from schema::beings)
// Baker, Apprentice are templates (from schema::templates)
}
```
---
## Cross-References
- [Characters](./10-characters.md) - Using templates and species
- [Relationships](./15-relationships.md) - Institutions can participate
- [Schedules](./14-schedules.md) - Resource linking
- [Behavior Trees](./11-behavior-trees.md) - Resource linking
- [Value Types](./18-value-types.md) - Field value types
## Related Concepts
- **Modularity**: Use statements enable file organization
- **Composition**: Templates provide trait-based composition
- **Type safety**: Enums prevent invalid values
- **World-building**: Locations and institutions model environments
- **Ontology**: Species define entity essence

View File

@@ -0,0 +1,311 @@
# Locations
Locations define places in your world -- rooms, buildings, cities, landscapes, or abstract spaces. They provide spatial context for characters, events, and narratives.
---
## Syntax
```bnf
<location-decl> ::= "location" <identifier> "{" <field>* <prose-block>* "}"
```
A location declaration consists of:
- The `location` keyword
- A unique name (identifier)
- A body block containing fields and optional prose blocks
Locations are one of the simpler declaration types -- they hold fields and prose blocks but do not support resource linking (`uses behaviors` / `uses schedule`) like characters or institutions.
---
## Basic Location
The simplest location has a name and descriptive fields:
```storybook
location BakersBakery {
type: bakery
capacity: 30
address: "14 Main Street"
open_hours: "06:00-18:00"
}
```
Fields can use any [value type](./18-value-types.md): integers, floats, strings, booleans, enums, lists, ranges, and durations.
---
## Fields
Location fields describe properties of the place:
```storybook
location BakerHome {
type: residence
bedrooms: 3
has_garden: true
garden_size_sqft: 450.0
residents: ["Martha", "David", "Jane"]
comfort_level: 0.85
}
```
### Common Field Patterns
| Field | Type | Description |
|-------|------|-------------|
| `type` | enum/identifier | Category of the place |
| `capacity` | integer | How many can be in this place |
| `size` | enum/float | Physical size |
| `coordinates` | integer/float | Position in a world map |
| `accessible` | boolean | Whether characters can enter |
These are conventions, not enforced schema. You define whatever fields are meaningful for your world.
---
## Prose Blocks
Locations support prose blocks for rich narrative content. Prose blocks are delimited by `---tag` markers:
```storybook
location BakersBakery {
type: bakery
capacity: 30
---description
A warm, inviting bakery on Main Street. The smell of fresh bread
wafts out the door every morning at dawn. Martha has run the shop
for fifteen years, and the locals consider it the heart of the
neighborhood.
---
---atmosphere
Flour dust catches the light from tall windows. A display case
holds rows of golden pastries. Behind the counter, the kitchen
hums with activity from 4 AM onward.
---
}
```
**Prose block rules:**
- Start with `---tag_name` on its own line
- Content is free-form text (Markdown supported)
- End with `---` on its own line
- The tag name becomes the key for retrieval
- Multiple prose blocks per location are allowed
- Each tag must be unique within the location
---
## Ranges
Locations can use range values for procedural variation:
```storybook
location MarketSquare {
type: outdoor_market
stalls: 10..25
daily_visitors: 50..200
noise_level: 0.4..0.9
}
```
When instantiated, values are selected from within the specified range. This is useful for locations that should vary across simulation runs.
---
## Lists
Locations can hold list values:
```storybook
location BakersBakery {
type: bakery
products: ["sourdough", "croissants", "rye bread", "cinnamon rolls"]
equipment: ["stone oven", "mixing station", "proofing cabinet"]
}
```
---
## Referencing Other Entities
Location fields can reference other declarations by name:
```storybook
location BakersBakery {
type: bakery
owner: Martha
neighborhood: MainStreet
part_of: TownCenter
}
```
These are identifier references -- they are not validated as cross-references at parse time, but the resolver checks that referenced names exist in the name table.
---
## Nested Structure with Fields
You can model spatial hierarchy using fields:
```storybook
location BakersBakery {
type: bakery
parent: MainStreet
// Zones within the bakery
has_kitchen: true
has_storefront: true
has_storage_room: true
// Dimensions
total_sqft: 1200
kitchen_sqft: 600
storefront_sqft: 400
storage_sqft: 200
}
location MainStreet {
type: street
parent: TownCenter
length_meters: 500
shops: 12
}
location TownCenter {
type: district
population: 2000
}
```
There is no built-in parent-child relationship for locations -- you model hierarchy through conventional field names like `part_of`, `parent`, or `contains`.
---
## Location with Enum Fields
Use [enums](./16-other-declarations.md#enums) for type-safe categorization:
```storybook
enum PlaceType {
residence, shop, workshop, office,
park, street, square, church
}
enum Accessibility {
public, private, restricted, members_only
}
location BakersBakery {
type: shop
accessibility: public
capacity: 30
}
location BakerHome {
type: residence
accessibility: private
capacity: 8
}
```
---
## Complete Example: Baker Family Locations
```storybook
use schema::enums::{PlaceType, Accessibility};
location BakersBakery {
type: shop
accessibility: public
owner: Martha
address: "14 Main Street"
capacity: 30
employees: 4
established: "2011"
specialty: "artisan sourdough"
daily_output_loaves: 80..120
---description
Martha Baker's artisan bakery, known throughout town for its
sourdough and pastries. The shop opens at 6 AM sharp, and by
mid-morning there's usually a line out the door.
---
---history
Originally a hardware store, Martha converted the space after
winning a local baking competition. The stone oven was imported
from France and is the heart of the operation.
---
}
location BakerHome {
type: residence
accessibility: private
address: "22 Elm Lane"
bedrooms: 4
has_garden: true
garden_size_sqft: 600
residents: ["Martha", "David", "Jane", "Tom"]
comfort_level: 0.9
---description
A comfortable family home on a quiet street. The kitchen is
oversized (Martha insisted) and there's always something
baking, even at home.
---
}
location BakersGuildHall {
type: office
accessibility: members_only
address: "7 Guild Row"
capacity: 100
meeting_room_capacity: 40
established: "1892"
---description
The historic headquarters of the Bakers Guild, where trade
matters are discussed and apprenticeships are arranged.
---
}
```
---
## Validation Rules
1. **Unique names**: Location names must be unique within their scope
2. **Valid field values**: All fields must have values that conform to [value types](./18-value-types.md)
3. **Unique field names**: No duplicate field names within a location
4. **Unique prose tags**: No duplicate prose block tags within a location
5. **Valid identifiers**: Location names must follow identifier rules (`[a-zA-Z_][a-zA-Z0-9_]*`)
---
## Locations vs. Other Declarations
| Aspect | Locations | Institutions | Characters |
|--------|-----------|-------------|------------|
| Purpose | Physical/abstract places | Organizations/groups | Individuals |
| Resource linking | No | Yes | Yes |
| Prose blocks | Yes | Yes | Yes |
| Species | No | No | Yes |
| Templates | No | No | Yes |
Locations are intentionally simple. They define *where* things happen. For *who* does things, use [characters](./10-characters.md). For *organizational structures*, use [institutions](./16b-institutions.md).
---
## Cross-References
- [Characters](./10-characters.md) -- Characters can reference locations via fields
- [Institutions](./16b-institutions.md) -- Institutions can be associated with locations
- [Schedules](./14-schedules.md) -- Schedule activities can reference locations
- [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

View File

@@ -0,0 +1,414 @@
# 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

View File

@@ -0,0 +1,703 @@
# Expression Language
The Storybook expression language enables conditions, queries, and logic throughout the system. Expressions appear in life arc transitions, behavior tree guards, decorator conditions, and relationship queries. This chapter provides a complete reference for expression syntax and semantics.
## What are Expressions?
Expressions are logical statements that evaluate to `true` or `false`. They combine:
- **Literals**: Numbers, strings, booleans
- **Identifiers**: References to fields and entities
- **Comparisons**: `==`, `!=`, `<`, `<=`, `>`, `>=`
- **Logical operators**: `and`, `or`, `not`
- **Field access**: `self.field`, `other.field`
- **Quantifiers**: `forall`, `exists` (for collections)
## Syntax
```bnf
<expression> ::= <literal>
| <identifier>
| <field-access>
| <comparison>
| <logical>
| <unary>
| <quantifier>
| "(" <expression> ")"
<literal> ::= <int> | <float> | <string> | <bool>
<identifier> ::= <simple-name>
| <qualified-path>
<field-access> ::= <expression> "." <identifier>
| "self" "." <identifier>
| "other" "." <identifier>
<comparison> ::= <expression> <comp-op> <expression>
<comp-op> ::= "==" | "!=" | "<" | "<=" | ">" | ">="
<logical> ::= <expression> "and" <expression>
| <expression> "or" <expression>
<unary> ::= "not" <expression>
| "-" <expression>
<quantifier> ::= ("forall" | "exists") <identifier> "in" <expression> ":" <expression>
```
## Literals
### Integer Literals
```storybook
42
-7
0
1000
```
### Float Literals
```storybook
3.14
-0.5
0.0
100.25
```
### String Literals
```storybook
"Martha"
"Sourdough takes patience."
"active"
```
Strings are enclosed in double quotes. Escape sequences: `\n`, `\t`, `\\`, `\"`.
### Boolean Literals
```storybook
true
false
```
## Identifiers
Identifiers reference fields or entities.
### Simple Identifiers
```storybook
health
enemy_count
is_ready
```
### Qualified Paths
```storybook
Martha.skill_level
Character.emotional_state
```
## Comparison Operators
### Equality: `==`
Tests if two values are equal.
```storybook
name == "Martha"
count == 5
status == active
```
**Type compatibility:**
- Both operands must be the same type
- Works with: int, float, string, bool, enum values
### Inequality: `!=`
Tests if two values are not equal.
```storybook
name != "Gregory"
health != 0
ready != true
```
### Less Than: `<`
Tests if left operand is less than right.
```storybook
health < 20
age < 18
distance < 10.0
```
**Valid types:** int, float
### Less Than or Equal: `<=`
```storybook
health <= 50
count <= max_count
```
### Greater Than: `>`
```storybook
strength > 10
bond > 0.5
```
### Greater Than or Equal: `>=`
```storybook
age >= 21
score >= 100
```
## Logical Operators
### AND: `and`
Both operands must be true.
```storybook
health < 50 and has_potion
is_ready and not is_busy
age >= 18 and age < 65
```
**Evaluation:** Short-circuit (if left is false, right is not evaluated)
### OR: `or`
At least one operand must be true.
```storybook
is_day or is_lit
health < 20 or surrounded
enemy_count == 0 or all_enemies_dead
```
**Evaluation:** Short-circuit (if left is true, right is not evaluated)
### Operator Precedence
From highest to lowest:
1. **Parentheses**: `(...)`
2. **Unary**: `not`, `-`
3. **Comparisons**: `==`, `!=`, `<`, `<=`, `>`, `>=`
4. **AND**: `and`
5. **OR**: `or`
**Examples:**
```storybook
not is_ready and is_awake
// Equivalent to: (not is_ready) and is_awake
health < 50 or is_poisoned and has_antidote
// Equivalent to: (health < 50) or (is_poisoned and has_antidote)
// Use parentheses for clarity:
(health < 50 or is_poisoned) and has_antidote
```
## Unary Operators
### NOT: `not`
Inverts a boolean value.
```storybook
not is_ready
not (health < 20)
not enemy_nearby and safe
```
### Negation: `-`
Negates a numeric value.
```storybook
-health
-10
-(max_value - current_value)
```
## Field Access
### Direct Field Access
```storybook
health
bond
emotional_state
```
References a field on the current entity.
### Dot Access
```storybook
Martha.skill_level
Character.emotional_state
enemy.health
```
Access fields on other entities.
### Self Access
In relationships and certain contexts, `self` refers to the current participant:
```storybook
self.bond
self.responsibility
self.trust
```
**Use case:** Relationship transitions, symmetric queries
### Other Access
In relationships, `other` refers to other participants:
```storybook
other.bond
other.aware_of_mentor
other.respect
```
**Use case:** Relationship queries with perspective
### Example in Life Arcs
```storybook
life_arc RelationshipState {
state new {
on self.bond > 0.7 and other.bond > 0.7 -> stable
}
state stable {
on self.bond < 0.3 -> troubled
on other.bond < 0.3 -> troubled
}
state troubled {
on self.bond < 0.1 or other.bond < 0.1 -> broken
}
state broken {}
}
```
## Quantifiers
Quantifiers test conditions over collections.
### ForAll: `forall`
Tests if a condition holds for all elements in a collection.
```storybook
forall e in enemies: e.defeated
forall item in inventory: item.weight < 10
```
**Syntax:**
```bnf
forall <variable> in <collection>: <predicate>
```
**Semantics:**
- Returns `true` if predicate is true for every element
- Returns `true` for empty collections (vacuously true)
**Examples:**
```storybook
// All enemies defeated?
forall enemy in enemies: enemy.health <= 0
// All party members ready?
forall member in party: member.is_ready
// All doors locked?
forall door in doors: door.is_locked
```
### Exists: `exists`
Tests if a condition holds for at least one element.
```storybook
exists e in enemies: e.is_hostile
exists item in inventory: item.is_healing_potion
```
**Syntax:**
```bnf
exists <variable> in <collection>: <predicate>
```
**Semantics:**
- Returns `true` if predicate is true for any element
- Returns `false` for empty collections
**Examples:**
```storybook
// Any enemy nearby?
exists enemy in enemies: enemy.distance < 10
// Any door unlocked?
exists door in doors: not door.is_locked
// Any ally wounded?
exists ally in allies: ally.health < ally.max_health * 0.5
```
### Nested Quantifiers
Quantifiers can nest:
```storybook
forall team in teams: exists player in team: player.is_leader
// Every team has at least one leader
exists room in dungeon: forall enemy in room.enemies: enemy.defeated
// At least one room has all enemies defeated
```
## Usage in Context
### Life Arc Transitions
```storybook
life_arc CombatState {
state idle {
on enemy_count > 0 -> combat
}
state combat {
on health < 20 -> fleeing
on enemy_count == 0 -> victorious
}
state fleeing {
on distance_from_enemies > 100 -> safe
}
state victorious {
on celebration_complete -> idle
}
state safe {
on health >= 50 -> idle
}
}
```
### Behavior Tree Conditions
```storybook
behavior GuardedAction {
if(health > 50 and has_weapon) {
AggressiveAttack
}
}
behavior ConditionalChoice {
choose tactics {
then melee {
if(distance < 5 and weapon_type == "sword")
MeleeAttack
}
then ranged {
if(distance >= 5 and has_arrows)
RangedAttack
}
}
}
```
### Behavior Tree Conditions
```storybook
behavior SmartAI {
choose strategy {
then aggressive {
if(health > 70 and enemy_count < 3)
Attack
}
then defensive {
if(health < 30 or enemy_count >= 5)
Defend
}
then balanced {
if(health >= 30 and health <= 70)
TacticalManeuver
}
}
}
```
## Type System
### Type Compatibility
Comparisons require compatible types:
| Operator | Left Type | Right Type | Valid? |
|----------|-----------|------------|--------|
| `==`, `!=` | int | int | ✓ |
| `==`, `!=` | float | float | ✓ |
| `==`, `!=` | string | string | ✓ |
| `==`, `!=` | bool | bool | ✓ |
| `==`, `!=` | enum | same enum | ✓ |
| `==`, `!=` | int | float | ✗ |
| `<`, `<=`, `>`, `>=` | int | int | ✓ |
| `<`, `<=`, `>`, `>=` | float | float | ✓ |
| `<`, `<=`, `>`, `>=` | string | string | ✗ |
### Implicit Coercion
**None.** Storybook has no implicit type coercion. All comparisons must be between compatible types.
**Error:**
```storybook
count == "5" // Error: int vs string
health < true // Error: int vs bool
```
**Correct:**
```storybook
count == 5
health < 50
```
## Special Keyword: `is`
The `is` keyword provides syntactic sugar for equality with enum values:
```storybook
// Instead of:
status == active
// You can write:
status is active
```
**More examples:**
```storybook
name is "Martha"
skill_level is master
emotional_state is focused
```
This is purely syntactic—`is` and `==` are equivalent.
## Complete Examples
### Simple Conditions
```storybook
health < 20
enemy_nearby
not is_ready
count > 5
```
### Complex Conditions
```storybook
(health < 20 and not has_potion) or surrounded
forall e in enemies: e.defeated
exists item in inventory: item.is_healing_potion and item.quantity > 0
```
### Life Arc with Complex Conditions
```storybook
life_arc CharacterMood {
state content {
on health < 30 or hunger > 80 -> distressed
on social_interaction > 0.8 -> happy
}
state distressed {
on health >= 50 and hunger < 30 -> content
on (health < 10 or hunger > 95) and help_available -> desperate
}
state happy {
on social_interaction < 0.3 -> content
on received_bad_news -> distressed
}
state desperate {
on help_received -> distressed
}
}
```
### Behavior with Quantifiers
```storybook
behavior SquadLeader {
choose leadership {
then regroup {
if(squad_has_wounded)
OrderRetreat
}
then advance {
if(squad_all_ready)
OrderAdvance
}
then hold_position {
if(not squad_all_ready)
OrderHold
}
}
}
```
### Relationship Query
```storybook
life_arc FriendshipQuality {
state new_friends {
on self.bond > 0.7 and other.bond > 0.7 -> strong_bond
on self.trust < 0.3 or other.trust < 0.3 -> shaky
}
state strong_bond {
on self.bond < 0.5 -> weakening
}
state weakening {
on self.bond < 0.2 or other.bond < 0.2 -> ended
on self.bond > 0.7 and other.bond > 0.7 -> strong_bond
}
state shaky {
on self.trust > 0.6 and other.trust > 0.6 -> new_friends
on self.trust < 0.1 or other.trust < 0.1 -> ended
}
state ended {}
}
```
## Validation Rules
1. **Type consistency**: Both sides of comparison must be compatible types
2. **Boolean context**: Logical operators (`and`, `or`, `not`) require boolean operands
3. **Field existence**: Referenced fields must exist on the entity
4. **Collection validity**: Quantifiers require collection-typed expressions
5. **Variable scope**: Quantifier variables only valid within their predicate
6. **No division by zero**: Arithmetic operations must not divide by zero
7. **Enum validity**: Enum comparisons must reference defined enum values
## Best Practices
### 1. Use Parentheses for Clarity
**Avoid:**
```storybook
health < 50 or is_poisoned and has_antidote
```
**Prefer:**
```storybook
(health < 50 or is_poisoned) and has_antidote
```
### 2. Break Complex Conditions
**Avoid:**
```storybook
on (health < 20 and not has_potion) or (surrounded and not has_escape) or (enemy_count > 10 and weapon_broken) -> desperate
```
**Prefer:**
```storybook
state combat {
on health < 20 and not has_potion -> desperate
on surrounded and not has_escape -> desperate
on enemy_count > 10 and weapon_broken -> desperate
}
```
### 3. Name Complex Conditions
For repeated complex conditions, consider using intermediate fields:
**Instead of:**
```storybook
on health < (max_health * 0.2) and enemy_count > 5 -> flee
```
**Consider:**
```storybook
// In character definition:
critically_wounded: health < (max_health * 0.2)
outnumbered: enemy_count > 5
// In life arc:
on critically_wounded and outnumbered -> flee
```
### 4. Use `is` for Enums
**Prefer:**
```storybook
status is active
emotional_state is focused
```
**Over:**
```storybook
status == active
emotional_state == focused
```
### 5. Quantifiers for Collections
**Avoid:**
```storybook
// Manual checks for each element
if enemy1.defeated and enemy2.defeated and enemy3.defeated
```
**Prefer:**
```storybook
if forall enemy in enemies: enemy.defeated
```
## Cross-References
- [Life Arcs](./13-life-arcs.md) - Transition conditions
- [Behavior Trees](./11-behavior-trees.md) - Guard and condition nodes
- [Decorators](./12-decorators.md) - Guard decorator
- [Relationships](./15-relationships.md) - Self/other field access
- [Value Types](./18-value-types.md) - Literal value types
## Related Concepts
- **Type safety**: Strong typing prevents type errors at compile time
- **Short-circuit evaluation**: AND/OR operators optimize evaluation
- **Quantifiers**: Enable expressive collection queries
- **Field access**: Context-sensitive (`self`, `other`) for relationships
- **Boolean algebra**: Standard logical operators with expected semantics

View File

@@ -0,0 +1,709 @@
# Values
Values are the fundamental data types in Storybook. Every field in a character, template, or other declaration contains a value. This chapter provides a complete reference for all supported value types.
## Value Types Overview
Storybook supports 12 value types:
| Type | Example | Use Case |
|------|---------|----------|
| **Int** | `42`, `-7` | Quantities, IDs, counts |
| **Float** | `3.14`, `-0.5` | Measurements, probabilities |
| **String** | `"Hello"`, `"Martha"` | Text, names, descriptions |
| **Bool** | `true`, `false` | Flags, switches |
| **Time** | `14:30`, `09:15:30` | Clock times, schedule blocks |
| **Duration** | `2h30m`, `45s` | Time intervals |
| **Range** | `20..40`, `0.5..1.0` | Template variation bounds |
| **Identifier** | `Martha`, `items::sword` | References to other declarations |
| **List** | `[1, 2, 3]`, `["a", "b"]` | Collections |
| **Object** | `{x: 10, y: 20}` | Structured data |
| **ProseBlock** | `---tag content ---` | Long-form narrative |
| **Override** | `TemplateX with {...}` | Template instantiation with modifications |
## Integer
Signed 64-bit integers.
### Syntax
```bnf
<int> ::= ["-"] <digit>+
<digit> ::= "0".."9"
```
### Examples
```storybook
character Hero {
age: 25
gold: 1500
reputation: -10
}
```
### Range
- Minimum: `-9,223,372,036,854,775,808`
- Maximum: `9,223,372,036,854,775,807`
### Use Cases
- Counts (items, population)
- Identifiers (IDs, keys)
- Scores (reputation, alignment)
- Whole quantities (gold pieces, HP)
## Float
64-bit floating-point numbers (IEEE 754 double precision).
### Syntax
```bnf
<float> ::= ["-"] <digit>+ "." <digit>+
| ["-"] <digit>+ ("e" | "E") ["+"|"-"] <digit>+
```
### Examples
```storybook
character Wizard {
mana: 100.0
spell_power: 1.5
corruption: 0.03
precision: 1e-6
}
```
### Special Values
- No `NaN` or `Infinity` support (use validation to prevent)
- Negative zero (`-0.0`) equals positive zero (`0.0`)
### Use Cases
- Probabilities (0.0 to 1.0)
- Percentages (0.0 to 100.0)
- Measurements with precision
- Ratios and scaling factors
## String
UTF-8 encoded text enclosed in double quotes.
### Syntax
```bnf
<string> ::= '"' <string-char>* '"'
<string-char> ::= <any-char-except-quote-or-backslash>
| <escape-sequence>
<escape-sequence> ::= "\n" | "\r" | "\t" | "\\" | "\""
```
### Escape Sequences
- `\n` - Newline
- `\r` - Carriage return
- `\t` - Tab
- `\\` - Backslash
- `\"` - Double quote
### Examples
```storybook
character Martha {
name: "Martha Baker"
greeting: "Fresh from the oven!"
multiline: "Line 1\nLine 2\nLine 3"
quote: "She said, \"The bread is ready!\""
}
```
### Limitations
- No raw strings (r"...") or multi-line literals
- For long text, use [prose blocks](#prose-blocks)
- Maximum length: Implementation-defined (typically several MB)
### Use Cases
- Character names
- Short descriptions
- Dialogue snippets
- Enum-like values (before proper enums)
## Boolean
Logical true/false values.
### Syntax
```bnf
<bool> ::= "true" | "false"
```
### Examples
```storybook
character Guard {
is_awake: true
has_seen_player: false
loyal_to_king: true
}
```
### Use Cases
- Feature flags (can_fly, is_hostile)
- State tracking (door_open, quest_complete)
- Conditions (is_friendly, accepts_bribes)
## Time
Clock time in 24-hour format.
### Syntax
```bnf
<time> ::= <hour> ":" <minute>
| <hour> ":" <minute> ":" <second>
<hour> ::= "0".."23"
<minute> ::= "0".."59"
<second> ::= "0".."59"
```
### Examples
```storybook
schedule BakerySchedule {
block {
start: 06:00
end: 08:30
action: baking::prepare_dough
}
block {
start: 14:30:15 // With seconds
end: 15:00:00
action: baking::afternoon_cleanup
}
}
character EarlyRiser {
wake_time: 05:30
bedtime: 21:00
}
```
### Validation
- Hours: 0-23 (24-hour format)
- Minutes: 0-59
- Seconds: 0-59 (optional)
- No AM/PM notation
- No timezone support (context-dependent)
### Use Cases
- Schedule blocks (see [Schedules](./16-schedules.md))
- Character routines
- Event timing
- Time-based conditions
## Duration
Time intervals with hour/minute/second components.
### Syntax
```bnf
<duration> ::= <duration-component>+
<duration-component> ::= <number> ("h" | "m" | "s")
<number> ::= <digit>+
```
### Examples
```storybook
character Traveler {
journey_time: 2h30m
rest_needed: 8h
sprint_duration: 45s
}
behavior TimedAction {
choose {
timeout(5m) {
CompleteObjective
}
cooldown(30s) {
UseSpecialAbility
}
}
}
```
### Components
- `h` - Hours
- `m` - Minutes
- `s` - Seconds
Can combine multiple components: `1h30m15s`
### Validation
- All components non-negative
- No fractional components (`1.5h` not allowed; use `1h30m`)
- Can specify same unit multiple times: `90m` = `1h30m` (normalized)
### Use Cases
- Behavior tree timeouts/cooldowns
- Travel times
- Cooldown periods
- Event durations
## Range
Numeric range with inclusive bounds (for templates only).
### Syntax
```bnf
<range> ::= <value> ".." <value>
```
Both bounds must be the same type (both int or both float).
### Examples
```storybook
template Villager {
age: 18..65
wealth: 10..100
height: 150.0..190.0 // Float range
}
template RandomEvent {
probability: 0.0..1.0
damage: 5..20
}
```
### Semantics
- **Templates only**: Ranges are only valid in templates
- **Instantiation**: When a template is used, a specific value within the range is selected
- **Inclusive bounds**: Both `min` and `max` are included
- **Order matters**: `min` must be ≤ `max`
### Validation
- Both bounds same type
- `min``max`
- Cannot use ranges in character/species/etc. (only templates)
### Use Cases
- Template variation
- Procedural generation
- Random NPC attributes
- Loot table ranges
## Identifier
Reference to another declaration by qualified path.
### Syntax
```bnf
<identifier> ::= <simple-name>
| <qualified-path>
<simple-name> ::= <ident>
<qualified-path> ::= <ident> ("::" <ident>)+
```
### Examples
```storybook
character Martha: Human { // Species reference
// ...
}
character Elena from Apprentice { // Template reference
// ...
}
character Guard {
uses behaviors: [
{ tree: guards::patrol } // Behavior reference
]
uses schedule: DailyRoutine // Schedule reference
}
relationship Partnership {
Martha // Character reference
Jane // Character reference
}
```
### Resolution
- **Unqualified**: Searches current module, then imports
- **Qualified**: `module::submodule::Name`
- **Validation**: Compiler ensures all references resolve
### Use Cases
- Species typing (`: Species`)
- Template inheritance (`from Template`)
- Behavior tree references
- Schedule references
- Relationship participants
- Cross-references
## List
Ordered collection of values.
### Syntax
```bnf
<list> ::= "[" "]"
| "[" <value> ("," <value>)* "]"
```
### Examples
```storybook
character Mage {
known_spells: ["Fireball", "Lightning", "Shield"]
spell_levels: [3, 5, 2]
party_members: [Martha, Jane, Elena]
}
character Traveler {
inventory: [
{item: "Sword", damage: 10},
{item: "Potion", healing: 50},
{item: "Key", opens: "TowerDoor"}
]
}
```
### Type Constraints
- **Homogeneous preferred**: All elements should be the same type
- **Heterogeneous allowed**: Mixed types permitted but discouraged
- **Empty lists**: `[]` is valid
### Operations
Lists are immutable at declaration time. Runtime list operations depend on the execution environment.
### Use Cases
- Collections (inventory, spells, party members)
- References (multiple behaviors, schedules, participants)
- Enum-like sets (before proper enums)
## Object
Structured data with named fields.
### Syntax
```bnf
<object> ::= "{" "}"
| "{" <field> ("," <field>)* "}"
<field> ::= <identifier> ":" <value>
```
### Examples
```storybook
character Hero {
position: {x: 100, y: 200}
stats: {
strength: 15,
dexterity: 12,
intelligence: 10
}
equipment: {
weapon: {
name: "Longsword",
damage: 10,
enchantment: "Fire"
},
armor: {
name: "Plate Mail",
defense: 8
}
}
}
```
### Nesting
Objects can be nested arbitrarily deep:
```storybook
character Complex {
deep: {
level1: {
level2: {
level3: {
value: 42
}
}
}
}
}
```
### Use Cases
- Structured data (position, stats)
- Nested configurations
- Inline data structures
- Complex field values
## Prose Blocks
Long-form narrative text with semantic tags.
### Syntax
```bnf
<prose-block> ::= "---" <tag> <content> "---"
<tag> ::= <identifier>
<content> ::= <any-text-except-triple-dash>
```
### Common Tags
- `---description`: General description
- `---backstory`: Character history
- `---appearance`: Physical description
- `---personality`: Behavioral traits
- `---motivation`: Goals and desires
- `---notes`: Meta-commentary
- `---ecology`: Species habitat/behavior
- `---culture`: Social structures
- `---narrative`: Story context
### Examples
```storybook
character Martha {
age: 34
---backstory
Martha learned to bake from her grandmother, starting at age
twelve. She now runs the most popular bakery in town, known
for her sourdough bread and unwavering quality standards.
---
---personality
Meticulous and patient, with an unwavering commitment to
quality. Tough but fair with her staff, and deeply loyal
to the customers who have supported her bakery for years.
---
}
species Dragon {
lifespan: 1000
---ecology
Dragons nest in high mountain caves and emerge every few decades
to hunt large prey. They hoard treasure as a mating display.
---
}
```
### Formatting
- Leading/trailing whitespace is preserved
- No escape sequences needed
- Can contain any characters except `---` on its own line
- Indentation is significant for readability but not semantics
### Multiple Prose Blocks
A single declaration can have multiple prose blocks with different tags:
```storybook
character Gandalf {
---appearance
An old man with a long gray beard, pointed hat, and staff.
---
---backstory
One of the Istari sent to Middle-earth to contest Sauron.
---
---personality
Patient and wise, but with a mischievous streak.
---
}
```
### Use Cases
- Character backstories
- Species descriptions
- World-building flavor text
- Design notes
- Narrative context
## Override
Template instantiation with field modifications.
### Syntax
```bnf
<override> ::= <qualified-path> "with" "{" <override-op>* "}"
<override-op> ::= <identifier> ":" <value> // Set
| "remove" <identifier> // Remove
| "append" <identifier> ":" <value> // Append (for lists)
```
### Examples
#### Basic Override
```storybook
template BaseWarrior {
strength: 10
dexterity: 8
weapon: "Sword"
}
character StrongWarrior {
stats: BaseWarrior with {
strength: 15 // Override strength
}
}
```
#### Remove Fields
```storybook
template FullEquipment {
helmet: "Iron"
chest: "Plate"
legs: "Mail"
boots: "Leather"
}
character LightFighter {
equipment: FullEquipment with {
remove helmet
remove chest
}
}
```
#### Append to Lists
```storybook
template BasicSpells {
spells: ["Fireball", "Shield"]
}
character AdvancedMage {
magic: BasicSpells with {
append spells: "Teleport"
append spells: "Lightning"
}
// Result: ["Fireball", "Shield", "Teleport", "Lightning"]
}
```
#### Complex Override
```storybook
template RogueTemplate {
stealth: 15
lockpicking: 12
backstab_damage: 20
equipment: ["Dagger", "Lockpicks"]
}
character MasterThief {
abilities: RogueTemplate with {
stealth: 20 // Set
remove backstab_damage // Remove
append equipment: "Grappling Hook" // Append
}
}
```
### Operations
#### `set` (default)
Replace a field's value:
```storybook
field_name: new_value
```
#### `remove`
Delete a field from the template:
```storybook
remove field_name
```
#### `append`
Add to a list field (field must be a list):
```storybook
append field_name: value_to_add
```
### Validation
- Base template must exist
- Overridden fields must exist in template
- Removed fields must exist in template
- Appended fields must be lists
- Type compatibility enforced
### Use Cases
- Customizing template instances
- Procedural character generation
- Variant creation
- Data composition
## Type Coercion
Storybook has **no implicit type coercion**. All type conversions must be explicit.
**Not allowed:**
```storybook
character Wrong {
count: "42" // Error: expected int, got string
flag: 1 // Error: expected bool, got int
}
```
**Correct:**
```storybook
character Right {
count: 42
flag: true
}
```
## Null and Optional
Storybook **does not have `null`**. For optional values, use:
1. **Template ranges** with 0 as lower bound:
```storybook
template MaybeWeapon {
weapon_count: 0..5
}
```
2. **Boolean flags**:
```storybook
character Guard {
has_weapon: false
}
```
3. **Empty lists**:
```storybook
character Unarmed {
weapons: []
}
```
## Summary Table
| Type | Mutable? | Comparable? | Valid in Templates? | Notes |
|------|----------|-------------|---------------------|-------|
| Int | No | Yes | Yes | 64-bit signed |
| Float | No | Yes | Yes | 64-bit IEEE 754 |
| String | No | Yes | Yes | UTF-8 |
| Bool | No | Yes | Yes | true/false |
| Time | No | Yes | No | HH:MM or HH:MM:SS |
| Duration | No | Yes | No | Compounds (2h30m) |
| Range | No | No | Yes (only) | Template variation |
| Identifier | No | Yes | Yes | Declaration reference |
| List | No | Yes | Yes | Ordered collection |
| Object | No | Yes | Yes | Named fields |
| ProseBlock | No | No | Yes | Narrative text |
| Override | No | No | Yes | Template modification |
## Cross-References
- [Characters](./10-characters.md) - Using values in character fields
- [Templates](./16-other-declarations.md#templates) - Range values and override syntax
- [Schedules](./14-schedules.md) - Time and duration in schedules
- [Behavior Trees](./11-behavior-trees.md) - Duration in decorators
- [Expressions](./17-expressions.md) - Using values in conditions
## Related Concepts
- **Immutability**: All values are immutable at declaration time
- **Type safety**: Strong static typing with no implicit coercion
- **Structural equivalence**: Objects/lists compared by structure, not identity
- **Prose as data**: Narrative text is first-class data, not comments

View File

@@ -0,0 +1,377 @@
# Validation Rules
The Storybook compiler performs multi-layered validation to catch errors before runtime. This chapter documents all validation rules, organized by declaration type, along with the error messages you can expect and how to fix them.
## Validation Layers
Storybook validation happens in four stages:
1. **Lexical**: Tokenization of raw text (invalid characters, malformed literals)
2. **Syntactic**: Grammar structure (missing braces, wrong keyword order)
3. **Semantic**: Cross-reference resolution, type checking, field merging
4. **Domain**: Narrative-specific constraints (bond ranges, schedule overlaps)
Errors at earlier stages prevent later stages from running.
## Character Validation
### Required Rules
| Rule | Description | Severity |
|------|-------------|----------|
| Unique name | Character names must be unique within their module | Error |
| Species exists | If `: Species` is used, the species must be defined | Error |
| Templates exist | All templates in `from` clause must be defined | Error |
| No circular inheritance | Template chains cannot form cycles | Error |
| Field type consistency | Field values must match expected types | Error |
| Behavior trees exist | All `uses behaviors` references must resolve | Error |
| Schedules exist | All `uses schedule` references must resolve | Error |
| Prose tag uniqueness | Each prose tag can appear at most once per character | Error |
### Examples
**Species not found:**
```storybook
character Martha: Hobbit { // Error: species 'Hobbit' not defined
age: 34
}
```
**Fix:** Define the species or correct the reference:
```storybook
species Hobbit {
lifespan: 130
}
character Martha: Hobbit {
age: 34
}
```
**Duplicate character name:**
```storybook
character Martha { age: 34 }
character Martha { age: 36 } // Error: duplicate character name 'Martha'
```
## Template Validation
| Rule | Description | Severity |
|------|-------------|----------|
| Unique name | Template names must be unique within their module | Error |
| Includes exist | All included templates must be defined | Error |
| No circular includes | Include chains cannot form cycles | Error |
| Range validity | Range bounds must satisfy min <= max | Error |
| Range type match | Both bounds of a range must be the same type | Error |
| Strict enforcement | Characters using strict templates cannot add extra fields | Error |
| Resource links valid | Behavior/schedule references must resolve | Error |
### Examples
**Invalid range:**
```storybook
template BadRange {
age: 65..18 // Error: range min (65) must be <= max (18)
}
```
**Strict template violation:**
```storybook
template Rigid strict {
required_stat: 10
}
character Constrained from Rigid {
required_stat: 15
extra_field: 42 // Error: field 'extra_field' not allowed by strict template 'Rigid'
}
```
## Behavior Tree Validation
| Rule | Description | Severity |
|------|-------------|----------|
| At least one node | Behavior body must contain at least one node | Error |
| Composite children | `choose` and `then` require at least one child | Error |
| Decorator child | Decorators require exactly one child | Error |
| Subtree exists | `include` must reference a defined behavior | Error |
| Expression validity | Condition expressions must be well-formed | Error |
| Duration format | Decorator durations must be valid (e.g., `5s`, `10m`) | Error |
| Repeat count valid | `repeat N` requires N >= 0 | Error |
| Repeat range valid | `repeat min..max` requires 0 <= min <= max | Error |
| Retry count valid | `retry N` requires N >= 1 | Error |
### Examples
**Empty composite:**
```storybook
behavior Empty {
choose options {
// Error: 'choose' requires at least one child
}
}
```
**Invalid subtree reference:**
```storybook
behavior Main {
include NonExistentBehavior // Error: behavior 'NonExistentBehavior' not defined
}
```
## Life Arc Validation
| Rule | Description | Severity |
|------|-------------|----------|
| At least one state | Life arc must contain at least one state | Error |
| Unique state names | State names must be unique within the life arc | Error |
| Valid transitions | Transition targets must reference defined states | Error |
| Expression validity | Transition conditions must be well-formed | Error |
| Field targets valid | On-enter field references must resolve | Error |
| Reachable states | All states should be reachable from initial state | Warning |
### Examples
**Invalid transition target:**
```storybook
life_arc Broken {
state active {
on timer_expired -> nonexistent // Error: state 'nonexistent' not defined
}
}
```
**Unreachable state (warning):**
```storybook
life_arc HasOrphan {
state start {
on ready -> middle
}
state middle {
on done -> end
}
state orphan {} // Warning: state 'orphan' is not reachable
state end {}
}
```
## Schedule Validation
| Rule | Description | Severity |
|------|-------------|----------|
| Time format | Times must be valid HH:MM or HH:MM:SS | Error |
| Extends exists | Base schedule must be defined | Error |
| No circular extends | Schedule chains cannot form cycles | Error |
| Named blocks unique | Block names must be unique within a schedule | Error |
| Action references valid | Action references must resolve to defined behaviors | Error |
| Constraint values valid | Temporal constraint values must reference defined enums | Error |
| Recurrence names unique | Recurrence names must be unique within a schedule | Error |
### Examples
**Invalid time format:**
```storybook
schedule Bad {
block work {
25:00 - 17:00 // Error: invalid hour '25'
action: work
}
}
```
**Circular extends:**
```storybook
schedule A extends B { }
schedule B extends A { } // Error: circular schedule extension detected
```
## Relationship Validation
| Rule | Description | Severity |
|------|-------------|----------|
| At least two participants | Relationships require >= 2 participants | Error |
| Participants exist | All participant names must reference defined entities | Error |
| Unique participants | Each participant appears at most once | Error |
| Field type consistency | Fields must have valid value types | Error |
### Examples
**Too few participants:**
```storybook
relationship Lonely {
Martha // Error: relationship requires at least 2 participants
bond: 0.5
}
```
## Species Validation
| Rule | Description | Severity |
|------|-------------|----------|
| Unique name | Species names must be unique within their module | Error |
| No circular includes | Include chains cannot form cycles | Error |
| Includes exist | All included species must be defined | Error |
| Field type consistency | Fields must have valid values | Error |
| Prose tag uniqueness | Each prose tag can appear at most once | Error |
## Enum Validation
| Rule | Description | Severity |
|------|-------------|----------|
| Unique enum name | Enum names must be unique within their module | Error |
| Unique variants | Variant names must be unique within the enum | Error |
| Non-empty | Enums must have at least one variant | Error |
| Valid identifiers | Variants must follow identifier rules | Error |
### Examples
**Duplicate variant:**
```storybook
enum Size {
tiny,
small,
small, // Error: duplicate variant 'small' in enum 'Size'
large
}
```
## Institution and Location Validation
| Rule | Description | Severity |
|------|-------------|----------|
| Unique name | Names must be unique within their module | Error |
| Resource links valid | Behavior/schedule references must resolve | Error |
| Field type consistency | Fields must have valid values | Error |
## Expression Validation
Expressions are validated wherever they appear (life arc transitions, behavior tree conditions, if decorators).
| Rule | Description | Severity |
|------|-------------|----------|
| Type consistency | Both sides of comparison must have compatible types | Error |
| Boolean context | Logical operators require boolean operands | Error |
| Field existence | Referenced fields must exist on the entity | Error |
| Collection validity | Quantifiers require collection-typed expressions | Error |
| Variable scope | Quantifier variables only valid within their predicate | Error |
| Enum validity | Enum comparisons must reference defined values | Error |
### Examples
**Type mismatch:**
```storybook
life_arc TypeError {
state checking {
on count == "five" -> done // Error: cannot compare int with string
}
state done {}
}
```
## Use Statement Validation
| Rule | Description | Severity |
|------|-------------|----------|
| Path exists | Imported paths must reference defined modules/items | Error |
| No circular imports | Modules cannot form circular dependency chains | Error |
| Valid identifiers | All path segments must be valid identifiers | Error |
| Grouped import validity | All items in `{}` must exist in the target module | Error |
### Examples
**Missing import:**
```storybook
use schema::nonexistent::Thing; // Error: module 'schema::nonexistent' not found
```
## Cross-File Validation
When resolving across multiple `.sb` files, the compiler performs additional checks:
| Rule | Description | Severity |
|------|-------------|----------|
| All references resolve | Cross-file references must find their targets | Error |
| No naming conflicts | Declarations must not collide across files in the same module | Error |
| Import visibility | Only public declarations can be imported | Error |
## Common Error Patterns
### Missing Definitions
The most common error is referencing something that does not exist:
```storybook
character Martha: Human from Baker {
specialty: sourdough
}
```
If `Human`, `Baker`, or the `sourdough` enum variant are not defined or imported, the compiler will report an error. Fix by adding the appropriate `use` statements:
```storybook
use schema::core_enums::{SkillLevel, Specialty};
use schema::templates::Baker;
use schema::beings::Human;
character Martha: Human from Baker {
specialty: sourdough
}
```
### Circular Dependencies
Circular references are rejected at every level:
- Templates including each other
- Species including each other
- Schedules extending each other
- Modules importing each other
Break cycles by restructuring into a hierarchy or extracting shared parts into a common module.
### Type Mismatches
Storybook has no implicit type coercion. Ensure values match their expected types:
```storybook
// Wrong:
character Bad {
age: "twenty" // Error: expected int, got string
is_ready: 1 // Error: expected bool, got int
}
// Correct:
character Good {
age: 20
is_ready: true
}
```
## Validation Summary
| Declaration | Key Constraints |
|-------------|----------------|
| Character | Unique name, valid species/templates, no circular inheritance |
| Template | Unique name, valid includes, valid ranges, strict enforcement |
| Behavior | Non-empty, valid composites, valid decorators, valid subtrees |
| Life Arc | Non-empty, unique states, valid transitions, reachable states |
| Schedule | Valid times, valid extends chain, unique block names |
| Relationship | >= 2 participants, valid references |
| Species | Unique name, valid includes, no cycles |
| Enum | Unique name, unique variants, non-empty |
| Institution | Unique name, valid resource links |
| Location | Unique name, valid field types |
| Use | Valid paths, no circular imports |
## Cross-References
- [Characters](./10-characters.md) - Character-specific validation
- [Behavior Trees](./11-behavior-trees.md) - Behavior validation
- [Life Arcs](./13-life-arcs.md) - Life arc validation
- [Schedules](./14-schedules.md) - Schedule validation
- [Expression Language](./17-expressions.md) - Expression validation
- [Value Types](./18-value-types.md) - Type system constraints