chore: prep v0.3 work

Signed-off-by: Sienna Meridian Satterwhite <sienna@r3t.io>
This commit is contained in:
2026-02-14 13:29:33 +00:00
parent 25d59d6107
commit 4e4e5500b0
29 changed files with 1708 additions and 6212 deletions

View File

@@ -40,7 +40,7 @@ When the grammar changes, update `zed-storybook/extension.toml` and change the `
## Git Workflow
Development happens directly on `main` until the language is stable. Releases are tagged with version numbers (e.g., `v0.2.0`). Branches are only used for external contributors or later development phases.
Development happens directly on `mainline` until the language is stable. Releases are tagged with version numbers (e.g., `v0.2.0`). Branches are only used for external contributors or later development phases.
Pre-commit hooks check: trailing whitespace, rustfmt, clippy.
@@ -74,6 +74,7 @@ Added four keywords for new type system:
- `storybook-editor/` - LSP server implementation
- `docs/` - Specifications and documentation
- `SBIR-v0.2.0-SPEC.md` - Storybook Intermediate Representation binary format
- `.claude/tmp` - Unlimited storage for temporary files. Use this for plans, reports, and other temporary data that is not part of the repository.
## Testing Philosophy

1
.serena/.gitignore vendored
View File

@@ -1 +0,0 @@
/cache

View File

@@ -1,127 +0,0 @@
# LSP Phase 4: Navigation Features
## Status: ✅ Basic Implementation Complete
**Implemented:** Single-file go-to-definition and find-references
**Date:** 2026-02-09
**Tests:** 89/89 passing (11 new navigation tests)
## Features Implemented
### Go-to-Definition
- Jump to symbol definition when clicking on an identifier
- Works for: characters, templates, behaviors, species, life_arcs, schedules, etc.
- Returns accurate location with proper line/column positions
- Handles multiline documents correctly
### Find References
- Find all occurrences of a symbol in the current file
- Word boundary detection (won't match "Alice" in "Alison")
- Returns all locations where symbol is referenced
- Includes both declarations and uses
## Implementation Details
### Files Modified
- `storybook/src/lsp/definition.rs` - Fixed mutability, added proper position tracking
- `storybook/src/lsp/references.rs` - Fixed mutability, word boundary checking
- `storybook/src/lsp/server.rs` - Updated to use immutable references (read locks)
- `storybook/src/lsp/navigation_tests.rs` - 11 comprehensive tests
### Current Architecture
- **Single-file navigation**: Works within each open document independently
- **Symbol table**: Built from AST for each document (HashMap<String, Vec<SymbolLocation>>)
- **No cross-file support yet**: Each file is isolated
## Testing Coverage
### Navigation Tests (11 tests)
1. `test_goto_definition_character` - Basic go-to-definition
2. `test_goto_definition_not_found` - Handle missing symbols
3. `test_goto_definition_template` - Template navigation
4. `test_goto_definition_behavior` - Behavior tree navigation
5. `test_goto_definition_multiline` - Multiline document navigation
6. `test_find_references_character` - Basic find references
7. `test_find_references_single_occurrence` - Single reference
8. `test_find_references_not_found` - Handle edge cases
9. `test_find_references_word_boundaries` - Exact word matching
10. `test_find_references_multiple_files_same_name` - Template reuse
11. `test_find_references_species` - Species references
### Example Usage
**Go-to-Definition:**
```storybook
character Alice { age: 7 }
character Bob { friend: Alice } // Cmd+Click "Alice" → jumps to line 1
```
**Find References:**
```storybook
template Child { age: number }
character Alice: Child {} // Right-click "Child" → shows both uses
character Bob: Child {}
```
## Future Enhancements (Cross-File Navigation)
### What's Missing
- **Cross-file references**: Can't navigate to definitions in other files
- **Use declarations**: `use characters::Alice` not resolved
- **Workspace-level NameTable**: No global symbol resolution
- **Template includes**: Can't find where templates are used across files
- **Species inheritance**: Can't trace species usage across files
### Implementation Plan for Cross-File Support
1. Add workspace-level state to LSP server:
```rust
struct WorkspaceState {
name_table: NameTable,
file_mapping: HashMap<usize, Url>,
}
```
2. Build combined NameTable from all open documents
3. Rebuild on document changes
4. Use NameTable for cross-file navigation
5. Handle `use` declarations for imports
### Why Not Implemented Yet
- Requires significant architectural changes to server
- Need to track all files in workspace (not just open documents)
- Need file watching for unopened files
- More complex testing scenarios
- Current single-file solution covers 80% of use cases for MVP
## Phase 4 Verification Commands
### Run Navigation Tests
```bash
cd /Users/sienna/Development/storybook/storybook
cargo test --lib lsp::navigation_tests
```
### Run All LSP Tests
```bash
cd /Users/sienna/Development/storybook/storybook
cargo test --lib lsp
```
**Result:** 89/89 tests passing ✓
## Next Steps
**Phase 5 Options:**
1. **Continue with plan**: Implement editing assistance (completion, formatting)
2. **Enhance Phase 4**: Add cross-file navigation using NameTable
3. **Move to Phase 6**: Start on inspect panel with relationship graph
**Recommendation**: Continue with Phase 5 (editing assistance) since:
- Completion and formatting are high-value features
- Cross-file navigation can be added later as enhancement
- Better to have full single-file experience than partial multi-file
## Notes
- Single-file navigation works well for most development workflows
- Users typically work on one file at a time in Zed
- Cross-file can be added incrementally without breaking existing features
- Current implementation is robust and well-tested

View File

@@ -1,142 +0,0 @@
# LSP Testing Status (Phase 3 Complete)
## Summary
**Phase 3 (LSP Server Core Features) testing complete**
- All LSP tests passing: 78/78 ✓
- All tree-sitter grammar tests passing: 27/27 ✓
- Code coverage significantly improved
- Behavior tree support fully tested in both LSP and tree-sitter
## Test Coverage
### LSP Tests (78 total)
Location: `/Users/sienna/Development/storybook/storybook/src/lsp/`
#### Behavior Tests (8 tests) - `behavior_tests.rs`
- ✅ test_behavior_parsing
- ✅ test_behavior_symbols
- ✅ test_behavior_symbol_kinds
- ✅ test_behavior_in_document_symbols
- ✅ test_behavior_with_subtrees
- ✅ test_behavior_simple_action
- ✅ test_behavior_selectors_and_sequences
#### Diagnostics Tests (15 tests) - `diagnostics_tests.rs`
- ✅ Parse error detection and reporting
- ✅ Error position tracking
- ✅ Error severity levels
- ✅ Utility functions (byte_offset_to_position, create_diagnostic)
- ✅ Edge cases (empty input, whitespace, comments only)
#### Document Edge Tests (20 tests) - `document_edge_tests.rs`
- ✅ Word-at-offset with unicode, underscores, boundaries
- ✅ Document updates and symbol table management
- ✅ All declaration types: species, characters, templates, life_arcs, schedules, behaviors, institutions
- ✅ Symbol extraction for all entity types
#### Existing Tests (35 tests)
- Integration tests, formatting, hover, completion, definition, references, symbols
### Tree-sitter Grammar Tests (27 total)
Location: `/Users/sienna/Development/storybook/tree-sitter-storybook/test/corpus/`
#### Behavior Tests (7 tests) - `behaviors.txt`
- ✅ Simple Behavior (single action)
- ✅ Selector Behavior (? { ... })
- ✅ Sequence Behavior (> { ... })
- ✅ Nested Behavior (selectors + sequences)
- ✅ Repeat Behavior (* { ... })
- ✅ Behavior with Subtree (@path::notation)
- ✅ Complex Nested Behavior (all node types)
#### Declaration Tests (17 tests) - `declarations.txt`
- ✅ All declaration types (use, character, template, life_arc, schedule, behavior, etc.)
#### Basic Tests (3 tests) - `basic.txt`
- ✅ Simple character, use declaration, prose block
## Coverage Improvements
**Before testing push:**
- document.rs: 80.11%
- symbols.rs: 93.04%
- diagnostics.rs: 0%
- behavior support: untested
- Total LSP tests: 34
**After testing push:**
- document.rs: 97.79% (+17.68%)
- symbols.rs: 95.24% (+2.20%)
- diagnostics.rs: fully tested
- behavior support: comprehensive test coverage
- Total LSP tests: 78 (+44 new tests, +129% increase)
## Run Commands
### LSP Tests
```bash
cd /Users/sienna/Development/storybook/storybook
cargo test --lib lsp
```
### Tree-sitter Tests
```bash
cd /Users/sienna/Development/storybook/tree-sitter-storybook
npm run test
```
**Note:** If Bash tool fails, use Serena's `execute_shell_command` instead.
## Behavior Tree Support Verified
Both LSP and tree-sitter grammar now have comprehensive behavior tree support:
### Node Types Tested:
- **action_node**: Simple action identifiers (e.g., `walk_around`)
- **selector_node**: `? { ... }` - Try options in order until one succeeds
- **sequence_node**: `> { ... }` - Execute children in sequence
- **repeat_node**: `* { ... }` - Repeat child forever
- **subtree_node**: `@path::to::tree` - Reference external behavior tree
### Syntax Examples:
```storybook
behavior SimpleBehavior {
walk_around
}
behavior ComplexBehavior {
? {
> {
check_threat
flee_to_safety
}
> {
check_resources
gather_resources
}
* {
idle
}
}
}
behavior WithSubtree {
> {
@helpers::check_preconditions
main_action
}
}
```
## Next Steps (Phase 4)
- Navigation features (go-to-definition, find references)
- Cross-file symbol resolution
- Template includes and species references
## Files Modified
- Created: `storybook/src/lsp/behavior_tests.rs`
- Created: `storybook/src/lsp/diagnostics_tests.rs`
- Created: `storybook/src/lsp/document_edge_tests.rs`
- Created: `tree-sitter-storybook/test/corpus/behaviors.txt`
- Modified: `storybook/src/lsp/mod.rs` (added test modules)
- Modified: `storybook/src/lsp/server.rs` (fixed imports and mutability)

View File

@@ -1,88 +0,0 @@
# Tree-sitter Grammar Commands
## Location
Tree-sitter grammar is at: `/Users/sienna/Development/storybook/tree-sitter-storybook/`
## Running Tests
**Use Serena's execute_shell_command when Bash tool fails:**
```bash
cd /Users/sienna/Development/storybook/tree-sitter-storybook && npm run test
```
This runs the tree-sitter test suite against all corpus files in `test/corpus/`.
## Test Corpus Structure
Test files are in `test/corpus/*.txt` format:
```
==================
Test Name
==================
[input code]
---
[expected parse tree]
```
### Key Parse Tree Patterns for Behaviors:
1. **All declarations wrap in `(declaration ...)`**
2. **Behavior nodes wrap children in `(behavior_node ...)`**
3. **Paths have internal structure:**
```
(path
(path_segments
(identifier)
(identifier)))
```
Not just `(path)`
### Example Behavior Test Structure:
```
behavior SimpleBehavior {
walk_around
}
---
(source_file
(declaration
(behavior
name: (identifier)
root: (behavior_node
(action_node (identifier))))))
```
## Regenerating Parser
If grammar.js changes:
```bash
cd /Users/sienna/Development/storybook/tree-sitter-storybook && npm run build
```
This runs `tree-sitter generate` and compiles the parser.
## Test Results (as of 2026-02-09)
✅ All 27 tests passing:
- 17 declaration tests
- 7 behavior tree tests (selector, sequence, repeat, nested, subtree, etc.)
- 3 basic tests
## Behavior Tree Node Types Tested
- `action_node` - Simple action identifiers
- `selector_node` - `? { ... }` - Try options in order
- `sequence_node` - `> { ... }` - Execute in sequence
- `repeat_node` - `* { ... }` - Repeat forever
- `subtree_node` - `@path::to::tree` - Reference external behavior
## Common Issues
1. **Bash tool failing with exit code 1** - Use Serena's execute_shell_command instead
2. **Path structure mismatch** - Remember paths include path_segments wrapper
3. **Missing declaration wrapper** - All top-level items wrap in `(declaration ...)`
4. **Missing behavior_node wrapper** - Behavior children wrap in `(behavior_node ...)`

View File

@@ -1,112 +0,0 @@
# the name by which the project can be referenced within Serena
project_name: "storybook"
# list of languages for which language servers are started; choose from:
# al bash clojure cpp csharp
# csharp_omnisharp dart elixir elm erlang
# fortran fsharp go groovy haskell
# java julia kotlin lua markdown
# matlab nix pascal perl php
# powershell python python_jedi r rego
# ruby ruby_solargraph rust scala swift
# terraform toml typescript typescript_vts vue
# yaml zig
# (This list may be outdated. For the current list, see values of Language enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py
# For some languages, there are alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
# Note:
# - For C, use cpp
# - For JavaScript, use typescript
# - For Free Pascal/Lazarus, use pascal
# Special requirements:
# Some languages require additional setup/installations.
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
# When using multiple languages, the first language server that supports a given file will be used for that file.
# The first language is the default language and the respective language server will be used as a fallback.
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
languages:
- rust
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8"
# whether to use project's .gitignore files to ignore files
ignore_all_files_in_gitignore: true
# list of additional paths to ignore in all projects
# same syntax as gitignore, so you can use * and **
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
# Below is the complete list of tools for convenience.
# To make sure you have the latest list of tools, and to view their descriptions,
# execute `uv run scripts/print_tool_overview.py`.
#
# * `activate_project`: Activates a project by name.
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
# * `create_text_file`: Creates/overwrites a file in the project directory.
# * `delete_lines`: Deletes a range of lines within a file.
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
# * `execute_shell_command`: Executes a shell command.
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
# * `initial_instructions`: Gets the initial instructions for the current project.
# Should only be used in settings where the system prompt cannot be set,
# e.g. in clients you have no control over, like Claude Desktop.
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
# * `insert_at_line`: Inserts content at a given line in a file.
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
# * `list_memories`: Lists memories in Serena's project-specific memory store.
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
# * `read_file`: Reads a file within the project directory.
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
# * `remove_project`: Removes a project from the Serena configuration.
# * `replace_lines`: Replaces a range of lines within a file with new content.
# * `replace_symbol_body`: Replaces the full definition of a symbol.
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
# * `search_for_pattern`: Performs a search for a pattern in the project.
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
# * `switch_modes`: Activates modes by providing a list of their names
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
excluded_tools: []
# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default)
included_optional_tools: []
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
fixed_tools: []
# list of mode names to that are always to be included in the set of active modes
# The full set of modes to be activated is base_modes + default_modes.
# If the setting is undefined, the base_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this setting overrides the global configuration.
# Set this to [] to disable base modes for this project.
# Set this to a list of mode names to always include the respective modes for this project.
base_modes:
# list of mode names that are to be activated by default.
# The full set of modes to be activated is base_modes + default_modes.
# If the setting is undefined, the default_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
# This setting can, in turn, be overridden by CLI parameters (--mode).
default_modes:
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""

View File

@@ -1,696 +0,0 @@
# LSP Implementation Audit Report
**Date:** 2026-02-12
**Auditor:** LSP Test Engineer
**Status:** ⚠️ COMPILATION ERRORS BLOCKING TESTS
---
## Executive Summary
The Storybook LSP implementation is **functionally comprehensive** but currently **broken in compilation**. The implementation includes all major LSP features with extensive test coverage (147 tests across 7 test modules), but two compilation errors prevent the test suite from running.
**Critical Findings:**
- ✅ 9 core LSP features implemented
- ✅ 147 unit tests written (102 focused tests + supporting modules)
- ❌ 2 compilation errors blocking all tests
- ✅ Tree-sitter grammar: 27/27 tests passing
- ⚠️ Single-file navigation only (no cross-file support)
---
## 1. LSP Features Inventory
### 1.1 Implemented LSP Features (9 Total)
| Feature | Status | Implementation File | Test Coverage |
|---------|--------|---------------------|---------------|
| **Hover** | ✅ Implemented | `hover.rs` | Via integration tests |
| **Completion** | ✅ Implemented | `completion.rs` | 10 dedicated tests |
| **Go-to-Definition** | ✅ Implemented | `definition.rs` | 11 navigation tests |
| **Find References** | ✅ Implemented | `references.rs` | 11 navigation tests |
| **Document Symbols** | ✅ Implemented | `symbols.rs` | 17 edge tests |
| **Diagnostics** | ✅ Implemented | `diagnostics.rs` | 20 dedicated tests |
| **Formatting** | ✅ Implemented | `formatting.rs` | Via integration tests |
| **Rename** | ✅ Implemented | `rename.rs` | Via integration tests |
| **Code Actions** | ✅ Implemented | `code_actions.rs` | 27 dedicated tests |
| **Semantic Tokens** | ✅ Implemented | `semantic_tokens.rs` | Via integration tests |
| **Inlay Hints** | ⚠️ Broken | `inlay_hints.rs` | **COMPILATION ERROR** |
**Total Lines of LSP Code:** 9,788 lines
### 1.2 Feature Details
#### Hover
- **File:** `storybook/src/lsp/hover.rs`
- **Capability:** `HoverProviderCapability::Simple(true)`
- **Functionality:** Displays type information and documentation on hover
- **Status:** Working (integration tested)
#### Completion
- **File:** `storybook/src/lsp/completion.rs`
- **Capability:** Trigger characters: `.`, `:`, `@`
- **Functionality:** Context-aware code completion for identifiers, keywords, templates
- **Tests:** 10 tests in `completion_tests.rs`
- **Known Issue:** Type annotation error on line 428 (`nesting_level` needs `: i32`)
#### Go-to-Definition
- **File:** `storybook/src/lsp/definition.rs`
- **Capability:** `definition_provider: Some(OneOf::Left(true))`
- **Functionality:** Jump to symbol definition within current file
- **Limitation:** Single-file only (no cross-file navigation)
- **Tests:** Covered by 11 navigation tests
#### Find References
- **File:** `storybook/src/lsp/references.rs`
- **Capability:** `references_provider: Some(OneOf::Left(true))`
- **Functionality:** Find all symbol references within current file
- **Features:** Word boundary detection, multiline support
- **Limitation:** Single-file only
- **Tests:** Covered by 11 navigation tests
#### Document Symbols
- **File:** `storybook/src/lsp/symbols.rs`
- **Capability:** `document_symbol_provider: Some(OneOf::Left(true))`
- **Functionality:** Outline view of characters, templates, behaviors, life_arcs, schedules, etc.
- **Coverage:** All declaration types supported
- **Tests:** 17 edge case tests
#### Diagnostics
- **File:** `storybook/src/lsp/diagnostics.rs`
- **Functionality:** Parse error detection and reporting with severity levels
- **Tests:** 20 comprehensive tests
- **Coverage:** Parse errors, position tracking, edge cases (empty input, whitespace, comments)
#### Formatting
- **File:** `storybook/src/lsp/formatting.rs`
- **Capability:** `document_formatting_provider: Some(OneOf::Left(true))`
- **Functionality:** Auto-formatting of Storybook code
- **Status:** Working (integration tested)
#### Rename
- **File:** `storybook/src/lsp/rename.rs`
- **Capability:** Rename with prepare provider
- **Functionality:** Rename symbols across the document
- **Status:** Working (integration tested)
#### Code Actions
- **File:** `storybook/src/lsp/code_actions.rs`
- **Capability:** `code_action_provider: Simple(true)`
- **Tests:** 27 dedicated tests
- **Functionality:** Quick fixes and refactoring actions
#### Semantic Tokens
- **File:** `storybook/src/lsp/semantic_tokens.rs`
- **Capability:** Full semantic token support
- **Functionality:** Fine-grained syntax highlighting based on semantic understanding
- **Legend:** Custom token types (characters, templates, behaviors, etc.)
- **Status:** Working (integration tested)
#### Inlay Hints
- **File:** `storybook/src/lsp/inlay_hints.rs`
- **Capability:** `inlay_hint_provider: Some(OneOf::Left(true))`
- **Known Issue:** Import error - references `crate::project::positions::PositionTracker` which doesn't exist
- **Correct Path:** Should be `crate::position::PositionTracker`
---
## 2. Tree-sitter Grammar Capabilities
### 2.1 Grammar Overview
- **Location:** `/Users/sienna/Development/storybook/tree-sitter-storybook/`
- **Grammar File:** `grammar.js` (326 lines)
- **Test Status:** ✅ 27/27 tests passing
### 2.2 Supported Constructs
#### Declaration Types (10)
1. `use` - Import statements
2. `character` - Character definitions with species, templates
3. `template` - Reusable field templates with includes
4. `life_arc` - State machines with states and transitions
5. `schedule` - Daily schedules with time blocks
6. `behavior` - Behavior trees with all node types
7. `institution` - Organizations and groups
8. `relationship` - Multi-party relationships with named participants
9. `location` - Places and settings
10. `species` - Species definitions with template includes
11. `enum` - Enumeration types
#### Behavior Tree Node Types (5)
- **action_node** - Simple action identifiers (e.g., `walk_around`)
- **selector_node** - `? { ... }` - Try options in order until one succeeds
- **sequence_node** - `> { ... }` - Execute children in sequence
- **repeat_node** - `* { ... }` - Repeat child forever
- **subtree_node** - `@path::to::tree` - Reference external behavior tree
#### Special Features
- **Prose Blocks** - External scanner (C) handles `---tag\n...\n---` syntax
- **Expression Support** - Full condition parsing (e.g., `self.age >= 18 and self.location is wonderland`)
- **Override Syntax** - `@field remove`, `@field append`
- **Path Resolution** - Module-style paths with `::`
### 2.3 Query Files
Located in `tree-sitter-storybook/queries/`:
- **highlights.scm** (154 lines) - Syntax highlighting mappings
- **outline.scm** - Symbol outline for navigation
- **brackets.scm** - Bracket matching (including prose blocks)
- **indents.scm** - Auto-indentation rules
- **injections.scm** - Language injection support
### 2.4 Test Corpus
Located in `test/corpus/`:
- **behaviors.txt** - 7 behavior tree tests
- **declarations.txt** - 17 declaration tests
- **basic.txt** - 3 basic syntax tests
**All 27 tests passing**
---
## 3. Test Coverage Analysis
### 3.1 Test Suite Breakdown
| Test Module | Tests | Focus Area | Status |
|-------------|-------|------------|--------|
| `behavior_tests.rs` | 7 | Behavior tree parsing & symbols | ⚠️ Blocked |
| `code_actions_tests.rs` | 27 | Quick fixes & refactoring | ⚠️ Blocked |
| `completion_tests.rs` | 10 | Code completion contexts | ⚠️ Blocked |
| `diagnostics_tests.rs` | 20 | Error detection & reporting | ⚠️ Blocked |
| `document_edge_tests.rs` | 17 | Symbol extraction & edge cases | ⚠️ Blocked |
| `navigation_tests.rs` | 11 | Go-to-def & find references | ⚠️ Blocked |
| `validation_tests.rs` | 10 | Input validation | ⚠️ Blocked |
| **Total** | **102** | | **⚠️ Blocked** |
**Additional Tests:**
- Integration tests in `tests.rs` and `parser_test.rs` (~45 tests)
- **Grand Total:** ~147 test functions
### 3.2 Coverage Quality
**Well-Covered Areas:**
- ✅ Behavior tree parsing (7 tests covering all node types)
- ✅ Code actions (27 tests - most comprehensive)
- ✅ Diagnostics (20 tests including edge cases)
- ✅ Document symbols (17 tests for all declaration types)
- ✅ Navigation (11 tests for single-file nav)
**Under-Tested Areas:**
- ⚠️ Hover (only integration tests, no dedicated unit tests)
- ⚠️ Formatting (only integration tests)
- ⚠️ Rename (only integration tests)
- ⚠️ Semantic tokens (only integration tests)
- ❌ Inlay hints (broken, no tests can run)
**Missing Test Coverage:**
- ❌ Cross-file navigation (not implemented)
- ❌ Multi-file completion (not implemented)
- ❌ Workspace-level symbol resolution (not implemented)
- ❌ Use declaration resolution (not implemented)
- ❌ Performance/stress tests (large files, many symbols)
- ❌ Concurrency tests (multiple clients, rapid edits)
---
## 4. Critical Issues Blocking Tests
### Issue #1: Inlay Hints Import Error
**File:** `storybook/src/lsp/inlay_hints.rs:134`
**Error:**
```
error[E0433]: failed to resolve: could not find `project` in the crate root
--> src/lsp/inlay_hints.rs:134:28
|
134 | positions: &mut crate::project::positions::PositionTracker,
| ^^^^^^^ could not find `project` in the crate root
```
**Root Cause:** Incorrect module path
**Expected Path:** `crate::position::PositionTracker`
**Fix Required:** Change `crate::project::positions::PositionTracker``crate::position::PositionTracker`
**Impact:** Blocks all LSP tests from compiling
---
### Issue #2: Completion Type Annotation Error
**File:** `storybook/src/lsp/completion.rs:428`
**Error:**
```
error[E0689]: can't call method `saturating_sub` on ambiguous numeric type `{integer}`
--> src/lsp/completion.rs:428:60
|
428 | Token::RBrace => nesting_level = nesting_level.saturating_sub(1),
| ^^^^^^^^^^^^^^
```
**Root Cause:** Missing type annotation on `nesting_level` variable
**Fix Required:** Add type annotation `: i32` to `let mut nesting_level`
**Impact:** Blocks all LSP tests from compiling
---
## 5. Architecture Assessment
### 5.1 Current Architecture
```
StorybookLanguageServer
├── documents: Arc<RwLock<HashMap<Url, Document>>>
│ └── Per-document state (AST, symbols, errors, positions)
└── workspace: Arc<RwLock<WorkspaceState>>
├── name_table: NameTable (currently unused)
└── file_urls: HashMap<usize, Url>
```
**Document Model:**
```rust
pub struct Document {
pub text: String,
pub ast: Option<SourceFile>,
pub parse_errors: Vec<ParseError>,
pub positions: PositionTracker,
}
```
**Symbol Table:** Built per-document from AST via `symbols::extract_symbols()`
### 5.2 Single-File vs. Multi-File Navigation
#### Currently Implemented (Single-File)
- ✅ Each document maintains its own symbol table
- ✅ Go-to-definition works within current file
- ✅ Find references works within current file
- ✅ Fast and simple (no cross-file coordination)
#### Not Implemented (Multi-File)
- ❌ No workspace-level NameTable integration
- ❌ Use declarations not resolved
- ❌ Cross-file template references not resolved
- ❌ Species references not resolved across files
- ❌ No global symbol index
**Why Multi-File Not Implemented:**
> "Current single-file solution covers 80% of use cases for MVP. Cross-file can be added later as enhancement without breaking existing features." - From `lsp-phase4-navigation` memory
### 5.3 Workspace State (Stub Implementation)
The `WorkspaceState` struct exists but is **not fully utilized**:
```rust
fn rebuild(&mut self, documents: &HashMap<Url, Document>) {
self.name_table = NameTable::new();
self.file_urls.clear();
for (file_index, (url, doc)) in documents.iter().enumerate() {
self.file_urls.insert(file_index, url.clone());
if let Some(ref ast) = doc.ast {
// TODO: Properly merge file name tables with file_index
// For now, we'll use the simple single-file approach
let _ = (ast, file_index); // Use variables to avoid warnings
}
}
}
```
**Observation:** The NameTable infrastructure exists in `crate::resolve::names::NameTable` but is not being populated or used by the LSP server.
---
## 6. Stability Assessment
### 6.1 Known Stability Issues
1. **Compilation Failures** (Severity: CRITICAL)
- Two errors preventing tests from running
- Both are simple fixes (import path + type annotation)
2. **Limited Cross-File Support** (Severity: MEDIUM)
- Users cannot navigate to definitions in other files
- Use declarations don't resolve to imports
- Limits usefulness for multi-file projects
3. **Missing Error Handling** (Severity: LOW)
- Some LSP methods use `.unwrap()` or `.expect()` without graceful degradation
- Could cause server crashes on unexpected input
4. **Performance Unknowns** (Severity: MEDIUM)
- No stress tests for large files (>10,000 lines)
- No benchmarks for workspace rebuilds
- Unknown behavior with many open documents (100+)
### 6.2 Code Quality Observations
**Strengths:**
- ✅ Comprehensive async/await usage (tower-lsp pattern)
- ✅ Proper use of RwLock for concurrent document access
- ✅ Modular design (separate files for each LSP feature)
- ✅ Rich test coverage (102 focused unit tests)
**Weaknesses:**
- ⚠️ Incomplete type annotations (causing compilation errors)
- ⚠️ Unused infrastructure (WorkspaceState, NameTable)
- ⚠️ Some features lack dedicated unit tests (hover, formatting, rename)
- ⚠️ No CI/CD automation mentioned in codebase
---
## 7. Zed Editor Integration
### 7.1 Extension Structure
- **Location:** `/Users/sienna/Development/storybook/zed-storybook/`
- **Type:** WASM-based Zed extension
- **Grammar:** Embeds tree-sitter-storybook
- **LSP:** Configured to use Storybook LSP server
### 7.2 Extension Components
- `extension.toml` - Extension metadata
- `languages/storybook/config.toml` - Language configuration
- File extension: `.sb`
- Line comments: `//`
- Block comments: `/* */`
- `grammars/storybook/` - Embedded tree-sitter grammar
- `extension.wasm` - Compiled extension (405KB)
### 7.3 Integration Status
- ✅ Tree-sitter grammar integrated
- ✅ Syntax highlighting configured
- ⚠️ LSP server integration status unknown (needs testing)
- ⚠️ Extension build process documented (`build-extension.sh`)
---
## 8. Test Strategy Recommendations
### 8.1 Immediate Actions (Phase 1: Stabilization)
**Priority 1: Fix Compilation Errors** (Est: 15 minutes)
1. Fix `inlay_hints.rs` import path
2. Fix `completion.rs` type annotation
3. Verify all tests compile: `cargo test --lib lsp --no-run`
4. Run full test suite: `cargo test --lib lsp`
**Priority 2: Verify Test Suite** (Est: 30 minutes)
1. Confirm all 102 tests pass
2. Document any unexpected failures
3. Identify flaky tests
**Priority 3: Add Missing Unit Tests** (Est: 2-4 hours)
1. Create `hover_tests.rs` with 10+ hover scenarios
2. Create `formatting_tests.rs` with 10+ formatting cases
3. Create `rename_tests.rs` with 10+ rename scenarios
4. Create `semantic_tokens_tests.rs` with token validation
### 8.2 Short-Term Enhancements (Phase 2: Coverage)
**Add Edge Case Tests** (Est: 4-6 hours)
- Large file handling (>10,000 lines)
- Deeply nested structures (>10 levels)
- Unicode identifiers and content
- Malformed input (truncated files, invalid UTF-8)
- Empty documents
- Documents with only comments
**Add Integration Tests** (Est: 4-6 hours)
- Multi-file scenarios (even if features not fully supported)
- Rapid editing sequences (type, delete, undo)
- Concurrent client connections
- Document sync edge cases (did_open, did_change, did_close)
**Add Performance Tests** (Est: 3-4 hours)
- Benchmark parse time for files of varying sizes
- Benchmark symbol extraction
- Benchmark completion latency
- Benchmark workspace rebuild time
- Memory usage profiling
### 8.3 Long-Term Goals (Phase 3: Multi-File Support)
**Cross-File Navigation** (Est: 1-2 weeks)
1. Populate WorkspaceState.name_table from all documents
2. Implement use declaration resolution
3. Implement cross-file go-to-definition
4. Implement cross-file find references
5. Add comprehensive multi-file tests
**Workspace Management** (Est: 1 week)
1. File watching for unopened files
2. Incremental rebuilds (only changed files)
3. Lazy loading for large workspaces
4. Cache invalidation strategies
### 8.4 Infrastructure (Phase 4: Automation)
**CI/CD Setup** (Est: 1-2 days)
1. GitHub Actions workflow for tests
2. Automated test runs on PRs
3. Code coverage reporting (tarpaulin or similar)
4. Performance regression detection
**Documentation** (Est: 2-3 days)
1. Testing guide for contributors
2. LSP feature documentation
3. Architecture diagrams
4. Troubleshooting guide
---
## 9. Coverage Targets
### 9.1 Current Coverage Estimate
Based on manual analysis:
- **Completion:** ~60% (10 tests, but missing edge cases)
- **Diagnostics:** ~90% (20 comprehensive tests)
- **Symbols:** ~85% (17 edge case tests)
- **Navigation:** ~70% (11 tests, single-file only)
- **Code Actions:** ~80% (27 tests)
- **Hover:** ~40% (only integration tests)
- **Formatting:** ~40% (only integration tests)
- **Rename:** ~40% (only integration tests)
- **Semantic Tokens:** ~40% (only integration tests)
- **Inlay Hints:** 0% (broken)
**Overall Estimated Coverage:** ~55-60%
### 9.2 Target Coverage Goals
**Phase 1 (Stabilization):**
- All features compile: 100%
- All existing tests pass: 100%
- Critical paths covered: 70%
**Phase 2 (Enhancement):**
- Overall line coverage: 80%
- Branch coverage: 70%
- All features have dedicated unit tests: 100%
**Phase 3 (Multi-File):**
- Cross-file features: 70%
- Integration tests: 80%
- Overall coverage: 85%
---
## 10. Prioritized Issues List
### Critical (Blocking)
1. **Fix inlay_hints.rs import error** - Prevents all tests from running
2. **Fix completion.rs type annotation** - Prevents all tests from running
### High Priority (Stability)
3. **Add unit tests for hover** - Feature exists but untested
4. **Add unit tests for formatting** - Feature exists but untested
5. **Add unit tests for rename** - Feature exists but untested
6. **Add unit tests for semantic_tokens** - Feature exists but untested
7. **Add edge case tests** - Unicode, large files, malformed input
8. **Add performance benchmarks** - Unknown behavior at scale
### Medium Priority (Enhancements)
9. **Implement cross-file navigation** - High user value
10. **Populate workspace NameTable** - Infrastructure exists but unused
11. **Add integration tests** - Multi-file, concurrent access
12. **Set up CI/CD** - Automation for confidence
### Low Priority (Nice-to-Have)
13. **Improve error handling** - Remove unwraps, add graceful degradation
14. **Add code coverage reporting** - Quantify test coverage
15. **Create architecture documentation** - Onboarding for contributors
---
## 11. Test Plan Summary
### Testing Phases
**Phase 1: Fix & Validate (1 day)**
- Fix 2 compilation errors
- Run and document all existing test results
- Identify any test failures
**Phase 2: Fill Gaps (3-5 days)**
- Add unit tests for hover, formatting, rename, semantic_tokens
- Add edge case tests (large files, unicode, malformed input)
- Add performance benchmarks
**Phase 3: Integration (1 week)**
- Add multi-file test scenarios
- Add concurrent access tests
- Add stress tests
**Phase 4: Automation (2-3 days)**
- Set up CI/CD
- Add code coverage reporting
- Document testing procedures
**Phase 5: Multi-File Support (2-3 weeks)**
- Implement cross-file navigation
- Implement workspace NameTable population
- Comprehensive multi-file testing
---
## 12. Success Metrics
### Short-Term (1 week)
- ✅ All tests compile without errors
- ✅ 100% of existing tests pass
- ✅ All LSP features have dedicated unit tests
- ✅ Code coverage > 70%
### Medium-Term (1 month)
- ✅ Code coverage > 80%
- ✅ CI/CD runs all tests automatically
- ✅ Performance benchmarks established
- ✅ No known critical bugs
### Long-Term (3 months)
- ✅ Cross-file navigation implemented
- ✅ Code coverage > 85%
- ✅ Comprehensive integration tests
- ✅ Documentation complete
---
## 13. Resources Required
### Tools
- Rust testing framework (cargo test) - ✅ Already installed
- Code coverage tool (tarpaulin or llvm-cov) - ⚠️ Needs installation
- CI/CD platform (GitHub Actions) - ✅ Available
- Benchmarking tool (criterion) - ⚠️ Needs integration
### Time Estimates
- **Phase 1 (Fix & Validate):** 1 day
- **Phase 2 (Fill Gaps):** 3-5 days
- **Phase 3 (Integration):** 5-7 days
- **Phase 4 (Automation):** 2-3 days
- **Phase 5 (Multi-File):** 10-15 days
**Total Estimated Time:** 21-31 days (4-6 weeks)
---
## 14. Conclusion
The Storybook LSP implementation is **architecturally sound** and **feature-rich**, with 9 major LSP features implemented and 147 tests written. However, **two simple compilation errors** are blocking the entire test suite from running.
**Immediate Action Required:**
1. Fix the two compilation errors (15 minutes)
2. Verify all 102 tests pass
3. Proceed with test gap filling and stabilization
**Strategic Recommendation:**
- Focus on **stabilization first** (Phases 1-2) before attempting multi-file support
- The single-file navigation is sufficient for MVP
- Cross-file support can be added incrementally without breaking existing features
**Risk Assessment:**
- **Low risk** to fix compilation errors and achieve stability
- **Medium risk** for multi-file support (requires architectural changes)
- **High value** in completing test coverage for existing features
The implementation is **close to production-ready** once compilation errors are resolved and test coverage gaps are filled.
---
## Appendix A: Test File Inventory
```
storybook/src/lsp/
├── behavior_tests.rs (7 tests)
├── code_actions_tests.rs (27 tests)
├── completion_tests.rs (10 tests)
├── diagnostics_tests.rs (20 tests)
├── document_edge_tests.rs (17 tests)
├── navigation_tests.rs (11 tests)
├── validation_tests.rs (10 tests)
├── tests.rs (~30 integration tests)
└── parser_test.rs (~15 parser tests)
Total: ~147 test functions
```
## Appendix B: LSP Method Implementation Status
```rust
impl LanguageServer for StorybookLanguageServer {
async fn initialize()
async fn initialized()
async fn shutdown()
async fn did_open()
async fn did_change()
async fn did_close()
async fn hover()
async fn completion()
async fn goto_definition()
async fn references()
async fn formatting()
async fn rename()
async fn code_action()
async fn semantic_tokens_full()
async fn inlay_hint() // Broken import
}
```
## Appendix C: Tree-sitter Test Results
```bash
cd /Users/sienna/Development/storybook/tree-sitter-storybook
npm run test
```
**Output:**
```
✓ Simple character
✓ Use declaration
✓ Prose block
✓ Simple Behavior
✓ Selector Behavior
✓ Sequence Behavior
✓ Nested Behavior
✓ Repeat Behavior
✓ Behavior with Subtree
✓ Complex Nested Behavior
✓ Use declaration - simple
✓ Use declaration - grouped import
✓ Use declaration - wildcard
✓ Character - full featured
✓ Template with includes
✓ Life arc with states and transitions
✓ Schedule with time blocks
✓ Behavior tree - all node types
✓ Institution
✓ Relationship with participants
✓ Location
✓ Species with includes
✓ Enum declaration
✓ Override syntax
✓ Complex expressions in conditions
✓ List and object values
✓ Dotted field paths
27/27 tests passing ✅
```

View File

@@ -1,464 +0,0 @@
# LSP Lexer Usage Audit
**Date:** 2026-02-12
**Auditor:** LSP Test Engineer
**Purpose:** Verify all LSP modules use the lexer exclusively (no ad-hoc parsing)
---
## Executive Summary
**Status:** ⚠️ **Mixed Compliance**
- **3 modules** properly use lexer ✅
- **8 modules** use ad-hoc parsing ❌
- **Critical Risk:** Hardcoded keyword lists in 3 modules
**Risk Level:** MEDIUM
- Inconsistent behavior between LSP and compiler
- Vulnerability to keyword changes (like recent behavior tree updates)
- Maintenance burden from duplicate logic
---
## Audit Results by Module
### ✅ Compliant Modules (Using Lexer)
#### 1. **completion.rs** - ✅ GOOD (with caveats)
**Status:** Uses Lexer properly for tokenization
**Lexer Usage:**
```rust
use crate::syntax::lexer::{Lexer, Token};
let lexer = Lexer::new(before);
```
**Found at lines:** 135, 142, 269, 277, 410, 417
**Issue:** ⚠️ Contains hardcoded keyword strings (8 occurrences)
- Lines with hardcoded keywords: "character", "template", "behavior", etc.
- **Risk:** Keywords could get out of sync with lexer
**Recommendation:** Extract keywords from lexer Token enum instead of hardcoding
---
#### 2. **semantic_tokens.rs** - ✅ EXCELLENT
**Status:** Uses Lexer exclusively, no manual parsing
**Lexer Usage:**
```rust
use crate::syntax::lexer::{Lexer, Token};
```
**Assessment:** **Best practice example** - Uses lexer for all tokenization, no hardcoded keywords, no manual string manipulation
---
#### 3. **code_actions.rs** - ✅ GOOD (with caveats)
**Status:** Uses Lexer for tokenization
**Issues:**
- ⚠️ Contains 15 instances of manual string parsing (`.split()`, `.chars()`, `.lines()`)
- ⚠️ Has 4 hardcoded keyword strings
- **Concern:** Mixed approach - uses lexer sometimes, manual parsing other times
**Recommendation:** Refactor to use lexer consistently throughout
---
### ❌ Non-Compliant Modules (Ad-Hoc Parsing)
#### 4. **hover.rs** - ❌ CRITICAL ISSUE
**Status:** NO lexer usage, extensive manual parsing
**Problems:**
**A. Manual Character-by-Character Parsing**
```rust
// Line 51-77: extract_word_at_position()
let chars: Vec<char> = line.chars().collect();
// Custom word boundary detection
while start > 0 && is_word_char(chars[start - 1]) {
start -= 1;
}
```
**Risk:** Custom tokenization logic differs from compiler's lexer
**B. Hardcoded Keyword List** (Lines 20-39)
```rust
match word.as_str() {
"character" => "**character** - Defines a character entity...",
"template" => "**template** - Defines a reusable field template...",
"life_arc" => "**life_arc** - Defines a state machine...",
"schedule" => "**schedule** - Defines a daily schedule...",
"behavior" => "**behavior** - Defines a behavior tree...",
"institution" => "**institution** - Defines an organization...",
"relationship" => "**relationship** - Defines a multi-party...",
"location" => "**location** - Defines a place...",
"species" => "**species** - Defines a species...",
"enum" => "**enum** - Defines an enumeration...",
"use" => "**use** - Imports declarations...",
"from" => "**from** - Applies templates...",
"include" => "**include** - Includes another template...",
"state" => "**state** - Defines a state...",
"on" => "**on** - Defines a transition...",
"strict" => "**strict** - Enforces that a template...",
_ => return None,
}
```
**Risk:** HIGH
- 16 hardcoded keywords that must stay in sync with lexer
- If lexer adds/removes keywords, hover won't update automatically
- Recent behavior tree changes could have broken this
**Recommendation:**
```rust
// BEFORE (current):
let word = extract_word_at_position(line_text, character)?;
// AFTER (proposed):
let lexer = Lexer::new(line_text);
let token_at_pos = find_token_at_position(&lexer, character)?;
match token_at_pos {
Token::Character => "**character** - Defines...",
Token::Template => "**template** - Defines...",
// etc - using Token enum from lexer
}
```
---
#### 5. **formatting.rs** - ❌ MANUAL PARSING
**Status:** NO lexer usage, line-by-line text processing
**Problems:**
```rust
// Line 53: Manual line processing
for line in text.lines() {
let trimmed = line.trim();
// Custom logic for braces, colons, etc.
}
```
**Risk:** MEDIUM
- Custom formatting logic may not respect language semantics
- Could format code incorrectly if it doesn't understand context
**Recommendation:** Use lexer to tokenize, then format based on tokens
- Preserves semantic understanding
- Respects string literals, comments, etc.
---
#### 6. **diagnostics.rs** - ❌ MANUAL PARSING
**Status:** NO lexer usage, manual brace counting
**Problems:**
```rust
// Lines 34-37: Manual brace counting
for (line_num, line) in text.lines().enumerate() {
let open_braces = line.chars().filter(|&c| c == '{').count();
let close_braces = line.chars().filter(|&c| c == '}').count();
}
// Line 79: Character-by-character processing
for ch in text.chars() {
// Custom logic
}
```
**Risk:** HIGH
- Brace counting doesn't account for braces in strings: `character Alice { name: "{" }`
- Doesn't respect comments: `// This { is a comment`
- Could generate false diagnostics
**Recommendation:** Use lexer tokens to track brace pairs accurately
---
#### 7. **references.rs** - ❌ MANUAL STRING PARSING
**Status:** NO lexer usage
**Problems:**
```rust
// Manual string parsing for word boundaries
```
**Risk:** MEDIUM
- May not correctly identify symbol boundaries
- Could match partial words
**Recommendation:** Use lexer to identify identifiers
---
#### 8. **rename.rs** - ❌ HARDCODED KEYWORDS
**Status:** NO lexer usage, contains hardcoded strings
**Problems:**
- 2 hardcoded keyword strings
- Manual symbol identification
**Risk:** MEDIUM
- May incorrectly rename keywords or miss valid renames
**Recommendation:** Use lexer to distinguish keywords from identifiers
---
#### 9. **definition.rs** - ⚠️ UNCLEAR
**Status:** No obvious lexer usage, no obvious manual parsing
**Assessment:** Likely uses AST-based approach (acceptable)
- May rely on symbols extracted from AST
- **Acceptable** if using `Document.ast` for symbol lookup
**Recommendation:** Verify it's using AST, not string parsing
---
#### 10. **inlay_hints.rs** - ⚠️ UNCLEAR
**Status:** No lexer usage detected, no obvious parsing
**Assessment:** Minimal code inspection needed
- May be stub or use AST-based approach
**Recommendation:** Full inspection needed
---
#### 11. **symbols.rs** - ✅ LIKELY COMPLIANT
**Status:** No manual parsing detected
**Assessment:** Appears to extract symbols from AST
- **Acceptable approach** - AST is the canonical representation
- No need for lexer if working from AST
---
## Summary Table
| Module | Lexer Usage | Manual Parsing | Hardcoded Keywords | Risk Level |
|--------|-------------|----------------|-------------------|------------|
| **completion.rs** | ✅ Yes | ❌ No | ⚠️ 8 keywords | MEDIUM |
| **semantic_tokens.rs** | ✅ Yes | ❌ No | ✅ None | LOW |
| **code_actions.rs** | ✅ Yes | ⚠️ 15 instances | ⚠️ 4 keywords | MEDIUM |
| **hover.rs** | ❌ No | ⚠️ Extensive | ⚠️ 16 keywords | **HIGH** |
| **formatting.rs** | ❌ No | ⚠️ Line-by-line | ✅ None | MEDIUM |
| **diagnostics.rs** | ❌ No | ⚠️ Char counting | ✅ None | **HIGH** |
| **references.rs** | ❌ No | ⚠️ Yes | ✅ None | MEDIUM |
| **rename.rs** | ❌ No | ⚠️ Yes | ⚠️ 2 keywords | MEDIUM |
| **definition.rs** | ⚠️ Unknown | ⚠️ Unknown | ✅ None | LOW |
| **inlay_hints.rs** | ⚠️ Unknown | ⚠️ Unknown | ✅ None | LOW |
| **symbols.rs** | N/A (AST) | ❌ No | ✅ None | LOW |
---
## Critical Findings
### 1. **hover.rs** - Highest Risk
- 16 hardcoded keywords
- Custom tokenization logic
- **Impact:** Recent behavior tree keyword changes may have broken hover
- **Fix Priority:** HIGH
### 2. **diagnostics.rs** - High Risk
- Manual brace counting fails in strings/comments
- Could generate false errors
- **Fix Priority:** HIGH
### 3. **Hardcoded Keywords** - Maintenance Burden
- **Total:** 30 hardcoded keyword strings across 4 files
- **Risk:** Keywords get out of sync with lexer
- **Recent Example:** Behavior tree syntax changes could have broken these
---
## Recommended Fixes
### Priority 1: hover.rs Refactoring
**Estimated Time:** 2-3 hours
**Changes:**
1. Add lexer import: `use crate::syntax::lexer::{Lexer, Token};`
2. Replace `extract_word_at_position()` with lexer-based token finding
3. Replace keyword match with Token enum match
4. Remove hardcoded keyword strings
**Benefits:**
- Automatic sync with lexer changes
- Consistent tokenization with compiler
- Easier maintenance
**Example Code:**
```rust
pub fn get_hover_info(text: &str, line: usize, character: usize) -> Option<Hover> {
let line_text = text.lines().nth(line)?;
let lexer = Lexer::new(line_text);
// Find token at character position
let token_at_pos = find_token_at_position(&lexer, character)?;
let content = match token_at_pos {
Token::Character => "**character** - Defines a character entity...",
Token::Template => "**template** - Defines a reusable field template...",
// Use Token enum - stays in sync automatically
};
Some(Hover { /* ... */ })
}
```
---
### Priority 2: diagnostics.rs Refactoring
**Estimated Time:** 1-2 hours
**Changes:**
1. Use lexer to tokenize text
2. Count LBrace/RBrace tokens (not characters)
3. Ignore braces in strings and comments automatically
**Benefits:**
- Correct handling of braces in all contexts
- No false positives
---
### Priority 3: Extract Keyword Definitions
**Estimated Time:** 1 hour
**Changes:**
1. Create `src/syntax/keywords.rs` module
2. Define keyword list from lexer Token enum
3. Use in completion, code_actions, rename
**Benefits:**
- Single source of truth for keywords
- Easy to keep in sync
---
## Testing Recommendations
After fixes, add tests for:
1. **Hover on keywords in strings** - Should NOT show hover
```rust
character Alice { name: "character" } // hovering "character" in string
```
2. **Diagnostics with braces in strings** - Should NOT count
```rust
character Alice { name: "{}" } // should not report brace mismatch
```
3. **Lexer consistency tests** - Verify LSP uses same tokens as compiler
```rust
#[test]
fn test_hover_uses_lexer_keywords() {
// Ensure hover keywords match lexer Token enum
}
```
---
## Long-Term Recommendations
### 1. Establish Coding Standards
Document that LSP modules should:
- ✅ Use lexer for all tokenization
- ✅ Use AST for semantic analysis
- ❌ Never do manual string parsing
- ❌ Never hardcode keywords
### 2. Code Review Checklist
Add to PR reviews:
- [ ] Does LSP code use lexer for tokenization?
- [ ] Are there any hardcoded keyword strings?
- [ ] Is there any manual `.split()`, `.chars()`, `.find()` parsing?
### 3. Shared Utilities
Create `src/lsp/lexer_utils.rs` with:
- `find_token_at_position()` - Common utility
- `get_keyword_docs()` - Centralized keyword documentation
- `is_keyword()` - Token-based keyword checking
---
## Impact Assessment
### Current State Risks
**Behavior Tree Changes (Recent):**
- Lexer/parser updated with new keywords
- ❌ `hover.rs` still has old hardcoded list
- ⚠️ Users may not see hover for new keywords
**Future Keyword Changes:**
- Any new keywords require updates in 4 separate files
- Easy to miss one, causing inconsistent behavior
**Bug Examples:**
```rust
// diagnostics.rs bug:
character Alice { description: "Contains } brace" }
// ^ Reports false "unmatched brace" error
// hover.rs bug:
character Alice { /* hover on "character" keyword here */ }
// ^ Works
"In a character block..." // hover on "character" in string
// ^ Also shows hover (WRONG - it's just a word in a string)
```
---
## Conclusion
**Overall Assessment:** NEEDS IMPROVEMENT
- **Compliance Rate:** 27% (3/11 modules)
- **Risk Level:** MEDIUM-HIGH
- **Recommended Action:** Refactor hover.rs and diagnostics.rs as priority
**Benefits of Fixing:**
1. Consistency with compiler behavior
2. Automatic sync with language changes
3. Reduced maintenance burden
4. Fewer bugs from edge cases
**Next Steps:**
1. Create GitHub issues for each Priority 1-2 fix
2. Refactor hover.rs (highest risk)
3. Refactor diagnostics.rs (high risk)
4. Extract keyword definitions (prevents future issues)
5. Add lexer usage to code review checklist
---
## Appendix: Files Analyzed
```
Total LSP modules audited: 11
✅ Compliant: 3 (27%)
⚠️ Partially compliant: 1 (9%)
❌ Non-compliant: 7 (64%)
Files examined:
- src/lsp/completion.rs
- src/lsp/hover.rs
- src/lsp/semantic_tokens.rs
- src/lsp/inlay_hints.rs
- src/lsp/definition.rs
- src/lsp/formatting.rs
- src/lsp/rename.rs
- src/lsp/references.rs
- src/lsp/code_actions.rs
- src/lsp/symbols.rs
- src/lsp/diagnostics.rs
```

File diff suppressed because it is too large Load Diff

View File

@@ -1,906 +0,0 @@
# Storybook Stabilization & Enhancement Team Plan
## Overview
This plan outlines a multi-agent team structure to tackle six critical workstreams:
1. **LSP Testing & Stabilization** - Comprehensive testing and bug fixing for the Language Server Protocol implementation
2. **Behavior Tree Refactoring** - Replacing symbolic syntax with human-friendly keywords (repeat, if, etc.)
3. **Resource Linking System** - Designing how to link behavior trees and schedules to characters and institutions
4. **SBIR Specification Validation** - Identifying gaps and missing elements in the IR spec
5. **Schedule System Enhancement** - Implementing year-long, composable schedule support
6. **Language Documentation** - Creating comprehensive, beginner-friendly documentation for non-programmer world builders
**Note:** The codebase uses "characters" not "entities". We can reuse existing infrastructure where possible.
## Team Structure
### Team Lead (Coordinator)
**Role:** Overall coordination, task assignment, progress tracking, and integration oversight
**Responsibilities:**
- Create and manage task board
- Assign tasks to specialists
- Monitor progress and unblock agents
- Coordinate dependencies between workstreams
- Synthesize findings into cohesive deliverables
- Handle final integration validation
---
### Agent 1: LSP Test Engineer
**Subagent Type:** `general-purpose` (needs full read/write/edit access)
**Primary Focus:** Testing and stabilizing the LSP implementation
**Assigned Tasks:**
- Task #1: Audit LSP implementation and create test strategy
- Task #2: Implement test suite and stabilization fixes
**Key Responsibilities:**
- Inventory all LSP features (hover, completion, go-to-definition, diagnostics, references, etc.)
- Analyze Tree-sitter grammar coverage
- Document current test coverage gaps
- Create comprehensive test strategy with prioritization
- Implement unit tests for each LSP feature
- Implement integration tests for multi-file scenarios
- Add edge case and error condition tests
- Fix identified stability issues
- Create regression tests
- Set up CI/CD for automated testing
**Deliverables:**
- LSP feature inventory document
- Test strategy and plan document
- Comprehensive test suite (unit + integration)
- Stability fixes and bug reports
- CI/CD configuration
- Testing documentation
**Success Criteria:**
- All LSP features have test coverage
- No known stability issues remain
- Tests run automatically in CI
- Documentation enables future contributors to add tests
---
### Agent 2: Behavior Tree Language Designer
**Subagent Type:** `general-purpose` (needs full read/write/edit access)
**Primary Focus:** Redesigning behavior tree syntax with human-friendly keywords
**Assigned Tasks:**
- Task #3: Analyze current syntax and design keyword system
- Task #4: Implement transformation system
**Key Responsibilities:**
- Catalog all current symbolic behavior tree representations
- Design keyword mappings:
- Decorators: `repeat(N)`, `retry(N)`, `timeout(seconds)`, `cooldown(seconds)`, `invert`, `if(condition)`
- Control: `if(condition)`, `sequence`, `selector`, `parallel`
- Actions: Human-readable action calls
- Create comprehensive grammar specification
- Update Tree-sitter grammar
- Modify parser to support new keywords
- Update compiler to translate keywords → SBIR
- Implement backward compatibility (if needed)
- Validate with existing examples (Alice in Wonderland)
- Update language documentation
**Deliverables:**
- Current syntax inventory
- Keyword mapping specification
- Grammar design document
- Example transformations (before/after)
- Updated Tree-sitter grammar
- Parser modifications
- Compiler updates
- Migration guide (if backward compatibility breaks)
- Updated documentation with new syntax examples
**Success Criteria:**
- All symbolic constructs have keyword equivalents
- Syntax is intuitive and readable
- Parser handles new keywords correctly
- Compiler generates correct SBIR
- Examples validate successfully
- Documentation is complete
---
### Agent 3: Resource Linking Architect
**Subagent Type:** `general-purpose` (needs full read/write/edit access)
**Primary Focus:** Designing and implementing comprehensive linking system for behaviors and schedules
**Assigned Tasks:**
- Task #5: Design resource linking system (behaviors + schedules)
- Task #6: Implement linking system
**Important:** Agent must discuss design and implementation with user at key checkpoints to ensure correctness.
**Key Responsibilities:**
**Behavior Linking:**
- Design behavior linking mechanisms for **characters** (note: codebase uses "characters" not "entities"):
- Direct assignment: `entity Alice { link behavior: WorkAtBakery }`
- Multiple behaviors: `link behaviors: [WorkAtBakery, SocialRoutine, RestAndRecover]`
- Priority system: `link behaviors: [{ tree: WorkAtBakery, priority: normal }, ...]`
- Conditional selection: `link behavior: WorkAtBakery when role == baker`
- Context-based: Link behaviors based on location/institution/state
- Design behavior linking for **institutions**:
- Institution default behaviors: `institution Bakery { link behavior: BakeryOperations }`
- Role-specific behaviors: `role worker { link behavior: BakeryWork }`
**Schedule Linking:**
- Design schedule linking mechanisms for **characters**:
- Direct assignment: `entity Alice { link schedule: BakerSchedule }`
- Conditional schedules: `link schedule: WorkdaySchedule when employed`
- State-based schedules: Different schedules for different life arc states
- Override system: Special schedules for events/holidays
- Design schedule linking for **institutions**:
- Operating hours: `institution Bakery { link schedule: BakeryHours }`
- Seasonal variations: `link schedule: WinterHours when season == winter`
**General Linking Design:**
- Design unified `link` keyword syntax
- Support linking in:
- Character definitions
- Species definitions (default links)
- Template definitions (inherited links)
- Institution definitions
- Institution role definitions
- Design SBIR representation:
- Link metadata in CHARACTERS section (currently ENTITIES in spec)
- Link metadata in INSTITUTIONS section
- Link resolution rules
- Priority and selection metadata
- Reuse existing infrastructure where possible
- Consider use cases:
- Character with multiple behaviors selected by context
- Character schedule changes based on life events
- Institution behaviors for different roles
- Institution schedules (hours of operation)
- Dynamic link resolution at runtime
- Coordinate with Behavior Tree Designer, Schedule Architect, and SBIR Analyst
- **Checkpoint 1:** Present linking design to user for review before implementation
- Implement parser support for `link` keyword (reuse existing parser infrastructure)
- Implement compiler translation to SBIR
- Create runtime link resolver
- **Checkpoint 2:** Review implementation approach with user before finalizing
- Validate with examples
- **Checkpoint 3:** Demo working implementation to user
**Deliverables:**
- Resource linking system architecture document
- Syntax specification for `link` keyword (behaviors + schedules)
- SBIR format proposal for links in CHARACTERS and INSTITUTIONS sections
- Selection/resolution algorithm specification
- Updated language syntax
- Parser modifications for `link` keyword
- Compiler updates
- Link resolver implementation
- Comprehensive examples:
- Entity with linked behavior
- Entity with linked schedule
- Entity with multiple linked behaviors
- Institution with linked behavior
- Institution with linked schedule (operating hours)
- Conditional/contextual linking
- State-based linking
- Priority-based selection
- Test suite for linking system
- Documentation
**Success Criteria:**
- Unified `link` keyword works for both behaviors and schedules
- Characters can link to behaviors AND schedules
- Institutions can link to behaviors AND schedules
- User has approved design and implementation approach
- Support for multiple links with selection rules
- Support for conditional/contextual selection
- Runtime resolver selects correct behavior/schedule
- Examples demonstrate real-world use cases
- SBIR encoding captures all linking semantics
- Integration with schedule system and life arcs works seamlessly
---
### Agent 4: Language Documentation Writer
**Subagent Type:** `general-purpose` (needs read access + ability to write documentation)
**Primary Focus:** Creating accessible, beginner-friendly language documentation for non-programmers
**Assigned Tasks:**
- Task #10: Create comprehensive language documentation for end users
**Key Responsibilities:**
- Create documentation for **non-technical world builders** (like Lonni)
- Document language from a **storyteller's perspective**, not a programmer's perspective
- Cover all language features with:
- Clear, simple explanations
- Practical examples from storytelling contexts
- Progressive complexity (beginner → intermediate → advanced)
- Common patterns and recipes
- Troubleshooting guides
- Structure documentation by use case:
- "Creating your first character"
- "Making characters behave realistically"
- "Setting up daily schedules"
- "Creating relationships between characters"
- "Designing locations and institutions"
- "Making characters respond to events"
- "Building complex behaviors"
- Document new features as they're implemented:
- Human-friendly behavior tree keywords (from Task #3/#4)
- Resource linking syntax (from Task #5/#6)
- Schedule composition (from Task #8/#9)
- Include:
- Tutorials
- How-to guides
- Reference documentation
- Concept explanations
- Glossary of terms
- Use consistent terminology throughout
- Coordinate with all other agents to document their features
- Get user feedback on documentation clarity
**Deliverables:**
- Getting Started Guide
- Language Tutorial (progressive lessons)
- Feature-by-feature reference
- Recipe/pattern library
- Troubleshooting guide
- Glossary
- Example storybooks (annotated)
- Quick reference card
**Success Criteria:**
- A non-programmer can learn the language from the documentation alone
- Documentation covers all language features
- Examples are compelling and storytelling-focused
- User (and test readers like Lonni) approve documentation clarity
- Documentation stays up-to-date with new features
---
### Agent 5: SBIR Specification Analyst
**Subagent Type:** `Explore` (read-only, deep analysis focus)
**Primary Focus:** Validating SBIR spec completeness and identifying gaps
**Assigned Tasks:**
- Task #7: Conduct comprehensive SBIR specification validation
**Key Responsibilities:**
- Review entire SBIR spec section-by-section
- Cross-reference spec against actual .sb language features
- Identify missing functionality:
- Type system gaps
- Missing instruction opcodes
- Incomplete constraint system
- Schedule representation limitations
- **Behavior linking representation** (coordinate with Agent 3)
- Debug information gaps
- Extensibility concerns
- Identify ambiguities or underspecified semantics
- Validate against use cases (especially schedules and behavior linking)
- Check binary format efficiency
- Review codegen contract completeness
- Propose additions and modifications
**Deliverables:**
- Specification gap analysis report
- List of ambiguities requiring clarification
- Proposed additions organized by section
- Use case validation results
- Priority ranking of issues
**Success Criteria:**
- Every .sb language feature is representable in SBIR
- All ambiguities are documented
- Schedule system gaps are clearly identified
- Behavior linking gaps are clearly identified
- Codegen contract covers all implementation needs
- Spec is sufficient for third-party implementations
---
### Agent 6: Schedule System Architect
**Subagent Type:** `general-purpose` (needs full read/write/edit access)
**Primary Focus:** Designing and implementing year-long composable schedules
**Assigned Tasks:**
- Task #8: Design year-long composable schedule system
- Task #9: Implement schedule system
**Key Responsibilities:**
- Design schedule composition hierarchy:
- Base: Daily schedule templates
- Week: 7-day compositions with variations
- Month: Weekly compositions with irregular handling
- Season: Quarterly templates
- Year: Full calendar year representation
- Design composition operators:
- Inheritance (extends base schedule)
- Override (replace blocks)
- Merge (combine schedules)
- Exception (one-off modifications)
- Design override system for:
- Holidays and festivals
- Special events
- Seasonal variations
- Life events
- Address calendar concerns:
- Leap years
- Different calendar systems
- Date arithmetic
- **Design integration with resource linking:**
- Schedule blocks can optionally specify behaviors
- Behavior selection based on time of day via schedule
- Schedule selection via `link schedule` in entities/institutions
- Coordinate with Agent 3 (Resource Linking Architect)
- Design SBIR representation:
- Schedule composition metadata
- Efficient encoding for repetition
- Override/exception format
- Behavior references in schedule blocks
- Implement in language:
- Syntax for schedule composition
- Parser support
- Compiler translation to SBIR
- Create runtime evaluation strategy
- Validate with realistic examples
**Deliverables:**
- Schedule system architecture document
- Composition operator specification
- SBIR format proposal (updates to section 9)
- Calendar system specification
- Updated language syntax for schedules
- Parser and compiler changes
- Schedule resolver/evaluator implementation
- Comprehensive examples:
- Simple daily schedule
- Weekly variations
- Seasonal schedules
- Holiday calendars
- Year-long character schedules with behavior links
- Test suite for schedule composition
- Documentation
**Success Criteria:**
- Can represent schedules up to one calendar year
- Schedules are composable with clear semantics
- Schedules can reference behaviors
- Minimal redundancy in representation
- Examples demonstrate real-world use cases
- Implementation matches specification
- SBIR encoding is space-efficient
- Integration with behavior linking works correctly
---
## Task Breakdown & Dependencies
### Phase 1: Analysis & Design (Parallel)
Can be worked on simultaneously by different agents:
**Task #1:** Audit LSP implementation and create test strategy
- **Agent:** LSP Test Engineer
- **Dependencies:** None
- **Duration Estimate:** Research/analysis phase
**Task #3:** Analyze current behavior tree syntax and design keyword system
- **Agent:** Behavior Tree Language Designer
- **Dependencies:** None
- **Duration Estimate:** Design phase
**Task #5:** Design resource linking system (behaviors + schedules)
- **Agent:** Resource Linking Architect
- **Dependencies:** None (but should coordinate with Tasks #3, #7, and #8)
- **Duration Estimate:** Design phase
**Task #7:** Conduct comprehensive SBIR specification validation
- **Agent:** SBIR Specification Analyst (Agent 5)
- **Dependencies:** None
- **Duration Estimate:** Analysis phase
**Task #8:** Design year-long composable schedule system
- **Agent:** Schedule System Architect (Agent 6)
- **Dependencies:** None (but should coordinate with Task #5 for behavior linking)
- **Duration Estimate:** Design phase
---
### Phase 2: Implementation (Partially Parallel)
**Task #2:** Implement LSP test suite and stabilization fixes
- **Agent:** LSP Test Engineer
- **Dependencies:** Task #1 (test strategy must be complete)
- **Duration Estimate:** Implementation phase
**Task #4:** Implement behavior tree keyword transformation system
- **Agent:** Behavior Tree Language Designer
- **Dependencies:** Task #3 (design must be complete)
- **Duration Estimate:** Implementation phase
**Task #6:** Implement resource linking system
- **Agent:** Resource Linking Architect
- **Dependencies:** Task #5 (design must be complete), Task #4 (behavior tree syntax should be stable)
- **Duration Estimate:** Implementation phase
**Task #9:** Implement year-long composable schedule system
- **Agent:** Schedule System Architect (Agent 6)
- **Dependencies:** Task #8 (design must be complete), Task #6 (behavior linking should be implemented for integration)
- **Duration Estimate:** Implementation phase
**Task #10:** Create comprehensive language documentation for end users
- **Agent:** Language Documentation Writer (Agent 4)
- **Dependencies:** None initially, but continuously updated as Tasks #4, #6, #9 complete
- **Duration Estimate:** Ongoing throughout all phases
---
### Phase 3: Consolidation (Sequential)
**Task #11:** Update SBIR specification with all enhancements
- **Agent:** Team Lead (or designated spec writer)
- **Dependencies:** Tasks #3, #5, #7, #8 (all designs and analysis must be complete)
- **Duration Estimate:** Documentation phase
**Responsibilities:**
- Incorporate findings from SBIR validation (Task #7)
- Add year-long schedule system spec (Task #8 output)
- Add behavior tree keyword documentation (Task #3 output)
- Add entity-behavior linking spec (Task #5 output)
- Update ENTITIES section for behavior links
- Update SCHEDULES section for behavior references
- Update instruction set if needed
- Add new sections if required
- Update examples throughout
- Increment version number (likely 0.2.0)
- Create migration guide
**Deliverables:**
- Updated SBIR specification (v0.2.0)
- Migration guide from v0.1.0
- Version changelog
- Updated examples
---
### Phase 4: Integration & Validation (Final)
**Task #12:** Integration validation and documentation
- **Agent:** Team Lead + all agents for their domains
- **Dependencies:** Tasks #2, #4, #6, #9, #10 (all implementations and spec must be complete)
- **Duration Estimate:** Testing and documentation phase
**Responsibilities:**
- Run full integration tests across all systems
- Validate LSP with new behavior tree keywords AND linking syntax
- Validate compiler with new schedule system
- Validate behavior linking and selection at runtime
- Test schedule + behavior linking integration
- Test SBIR serialization/deserialization
- Run Alice in Wonderland example through full pipeline
- Create end-to-end examples demonstrating all features
- Update user documentation
- Create developer guide
- Document breaking changes
- Create release notes
**Deliverables:**
- Integration test results
- End-to-end examples showing:
- Character with multiple behaviors
- Schedule-based behavior selection
- Conditional behavior linking
- Full lifecycle from .sb → .sbc → runtime
- User documentation (updated)
- Developer guide
- Release notes for v0.2.0
**Success Criteria:**
- All systems work together seamlessly
- Can create entity with behaviors linked via all supported mechanisms
- Schedule integration with behaviors works correctly
- LSP supports all new syntax
- Examples validate end-to-end
---
## Dependency Graph
```
┌───────────────────────────────────────────────────────────────────────┐
│ Phase 1: Analysis & Design (Parallel, with coordination) │
├───────────────────────────────────────────────────────────────────────┤
│ │
│ Task #1: LSP Audit Task #3: BT Design │
│ (LSP Test Engineer) (BT Designer) │
│ │ │ │
│ │ │ ← coordinates with → │
│ │ │ ↓ │
│ │ Task #5: Linking Design Task #8: Sched│
│ │ (Linking Architect) (Sched Arch) │
│ │ │ │ │
│ │ │ ← coordinates with → │ │
│ │ │ │
│ Task #7: SBIR Validation ←──────────┼───────────────────────────────│
│ (SBIR Analyst) │ │
│ │
└───────────────────────────────────────────────────────────────────────┘
┌───────────────────────────────────────────────────────────────────────┐
│ Phase 2: Implementation (Partially Sequential) │
├───────────────────────────────────────────────────────────────────────┤
│ │
│ Task #2: LSP Tests Task #4: BT Implementation │
│ (depends on #1) (depends on #3) │
│ │ │
│ ↓ │
│ Task #6: Linking Implementation │
│ (depends on #4, #5) │
│ │ │
│ ↓ │
│ Task #9: Schedule Implementation │
│ (depends on #6, #8) │
│ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Task #10: Language Documentation (ongoing, updates as │ │
│ │ features complete: #4, #6, #9) │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
└───────────────────────────────────────────────────────────────────────┘
┌───────────────────────────────────────────────────────────────────────┐
│ Phase 3: Consolidation │
├───────────────────────────────────────────────────────────────────────┤
│ │
│ Task #11: Update SBIR Spec │
│ (depends on Tasks #3, #5, #7, #8) │
│ │
└───────────────────────────────────────────────────────────────────────┘
┌───────────────────────────────────────────────────────────────────────┐
│ Phase 4: Integration │
├───────────────────────────────────────────────────────────────────────┤
│ │
│ Task #12: Integration Validation & Technical Docs │
│ (depends on Tasks #2, #4, #6, #9, #10, #11) │
│ │
│ Note: Task #10 (Language Docs) continues updating throughout │
│ │
└───────────────────────────────────────────────────────────────────────┘
```
---
## Resource Linking: Design Considerations
### Linking Mechanisms to Support
#### 1. Character Behavior Linking
**Simple Direct Link:**
```sb
character Alice : Human {
link behavior: CuriousExplorer
}
```
**Multiple Behaviors with Priorities:**
```sb
character Alice : Human {
link behaviors: [
{ tree: HandleUrgentNeeds, priority: critical }
{ tree: WorkAtBakery, priority: normal, when: schedule.activity == work }
{ tree: SocialInteraction, priority: normal, when: schedule.activity == leisure }
{ tree: Sleep, priority: normal, when: schedule.activity == sleep }
{ tree: Idle, priority: low }
]
}
```
**Context-Based Behavior:**
```sb
character Alice : Human {
link behaviors: [
{ tree: WorkAtBakery, when: at_location(Bakery) }
{ tree: HomeRoutine, when: at_location(Home) }
{ tree: Wander, default: true }
]
}
```
#### 2. Character Schedule Linking
**Direct Schedule Link:**
```sb
character Alice : Human {
link schedule: BakerSchedule
}
```
**Conditional Schedule Link:**
```sb
character Alice : Human {
link schedule: WorkdaySchedule when employed == true
link schedule: UnemployedSchedule when employed == false
}
```
**State-Based Schedule:**
```sb
character Alice : Human {
life_arc: PersonArc at Adult
link schedules: [
{ schedule: ChildSchedule, when: state == Child }
{ schedule: AdultSchedule, when: state == Adult }
{ schedule: ElderSchedule, when: state == Elder }
]
}
```
#### 3. Institution Behavior Linking
**Institution-Level Behavior:**
```sb
institution Bakery {
link behavior: BakeryOperations
roles {
owner {
link behavior: ManageBakery
}
worker {
link behavior: BakeryWork
}
}
}
```
**Contextual Institution Behavior:**
```sb
institution Bakery {
link behaviors: [
{ tree: BusyService, when: customer_queue > 5 }
{ tree: NormalService, default: true }
]
}
```
#### 4. Institution Schedule Linking
**Operating Hours:**
```sb
institution Bakery {
link schedule: BakeryHours
}
```
**Seasonal Schedules:**
```sb
institution Bakery {
link schedules: [
{ schedule: SummerHours, when: season == summer }
{ schedule: WinterHours, when: season == winter }
{ schedule: StandardHours, default: true }
]
}
```
**Role-Specific Schedules:**
```sb
institution Bakery {
roles {
owner {
link schedule: OwnerSchedule
}
worker {
link schedule: WorkerSchedule
}
}
}
```
#### 5. Species Default Links
**Default Behavior and Schedule:**
```sb
species Human {
components: HumanComponents
link behaviors: [HandleBasicNeeds, SocialDrive, CuriosityDrive]
link schedule: DefaultHumanSchedule
}
```
#### 6. Template Inherited Links
**Template with Links:**
```sb
template WonderlandCreature {
link behavior: WonderlandBehavior
link schedule: WonderlandSchedule
}
character CheshireCat : Cat using WonderlandCreature {
// inherits links from template
// can override with own links
link behavior: CheshireBehavior // overrides template
}
```
### SBIR Representation Questions
Agent 3 (Resource Linking Architect) should address:
**For Behavior Links:**
1. How are behavior references encoded in the CHARACTERS section (ENTITIES in spec)?
2. How are behavior references encoded in the INSTITUTIONS section?
3. How are selection rules/predicates encoded?
4. How are priorities represented?
5. How does the runtime resolve which behavior to execute?
6. Can multiple behaviors run simultaneously (parallel execution)?
7. How do conditions inject behaviors (override system)?
**For Schedule Links:**
8. How are schedule references encoded in the CHARACTERS section?
9. How are schedule references encoded in the INSTITUTIONS section?
10. How are conditional schedule links resolved at runtime?
11. How do schedule links interact with behavior links?
12. Can a character have both a direct schedule link AND schedule blocks with inline behaviors?
**General:**
13. What is the precedence order for link resolution (species → template → character)?
14. How are link overrides represented in SBIR?
15. What happens when multiple links match at runtime (conflict resolution)?
16. What existing infrastructure can be reused (parser, compiler, etc.)?
---
## Coordination Strategy
### Communication Patterns
1. **Phase Kickoffs:** Team lead provides context and coordinates agent startup for each phase
2. **Design Reviews with User:** After Tasks #1, #3, #5, #7, #8 complete, agents present designs to USER for approval before implementation
- **Critical:** Task #5 (linking design) MUST be reviewed by user before Task #6 (implementation)
3. **Cross-Agent Coordination:**
- Agent 3 (Linking) coordinates with Agent 2 (BT) on syntax
- Agent 3 (Linking) coordinates with Agent 5 (Schedule) on integration
- Agent 4 (SBIR) reviews all designs for spec implications
4. **Progress Updates:** Agents report completion and blockers to team lead AND user at checkpoints
5. **Implementation Checkpoints:** Agent 3 (Linking) discusses implementation approach with user before finalizing
6. **Integration Checkpoints:** Before Task #10, synchronize all design outputs
7. **Final Review:** Before Task #11, validate all implementations with user
### Handoff Points
- **LSP → BT Designer:** If LSP tests reveal issues with behavior tree parsing
- **BT Designer → Linking Architect:** Behavior tree syntax must be stable before implementing linking
- **Linking Architect → Schedule Architect:** Linking design informs schedule-behavior integration
- **SBIR Analyst → All Designers:** Gap analysis informs all designs
- **SBIR Analyst → Team Lead:** Findings inform Task #10 (spec updates)
- **All Designers → Team Lead:** Design outputs feed into Task #10
- **All Implementers → Team Lead:** Implementations validated in Task #11
---
## Risk Mitigation
### Potential Issues
1. **Backward Compatibility Breaks:** Behavior tree refactoring may break existing .sb files
- **Mitigation:** Design migration path; consider supporting both syntaxes temporarily
2. **SBIR Binary Format Changes:** Schedule and linking enhancements will require breaking changes
- **Mitigation:** Version bump to 0.2.0; provide conversion tooling
3. **LSP Instability During Development:** Changes to parser/compiler may break LSP
- **Mitigation:** LSP tests run continuously; prioritize stability fixes
4. **Linking System Complexity:** Multiple linking mechanisms may create ambiguity
- **Mitigation:** Clear precedence rules; comprehensive examples; runtime warnings for conflicts
5. **Scope Creep:** Each workstream could expand significantly
- **Mitigation:** Strict adherence to task definitions; defer non-essential work
6. **Integration Failures:** Systems may not work together cleanly
- **Mitigation:** Early integration checkpoints; continuous testing; coordination meetings
7. **Performance Concerns:** Complex behavior selection could impact runtime
- **Mitigation:** Design efficient selection algorithm; benchmark early
---
## Success Metrics
### LSP Workstream
- [ ] 90%+ test coverage for LSP features
- [ ] Zero known critical bugs
- [ ] All LSP features work with new syntax (BT keywords + linking)
- [ ] CI tests pass
### Behavior Tree Workstream
- [ ] All symbolic constructs have keyword replacements
- [ ] Alice in Wonderland example validates with new syntax
- [ ] Documentation includes before/after examples
- [ ] Compiler generates correct SBIR
### Resource Linking Workstream
- [ ] User approves linking design (Checkpoint 1)
- [ ] Unified `link` keyword supports behaviors and schedules
- [ ] Character behavior linking works (single + multiple + conditional)
- [ ] Character schedule linking works (single + multiple + conditional)
- [ ] Institution behavior linking works
- [ ] Institution schedule linking works (operating hours)
- [ ] All linking mechanisms implemented and tested
- [ ] User approves implementation approach (Checkpoint 2)
- [ ] Clear syntax for all use cases
- [ ] Runtime link resolver works correctly for behaviors
- [ ] Runtime link resolver works correctly for schedules
- [ ] Examples demonstrate all linking patterns
- [ ] SBIR encoding captures all linking semantics
- [ ] Integration between behavior links and schedule links works
- [ ] User validates working implementation (Checkpoint 3)
### SBIR Validation Workstream
- [ ] All identified gaps documented
- [ ] Priority recommendations provided
- [ ] Schedule system requirements captured
- [ ] Linking system requirements captured
- [ ] Spec ambiguities clarified
### Schedule System Workstream
- [ ] Can represent 365-day schedules
- [ ] Schedules compose with clear semantics
- [ ] Schedules can reference behaviors
- [ ] Examples demonstrate real-world use
- [ ] SBIR encoding is efficient
- [ ] Runtime resolver works correctly
- [ ] Integration with behavior linking works
### Integration
- [ ] All systems work together seamlessly
- [ ] End-to-end pipeline validated (source → SBIR → runtime)
- [ ] Can create complex entities with schedules + behaviors
- [ ] Documentation complete
- [ ] Release ready
---
## Next Steps
1. **Review this plan** - Approve, modify, or expand as needed
2. **Prioritize workstreams** - Determine if any workstream is more critical
3. **Spawn team** - Create agents with assigned roles
4. **Phase 1 kickoff** - Start analysis and design tasks with coordination meetings
5. **Design review** - Gate between Phase 1 and Phase 2
6. **Implementation** - Execute Phase 2 tasks sequentially where needed
7. **Specification update** - Execute Task #10
8. **Integration** - Execute Task #11
9. **Release** - Publish v0.2.0 with all enhancements
---
## Questions for Review
1. **Linking mechanisms:** Are all the proposed linking mechanisms necessary? Should we start with a subset?
2. **Link keyword scope:** Should `link` be the unified keyword for both behaviors and schedules, or use `link behavior:` and `link schedule:` explicitly?
3. **Institution linking:** Should institutions support the same linking flexibility as entities, or a simpler subset?
4. **Agent allocation:** Should any workstream have multiple agents (e.g., separate linking designer and implementer)?
5. **Timeline:** Are there hard deadlines or priorities among the five workstreams?
6. **Backward compatibility:** How important is maintaining compatibility with v0.1.0?
7. **Scope:** Should we defer any feature (e.g., parallel behavior execution, complex conditional linking) to v0.3.0?
8. **Integration complexity:** Should linking and schedules be designed together from the start, or sequentially?
9. **Success criteria:** Are the metrics sufficient, or should we add more specific targets?
10. **Link resolution algorithm:** Should behavior/schedule selection be designed upfront, or emerge from the linking design?
11. **Schedule-behavior interaction:** When a schedule block specifies a behavior AND the entity has linked behaviors, which takes precedence?

1706
docs/TYPE-SYSTEM.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,336 +0,0 @@
# Alice's Adventures in Wonderland - Storybook Example
A comprehensive demonstration of the Storybook DSL, modeling Lewis Carroll's *Alice's Adventures in Wonderland* with accuracy to the source material and showcasing all advanced language features.
## Overview
This example shows how Storybook enables complex narrative modeling for agent simulation games. It demonstrates:
- **Advanced behavior trees** for complex, context-dependent character actions
- **Life arcs** tracking transformative character journeys
- **Schedules** modeling eternal time loops and recurring events
- **Template composition** with inheritance and strict mode
- **Bidirectional relationships** with asymmetric perspectives
- **Cross-file references** creating an interconnected world model
## Contents
### Schema Layer
**`schema/core_enums.sb`**
- Core value types used throughout: `Size`, `EmotionalState`, `CardSuit`, `CardRank`, `TimeState`, `ManifestationLevel`
- Demonstrates enumeration definitions
**`schema/templates.sb`**
- Base template `WonderlandCreature` for all sentient beings
- Specialized templates with `include`: `SizeChanging`, `MadTeaPartyMember`, `Supernatural`
- **Strict template** `PlayingCard` enforcing concrete values
- Shows vertical inheritance (includes) and horizontal composition (multiple `from` clauses)
**`schema/species.sb`**
- Species definitions: `Human`, `Rabbit`, `Cat`, `Hare`, `Dormouse`, `Caterpillar`, `PlayingCardPerson`
- Rich prose blocks describing characteristics and abilities
### World Layer
#### Characters
**`alice.sb`** - The protagonist
- Inherits from `SizeChanging` template
- **Life arc `AliceJourney`** with states: `falling`, `tiny_alice`, `giant_alice`, `normal_alice_garden`, `enlightened_alice`
- Shows how life arcs track transformative journeys with state-specific field modifications
**`white_rabbit.sb`** - The anxious herald
- **Behavior tree `WhiteRabbit_ConstantlyLate`** using selectors (`?`) and sequences (`>`)
- Demonstrates hierarchical behavior modeling with panic strategies
**`cheshire_cat.sb`** - The enigmatic guide
- **Three behavior trees**:
- `CheshireCat_AppearDisappear` - context-dependent materialization
- `CheshireCat_GradualManifestation` - piece-by-piece appearance (grin first!)
- `CheshireCat_GradualDematerialization` - fading away (grin lingers longest)
- Shows complex multi-step sequences with timing and state transitions
**`mad_tea_party.sb`** - The eternal tea party trio
- Three characters: `MadHatter`, `MarchHare`, `Dormouse`
- **Schedule `MadTeaPartyRotation`** modeling the time loop (always 6 o'clock)
- **Behavior `MadTeaParty_CoordinatedMadness`** showing multi-agent coordination
- Demonstrates repeater decorator (`*`) for infinite loops
**`royal_court.sb`** - The Court of Hearts
- Characters: `QueenOfHearts`, `KingOfHearts`, `CardGardenerTwo`, `CardGardenerFive`, `CardGardenerSeven`
- Inherits from `PlayingCard` strict template - card suit/rank must be concrete
- **Behavior `QueenOfHearts_RagePattern`** - hair-trigger temper response
- **Behavior `KingOfHearts_SecretPardons`** - background mercy system
**`caterpillar.sb`** - The philosophical teacher
- **Behavior `Caterpillar_SocraticMethod`** - interrogative teaching style
- Shows question-answer tree structures
#### Locations
**`wonderland_places.sb`**
- `RabbitHole`, `HallOfDoors`, `Garden`, `MadTeaPartyTable`, `CroquetGround`, `QueensPalace`, `MushroomTop`
- Each location has physical properties, symbolic meaning, and narrative significance
- Demonstrates rich prose blocks for description and analysis
#### Institutions
**`wonderland_institutions.sb`**
- `CourtOfHearts` - tyrannical monarchy with interesting power dynamics
- `MadTeaParty` - eternal social gathering stuck in time
- `WonderlandDreamLogic` - the meta-institution governing reality itself
- Shows how social structures can be modeled with hierarchies and rules
#### Relationships
**`wonderland_relationships.sb`**
- **Bidirectional relationships** with `self` and `other` blocks showing asymmetric perspectives:
- `AliceAndWhiteRabbit` - pursuer/unwitting guide
- `AliceAndCheshireCat` - seeker/amused observer
- `QueenAndKing` - tyrant/secret rebel
- `AliceAndCaterpillar` - frustrated student/Socratic teacher
- Demonstrates how different characters perceive the same relationship differently
#### Behaviors
**`alice_behaviors.sb`** - Alice's strategic behaviors
- `Alice_SizeManagement` - learning to control size through trial and error
- `Alice_NavigateConversation` - dealing with nonsensical logic
- `Alice_EmotionalJourney` - state transitions from curiosity to enlightenment
- `Alice_ProblemSolving` - adapting normal-world logic to Wonderland
## Language Features Demonstrated
### 1. Template Composition
```storybook
template WonderlandCreature {
current_size: Size
emotional_state: EmotionalState
follows_logic: false..true
}
template SizeChanging {
include WonderlandCreature
natural_size: Size
size_changes_today: 0..50
}
character Alice from SizeChanging {
// Inherits all fields from WonderlandCreature and SizeChanging
age: 7
current_size: normal
}
```
### 2. Strict Templates
```storybook
template strict PlayingCard {
suit: CardSuit
rank: CardRank
// Characters using this template MUST provide concrete values
}
character QueenOfHearts from PlayingCard {
suit: hearts // Required: must be concrete enum value
rank: queen // Required: must be concrete enum value
}
```
### 3. Life Arcs
```storybook
life_arc AliceJourney {
state tiny_alice {
on enter {
Alice.current_size: tiny
Alice.size_changes_today: +1
}
}
state giant_alice {
on enter {
Alice.current_size: huge
}
}
}
```
### 4. Schedules
```storybook
schedule MadTeaPartyRotation {
18:00 -> 18:01: TeaRound { }
18:01 -> 18:02: RiddlePhase { }
// ... more phases
18:05 -> 18:00: LoopToBeginning { } // Loops back!
}
```
### 5. Behavior Trees
```storybook
behavior CheshireCat_AppearDisappear {
? { // Selector: try branches until one succeeds
> { // Sequence: all must succeed in order
IsInvisible
DecideToAppear
GradualManifestation
}
> {
IsVisible
DecideToLeave
GradualDematerialization
}
}
}
```
### 6. Repeater Decorator
```storybook
behavior MadTeaParty_CoordinatedMadness {
* { // Repeater: loop forever
? {
> { AskRiddle; ReceiveNoAnswer }
> { RotateSeats; CheckTime }
}
}
}
```
### 7. Bidirectional Relationships
```storybook
relationship QueenAndKing {
QueenOfHearts
KingOfHearts
bond: 0.4
self {
// Queen's perspective
role: dominant_spouse
aware_of_pardons: false
}
other {
// King's perspective
role: secret_moderator
subverts_authority: 1.0
}
}
```
### 8. Rich Prose Blocks
```storybook
character CheshireCat {
---description
A large cat with a permanent, unsettling grin. Possesses the
ability to appear and disappear at will, often leaving only
its grin behind.
---
---philosophy
The Cheshire Cat represents the absurdist nature of Wonderland
itself. His vanishing act defies physical law but seems
perfectly natural in Wonderland's logic.
---
}
```
### 9. Cross-File References
```storybook
// In alice.sb
use schema::core_enums::{Size, EmotionalState};
use schema::templates::SizeChanging;
character Alice from SizeChanging {
current_size: normal // Uses Size enum from core_enums
}
```
### 10. Field Modifications in Life Arcs
```storybook
state enlightened_alice {
on enter {
Alice.emotional_state: brave
Alice.awareness_of_absurdity: 1.0 // Absolute assignment
Alice.size_changes_today: +1 // Increment
}
}
```
## Accuracy to Source Material
This example stays faithful to Carroll's original text:
- **Mad Tea Party**: Time frozen at 6 o'clock, rotating seats, butter in the watch
- **Cheshire Cat**: Grin appearing first/last, cryptic directions, "we're all mad here"
- **Queen of Hearts**: Constant "Off with their heads!", card gardeners, croquet with flamingos
- **Alice's transformations**: Specific size states from the book
- **Caterpillar's advice**: Terse questions, mushroom sides
- **Character dynamics**: White Rabbit's anxiety, Dormouse's drowsiness, King's secret mercy
## Running the Example
```bash
# Validate the entire project
sb validate examples/alice-in-wonderland/
# Query characters
sb query "characters where follows_logic == false"
# Inspect a specific character
sb inspect Alice
# Show all relationships
sb query "relationships where bond > 0.5"
```
## What This Demonstrates
### For Content Authors (Lonni)
- **Rich character modeling**: Personality traits, motivations, relationships
- **Narrative structure**: Life arcs track character journeys
- **World building**: Locations, institutions, social dynamics
- **Prose integration**: Backstories, descriptions, and philosophical notes
### For Developers (Sienna)
- **Complex behavior trees**: Multi-level selectors, sequences, repeaters
- **State management**: Life arcs with field modifications
- **Scheduling systems**: Time loops and recurring events
- **Type safety**: Strict templates enforce constraints
- **Cross-referencing**: Build interconnected world models
### For Agent Simulation
This model could drive an agent-based simulation where:
- Alice's behavior tree decides how to navigate conversations and obstacles
- The Mad Tea Party schedule creates a time-loop environment
- Cheshire Cat's appearance/disappearance behavior creates mystery
- Queen's rage pattern generates conflict
- Relationships determine interaction dynamics
## Extending This Example
Ideas for additions:
- **More chapters**: Mock Turtle, Gryphon, Trial scene
- **Croquet game logic**: Behavior trees for live hedgehog/flamingo equipment
- **Size change mechanics**: Fine-grained mushroom nibbling behavior
- **Dream logic system**: Meta-rules governing Wonderland physics
- **Alice's awakening**: Final life arc state transitioning back to reality
## License
Source material: *Alice's Adventures in Wonderland* by Lewis Carroll (public domain)
Storybook adaptation: MIT License

View File

@@ -1,73 +0,0 @@
//! Species definitions for Wonderland inhabitants
species Human {
lifespan: 70
---description
Visitors from the normal world above. Rare in Wonderland.
Subject to size-changing effects of local flora.
---
}
species Rabbit {
lifespan: 10
---description
Wonderland rabbits often wear waistcoats, carry pocket watches,
and exhibit extreme punctuality anxiety. May be anthropomorphic.
---
}
species Cat {
lifespan: 15
---description
Cheshire variety can vanish at will, leaving only a grin.
Ordinary cats (like Dinah) remain in the world above.
---
}
species Hare {
lifespan: 8
---description
March Hares display heightened madness, especially during
breeding season. Often found at eternal tea parties.
---
}
species Dormouse {
lifespan: 5
---description
Extremely somnolent. Can sleep through tea parties, pinching,
and being used as a cushion. Occasionally recites tales in sleep.
---
}
species Caterpillar {
lifespan: 1
---description
Large, blue, hookah-smoking variety. Philosophically inclined.
Offers cryptic advice about size-changing mushrooms.
---
}
species PlayingCardPerson {
lifespan: 100
---description
Animated playing cards forming the Court of Hearts hierarchy.
Flat, rectangular bodies. Gardeners, soldiers, and royalty.
---
}
species Flamingo {
lifespan: 40
---description
Unwilling participants in croquet as live mallets.
Tendency to look back at player with puzzled expressions.
---
}
species Hedgehog {
lifespan: 6
---description
Pressed into service as croquet balls. Frequently unroll
and wander away mid-game, frustrating players.
---
}

View File

@@ -1,61 +0,0 @@
//! Template definitions for Wonderland entities
//! v0.2.0: Templates now include behavior and schedule references
use schema::core_enums::{Size, EmotionalState};
// Base template for all sentient beings in Wonderland
template WonderlandCreature {
current_size: Size
emotional_state: EmotionalState
speaks_english: true
awareness_of_absurdity: 0.0..1.0
}
// Template for size-changing entities (Alice, mushrooms victims)
template SizeChanging {
include WonderlandCreature
natural_size: Size
min_size: Size
max_size: Size
size_changes_today: 0..50
}
// Template for playing card entities
template PlayingCard strict {
include WonderlandCreature
suit: CardSuit
rank: CardRank
fear_of_queen: 0.8..1.0
follows_logic: false
}
// Template for residents of the Mad Tea Party
template MadTeaPartyMember {
include WonderlandCreature
uses behaviors: EndlessTeaParty, MoveToNextSeat
uses schedule: TeaPartySchedule
stuck_at_teatime: true
riddles_asked: 0..1000
follows_logic: false
current_seat_position: 0..100
}
// Template for royal court members
template CourtMember {
include WonderlandCreature
uses schedule: CourtSchedule
loyalty_to_queen: 0.0..1.0
times_threatened_with_beheading: 0..100
survival_instinct: 0.5..1.0
}
// Template for mysterious/supernatural beings
template Supernatural {
include WonderlandCreature
follows_logic: false
}

View File

@@ -1,22 +0,0 @@
# Alice's Adventures in Wonderland - Storybook Example Project
# A comprehensive demonstration of all Storybook language features
[project]
name = "alice-in-wonderland"
version = "1.0.0"
description = "Complete Alice in Wonderland narrative model showcasing advanced Storybook language features"
author = "Lewis Carroll (adapted)"
[paths]
schema = "schema"
world = "world"
[validation]
# Enable strict validation to catch errors
strict_mode = true
# Warn about unused declarations
warn_unused = true
# Require all cross-references to resolve
require_resolution = true

View File

@@ -1,169 +0,0 @@
//! Behavior trees for Wonderland characters
//!
//! v0.2.0: These are referenced by schedule blocks
// Queen's behaviors
behavior RuleWithTyranny {
repeat {
choose {
demand_impossible_task
shout_off_with_their_heads
criticize_garden_roses
inspect_card_soldiers
}
}
}
behavior CroquetAndExecutions {
then {
set_up_croquet_course
repeat {
choose {
play_croquet_round
order_execution
argue_with_everyone
}
}
}
}
behavior PlayCroquet {
repeat {
then {
grab_flamingo_mallet
aim_at_hedgehog
if(hedgehog_uncurls) {
swing_flamingo
}
argue_about_rules
}
}
}
// Mad Tea Party behaviors
behavior EndlessTeaParty {
repeat {
then {
pour_tea
ask_riddle
change_subject_nonsensically
if(no_clean_cups) {
move_to_next_seat
}
}
}
}
behavior MoveToNextSeat {
then {
stand_up
move_one_place_on
sit_down
continue_conversation_mid_sentence
}
}
// White Rabbit behaviors
behavior AlwaysLate {
repeat {
then {
check_pocket_watch
gasp_in_horror
run_frantically
drop_gloves
mutter_about_duchess
}
}
}
behavior CheckPocketWatch {
then {
pull_out_watch
squint_at_time
shake_watch
hold_to_ear
sigh_dramatically
}
}
// Caterpillar behaviors
behavior PhilosophizeOnMushroom {
repeat {
then {
smoke_hookah
if(someone_approaches) {
ask_who_are_you
}
make_cryptic_statement
look_contemptuous
}
}
}
// Cheshire Cat behaviors
behavior AppearAtRandom {
repeat {
choose {
fade_in_slowly
appear_in_tree
materialize_grin_first
then {
speak_enigmatically
vanish_gradually
}
}
}
}
behavior LeaveOnlyGrin {
then {
begin_fading
fade_body
fade_head
leave_grin_floating
eventually_fade_grin
}
}
// Court behaviors
behavior CourtDuties {
then {
attend_queen
avoid_execution
paint_roses_red
march_in_formation
}
}
// Alice's behaviors
behavior ExploreWonderland {
repeat {
choose {
then {
encounter_strange_character
ask_logical_question
receive_illogical_answer
be_confused
}
then {
find_food_or_drink
if(risky) {
eat_it_anyway
}
change_size_unexpectedly
}
try_to_recite_poetry_incorrectly
}
}
}
behavior TryToGetHome {
repeat {
then {
ask_for_directions
receive_confusing_directions
get_more_lost
sigh_about_missing_home
}
}
}

View File

@@ -1,115 +0,0 @@
//! Alice: The protagonist navigating Wonderland's absurdities
//! v0.2.0: Now includes behavior references for her exploration patterns
use schema::core_enums::{Size, EmotionalState};
use schema::templates::SizeChanging;
use schema::beings::Human;
character Alice: Human from SizeChanging {
uses behaviors: [
{ tree: ExploreWonderland },
{ tree: TryToGetHome }
]
// Core identity
age: 7
natural_size: normal
current_size: normal
min_size: tiny
max_size: huge
size_changes_today: 12
// Personality traits
emotional_state: curious
follows_logic: true
awareness_of_absurdity: 0.9
// Wonderland-specific state
knows_multiplication: false // Gets confused underground
can_recite_poetry_correctly: false // Always gets verses wrong
---backstory
A curious young girl who followed a White Rabbit down a hole and
found herself in a world where logic fails, size is mutable, and
everyone speaks in riddles and contradictions.
She tries to maintain her composure and Victorian manners even as
she shrinks to inches, grows to fill rooms, and encounters
impossible characters hosting impossible tea parties.
---
}
// Alice's transformative journey through Wonderland
life_arc AliceJourney {
---description
Tracks Alice's physical and emotional transformations as she
navigates Wonderland's surreal challenges. Each state represents
a key phase of her adventure.
---
state falling {
on enter {
Alice.current_size: normal
Alice.emotional_state: curious
}
---narrative
Tumbling down the rabbit hole, Alice has time to wonder about
geography, Dinah the cat, and whether she'll fall through to
the Antipodes. The fall seems endless.
---
}
state tiny_alice {
on enter {
Alice.current_size: tiny
Alice.emotional_state: frightened
Alice.size_changes_today: 13
}
---narrative
Only three inches tall, Alice can fit through the tiny door to
the garden but cannot reach the key on the glass table. She
finds herself crying a pool of tears.
---
}
state giant_alice {
on enter {
Alice.current_size: huge
Alice.emotional_state: confused
Alice.size_changes_today: 13
}
---narrative
Grown so large her head hits the ceiling, Alice floods the hall
with her tears. The White Rabbit mistakes her giant arm for a
monster and attempts to burn the house down.
---
}
state normal_alice_garden {
on enter {
Alice.current_size: normal
Alice.emotional_state: brave
}
---narrative
Finally the right size, Alice enters the beautiful garden and
encounters the Queen's croquet ground, where flamingos serve
as mallets and hedgehogs as balls.
---
}
state enlightened_alice {
on enter {
Alice.emotional_state: brave
Alice.awareness_of_absurdity: 1.0
}
---narrative
Having traversed the madness of Wonderland, Alice realizes
"you're nothing but a pack of cards!" Her awareness of the
absurdity grants her power over the dream.
---
}
}

View File

@@ -1,155 +0,0 @@
//! The Caterpillar: Philosophical advisor and size-change expert
use schema::core_enums::{Size, EmotionalState};
use schema::templates::Supernatural;
use schema::beings::Caterpillar;
character TheCaterpillar: Caterpillar from Supernatural {
// Physical traits
current_size: normal // Large for a caterpillar
color: blue
smoking_hookah: true
// Personality
emotional_state: melancholy
follows_logic: false
awareness_of_absurdity: 1.0
// Supernatural/philosophical nature
can_disappear: false
defies_physics: true // A smoking caterpillar defies biology
offers_cryptic_advice: true
// Communication style
speaks_in_short_questions: true
makes_alice_explain_herself: true
patient_with_confusion: false
// Size-change knowledge
knows_mushroom_properties: true
understanding_of_transformation: 1.0
---description
A large blue caterpillar sitting atop a mushroom, smoking
a hookah. Speaks in short, terse sentences, usually questions.
Forces Alice to confront her identity crisis through Socratic
method.
Knows which side of the mushroom makes you taller, which side
makes you shorter. This knowledge is crucial for Alice's ability
to control her size changes.
---
---philosophical_role
The Caterpillar represents transformation and the difficulty
of maintaining identity through change. He asks "Who are YOU?"
when Alice herself doesn't know anymore.
His own impending transformation (chrysalis → butterfly) mirrors
Alice's transformation through Wonderland. Both are changing,
both struggle with "who am I?"
---
}
behavior Caterpillar_SocraticMethod {
---description
The Caterpillar's interrogative conversation style. He asks
questions, contradicts answers, and forces self-examination.
---
then interrogation_sequence {
// Initial confrontation
then opening_question {
RemoveHookahFromMouth
StareInSilence
AskWhoAreYou
}
// Alice's confused response
then contradiction_cycle {
AliceExplainsShesChanged
Caterpillar_StatesDisagreement
AliceExplainsMore
Caterpillar_Contradicts
}
// Philosophical exchange
choose debate_topic {
// On change and identity
then identity_crisis {
AliceMentionsDifferentSizes
Caterpillar_DismissesComplaint
AliceSuggestsFutureChange
Caterpillar_ShowsIndifference
}
// On memory and self
then memory_test {
AskWhatAliceCantRemember
AliceRecitesPoem
RecitationIsWrong
CriticizeStrictly
}
}
// Eventual aid (after sufficient confusion)
then reluctant_guidance {
AskWhatSizeAliceWants
AliceExplainsPreference
OfferCrypticAdvice
NotSpecifyWhichSide
LeaveAliceToExperiment
}
// Transformation and departure
then exit {
CrawlDownMushroom
Vanish
}
}
}
behavior Caterpillar_MushroomAdvice {
---description
The Caterpillar's guidance about the size-changing mushroom.
Deliberately vague to force Alice to experiment and learn.
---
then cryptic_instruction {
// Verify Alice's distress about size
then assess_problem {
ObserveAliceHeight
AskIfContentNow
AliceExplainsDesireToBeNormal
}
// Offer cryptic instruction
then vague_direction {
Point AtMushroom
Say
PauseForEffect
Add
}
// Respond to clarification requests
choose handle_confusion {
then refuse_clarification {
AliceAsksWhichSide
Caterpillar_StatesObvious
RefuseToElaborate
}
then already_departed {
AliceLooksAtRoundMushroom
RealizesAmbiguity
Caterpillar_AlreadyGone
}
}
// Let Alice figure it out
then mysterious_exit {
CrawlAway
BeginTransformation
LeaveAliceWithPuzzle
}
}
}

View File

@@ -1,203 +0,0 @@
//! Cheshire Cat: The enigmatic guide with a permanent grin
use schema::core_enums::{Size, EmotionalState, ManifestationLevel};
use schema::templates::Supernatural;
use schema::beings::Cat;
character CheshireCat: Cat from Supernatural {
// Physical state
current_size: normal
manifestation: fully_visible
grin_visible: true
// Personality
emotional_state: amused
follows_logic: false
awareness_of_absurdity: 1.0
// Supernatural abilities
can_disappear: true
defies_physics: true
offers_cryptic_advice: true
// Cat traits
purrs: true
has_claws: true
lands_on_feet: true // Even when vanishing
---description
A large cat with a permanent, unsettling grin. Possesses the ability
to appear and disappear at will, often leaving only its grin behind.
Speaks in riddles and offers directions that confuse more than clarify.
Known for philosophical observations like "We're all mad here" and
"I'm not crazy, my reality is just different than yours."
---
---philosophy
The Cheshire Cat represents the absurdist nature of Wonderland itself.
His ability to vanish piece by piece (usually starting with the tail
and ending with the grin) defies physical law but seems perfectly
natural in Wonderland's logic.
He tells Alice that everyone in Wonderland is mad, including himself
and her. This is not a judgment but an observation: madness is the
natural state where logic has no power.
---
}
behavior CheshireCat_AppearDisappear {
---description
Complex behavior modeling the Cheshire Cat's gradual materialization
and dematerialization. Uses decorators to add timing and conditions.
---
// Root selector: decide action based on current state
choose state_dependent_action {
// If invisible, consider appearing
then appear_from_nothing {
IsInvisible
DecideToAppear
GradualManifestation
}
// If visible, might give advice or disappear
choose visible_options {
// Give cryptic advice
then confuse_alice {
IsFullyVisible
ObserveAliceConfusion
GrinWider
OfferUnhelpfulDirections
}
// Begin disappearing
then fade_away {
IsFullyVisible
DecideToLeave
GradualDematerialization
}
}
// If partial, continue transition
then continue_manifestation {
IsPartiallyManifest
ContinueTransition
}
}
}
behavior CheshireCat_GradualManifestation {
---description
Models the piece-by-piece appearance of the Cheshire Cat.
Always ends with the grin appearing last (or first).
---
then materialize_piece_by_piece {
// Start with grin (the signature move)
then grin_first {
SetManifestationLevelPartialGrin
WaitTwoSeconds
AliceNoticesGrin
}
// Eyes appear
then add_eyes {
AddEyes
SetManifestationLevelPartialBody
WaitOneAndHalfSeconds
}
// Head materializes around grin
then form_head {
AddHead
WaitOneSecond
}
// Full body appears
then complete_body {
AddBody
AddTail
SetManifestationLevelFullyVisible
GreetAlice
}
}
}
behavior CheshireCat_GradualDematerialization {
---description
Models the piece-by-piece disappearance. The grin lingers
"quite some time after the rest of it had gone."
---
then vanish_piece_by_piece {
// Tail vanishes first
then tail_first {
FadeTail
WaitOneSecond
}
// Body fades
then fade_body {
FadeBody
SetManifestationLevelPartialBody
WaitOneAndHalfSeconds
}
// Head disappears, leaving grin
then leave_grin_behind {
FadeHead
LeaveEyes
SetManifestationLevelPartialGrin
WaitTwoSeconds
AliceRemarksOnGrinWithoutCat
}
// Finally, grin vanishes
then grin_last {
FadeGrin
SetManifestationLevelInvisible
}
}
}
behavior CheshireCat_OfferAdvice {
---description
The Cat's advice-giving behavior: cryptic, circular, and often
more confusing than helpful.
---
choose cryptic_response {
// If asked for directions
then unhelpful_directions {
AliceAsksWhichWay
choose either_way_works {
then point_left {
PointLeft
SayDirections
}
then point_right {
PointRight
SayDirections
}
}
AddPhilosophically
GrinKnowingly
}
// If asked about the game
then mysterious_answer {
AliceAsksAboutCroquet
Say
WaitForResponse
VanishGradually
}
// General philosophical musing
then unsolicited_wisdom {
ObserveAlicesSituation
OfferUnsolicitedWisdom
VanishBeforeExplanation
}
}
}

View File

@@ -1,287 +0,0 @@
//! The Mad Tea Party trio: stuck in eternal teatime
use schema::core_enums::{Size, EmotionalState, TimeState};
use schema::templates::MadTeaPartyMember;
use schema::beings::{Human, Hare, Dormouse};
character MadHatter: Human from MadTeaPartyMember {
// Physical traits
current_size: normal
wears_top_hat: true
hat_size_label: "10/6" // Price tag still attached
// Personality
emotional_state: confused
follows_logic: false
awareness_of_absurdity: 0.1 // Unaware of his own madness
// Tea party state
stuck_at_teatime: true
current_seat_position: 1
riddles_asked: 847
unanswerable_riddles: 847 // All of them
// Time relationship
quarreled_with_time: true
murdered_time: true // According to Time
time_frozen_at: 18:00 // 6 o'clock, always
---backstory
Once sang at a concert for the Queen of Hearts. Accused of
"murdering the time" for his poor performance of "Twinkle,
twinkle, little bat." As punishment, Time refuses to move
for him - it's always six o'clock, always tea-time.
Now stuck rotating around a table with the March Hare and
Dormouse, moving to the next seat as dishes get dirty,
asking riddles with no answers.
---
}
character MarchHare: Hare from MadTeaPartyMember {
// Physical traits
current_size: normal
whiskers_twitching: true
// Personality
emotional_state: amused
follows_logic: false
awareness_of_absurdity: 0.05
// Tea party state
stuck_at_teatime: true
current_seat_position: 2
riddles_asked: 723
// March madness (breeding season)
madness_level: 1.0 // It's always March for him too
offers_nonexistent_wine: true
---backstory
Partner in madness with the Hatter. The March Hare embodies
the saying "mad as a March hare" - the wild behavior of
hares during breeding season.
Delights in contradiction: offering wine when there's only
tea, claiming things are "the same" when they're opposite,
dipping watches in tea to fix them with "the best butter."
---
}
character TheDormouse: Dormouse from MadTeaPartyMember {
// Physical traits
current_size: tiny
currently_sleeping: true
// Personality
emotional_state: melancholy
follows_logic: true // When awake, which is rare
awareness_of_absurdity: 0.6
// Tea party state
stuck_at_teatime: true
current_seat_position: 0 // Between Hatter and March Hare
riddles_asked: 3
// Sleep patterns
sleep_cycles_per_hour: 12
used_as_cushion: true
pinched_to_wake: 15..100 // Times per tea party
---backstory
A chronically sleepy dormouse who serves as a cushion
between the Hatter and March Hare. They rest their elbows
on him and talk over his head.
Occasionally rouses to tell meandering stories about three
sisters living in a treacle well, drawing all manner of
things beginning with M - mousetraps, the moon, memory,
and muchness.
---
---notable_quote
"I breathe when I sleep is the same thing as I sleep when
I breathe!" - said in his sleep, demonstrating the circular
logic of the tea party even while unconscious.
---
}
// The eternal tea party schedule - always 6 o'clock
schedule MadTeaPartyRotation {
---description
Models the endless, circular nature of the Mad Tea Party.
Because time is frozen at 6 o'clock (tea-time), they never
wash dishes - instead they rotate around the table as each
seat's dishes get dirty.
---
18:00 -> 18:01: TeaRound {
---narrative
Begin a new rotation. All participants have tea, ask
riddles, and engage in nonsensical conversation.
The Dormouse starts awake, attempts to contribute,
then falls asleep again mid-sentence.
---
}
18:01 -> 18:02: RiddlePhase {
---narrative
The Hatter asks "Why is a raven like a writing-desk?"
Alice attempts to solve it. The Hatter admits he doesn't
know the answer. No one knows the answer. There is no
answer. This is the point.
---
}
18:02 -> 18:03: ContradictionPhase {
---narrative
March Hare contradicts Alice: "You should say what you mean."
Alice: "I do!"
Hatter: "Not the same thing a bit! 'I see what I eat' vs
'I eat what I see'!"
The logic spirals into beautiful nonsense.
---
}
18:03 -> 18:04: DormouseStory {
---narrative
They pinch the Dormouse awake. He tells a drowsy story
about three sisters living in a treacle-well, drawing
treacle, drawing things that begin with M.
The story makes no sense but continues anyway.
---
}
18:04 -> 18:05: RotateSeats {
---narrative
"Move down!" The dirty dishes pile up. Everyone shifts
to the next seat clockwise around the table.
This is their solution to never washing dishes: infinite
table, infinite seats, infinite tea-time.
---
}
18:05 -> 18:06: LoopToBeginning {
---narrative
Time hasn't moved. It's still 6 o'clock. It's always
6 o'clock. The party begins again, identical to the last,
identical to the next.
The Dormouse is asleep. The Hatter checks his broken watch.
The March Hare offers wine that doesn't exist.
Forever.
---
}
}
behavior MadTeaParty_CoordinatedMadness {
---description
Models the three-way coordination of the Mad Tea Party members.
They interrupt each other, build on each other's nonsense,
and create a cascade of illogic.
---
then setup_and_loop {
// Initialization: Set up eternal tea time
then initialize {
SetTimeStateFrozen
SetCurrentTimeToSix
VerifyTimeStillSix
}
// Main party loop (runs forever)
repeat {
then {
// Selector: Choose a mad activity
choose mad_activity {
// Riddle sequence
then riddles {
MadHatter_AskRiddle
AliceAttemptsSolution
MadHatter_AdmitsNoAnswer
MarchHare_ChangesSubject
}
// Contradition game
then contradictions {
AliceMakesStatement
MarchHare_ContradictLogic
MadHatter_BuildsOnContradiction
Dormouse_MuttersInSleep
}
// Story time
then story_time {
PinchDormouse
Dormouse_WakesGroggily
Dormouse_BeginsMeanderingStory
Dormouse_FallsAsleepMidWord
}
// Butter the watch
then butter_watch {
MadHatter_ChecksBrokenWatch
MarchHare_OffersButterAsRepair
DipWatchInTea
ExamineWatchHopefully
DeclareItStillBroken
}
// Seat rotation
then seat_rotation {
DeclareNoRoom
ShiftSeatsClockwise
IncrementSeatPositions
}
}
// Always end by verifying time hasn't moved
then verify_time {
CheckTime
ConfirmStillSixOClock
SighPhilosophically
}
}
}
}
}
behavior Dormouse_SleepCycle {
---description
Models the Dormouse's constant oscillation between sleep
and brief, drowsy wakefulness. Uses a repeater decorator.
---
repeat {
then {
then sleep_phase {
FallAsleep
BeUsedAsCushion
WaitForPinch
}
then wake_phase {
WakeWithStart
MutterConfusedly
choose response {
then tell_story {
BeginStory
DescribeTheirNames
ExplainTreacleWell
FallAsleepMidSentence
}
then mutter {
MakeCircularStatement
CloseEyesAgain
}
}
}
}
}
}

View File

@@ -1,318 +0,0 @@
//! The Royal Court of Hearts: tyrannical hierarchy
use schema::core_enums::{Size, EmotionalState, CardSuit, CardRank};
use schema::templates::{PlayingCard, CourtMember};
use schema::beings::PlayingCardPerson;
character QueenOfHearts: PlayingCardPerson from PlayingCard, CourtMember {
// Card identity
suit: hearts
rank: queen
current_size: normal
fear_of_queen: 0.0 // She IS the Queen
// Personality
emotional_state: angry
follows_logic: false
awareness_of_absurdity: 0.0
// Royal traits
loyalty_to_queen: 1.0 // To herself
times_threatened_with_beheading: 0 // She's the one doing the threatening
survival_instinct: 0.1 // Reckless with her own safety
// Tyrannical nature
temper: 1.0
mercy: 0.0
subjects_beheaded_today: 47 // So far today
off_with_their_heads_count: 347 // Total for today
// Game preferences
cheats_at_croquet: true
patience_for_rules: 0.0
---description
The terrifying matriarch of Wonderland's Court of Hearts. Quick
to rage, quicker to order executions. Her signature phrase
"Off with their heads!" rings out constantly across the croquet
grounds and palace halls.
Plays croquet with live flamingos and hedgehogs, cheats brazenly,
and flies into a fury when contradicted or when anyone wins.
---
---psychological_profile
The Queen represents arbitrary authority and irrational rage.
She sees slights everywhere, interprets everything as disrespect,
and her solution to all problems is immediate execution.
Notably, while she orders constant beheadings, the King quietly
pardons everyone afterward. The Queen never notices this
undermining of her authority.
---
}
character KingOfHearts: PlayingCardPerson from PlayingCard, CourtMember {
// Card identity
suit: hearts
rank: king
current_size: small // Shorter than the Queen
fear_of_queen: 0.95 // Terrified but hides it well
// Personality
emotional_state: frightened
follows_logic: true
awareness_of_absurdity: 0.7
// Royal traits
loyalty_to_queen: 1.0 // Out of fear
times_threatened_with_beheading: 156 // Even kings aren't safe
survival_instinct: 1.0
// Peacemaking nature
mercy: 1.0
secretly_pardons_everyone: true
attempts_to_calm_queen: true
---description
The meek and mild King of Hearts, thoroughly dominated by
his wife. He attempts to moderate her rage with whispered
pleas like "Consider, my dear: she is only a child!"
Serves as judge at the trial, but his authority is purely
nominal. Secretly pardons all the Queen's execution orders,
which is how anyone survives in Wonderland.
---
}
character CardGardenerTwo: PlayingCardPerson from PlayingCard {
suit: spades
rank: two
current_size: normal
emotional_state: frightened
fear_of_queen: 1.0
follows_logic: true
awareness_of_absurdity: 0.8
// Gardener traits
currently_painting_roses: true
roses_painted_white_to_red: 247 // About halfway done
mistakes_admitted: 1 // The white rose tree
---description
One of three card gardeners (Two, Five, Seven) caught painting
white roses red. They planted a white rose tree by mistake
when the Queen wanted red. Now desperately painting before
she arrives, knowing the penalty is beheading.
---
}
character CardGardenerFive: PlayingCardPerson from PlayingCard {
suit: spades
rank: five
current_size: normal
emotional_state: angry
fear_of_queen: 1.0
follows_logic: true
awareness_of_absurdity: 0.8
currently_painting_roses: true
quick_to_blame_others: true
splashed_by_seven: true
---description
The irritable middle gardener who gets splashed with paint
and immediately blames Seven. More concerned with assigning
fault than finishing the job before the Queen arrives.
---
}
character CardGardenerSeven: PlayingCardPerson from PlayingCard {
suit: spades
rank: seven
current_size: normal
emotional_state: angry
fear_of_queen: 1.0
follows_logic: true
awareness_of_absurdity: 0.8
currently_painting_roses: true
accused_of_bringing_tulip_roots: true
elbow_jogged_five: true
---description
The gardener blamed for both jogging Five's elbow and for
bringing the cook tulip-roots instead of onions. Accused
of all manner of things, deserves beheading according to
the Queen.
---
}
behavior QueenOfHearts_RagePattern {
---description
Models the Queen's hair-trigger temper and constant execution
orders. Any perceived slight triggers the same response.
Uses a selector to try different rage escalations, all ending
in "Off with their heads!"
---
// Repeats forever - the Queen never runs out of rage
repeat {
then rage_cycle {
// Wait for any stimulus
WaitForInteraction
// Selector: Interpret stimulus as offense
choose perceived_offense {
// Minor perceived slight
then minor_slight {
DetectMinorIrregularity
TurnCrimson
Glare
Scream
StompFoot
}
// Someone wins at croquet
then croquet_outrage {
ObserveSomeoneScoring
DeclareCheating
Rage
OrderExecution
}
// Anyone speaks back
then contradiction_fury {
HearContradiction
TurnPurpleWithFury
Shriek
TurnToKing
DemandAgreement
}
// Painted roses discovered
then painting_discovery {
NoticePaintBrushes
DemandExplanation
InterruptExplanation
OrderImmediateBeheading
}
// Default: random rage
then irrational_anger {
FeelIrrationalAnger
LookForTarget
FindTarget
ScreamOffWithTheirHeads
}
}
// King attempts to moderate
choose king_intervention {
then whispered_plea {
King_WhispersPleas
Queen_IgnoresEntirely
}
then reminder_backfires {
King_RemindsOfMercy
Queen_GlaresAtKing
ConsiderBeheadingKingToo
}
}
// Execution order given (but secretly pardoned later)
then execution_ordered {
IncrementBeheadingCount
SoldiersLookUncertain
VictimPleadsOrFlees
}
}
}
}
behavior CardGardeners_DesperatePainting {
---description
Three gardeners frantically painting white roses red before
the Queen discovers their mistake. Models coordinated panic.
---
then desperate_work {
// Initial panic
then assessment {
CheckQueensPosition
EstimateTimeRemaining
PaintFaster
}
// Coordination breaks down under stress - repeat until Queen arrives
repeat {
choose panic_actions {
// Blame game
then argument {
Five_GetsSplashed
Five_BlameSeven
Seven_DefendsHimself
Two_AttemptsMediation
AllArgumentInterrupted
}
// Desperate painting
then frantic_painting {
Two_PaintsRose
Five_PaintsRose
Seven_PaintsRose
}
// Discovery and panic
then discovery {
HearQueensProcession
Five_Shouts
AllThrowThemselvesFlat
AwaitFate
}
}
}
}
}
behavior KingOfHearts_SecretPardons {
---description
The King's quiet subversion of the Queen's execution orders.
Runs in background after each of her rage episodes.
---
// Repeats forever - the King never stops being merciful
repeat {
then mercy_cycle {
// Wait for Queen's execution order
WaitForOffWithTheirHeads
// Let some time pass
WaitThirtySeconds
// Secretly pardon
choose pardon_method {
then whispered_pardon {
QueenIsDistracted
QuietlyApproachSoldiers
WhisperPardon
SoldiersNodRelief
VictimQuietlyEscapes
}
then written_pardon {
WritePardonOrder
SlipItToKnave
KnaveDeliversMercy
EveryonePretendExecutionHappened
}
}
// This is how anyone survives in Wonderland
DecrementActualBeheadingCount
}
}
}

View File

@@ -1,75 +0,0 @@
//! White Rabbit: The anxious herald of Wonderland
use schema::core_enums::{Size, EmotionalState};
use schema::templates::{WonderlandCreature, CourtMember};
use schema::beings::Rabbit;
character WhiteRabbit: Rabbit from WonderlandCreature, CourtMember {
// Physical traits
current_size: small
wears_waistcoat: true
has_pocket_watch: true
// Personality
emotional_state: frightened
follows_logic: true
awareness_of_absurdity: 0.3
// Court relations
loyalty_to_queen: 0.95
times_threatened_with_beheading: 47
survival_instinct: 1.0
// Time obsession
minutes_late: 2..1000 // Always perceives himself as late
watch_checks_per_hour: 30
---appearance
A white rabbit with pink eyes, dressed in a waistcoat with a
watch-pocket. Constantly glances at his pocket watch while
muttering "Oh dear! Oh dear! I shall be too late!"
---
}
behavior WhiteRabbit_ConstantlyLate {
---description
Models the White Rabbit's perpetual anxiety about time and
his duties to the Queen. Uses a selector to try multiple
panic responses.
---
// Top-level selector: try different panic strategies
choose panic_response {
// Sequence: Check time, panic, flee
then check_time {
CheckPocketWatch
RealizeHowLate
MutterAnxiously
ScurryToDestination
}
// Sequence: Encounter obstacle, panic more
then obstacle_panic {
EncounterObstacle
DropGloves
DropFan
PanicFurther
ReverseDirection
}
// Sequence: See Queen, extreme panic
then queen_panic {
SpotQueen
FlattenEarsInFear
TremblingBow
AwaitCommands
}
// Fallback: Just keep running
then default_panic {
CheckWatch
RunInCircles
CheckWatchAgain
}
}
}

View File

@@ -1,169 +0,0 @@
use schema::core_enums::{
GovernmentType, GovernmentStyle, HierarchyStyle,
Temperament, Power, JudicialPresumption, Sentence,
GatheringType, Purpose, SeatRotation, Enforcement
};
institution CourtOfHearts {
type: monarchy
government_style: absolute_tyranny
hierarchy: rigid
rule_of_law: false
// Leadership
monarch: QueenOfHearts
consort: KingOfHearts
monarch_temperament: volatile
actual_power: queen_only
// Court composition
soldiers: 10 // Clubs
courtiers: 10 // Diamonds
royal_children: 10 // Hearts
gardeners: 3 // Spades
executioner: 1 // Rarely needed, thanks to King's pardons
// Judicial system
trial_procedure: "sentence first, verdict afterwards"
presumption: "guilt"
most_common_sentence: "beheading"
actual_executions: 0 // King pardons everyone
// Cultural norms
bowing_required: true
contradiction_forbidden: true
winning_at_games_forbidden: true // Only Queen may win
---description
The tyrannical monarchy ruling Wonderland. Led by the Queen
of Hearts, whose primary form of governance is shouting
"Off with their heads!" at any perceived slight.
The King serves as a moderating force, quietly pardoning those
the Queen condemns. This creates a strange equilibrium: the Queen
maintains authority through terror, but no one actually dies.
---
---power_structure
Nominal Structure:
Queen (absolute power)
├─ King (theoretical co-ruler)
├─ Knave (herald, blamed for tart theft)
├─ Soldiers (enforcers)
├─ Courtiers (advisors, sycophants)
└─ Gardeners (groundskeepers)
Actual Power Flow:
Queen (rage and threats)
└─ King (secret pardons, actual mercy)
The entire institution runs on the contradiction between
apparent severity and actual leniency.
---
}
institution MadTeaParty {
type: eternal_social_gathering
purpose: tea_consumption
stuck_in_time: true
time_frozen_at: 18:00
// Members
permanent_members: 3
temporary_visitors: 0..5 // Like Alice
member_sanity: 0.0
// Rules (such as they are)
logic_required: false
personal_remarks: encouraged
riddles_must_have_answers: false
changing_seats_mandatory: true
wine_offering_despite_absence: true
// Temporal properties
can_wash_dishes: false // No time between teas
solution_to_dirty_dishes: rotation
---description
An eternal tea party hosted by the Mad Hatter and March Hare,
with the Dormouse as perpetual cushion. Stuck in a time loop
at 6 o'clock because the Hatter offended Time itself.
The party follows the logic of madness: riddles have no answers,
wine is offered but doesn't exist, personal remarks are standard,
and when dishes get dirty, they simply move to the next seat
around the infinite table.
---
---social_dynamics
The Hatter and March Hare function as a unit of coordinated
madness, building on each other's nonsense. They speak in
contradictions and circular arguments.
The Dormouse serves both as furniture (cushion) and occasional
entertainment (drowsy stories). He's simultaneously part of
the institution and subjected to it (pinched, used as pillow,
tea poured on his nose).
Visitors like Alice are immediately drawn into the madness,
forced to participate in unanswerable riddles and illogical
debates. Escape is possible only by declaring "I'll never come
here again! It's the stupidest tea-party I ever was at!"
---
}
institution WonderlandDreamLogic {
type: fundamental_reality_framework
governs: "all of Wonderland"
consistency: none
predictability: zero
// Physical laws
gravity: negotiable
size: mutable
time: optional
causality: reversed // Effect before cause is common
// Social laws
hierarchy: based_on_volume // Loudest voice wins
authority: arbitrary
punishment: threatened_constantly_executed_never
madness: mandatory
// Linguistic laws
words_mean: "what I choose them to mean"
statements: often_self_contradicting
questions: frequently_unanswerable
logic: deliberately_violated
---description
The overarching "institution" of Wonderland itself - the dream
logic that governs every interaction and event. This is not an
organization but the fundamental rule system (or lack thereof)
of the world.
In Wonderland:
- Size changes based on food and drink
- Time can be quarreled with and stopped
- Cats can vanish, leaving only grins
- Tea parties last forever
- Playing cards serve as people
- Executions are ordered but never happen
- Caucus races have no winners (everyone wins)
---
---philosophical_foundation
Wonderland operates on dream logic, which is to say: the logic
of the unconscious mind, where contradictions coexist, authority
is absurd, and rules change moment to moment.
Alice's attempts to apply normal-world logic fail constantly.
Her lessons in mathematics don't work underground. Her recitation
of poems comes out wrong. Her Victorian manners are useless against
the Queen's rage.
The only way to survive Wonderland is to either embrace the
madness (like the Hatter) or maintain a core of sanity while
surfing the absurdity (like Alice eventually learns).
---
}

View File

@@ -1,227 +0,0 @@
//! Locations in Wonderland: surreal geography
use schema::core_enums::TimeState;
location RabbitHole {
depth: 1000..4000 // Miles deep, or so Alice calculates
falls_like: tunnel
lined_with: ["cupboards", "bookshelves", "maps", "pictures"]
contains_marmalade_jar: true
jar_is_empty: true
---description
A deep hole under a hedge, leading straight down like a well.
The fall is impossibly long, giving Alice time to wonder about
geography, talk to herself about Dinah the cat, and examine
the curious furnishings along the walls.
She falls so slowly (or the hole is so deep) that she has time
to take a jar labeled "ORANGE MARMALADE" from a shelf, discover
it empty, and replace it in a cupboard further down.
---
---physical_properties
Defies normal physics. The fall should be fatal but Alice lands
gently on sticks and dry leaves. The sides are inexplicably
furnished like a house. The depth is impossible.
This is the threshold between normal world and Wonderland -
logic breaks down in the tunnel itself.
---
}
location HallOfDoors {
shape: "long and low"
lit_by: "lamps hanging from roof"
number_of_doors: 20..50
all_locked: true
// The tiny door
has_tiny_door: true
tiny_door_height_inches: 15
tiny_door_leads_to: garden
// The glass table
has_glass_table: true
table_legs: 3
golden_key_on_table: true
bottle_appears_spontaneously: true
---description
A long, low hall with doors all around. All doors are locked.
Alice tries every one, walking down one side and up the other
in sadness and frustration.
A three-legged glass table holds a tiny golden key. After much
searching, Alice finds it unlocks a curtain-concealed door only
fifteen inches high. Through it, she glimpses the beautiful
garden she longs to reach.
---
}
location Garden {
beauty_level: 1.0
has_rose_trees: true
roses_should_be: red
roses_actually_are: white // Being hastily painted
has_croquet_ground: true
// Garden features
has_fountains: true
has_flower_beds: true
desirability_to_alice: 1.0
// Transformation site
where_alice_becomes_normal_size: true
---description
The lovely garden Alice glimpses through the tiny door. Filled
with bright flowers and cool fountains. Represents normalcy
and beauty in contrast to Wonderland's chaos.
Contains the Queen's croquet ground, where the beauty quickly
gives way to tyranny and absurdity as flamingos serve as
mallets and hedgehogs as balls.
---
---symbolism
The garden represents Alice's desire for order and sense.
She spends much of the early story trying to reach it,
shrinking and growing to fit through the door.
When she finally arrives, it's less paradise than she imagined -
the Queen's mad croquet game and constant execution threats
make it as chaotic as everywhere else in Wonderland.
---
}
location MadTeaPartyTable {
time_state: frozen
current_time: 18:00 // Always 6 o'clock
size: very_large
seats_occupied: 3
seats_available: 97..997
// Table state
covered_in_dirty_dishes: true
never_washed: true
rotation_direction: clockwise
// Refreshments
has_tea: true
has_wine: false // Despite March Hare's offers
has_butter: true // For watch repairs
has_bread_knife: true // To spread butter
---description
A large table set out under a tree in front of a house. Three
participants (Hatter, March Hare, Dormouse) crowd into one corner
despite abundant space.
Because Time refuses to move past six o'clock, it's always tea-time.
They never have time to wash dishes, so they rotate around the
table to clean seats as the previous ones get dirty.
---
---temporal_paradox
The table exists in a time loop. The same conversations happen
repeatedly. The same riddles are asked. The same butter is used
on the same watch.
"Suppose we change the subject" is said eternally, but the subject
never truly changes. The Dormouse tells the same story about the
treacle well forever.
---
}
location CroquetGround {
belongs_to: queen_of_hearts
terrain: "all ridges and furrows"
game_in_progress: true
rules_exist: false
// Live equipment
mallets_are: flamingos
balls_are: hedgehogs
arches_are: card_soldiers
// Game state
players_play_simultaneously: true
cheating_allowed: true // For Queen only
queen_always_wins: true
---description
The Queen's croquet ground, where the game is pure chaos.
Live flamingos serve as mallets but twist around to look at
players. Live hedgehogs serve as balls but unroll and crawl away.
Soldiers bend to form arches but walk off to other parts of the
ground.
All players play at once without waiting turns, quarreling and
fighting for hedgehogs. The Queen goes stamping about shouting
"Off with their heads!" every minute.
---
---game_theory
The game has no rules, or rather, the only rule is that the
Queen wins. The equipment is deliberately uncooperative. The
terrain is maximally difficult. Victory is impossible.
This is Wonderland's version of sport: a perfectly designed
system for generating frustration, with arbitrary authority
(the Queen) as the only arbiter.
---
}
location QueensPalace {
architectural_style: "playing card"
inhabitants: card_people
staff: ["soldiers", "courtiers", "gardeners", "cooks"]
// Court features
has_throne_room: true
has_croquet_ground: true
has_kitchens: true // Where Duchess's cook adds too much pepper
// Justice system
has_courtroom: true
presumption_of_innocence: false
sentence_before_verdict: true // "Sentence first! Verdict afterwards!"
---description
The palace of the King and Queen of Hearts. Everything is
decorated with hearts. Inhabitants are all playing cards -
soldiers (clubs), courtiers (diamonds), royalty (hearts).
The court system operates on Wonderland logic: sentences are
pronounced before verdicts, evidence is nonsensical, and the
Queen shouts for executions regardless of guilt or innocence.
---
}
location MushroomTop {
height_above_ground: 4..5 // Feet
diameter: 2..3 // Feet
mushroom_color: white_with_spots
inhabited_by: caterpillar
// Size-changing properties
one_side_makes_taller: true
other_side_makes_shorter: true
which_is_which: ambiguous // Round mushroom has no clear "sides"
// Atmosphere
hookah_smoke_present: true
philosophical_discussions: true
---description
The top of a large mushroom where the Caterpillar sits smoking
a hookah. About the same height as Alice (when she's normal-sized,
which is rare).
The mushroom has magical properties: one side makes you grow,
the other makes you shrink. Alice must figure out which is which
through dangerous experimentation, resulting in her neck growing
like a serpent at one point.
---
}

View File

@@ -1,278 +0,0 @@
//! Relationships in Wonderland: connections and dynamics
use schema::core_enums::EmotionalState;
// Alice's pursuit of the White Rabbit - what draws her into Wonderland
relationship AliceAndWhiteRabbit {
Alice {
// Alice's perspective
role: pursuer
motivation: curiosity
emotional_investment: 0.7
understands_other: false
---perspective
Alice follows the White Rabbit out of pure curiosity. "How
remarkable!" she thinks when he checks his watch. The Rabbit
represents the mystery of Wonderland - always rushing ahead,
never looking back, leading her deeper into strangeness.
---
}
WhiteRabbit {
// White Rabbit's perspective
role: unwitting_guide
motivation: avoid_being_late
emotional_investment: 0.0
aware_of_alice: false // Too preoccupied
---perspective
The White Rabbit barely notices Alice exists. He's consumed
by his own anxiety about being late for the Duchess, then
the Queen. Alice is just another obstacle between him and
punctuality.
---
}
}
// Alice and the Cheshire Cat - mysterious guide and confused visitor
relationship AliceAndCheshireCat {
Alice {
// Alice's perspective
role: seeker_of_guidance
emotional_state: confused
trusts_cat: 0.5 // Somewhat unsettling but helpful
---perspective
Alice finds the Cat both helpful and disturbing. He offers
directions (though everyone he points to is mad), listens
to her complaints about the croquet game, and provides the
philosophical framework "we're all mad here."
His disappearing act is unnerving but she's glad to have
someone to talk to who doesn't threaten her with beheading.
---
}
CheshireCat {
// Cheshire Cat's perspective
role: amused_observer
emotional_state: amused
helps_because: entertainment
---perspective
The Cat finds Alice endlessly entertaining. She's trying
to apply logic to Wonderland, which is inherently funny.
He helps her just enough to keep the show going, offering
directions that aren't wrong but aren't particularly helpful.
"We're all mad here. I'm mad. You're mad." This is both
warning and welcome. He's inviting her to accept the
absurdity.
---
}
bond: 0.6
}
// The Mad Hatter and March Hare - partners in madness
relationship HatterAndHare {
MadHatter {
// Hatter's perspective
role: co_conspirator
coordination: 1.0
builds_on_others_nonsense: true
---perspective
The Hatter and March Hare think as one unit of madness.
When one makes a nonsensical statement, the other builds
on it. They finish each other's contradictions. They
coordinate their assaults on logic.
"You might just as well say 'I see what I eat' is the
same as 'I eat what I see'!" - this kind of parallel
construction shows their synchronized absurdity.
---
}
MarchHare {
// March Hare's perspective (same as Hatter's - they're unified)
role: co_conspirator
coordination: 1.0
builds_on_others_nonsense: true
---perspective
From the March Hare's side, it's identical. They're two
halves of the same mad whole. Where one leads in nonsense,
the other follows. Together they create an impenetrable
wall of illogic.
The Dormouse serves as their shared cushion and occasional
entertainment, but the true relationship is between the
two perpetrators of madness.
---
}
bond: 0.95 // Deep partnership
}
// The Queen and King - tyranny and secret rebellion
relationship QueenAndKing {
QueenOfHearts {
// Queen's perspective
role: dominant_spouse
aware_of_pardons: false // Completely oblivious
expects: total_obedience
---perspective
The Queen views the King as a minor annoyance who occasionally
needs to be threatened. She expects him to agree with her
rage, support her execution orders, and generally stay out
of her way.
She has no idea he undermines every execution order. Her
blindness to his quiet rebellion is the only thing that
keeps the marriage (and Wonderland) functioning.
---
}
KingOfHearts {
// King's perspective
role: secret_moderator
loves_queen: 0.3
fears_queen: 0.9
subverts_authority: 1.0
---perspective
The King lives in constant fear but maintains his rebellion
through whispered pardons. "Consider, my dear: she is only
a child!" - these timid pleas fall on deaf ears.
His real power is exercised in secret: pardoning those the
Queen condemns, preventing the executions she orders. He's
the true ruler of Wonderland, governing through mercy while
she rages in impotent fury.
---
}
bond: 0.4 // Marriage held together by fear and secret subversion
}
// Alice and the Caterpillar - student and philosophical teacher
relationship AliceAndCaterpillar {
Alice {
// Alice's perspective
role: confused_student
emotional_state: frustrated
seeking: answers_about_size
---perspective
Alice finds the Caterpillar incredibly frustrating. He asks
"Who are YOU?" when she's having an identity crisis. He
contradicts everything she says. He refuses to elaborate
on his cryptic advice about the mushroom.
Yet he ultimately helps her gain control over her size
changes, providing the knowledge she needs even if his
manner is infuriating.
---
}
Caterpillar {
// Caterpillar's perspective
role: socratic_teacher
emotional_state: melancholy
teaching_method: contradiction
---perspective
The Caterpillar forces Alice to confront her confusion
through questioning. "Who are YOU?" is not rhetorical -
he's making her face the fact that she doesn't know.
His advice about the mushroom is deliberately incomplete.
She must experiment, fail, grow too large, shrink too
small, before mastering the technique. This is teaching
through experience, not explanation.
---
}
bond: 0.5
}
// Card Gardeners - fearful colleagues
relationship GardenersFearfulColleagues {
CardGardenerTwo {
// Two's perspective
role: mediator
tries_to_calm: true
explains_mistake: true
---perspective
Two attempts to maintain focus on the task: paint the
roses before the Queen arrives. When Five and Seven argue,
he tries to mediate. When Alice asks questions, he explains
their predicament honestly.
He's the voice of desperate pragmatism in a hopeless situation.
---
}
CardGardenerFive {
// Five's perspective
role: blame_assigner
gets_splashed: true
quick_to_anger: true
---perspective
Five is more concerned with who's at fault than with solving
the problem. When paint splashes him, he immediately blames
Seven. This finger-pointing wastes precious time but feels
necessary to his sense of justice.
His anger is fear displaced - they're all about to be
beheaded, so at least someone should be blamed properly.
---
}
bond: 0.6
}
// The Dormouse and the Tea Party hosts - cushion and tormentors
relationship DormouseAndHosts {
TheDormouse {
// Dormouse's perspective
role: unwilling_participant
would_rather: sleep
stories_interrupted: always
---perspective
The Dormouse just wants to sleep. He's pinched awake,
used as a cushion, has tea poured on his nose, and whenever
he starts a story, he's interrupted or falls asleep mid-sentence.
His relationship with the Hatter and March Hare is one of
resigned tolerance. They're his tormentors but also his
companions in the eternal tea party. He can't escape, so
he sleeps.
---
}
MadHatter {
// Hatter's perspective (and March Hare's - they treat Dormouse identically)
role: user_of_furniture
values_dormouse_as: cushion_and_entertainment
consideration: minimal
---perspective
To the Hatter and March Hare, the Dormouse is both furniture
and occasional diversion. They rest their elbows on him
without thinking. They wake him when they want a story,
then ignore him mid-tale.
There's no malice, just complete disregard for his comfort.
This is how the mad treat the merely sleepy.
---
}
bond: 0.4
}

View File

@@ -1,89 +0,0 @@
//! Schedules for Wonderland characters
//!
//! v0.2.0 upgrade: Adding year-long schedule composition features
//! - Schedule inheritance and composition
//! - Behavior tree references
//! - Recurrence patterns for special events
// Base schedule for court members
schedule CourtSchedule {
block morning_duties { 08:00 -> 12:00, action: CourtDuties }
block lunch { 12:00 -> 13:00, action: Eating }
block afternoon_duties { 13:00 -> 17:00, action: CourtDuties }
block evening_rest { 18:00 -> 22:00, action: Resting }
}
// Queen's schedule (extends court schedule with special blocks)
schedule QueenSchedule extends CourtSchedule {
override morning_duties {
08:00 -> 12:00
action: RuleWithTyranny
mood: "imperious"
}
override afternoon_duties {
13:00 -> 17:00
action: CroquetAndExecutions
}
// Croquet games on specific days
recurrence CroquetDay on Thursday {
block croquet {
14:00 -> 17:00
action: PlayCroquet
mallets: "flamingos"
balls: "hedgehogs"
}
}
}
// Mad Tea Party schedule (perpetually stuck at tea time)
schedule TeaPartySchedule {
block eternal_teatime {
18:00 -> 18:01
action: EndlessTeaParty
time_moves: false
}
recurrence MoveChairs on Daily {
block chair_rotation {
18:00 -> 18:00
action: MoveToNextSeat
}
}
}
// White Rabbit's frantic schedule
schedule RabbitSchedule {
block panic_mode {
00:00 -> 23:59
action: AlwaysLate
anxiety: "extreme"
}
recurrence ImportantDate on FirstOfMonth {
block extra_panic {
06:00 -> 06:30
action: CheckPocketWatch
repetitions: 1000
}
}
}
// Caterpillar's leisurely schedule
schedule CaterpillarSchedule {
block smoke_hookah { 10:00 -> 16:00, action: PhilosophizeOnMushroom }
block metamorphosis_rest { 16:00 -> 23:59, action: Sleeping }
}
// Cheshire Cat's schedule (mostly appearing and disappearing)
schedule CheshireSchedule {
block appear { 00:00 -> 23:59, action: AppearAtRandom }
recurrence GrinningTime on Daily {
block extra_grin {
12:00 -> 12:01
action: LeaveOnlyGrin
}
}
}

View File

@@ -1,36 +0,0 @@
#!/bin/bash
# Script to install the Storybook extension for Zed (development mode)
set -e
echo "Installing Storybook extension for Zed..."
# Get the absolute path to the extension directory
EXTENSION_DIR="$(cd "$(dirname "$0")/zed-storybook" && pwd)"
# Create Zed extensions directory if it doesn't exist
mkdir -p ~/.local/share/zed/extensions/installed
# Create symlink
LINK_PATH=~/.local/share/zed/extensions/installed/storybook
if [ -L "$LINK_PATH" ]; then
echo "Removing existing symlink..."
rm "$LINK_PATH"
fi
echo "Creating symlink..."
ln -s "$EXTENSION_DIR" "$LINK_PATH"
echo ""
echo "✅ Extension installed successfully!"
echo ""
echo "Next steps:"
echo "1. Restart Zed"
echo "2. Open a .sb file (try: $PWD/test-extension.sb)"
echo "3. The extension should activate automatically"
echo ""
echo "To install the LSP server for enhanced features:"
echo " cargo install --path storybook --bin storybook-lsp"
echo ""

View File

@@ -1,41 +0,0 @@
// Test file for Zed Storybook extension
use schema::core::TestType;
character TestCharacter: Human {
name: "Test"
age: 25
active: true
---backstory
This is a **test character** with some markdown:
- Item 1
- Item 2
*Italic text* for testing.
---
}
template TestTemplate {
field1: "value"
field2: 42
}
relationship TestRelationship {
TestCharacter {
role: "primary"
}
}
life_arc TestArc {
state initial {
on enter {
status: "active"
}
on age > 21 -> adult
}
state adult {
}
}