diff --git a/CLAUDE.md b/.claude/CLAUDE.md similarity index 88% rename from CLAUDE.md rename to .claude/CLAUDE.md index beb8143..ef38c21 100644 --- a/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -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 diff --git a/.serena/.gitignore b/.serena/.gitignore deleted file mode 100644 index 14d86ad..0000000 --- a/.serena/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/cache diff --git a/.serena/memories/lsp-phase4-navigation.md b/.serena/memories/lsp-phase4-navigation.md deleted file mode 100644 index 636e8a3..0000000 --- a/.serena/memories/lsp-phase4-navigation.md +++ /dev/null @@ -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>) -- **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, - } - ``` -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 diff --git a/.serena/memories/lsp-testing-status.md b/.serena/memories/lsp-testing-status.md deleted file mode 100644 index 12fbcba..0000000 --- a/.serena/memories/lsp-testing-status.md +++ /dev/null @@ -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) diff --git a/.serena/memories/tree-sitter-commands.md b/.serena/memories/tree-sitter-commands.md deleted file mode 100644 index 344c143..0000000 --- a/.serena/memories/tree-sitter-commands.md +++ /dev/null @@ -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 ...)` diff --git a/.serena/project.yml b/.serena/project.yml deleted file mode 100644 index 7f6618c..0000000 --- a/.serena/project.yml +++ /dev/null @@ -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: "" diff --git a/LSP_AUDIT_REPORT.md b/LSP_AUDIT_REPORT.md deleted file mode 100644 index aa7844d..0000000 --- a/LSP_AUDIT_REPORT.md +++ /dev/null @@ -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>> -│ └── Per-document state (AST, symbols, errors, positions) -└── workspace: Arc> - ├── name_table: NameTable (currently unused) - └── file_urls: HashMap -``` - -**Document Model:** -```rust -pub struct Document { - pub text: String, - pub ast: Option, - pub parse_errors: Vec, - 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) { - 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 ✅ -``` diff --git a/LSP_LEXER_AUDIT.md b/LSP_LEXER_AUDIT.md deleted file mode 100644 index 7c72139..0000000 --- a/LSP_LEXER_AUDIT.md +++ /dev/null @@ -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 = 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 { - 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 -``` diff --git a/LSP_TEST_STRATEGY.md b/LSP_TEST_STRATEGY.md deleted file mode 100644 index f4ad493..0000000 --- a/LSP_TEST_STRATEGY.md +++ /dev/null @@ -1,1021 +0,0 @@ -# LSP Testing Strategy -**Version:** 1.0 -**Date:** 2026-02-12 -**Owner:** LSP Test Engineer - ---- - -## Executive Summary - -This document outlines a comprehensive testing strategy for the Storybook LSP implementation, designed to achieve **85% code coverage** and **zero critical bugs** within 4-6 weeks. The strategy is divided into 5 phases, prioritized by immediate blocking issues first, followed by coverage expansion, integration testing, automation, and finally multi-file support. - ---- - -## Strategy Goals - -### Primary Objectives -1. **Fix Critical Bugs:** Resolve 2 compilation errors blocking all tests -2. **Achieve Stability:** 100% of tests pass reliably -3. **Expand Coverage:** Reach 80%+ code coverage across all LSP features -4. **Enable Automation:** Set up CI/CD for continuous testing -5. **Support Multi-File:** Prepare infrastructure for cross-file navigation - -### Success Metrics -- **Week 1:** All tests compile and run (100% pass rate) -- **Week 2:** All features have dedicated unit tests (70% coverage) -- **Week 3:** Integration tests complete (80% coverage) -- **Week 4:** CI/CD operational, benchmarks established -- **Weeks 5-6:** Multi-file support tested (85% coverage) - ---- - -## Testing Pyramid - -``` - /\ - / \ E2E Tests (5%) - /____\ - Zed extension integration - / \ - Real-world scenarios - / INTEG \ - /__________\ Integration Tests (15%) - / \ - Multi-file scenarios - / UNIT TESTS \ - Concurrent access - /________________\ - Document lifecycle - / \ - / UNIT TESTS 80% \ Unit Tests (80%) -/____________________\ - Feature-specific tests - - Edge cases - - Error conditions -``` - -**Rationale:** -- **80% Unit Tests** - Fast feedback, easy to debug, high confidence in individual components -- **15% Integration Tests** - Validate feature interactions, realistic scenarios -- **5% E2E Tests** - Validate actual editor integration (Zed) - ---- - -## Phase 1: Stabilization (Days 1-2) - -### Objective -Fix blocking compilation errors and establish baseline test health. - -### Tasks - -#### 1.1 Fix Compilation Errors -**Priority:** CRITICAL -**Estimated Time:** 30 minutes - -**Bug #1: Inlay Hints Import Path** -- **File:** `storybook/src/lsp/inlay_hints.rs:134` -- **Current:** `crate::project::positions::PositionTracker` -- **Fix:** `crate::position::PositionTracker` -- **Verification:** `cargo check` - -**Bug #2: Completion Type Annotation** -- **File:** `storybook/src/lsp/completion.rs:421` -- **Current:** `let mut nesting_level = 0;` -- **Fix:** `let mut nesting_level: i32 = 0;` -- **Verification:** `cargo check` - -#### 1.2 Baseline Test Run -**Priority:** CRITICAL -**Estimated Time:** 1 hour - -```bash -# Compile tests -cd /Users/sienna/Development/storybook/storybook -cargo test --lib lsp --no-run - -# Run all LSP tests -cargo test --lib lsp - -# Document results -# - Total tests run -# - Pass/fail counts -# - Any flaky tests -# - Performance outliers -``` - -**Deliverable:** Test baseline report -- Total test count (expect ~147) -- Pass rate (target: 100%) -- Test execution time -- Flaky test identification - -#### 1.3 Tree-sitter Verification -**Priority:** HIGH -**Estimated Time:** 30 minutes - -```bash -cd /Users/sienna/Development/storybook/tree-sitter-storybook -npm run test -``` - -**Verification:** All 27 tests pass - -### Phase 1 Deliverables -- ✅ All compilation errors fixed -- ✅ All tests compile successfully -- ✅ Baseline test report with 100% pass rate -- ✅ Tree-sitter tests verified -- ✅ List of any identified issues for Phase 2 - ---- - -## Phase 2: Coverage Expansion (Days 3-7) - -### Objective -Fill test coverage gaps for under-tested features and add edge case testing. - -### 2.1 Feature-Specific Unit Tests - -#### 2.1.1 Hover Tests -**File:** Create `storybook/src/lsp/hover_tests.rs` -**Estimated Time:** 3 hours -**Target:** 15 tests - -**Test Categories:** -1. **Basic Hover** (3 tests) - - Hover on character name - - Hover on template name - - Hover on behavior name - -2. **Type Information** (4 tests) - - Hover on field shows type - - Hover on species reference - - Hover on template reference - - Hover on behavior reference - -3. **Documentation** (4 tests) - - Hover shows field documentation - - Hover shows prose blocks - - Hover on state shows transitions - - Hover on schedule shows time blocks - -4. **Edge Cases** (4 tests) - - Hover on whitespace (returns None) - - Hover on comment (returns None) - - Hover at EOF (returns None) - - Hover on invalid position (returns None) - -**Coverage Target:** 85% - -#### 2.1.2 Formatting Tests -**File:** Create `storybook/src/lsp/formatting_tests.rs` -**Estimated Time:** 3 hours -**Target:** 15 tests - -**Test Categories:** -1. **Indentation** (5 tests) - - Character block indentation - - Template block indentation - - Nested behavior indentation - - Life arc state indentation - - Consistent tab/space usage - -2. **Spacing** (4 tests) - - Spacing around colons - - Spacing around braces - - Line breaks between declarations - - Trailing whitespace removal - -3. **Alignment** (3 tests) - - Field alignment in blocks - - Comment alignment - - Multiline value alignment - -4. **Edge Cases** (3 tests) - - Empty document formatting - - Already-formatted document (no changes) - - Document with syntax errors (graceful handling) - -**Coverage Target:** 80% - -#### 2.1.3 Rename Tests -**File:** Create `storybook/src/lsp/rename_tests.rs` -**Estimated Time:** 2 hours -**Target:** 12 tests - -**Test Categories:** -1. **Basic Rename** (4 tests) - - Rename character (updates all references) - - Rename template (updates all uses) - - Rename behavior (updates all calls) - - Rename field (updates all occurrences) - -2. **Scope Testing** (3 tests) - - Rename doesn't affect different scope - - Rename preserves capitalization context - - Rename updates definition + all uses - -3. **Validation** (3 tests) - - Reject invalid identifier names - - Reject rename to existing symbol - - Reject rename of built-in keywords - -4. **Edge Cases** (2 tests) - - Rename at EOF - - Rename in comment (should fail gracefully) - -**Coverage Target:** 80% - -#### 2.1.4 Semantic Tokens Tests -**File:** Create `storybook/src/lsp/semantic_tokens_tests.rs` -**Estimated Time:** 3 hours -**Target:** 15 tests - -**Test Categories:** -1. **Token Types** (7 tests) - - Character tokens (type.character) - - Template tokens (type.template) - - Behavior tokens (type.behavior) - - Keyword tokens (keyword.declaration) - - Field tokens (property) - - String tokens (string) - - Number tokens (constant.numeric) - -2. **Token Modifiers** (3 tests) - - Definition modifier - - Reference modifier - - Deprecated modifier (if applicable) - -3. **Complex Scenarios** (3 tests) - - Nested structures (correct scoping) - - Multiline declarations - - Mixed token types in single line - -4. **Edge Cases** (2 tests) - - Empty document (no tokens) - - Syntax errors (partial tokenization) - -**Coverage Target:** 80% - -### 2.2 Edge Case Testing Suite - -#### 2.2.1 Large File Tests -**File:** Create `storybook/src/lsp/stress_tests.rs` -**Estimated Time:** 4 hours -**Target:** 10 tests - -**Test Categories:** -1. **Size Tests** (4 tests) - - 1,000 line document - - 10,000 line document - - 50,000 line document - - Document with 1,000+ symbols - -2. **Depth Tests** (3 tests) - - 10-level nested behaviors - - 20-level nested behaviors - - Deeply nested template includes - -3. **Performance Tests** (3 tests) - - Parse time < 100ms for 1,000 lines - - Symbol extraction < 50ms - - Completion latency < 20ms - -**Coverage Target:** N/A (performance validation) - -#### 2.2.2 Unicode and Special Characters -**File:** Add to `storybook/src/lsp/document_edge_tests.rs` -**Estimated Time:** 2 hours -**Target:** 8 tests - -**Test Categories:** -1. **Unicode Identifiers** (3 tests) - - Chinese character names: `character 爱丽丝 {}` - - Emoji in prose: `---backstory\n😊\n---` - - Mixed scripts: `character Αλίκη {}` - -2. **Special Characters** (3 tests) - - Underscores in identifiers - - Hyphens in strings - - Escape sequences in strings - -3. **Boundary Conditions** (2 tests) - - Zero-width characters - - RTL text in prose blocks - -**Coverage Target:** 85% - -#### 2.2.3 Malformed Input Tests -**File:** Create `storybook/src/lsp/error_recovery_tests.rs` -**Estimated Time:** 3 hours -**Target:** 12 tests - -**Test Categories:** -1. **Truncated Files** (4 tests) - - Incomplete character block - - Unclosed prose block - - Missing closing brace - - Truncated at field value - -2. **Invalid UTF-8** (2 tests) - - Invalid byte sequences - - Null bytes in content - -3. **Syntax Errors** (4 tests) - - Missing colons in fields - - Invalid identifiers (starting with numbers) - - Unmatched braces - - Invalid keywords - -4. **Graceful Degradation** (2 tests) - - Partial symbol extraction on errors - - Diagnostics still generated - - Server doesn't crash - -**Coverage Target:** 90% - -### Phase 2 Deliverables -- ✅ 4 new test modules created (~57 new tests) -- ✅ Coverage increased from ~60% to 80% -- ✅ All features have dedicated unit tests -- ✅ Edge cases comprehensively tested - ---- - -## Phase 3: Integration Testing (Days 8-12) - -### Objective -Validate feature interactions and real-world scenarios. - -### 3.1 Multi-File Scenarios - -#### 3.1.1 Multi-File Test Suite -**File:** Create `storybook/src/lsp/integration_tests.rs` -**Estimated Time:** 6 hours -**Target:** 15 tests - -**Test Categories:** -1. **Use Declarations** (3 tests) - - Import character from another file - - Import template from another file - - Wildcard imports (`use characters::*`) - -2. **Cross-File References** (4 tests) - - Template include from another file - - Species reference from another file - - Behavior subtree reference (`@module::tree`) - - Relationship participants from other files - -3. **Workspace State** (3 tests) - - Workspace rebuild on file add - - Workspace rebuild on file remove - - Workspace rebuild on file modify - -4. **Symbol Resolution** (3 tests) - - Go-to-definition across files (even if not fully supported) - - Find references across files (even if not fully supported) - - Completion shows cross-file symbols (even if not fully supported) - -5. **Edge Cases** (2 tests) - - Circular dependencies - - Missing import targets - -**Note:** These tests document **expected behavior** even if cross-file support isn't fully implemented. They serve as regression tests for when Phase 5 is implemented. - -**Coverage Target:** Establish baseline for multi-file features - -#### 3.1.2 Concurrent Access Tests -**File:** Create `storybook/src/lsp/concurrency_tests.rs` -**Estimated Time:** 4 hours -**Target:** 8 tests - -**Test Categories:** -1. **Multiple Clients** (3 tests) - - Two clients open same document - - Simultaneous edits from different clients - - One client closes while other edits - -2. **Rapid Operations** (3 tests) - - Rapid did_change events - - Open/close/reopen sequences - - Completion requests during editing - -3. **Locking** (2 tests) - - No deadlocks on concurrent reads - - Write lock releases properly - -**Coverage Target:** Validate concurrency safety - -### 3.2 Document Lifecycle Tests - -#### 3.2.1 Lifecycle Integration -**File:** Add to `storybook/src/lsp/integration_tests.rs` -**Estimated Time:** 3 hours -**Target:** 10 tests - -**Test Categories:** -1. **Open/Edit/Close** (4 tests) - - Normal lifecycle (open → edit → close) - - Multiple edits before close - - Close without edit - - Reopen after close - -2. **State Consistency** (3 tests) - - Symbols update on edit - - Diagnostics update on edit - - Workspace rebuilds on change - -3. **Error Recovery** (3 tests) - - Server survives parse errors - - Server survives malformed edits - - Server recovers from invalid positions - -**Coverage Target:** 90% of document.rs - -### Phase 3 Deliverables -- ✅ Integration test suite (33 tests) -- ✅ Multi-file behavior documented -- ✅ Concurrency safety validated -- ✅ Document lifecycle coverage > 90% - ---- - -## Phase 4: Automation & Performance (Days 13-15) - -### Objective -Enable automated testing and establish performance baselines. - -### 4.1 CI/CD Setup - -#### 4.1.1 GitHub Actions Workflow -**File:** Create `.github/workflows/lsp-tests.yml` -**Estimated Time:** 4 hours - -**Workflow Components:** -1. **Test Jobs** - - Rust version: stable, nightly - - OS: ubuntu-latest, macos-latest - - Run: `cargo test --lib lsp` - -2. **Coverage Job** - - Tool: cargo-tarpaulin or cargo-llvm-cov - - Upload to: codecov.io or coveralls.io - - Fail if coverage < 75% - -3. **Tree-sitter Job** - - Setup: Node.js 18+ - - Run: `cd tree-sitter-storybook && npm test` - -4. **Benchmark Job** - - Run: `cargo bench --bench lsp_benchmarks` - - Upload results for regression tracking - -**Triggers:** -- On push to main -- On pull requests -- Nightly (for performance tracking) - -#### 4.1.2 Pre-commit Hooks -**File:** Update `.github/workflows/pre-commit.yml` or `lefthook.yml` -**Estimated Time:** 1 hour - -**Hooks:** -- `cargo test --lib lsp` (fast tests only) -- `cargo clippy` (linting) -- `cargo fmt --check` (formatting) - -### 4.2 Performance Benchmarking - -#### 4.2.1 Benchmark Suite -**File:** Create `storybook/benches/lsp_benchmarks.rs` -**Estimated Time:** 6 hours - -**Benchmarks:** -1. **Parse Benchmarks** (4 benchmarks) - - Small file (100 lines) - - Medium file (1,000 lines) - - Large file (10,000 lines) - - Very large file (50,000 lines) - -2. **Symbol Extraction** (3 benchmarks) - - 10 symbols - - 100 symbols - - 1,000 symbols - -3. **Completion** (3 benchmarks) - - Field completion (10 options) - - Template completion (100 options) - - Completion in large file - -4. **Navigation** (3 benchmarks) - - Go-to-definition in small file - - Go-to-definition in large file - - Find references (100 occurrences) - -5. **Workspace** (2 benchmarks) - - Workspace rebuild (10 files) - - Workspace rebuild (100 files) - -**Tool:** Use `criterion.rs` for statistical analysis - -**Baselines:** -- Parse: < 10ms per 1,000 lines -- Symbol extraction: < 5ms per 100 symbols -- Completion: < 20ms latency -- Navigation: < 10ms per operation -- Workspace rebuild: < 100ms per 10 files - -#### 4.2.2 Memory Profiling -**Estimated Time:** 3 hours - -**Profiling Scenarios:** -1. Memory usage with 100 open documents -2. Memory usage with 1,000+ symbols -3. Memory leak detection (long-running session) - -**Tools:** -- `valgrind` (Linux) -- `instruments` (macOS) -- `heaptrack` (cross-platform) - -### Phase 4 Deliverables -- ✅ CI/CD pipeline operational -- ✅ Code coverage reporting automated -- ✅ Benchmark suite established -- ✅ Performance baselines documented -- ✅ Memory profiling completed - ---- - -## Phase 5: Multi-File Support (Days 16-30) - -### Objective -Implement and test cross-file navigation and workspace features. - -### 5.1 Architecture Implementation - -#### 5.1.1 Workspace NameTable Integration -**File:** `storybook/src/lsp/server.rs` -**Estimated Time:** 8 hours - -**Changes:** -1. Populate `WorkspaceState.name_table` in `rebuild()` -2. Use file indices from NameTable -3. Store symbol locations with file indices -4. Expose workspace-level symbol lookup - -**Testing:** -- Unit tests for NameTable population -- Verify symbol file indices correct -- Test incremental updates - -#### 5.1.2 Cross-File Go-to-Definition -**File:** `storybook/src/lsp/definition.rs` -**Estimated Time:** 6 hours - -**Changes:** -1. Check local document symbols first (fast path) -2. Fall back to workspace NameTable -3. Resolve file URL from file index -4. Return Location with correct file URL - -**Testing:** -- Go to character in another file -- Go to template in another file -- Go to behavior in another file -- Handle missing symbols gracefully - -#### 5.1.3 Cross-File Find References -**File:** `storybook/src/lsp/references.rs` -**Estimated Time:** 6 hours - -**Changes:** -1. Search all open documents (not just current) -2. Use workspace NameTable for symbol lookup -3. Aggregate results from multiple files -4. Return Locations with file URLs - -**Testing:** -- Find character references across files -- Find template uses across files -- Find behavior calls across files -- Performance with 100+ open files - -#### 5.1.4 Use Declaration Resolution -**File:** Create `storybook/src/lsp/imports.rs` -**Estimated Time:** 8 hours - -**Changes:** -1. Parse `use` declarations -2. Resolve module paths to file URLs -3. Populate symbol table from imports -4. Handle grouped imports (`use foo::{bar, baz}`) -5. Handle wildcard imports (`use foo::*`) - -**Testing:** -- Simple use declaration -- Grouped imports -- Wildcard imports -- Nested module paths -- Missing import targets - -### 5.2 Multi-File Test Suite - -#### 5.2.1 Cross-File Navigation Tests -**File:** Create `storybook/src/lsp/cross_file_tests.rs` -**Estimated Time:** 6 hours -**Target:** 20 tests - -**Test Categories:** -1. **Go-to-Definition** (5 tests) - - Navigate to character in other file - - Navigate to template in other file - - Navigate to behavior in other file - - Navigate with nested modules - - Navigate with use declarations - -2. **Find References** (5 tests) - - Find character uses across files - - Find template includes across files - - Find behavior calls across files - - Find species references across files - - Performance with 50+ files - -3. **Completion** (5 tests) - - Complete imported symbols - - Complete from wildcard imports - - Complete nested module paths - - Complete with use declarations - - Don't show non-imported symbols - -4. **Workspace Management** (5 tests) - - Add file updates workspace - - Remove file updates workspace - - Modify file updates workspace - - Rename file updates workspace - - Large workspace (100+ files) - -**Coverage Target:** 85% of cross-file features - -#### 5.2.2 Import Resolution Tests -**File:** Create `storybook/src/lsp/import_tests.rs` -**Estimated Time:** 4 hours -**Target:** 15 tests - -**Test Categories:** -1. **Simple Imports** (3 tests) - - `use characters::Alice;` - - `use templates::Child;` - - `use behaviors::Walk;` - -2. **Grouped Imports** (3 tests) - - `use characters::{Alice, Bob};` - - `use templates::{Child, Adult};` - - Mixed types in group - -3. **Wildcard Imports** (3 tests) - - `use characters::*;` - - Multiple wildcards from different modules - - Wildcard precedence - -4. **Nested Modules** (3 tests) - - `use world::characters::Alice;` - - `use world::locations::wonderland::Garden;` - - Deep nesting (5+ levels) - -5. **Edge Cases** (3 tests) - - Import non-existent symbol - - Circular imports - - Import from self - -**Coverage Target:** 90% of import resolution - -### Phase 5 Deliverables -- ✅ Cross-file navigation implemented -- ✅ Use declaration resolution working -- ✅ Workspace NameTable populated -- ✅ 35 new multi-file tests -- ✅ Overall coverage > 85% - ---- - -## Test Execution Strategy - -### Daily Test Runs -```bash -# Quick sanity check (< 5 seconds) -cargo test --lib lsp -- --test-threads=1 --nocapture - -# Full test suite (< 2 minutes) -cargo test --lib lsp - -# With coverage (< 5 minutes) -cargo tarpaulin --lib --out Html --output-dir coverage - -# Tree-sitter tests (< 10 seconds) -cd tree-sitter-storybook && npm test -``` - -### Weekly Test Runs -```bash -# Performance benchmarks (~ 10 minutes) -cargo bench --bench lsp_benchmarks - -# Memory profiling (~ 15 minutes) -./scripts/memory_profile.sh - -# Stress tests (~ 20 minutes) -cargo test --lib lsp --release -- stress_tests -``` - -### Pre-Release Test Runs -```bash -# Full suite with coverage -cargo tarpaulin --lib --out Html --output-dir coverage - -# Performance regression check -cargo bench --bench lsp_benchmarks -- --save-baseline main - -# Integration tests -cargo test --test '*' - -# E2E tests (manual) -# 1. Build Zed extension -# 2. Test in Zed editor -# 3. Validate all LSP features work -``` - ---- - -## Coverage Measurement - -### Tools -1. **cargo-tarpaulin** - Code coverage for Rust - ```bash - cargo install cargo-tarpaulin - cargo tarpaulin --lib --out Html --output-dir coverage - ``` - -2. **cargo-llvm-cov** - Alternative coverage tool - ```bash - cargo install cargo-llvm-cov - cargo llvm-cov --html --lib - ``` - -### Coverage Targets by Phase - -| Phase | Target | Focus | -|-------|--------|-------| -| Phase 1 | 60% | Existing tests | -| Phase 2 | 80% | Feature coverage | -| Phase 3 | 82% | Integration | -| Phase 4 | 83% | Automation | -| Phase 5 | 85% | Multi-file | - -### Coverage Exemptions -- Generated code (tree-sitter bindings) -- Test utilities and fixtures -- Deprecated code paths -- Unreachable error handling (panic paths) - ---- - -## Risk Management - -### High-Risk Areas - -1. **Concurrency Bugs** - - **Risk:** Deadlocks, race conditions in RwLock usage - - **Mitigation:** Dedicated concurrency test suite, stress testing - - **Detection:** Thread sanitizer, long-running tests - -2. **Performance Regressions** - - **Risk:** Features slow down with large files/workspaces - - **Mitigation:** Benchmark suite, performance tracking in CI - - **Detection:** Criterion benchmarks, regression alerts - -3. **Memory Leaks** - - **Risk:** Documents not cleaned up, symbol table grows unbounded - - **Mitigation:** Memory profiling, leak detection tools - - **Detection:** Valgrind, long-running session tests - -4. **Cross-File State Corruption** - - **Risk:** NameTable inconsistencies, stale file references - - **Mitigation:** Workspace state validation tests - - **Detection:** Integration tests, state invariant checks - -### Medium-Risk Areas - -1. **Unicode Handling** - - **Risk:** Position calculations off by one with multi-byte chars - - **Mitigation:** Comprehensive unicode test suite - - **Detection:** Unicode-heavy test files - -2. **Error Recovery** - - **Risk:** Server crashes on malformed input - - **Mitigation:** Fuzz testing, malformed input tests - - **Detection:** Error recovery test suite - -3. **Zed Integration** - - **Risk:** LSP features not working in actual editor - - **Mitigation:** E2E testing in Zed - - **Detection:** Manual testing, user feedback - ---- - -## Test Maintenance - -### Test Naming Convention -```rust -// Pattern: test___ -#[test] -fn test_goto_definition_character_in_same_file() { ... } - -#[test] -fn test_completion_field_after_colon() { ... } - -#[test] -fn test_diagnostics_parse_error_missing_brace() { ... } -``` - -### Test Organization -``` -src/lsp/ -├── *_tests.rs # Feature-specific unit tests -├── integration_tests.rs # Multi-feature integration -├── stress_tests.rs # Performance and scale -└── cross_file_tests.rs # Multi-file scenarios -``` - -### Test Documentation -- Each test file has module-level doc comment explaining scope -- Each test has doc comment explaining scenario -- Complex tests have inline comments for key assertions - -### Test Refactoring Guidelines -- Extract common test fixtures to `test_utils.rs` -- Use builder pattern for complex test data -- Keep tests independent (no shared mutable state) -- Aim for tests < 50 lines each - ---- - -## Appendix A: Test Counting Summary - -### Current Tests (Phase 1) -- behavior_tests.rs: 7 -- code_actions_tests.rs: 27 -- completion_tests.rs: 10 -- diagnostics_tests.rs: 20 -- document_edge_tests.rs: 17 -- navigation_tests.rs: 11 -- validation_tests.rs: 10 -- Integration tests: ~45 -- **Total: ~147 tests** - -### New Tests by Phase - -**Phase 2 (+57 tests):** -- hover_tests.rs: 15 -- formatting_tests.rs: 15 -- rename_tests.rs: 12 -- semantic_tokens_tests.rs: 15 - -**Phase 3 (+33 tests):** -- integration_tests.rs: 25 -- concurrency_tests.rs: 8 - -**Phase 4 (+15 benchmarks):** -- lsp_benchmarks.rs: 15 benchmarks - -**Phase 5 (+35 tests):** -- cross_file_tests.rs: 20 -- import_tests.rs: 15 - -**Grand Total: ~287 tests + 15 benchmarks** - ---- - -## Appendix B: Test Commands Reference - -```bash -# === LSP Tests === - -# Run all LSP tests -cargo test --lib lsp - -# Run specific test file -cargo test --lib lsp::hover_tests - -# Run single test -cargo test --lib lsp::hover_tests::test_hover_on_character - -# Run tests with output -cargo test --lib lsp -- --nocapture - -# Run tests in single thread (for debugging) -cargo test --lib lsp -- --test-threads=1 - -# === Tree-sitter Tests === - -# Run all tree-sitter tests -cd tree-sitter-storybook && npm test - -# Run with verbose output -cd tree-sitter-storybook && npm test -- --debug - -# === Coverage === - -# Generate HTML coverage report -cargo tarpaulin --lib --out Html --output-dir coverage - -# Coverage with specific minimum threshold -cargo tarpaulin --lib --fail-under 80 - -# === Benchmarks === - -# Run all benchmarks -cargo bench --bench lsp_benchmarks - -# Run specific benchmark -cargo bench --bench lsp_benchmarks -- parse - -# Save baseline -cargo bench --bench lsp_benchmarks -- --save-baseline main - -# Compare to baseline -cargo bench --bench lsp_benchmarks -- --baseline main - -# === Memory Profiling === - -# Linux (valgrind) -valgrind --leak-check=full --show-leak-kinds=all \ - cargo test --lib lsp - -# macOS (instruments) -instruments -t Leaks cargo test --lib lsp - -# === Linting === - -# Run clippy -cargo clippy --lib - -# Run clippy with strict rules -cargo clippy --lib -- -D warnings - -# Format check -cargo fmt --check - -# Auto-format -cargo fmt -``` - ---- - -## Appendix C: Coverage Report Template - -```markdown -# LSP Test Coverage Report -**Date:** YYYY-MM-DD -**Commit:** - -## Summary -- **Overall Coverage:** XX% -- **Tests Run:** XXX -- **Tests Passed:** XXX -- **Tests Failed:** X -- **Duration:** XX seconds - -## Coverage by Module -| Module | Coverage | Lines Covered | Total Lines | -|--------|----------|---------------|-------------| -| server.rs | XX% | XXX / XXX | XXX | -| hover.rs | XX% | XXX / XXX | XXX | -| completion.rs | XX% | XXX / XXX | XXX | -| definition.rs | XX% | XXX / XXX | XXX | -| references.rs | XX% | XXX / XXX | XXX | -| symbols.rs | XX% | XXX / XXX | XXX | -| diagnostics.rs | XX% | XXX / XXX | XXX | -| formatting.rs | XX% | XXX / XXX | XXX | -| rename.rs | XX% | XXX / XXX | XXX | -| code_actions.rs | XX% | XXX / XXX | XXX | -| semantic_tokens.rs | XX% | XXX / XXX | XXX | -| inlay_hints.rs | XX% | XXX / XXX | XXX | - -## Uncovered Lines -- server.rs: lines XXX-XXX (error handling) -- completion.rs: line XXX (unreachable branch) - -## Recommendations -- [ ] Add tests for uncovered error paths -- [ ] Increase coverage in completion.rs -- [ ] ... -``` - ---- - -## Conclusion - -This testing strategy provides a **clear roadmap** from the current broken state (compilation errors) to a fully tested, production-ready LSP implementation with 85% coverage. The phased approach allows for **incremental progress** while maintaining **immediate value** at each phase: - -- **Phase 1** - Unblocks development -- **Phase 2** - Achieves stability -- **Phase 3** - Validates integration -- **Phase 4** - Enables automation -- **Phase 5** - Adds advanced features - -By following this strategy, the Storybook LSP will become **robust, maintainable, and reliable** for end users. diff --git a/TEAM_PLAN.md b/TEAM_PLAN.md deleted file mode 100644 index 18aedeb..0000000 --- a/TEAM_PLAN.md +++ /dev/null @@ -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? - diff --git a/docs/TYPE-SYSTEM.md b/docs/TYPE-SYSTEM.md new file mode 100644 index 0000000..ba84623 --- /dev/null +++ b/docs/TYPE-SYSTEM.md @@ -0,0 +1,1706 @@ +# Storybook Type System + +**Version**: 0.3.0 +**Status**: Draft + +## Overview + +The Storybook type system is a **declarative, pure functional DSL** for defining narrative simulations. It separates type definitions and logic (language layer) from state management and mutation (runtime layer). + +### Core Principles + +1. **Language is pure** - no mutation, no state changes, only declarations +2. **Templates are record types** - universal structural type definitions +3. **Entities are typed values** - characters, institutions, locations are instances +4. **Behaviors are functional** - control flow and pattern matching +5. **Actions are the boundary** - where language meets runtime + +### Core Declarations + +- **`template`**: Record type definitions (structural types) +- **`character`/`institution`/`location`**: Typed value instances +- **`concept`**: Base type declarations for pattern matching +- **`sub_concept`**: Enumerated and typed subtypes (tagged union members) +- **`concept_comparison`**: Compile-time pattern matching over subtype combinations +- **`action`**: Signature declarations for runtime-implemented operations + +This system enables static validation of entity relationships, behavior conditions, and data structures while maintaining readability for narrative design. + +--- + +## Architecture: Language vs Runtime + +### Language Layer (Storybook DSL) + +**Pure, declarative, no mutation:** +- Defines types (templates, concepts) +- Defines values (characters, institutions, locations) +- Defines logic (behaviors, pattern matching) +- Declares action signatures (interface to runtime) + +**Example:** +```storybook +template Person { + age: Number, + profession: Profession +} + +character Martha: Person { + age: 34, + profession: Baker +} + +action bake(baker: Baker, item: BakingItem) + +behavior BakingWork { + then { + check_orders + bake + } +} +``` + +### Runtime Layer (Implementation) + +**Stateful, manages mutation:** +- Holds character state +- Executes actions (implements mutations) +- Runs behavior trees +- Updates world state over time + +**Example (Rust):** +```rust +enum Action { + Bake { baker: EntityId, item: ItemId }, + CheckOrders { baker: EntityId }, + PrepareIngredients { baker: EntityId, recipe: RecipeId }, +} + +impl Runtime { + fn execute_action(&mut self, action: Action) { + match action { + Action::Bake { baker, item } => { + let character = self.get_character_mut(baker); + let baked_item = self.get_item(item).bake(); + character.inventory.add(baked_item); + character.energy -= 10; + } + Action::CheckOrders { baker } => { + let character = self.get_character_mut(baker); + let orders = self.query_orders(); + character.task_queue.extend(orders); + } + Action::PrepareIngredients { baker, recipe } => { + // Implementation + } + } + } +} +``` + +### Actions: The Boundary + +Actions are **declared in Storybook** (signatures) but **implemented in runtime** (behavior). + +**Language sees:** +```storybook +/// Bakes an item in the oven +/// +/// The baker must have sufficient energy and the item must be prepared. +/// Updates baker's inventory and reduces energy. +action bake(baker: Baker, item: BakingItem) +``` + +**Runtime implements:** +```rust +impl Runtime { + fn bake(&mut self, baker: EntityId, item: ItemId) { + let character = self.get_character_mut(baker); + let baked = self.get_item(item).bake(); + character.inventory.add(baked); + character.energy -= 10; + } +} +``` + +**Benefits:** +- ✅ Language stays pure and type-safe +- ✅ Runtime has implementation flexibility +- ✅ Clear contract between layers +- ✅ Can add standard library later without changing language + +--- + +## Core Declarations + +### `template` - Record Type Definition + +A `template` defines a structural record type. Templates are the universal mechanism for defining structured data in Storybook. + +**Syntax:** +```storybook +template TypeName { + field1: Type, + field2: Type, + ... +} +``` + +**Examples:** +```storybook +template Person { + age: Number, + species_type: Species, + profession: Profession +} + +template Building { + owner: Person, // Reference to Person template + capacity: Number, + place: Settlement // Reference to Settlement template +} + +template Settlement { + terrain: Terrain, + population: Number +} + +template FamilialBond { + parent: Person, // Reference to Person template + child: Person, // Reference to Person template + strength: Number +} +``` + +**Purpose:** +- Define reusable record structures +- Provide types for characters, institutions, locations, relationships +- Enable type checking for fields and references + +**Field Types:** +Templates support both value types and reference types: + +**Value Types:** +- `Number` - integer values (e.g., `age: 34`) +- `Decimal` - floating-point values (e.g., `price: 19.99`) +- `Text` - text values (e.g., `name: "Martha"`) +- `Boolean` - boolean values (e.g., `active: true`) + +**Range Declarations:** +For procedural generation, templates can specify ranges instead of concrete values: +```storybook +template Person { + age: 18..80, // Random age between 18 and 80 + height: 150..200, // Random height in cm + wealth: 100..10000 // Random wealth amount +} +``` + +When a character instantiates a template with ranges, it must provide concrete values within those ranges: +```storybook +character Martha: Person { + age: 34, // Must be between 18 and 80 + height: 165, // Must be between 150 and 200 + wealth: 5000 // Must be between 100 and 10000 +} +``` + +**Reference Types:** +Templates can reference concepts and other templates: +```storybook +template Baker { + profession: Profession, // Reference to concept + place: Settlement, // Reference to Settlement template + tools: BakingTools // Reference to BakingTools template +} +``` + +Note: Template fields reference **template types** (Person, Settlement, Building), not declaration keywords (character, location, institution). + +**Reserved Keywords:** +Field names cannot use reserved keywords. Use suffixes or alternatives instead: +```storybook +// ✗ Invalid - 'species' is a keyword +template Person { + age: Number, + species: Species, // Error! + profession: Profession +} + +// ✓ Valid - use alternative names +template Person { + age: Number, + species_type: Species, // OK + profession: Profession +} +``` + +Common alternatives: +- `species` → `species_type`, `creature_type` +- `location` → `location_ref`, `place` +- `character` → `character_ref`, `person` +- `template` → `template_name`, `template_ref` +- `behavior` → `behavior_ref`, `action_tree` + +**Template Composition:** +Templates can reference other templates and concepts in their fields. + +--- + +### Entities: Typed Value Instances + +Characters, institutions, locations, and relationships are **typed values** - instances of template types. + +**Syntax:** +```storybook +character Name: TemplateName { + field1: value, + field2: value, + ... +} + +institution Name: TemplateName { + field1: value, + field2: value, + ... +} + +location Name: TemplateName { + field1: value, + field2: value, + ... +} + +relationship Name: TemplateName { + field1: value, + field2: value, + ... +} +``` + +**Examples:** +```storybook +character Martha: Person { + age: 34, + species_type: Human, + profession: Baker +} + +institution Bakery: Building { + owner: Martha, + capacity: 20, + place: TownSquare +} + +location TownSquare: Settlement { + terrain: Plains, + population: 500 +} + +relationship ParentChild: FamilialBond { + parent: Martha, + child: Jane, + strength: 10 +} +``` + +**Type Checking:** +- Values must match their template's field types +- Values must fall within range constraints (if specified in template) +- All required fields must be provided +- References must resolve to declared entities + +**Example:** +```storybook +template Person { + age: 18..80, + profession: Profession +} + +// ✓ Valid - within constraints +character Martha: Person { + age: 34, // 18 <= 34 <= 80 + profession: Baker +} + +// ✗ Error - age out of range +character TooYoung: Person { + age: 12, // 12 < 18 (violates constraint) + profession: Child +} +``` + +**State Management:** +- Entities are values **at declaration time** +- State changes are managed by the runtime (outside the language) +- Language defines initial state, runtime manages ongoing state + +--- + +### `action` - Runtime Operation Signature + +An `action` declares the signature of a runtime-implemented operation. Actions are the interface between the pure language layer and the stateful runtime layer. + +**Syntax:** +```storybook +/// Documentation comment (required) +/// +/// Multi-line docstrings explain what the action does, +/// its preconditions, and its effects. +action name(param1: Type, param2: Type, ...) +``` + +**Examples:** +```storybook +/// Bakes an item in the oven +/// +/// The baker must have sufficient energy and the item must be prepared. +/// Updates baker's inventory and reduces energy. +action bake(baker: Baker, item: BakingItem) + +/// Checks pending orders and updates the baker's task list +/// +/// Queries the order queue and populates the baker's work queue. +action check_orders(baker: Baker) + +/// Moves a character to a new location +/// +/// Updates the character's location and triggers any location-based events. +action move_to(character: Person, destination: Settlement) +``` + +**Documentation Requirement:** +- Actions must have a docstring explaining their behavior +- This helps runtime implementers understand intent +- Serves as contract between language and runtime + +**Type Checking:** +- Action calls in behaviors are validated against signatures +- Parameter types must match +- Unknown actions are compile errors + +**Implementation:** +- Signatures are declared in `.sb` files (typically `actions.sb`) +- Implementations are provided by the runtime +- Standard library of common actions may come in future versions + +**Current Limitations:** +- Actions have no return values (this version) +- Actions are statements, not expressions +- No support for action composition + +--- + +### `concept` - Base Type Declaration + +A `concept` declares a base type with no inherent structure. It serves as a parent for related `sub_concept` declarations. + +**Syntax:** +```storybook +concept TypeName +``` + +**Example:** +```storybook +concept Cup +concept Customer +concept Vendor +``` + +**Purpose:** +- Establish type namespaces for related subtypes +- Provide type identity for values in the system +- Enable type checking in behaviors and conditions + +**When to use:** +- When you need a type that will have multiple variants or aspects +- To create type-safe enumerations through `sub_concept` +- As a base for compile-time pattern matching via `concept_comparison` + +--- + +### `sub_concept` - Subtype Definition + +A `sub_concept` defines members of a tagged union for a parent concept. Sub_concepts are associated with their parent through **dot notation** (explicit parent reference). + +**Syntax:** + +**Enumerated Form** (fixed set of values): +```storybook +sub_concept Parent.Name { + Variant1, + Variant2, + Variant3 +} +``` + +**Typed Form** (structured with fields): +```storybook +sub_concept Parent.RecordName { + field1: TypeOrAny, + field2: TypeOrAny +} +``` + +**Parent Declaration:** +The parent is explicitly declared using dot notation: +- `Cup.Type` → parent: `Cup`, name: `Type` +- `Cup.Size` → parent: `Cup`, name: `Size` +- `Cupcake.Flavor` → parent: `Cupcake`, name: `Flavor` + +**Why dot notation?** +- ✅ Prevents accidental naming collisions (`Cupcake` won't match `Cup`) +- ✅ Makes parent-child relationships explicit and clear +- ✅ Reads naturally: "Cup's Type", "Cup's Size" +- ✅ No ambiguity - parser knows exact parent +- ✅ Allows arbitrary sub_concept names without prefix requirements + +**Examples:** + +```storybook +// Parent concepts +concept Cup; +concept Cupcake; + +// Cup sub_concepts (tagged union members) +sub_concept Cup.Size { + Small, + Medium, + Large +} + +sub_concept Cup.Type { + Ceramic, + Glass, + Plastic +} + +sub_concept Cup.Color { + Red, + Blue, + Green +} + +// Cupcake sub_concepts (no confusion with Cup) +sub_concept Cupcake.Flavor { + Strawberry, + Chocolate, + Raspberry +} + +// Typed sub_concept (record-like) +sub_concept Vendor.Inventory { + Bread: any, + Pastries: any, + Cakes: any, + Cup: any +} +``` + +**Type Checking Rules:** +- ✅ Field values must be **identifiers** (references to other concepts/sub_concepts or `any`) +- ❌ Field values cannot be value types (Text, Number, Decimal, Boolean) + +```storybook +// ✅ VALID - identifier references +sub_concept Inventory { + item: Product, + container: Cup, + quantity: any +} + +// ❌ INVALID - value types not allowed +sub_concept BadInventory { + name: "string", // ✗ string literal + count: 42, // ✗ integer literal + active: true // ✗ boolean literal +} +``` + +**Purpose:** +- **Enumerated**: Define a fixed set of mutually exclusive values +- **Typed**: Define structured data with type-safe fields +- Both forms create tagged union members of the parent concept + +**Relationship to Parent:** +Sub_concepts are **tagged union members**, not inheritance: +- `CupSize.Small` is a distinct variant of the `Cup` union +- `CupType.Glass` is another distinct variant of the `Cup` union +- They coexist as different aspects/facets of the same base type + +--- + +### `concept_comparison` - Compile-time Pattern Matching + +A `concept_comparison` performs compile-time pattern matching over combinations of sub_concept values, mapping them to derived variant names. + +**Syntax:** +```storybook +concept_comparison ComparisonName { + VariantName1: { + SubConceptName1: condition1, + SubConceptName2: condition2, + ... + }, + VariantName2: { + SubConceptName1: condition1, + SubConceptName2: condition2, + ... + } +} +``` + +**Condition Syntax:** +- **`any`**: Matches any value of the specified sub_concept type +- **`Type is Value1 or Type is Value2`**: Matches specific enumerated values + +**Example:** +```storybook +concept Cup; + +sub_concept Cup.Size { + Small, Medium, Large +} + +sub_concept Cup.Type { + Ceramic, Glass, Plastic +} + +sub_concept Cup.Color { + Red, Blue, Green +} + +concept_comparison CustomerNumbererestInCups { + Numbererested: { + Cup.Size: any, // Any size + Cup.Type: Cup.Type is Glass or Cup.Type is Plastic, // Only Glass or Plastic + Cup.Color: Cup.Color is Red or Cup.Color is Blue // Only Red or Blue + }, + NotNumbererested: { + Cup.Size: any, + Cup.Type: any, + Cup.Color: any + }, + Maybe: { + Cup.Size: any, + Cup.Type: any, + Cup.Color: any + } +} +``` + +**Pattern Matching Semantics:** +- The comparison evaluates **at compile-time** +- Given concrete sub_concept values, determines which variant they match +- Used in behavior conditions to enable type-safe decision making + +**Usage in Behaviors:** +```storybook +behavior SellAtMarket { + repeat { + then { + greet_customer + show_products + if(CustomerNumbererestInCups.Numbererested.Cup.Size is Medium or Cup.Size is Large) { + make_sale(Cup) + } + thank_customer + } + } +} +``` + +**Purpose:** +- Create derived types from combinations of existing sub_concepts +- Enable compile-time validation of complex conditions +- Provide type-safe pattern matching for behaviors + +**Mixing Enumerated and Typed Sub_concepts:** +Concept_comparisons can reference both enumerated and typed sub_concepts in the same pattern (support for this is being implemented). + +--- + +## Type Compatibility + +### Subtyping Rules + +Sub_concepts are tagged union members of their parent concept: + +``` +CupSize.Small <: Cup +CupType.Glass <: Cup +CupColor.Red <: Cup +``` + +### Substitution + +**Where sub_concept values can be used:** +- As arguments to actions that expect the parent concept +- In field assignments expecting the parent type +- In conditions and comparisons + +**Example:** +```storybook +action serve(item: Cup) { + // Implementation +} + +// Valid calls - sub_concepts substitute for parent +serve(CupSize.Small) +serve(CupType.Glass) +serve(CupColor.Red) +``` + +### Type Checking + +**Compile-time:** +- Sub_concept field types must be identifiers (not value types) +- Pattern matching in `concept_comparison` is validated +- Type references must resolve to declared concepts + +**Runtime:** +- Values are tagged with their specific sub_concept variant +- Pattern matching evaluates to variant names +- Type information preserved for behavior execution + +--- + +## `any` Keyword + +The `any` keyword represents **any value of a specific type**, not a universal type. + +**Semantics:** +```storybook +sub_concept VendorInventory { + Bread: any, // any value of type Bread + Pastries: any, // any value of type Pastries + Cup: any // any value of type Cup (includes all CupSize, CupType, CupColor) +} + +concept_comparison Example { + AllCups: { + CupSize: any, // matches Small, Medium, Large + CupType: any, // matches Ceramic, Glass, Plastic + CupColor: any // matches Red, Blue, Green + } +} +``` + +**Not a universal type:** +- `any` is scoped to the field's declared type +- Does not mean "any type in the system" +- Provides flexibility while maintaining type safety + +--- + +## Design Guidelines + +### When to use `concept` +- You need a base type for multiple related variants +- You want type-safe enumerations +- You need to group related aspects of an entity + +### When to use enumerated `sub_concept` +- You have a fixed set of mutually exclusive values +- Values are symbolic/categorical (not data-bearing) +- You need type-safe pattern matching over the values + +### When to use typed `sub_concept` +- You need structured data with multiple fields +- Fields reference other concepts or need flexibility (`any`) +- You want record-like types within the concept system + +### When to use `concept_comparison` +- You need to map combinations of sub_concepts to outcomes +- Complex conditional logic benefits from compile-time validation +- Behavior trees need type-safe decision points + +--- + +## Examples + +### Simple Enumeration +```storybook +concept Season; + +sub_concept Season.Name { + Spring, + Summer, + Fall, + Winter +} +``` + +### Multi-faceted Type +```storybook +concept Food; + +sub_concept Food.Type { + Bread, + Pastry, + Cake +} + +sub_concept Food.Freshness { + Fresh, + Stale, + Spoiled +} + +concept_comparison FoodQuality { + Excellent: { + Food.Type: any, + Food.Freshness: Food.Freshness is Fresh + }, + Poor: { + Food.Type: any, + Food.Freshness: Food.Freshness is Stale or Food.Freshness is Spoiled + } +} +``` + +### Record Type +```storybook +concept Inventory; + +sub_concept Inventory.Record { + item_type: Product, + quantity: any, + location: StorageArea +} +``` + +--- + +## Implementation Notes + +### Parser +- Sub_concept parent inference uses prefix matching on the concept name +- Enumerated vs typed sub_concepts are disambiguated by presence of `:` after first identifier +- `any` keyword is parsed as `Value::Any` in the AST + +### AST Representation +```rust +pub struct ConceptDecl { + pub name: Text, + pub span: Span, +} + +pub struct SubConceptDecl { + pub name: Text, + pub parent_concept: Text, // Inferred from naming convention + pub kind: SubConceptKind, + pub span: Span, +} + +pub enum SubConceptKind { + Enum { variants: Vec }, + Record { fields: Vec }, +} + +pub struct ConceptComparisonDecl { + pub name: Text, + pub variants: Vec, + pub span: Span, +} + +pub struct VariantPattern { + pub name: Text, + pub conditions: Vec, + pub span: Span, +} + +pub enum Condition { + Any, + Is(Vec), // "is Value1 or Value2" +} +``` + +--- + +--- + +## Species and Template Inheritance + +### Species as Base Types with Defaults + +Species define base record types with default values that templates can extend and characters can override. + +**Syntax:** +```storybook +species SpeciesName { + field: Type = default_value, + ... +} +``` + +**Example:** +```storybook +species Human { + bipedal: Boolean = true, + has_hair: Boolean = true, + base_lifespan: Number = 80, + can_use_magic: Boolean = false +} + +species Elf { + bipedal: Boolean = true, + pointed_ears: Boolean = true, + base_lifespan: Number = 1000, + can_use_magic: Boolean = true +} +``` + +### Template Extension + +Templates extend species using `:` syntax and can override species defaults or add new fields. + +**Syntax:** +```storybook +template TemplateName: SpeciesName { + field: Type = default, // Override species field + new_field: Type, // Add new required field + new_field2: Type = default // Add new field with default +} +``` + +**Example:** +```storybook +template Person: Human { + // Inherits: bipedal, has_hair, base_lifespan, can_use_magic (with defaults) + age: Number, // New required field + name: Text // New required field +} + +template Cyborg: Human { + // Override species defaults + base_lifespan: Number = 200, // Cyborgs live longer + organic: Boolean = false, // New field + + // Add new fields + model: Text, // Required + battery_level: Number = 100 // With default +} +``` + +### Override Priority Chain + +**Character > Template > Species** + +When a field is defined at multiple levels, the most specific definition wins: + +```storybook +species Human { + strength: Number = 10, + intelligence: Number = 10, + speed: Number = 10 +} + +template Warrior: Human { + strength: Number = 15, // Override species default + weapon: Text // New required field +} + +character Conan: Warrior { + strength: 20, // Override template (which overrode species) + weapon: "Greatsword", // Required by template + intelligence: 5 // Override species default + // speed: 10 (from species, no overrides) +} +``` + +**Resolution order:** +1. Check character fields - use if present +2. Check template fields - use if present and not in character +3. Check species fields - use if not overridden +4. Error if no value found and field is required + +### Character Instantiation with Inheritance + +```storybook +character Martha: Person { + // Required template fields (no defaults) + age: 34, + name: "Martha", + + // Optional overrides of species defaults + bipedal: false, // She has one leg + can_use_magic: true, // Exceptional human + + // Inherited from species (use defaults) + // has_hair: true (from Human) + // base_lifespan: 80 (from Human) +} +``` + +### Benefits + +✅ **Layered defaults** - species → template → character +✅ **No redundancy** - don't repeat common defaults +✅ **Composable** - templates customize species for specific roles +✅ **Exceptional cases** - characters override when needed +✅ **Clear precedence** - explicit override chain + +--- + +## Life Arcs as Entity State + +### Core Concept + +**Life arcs represent the current state of an entity in various state machines.** + +An entity (character/location/institution) is not just data - it has **state** that changes over time. Life arcs define: +- What states exist (Baby, Child, Adult, Elder) +- How to transition between states (when age >= 18) +- What behaviors are available in each state + +**The entity's life arc assignments ARE its current state in those state machines.** + +### Entity State Model + +```storybook +character Martha: Baker { + // Data fields + age: 34, + skill_level: 8, + reputation: 85, + + // STATE - current position in life arc state machines + life_arcs: { + Human: Adult, // In "Adult" state of Human state machine + Baker: Master, // In "Master" state of Baker state machine + Reputation: Famous // In "Famous" state of Reputation state machine + } +} +``` + +**Martha's state is:** +- Age progression: Adult (can Work, Train, Manage) +- Career progression: Master (can BakingWork, TrainApprentice, InnovateTechniques) +- Social progression: Famous (can Influence, NetworkGlobally) + +### Life Arcs Define State Machines + +```storybook +life_arc Human requires { age: Number } { + Baby { + when age < 2 + can use behaviors: [Cry, Sleep, Eat] + -> Child when age >= 2 + } + + Child { + when age >= 2 and age < 12 + can use behaviors: [Play, Learn, Eat, Sleep] + -> Adolescent when age >= 12 + } + + Adolescent { + when age >= 12 and age < 18 + can use behaviors: [Play, Learn, Socialize, Work] + -> Adult when age >= 18 + } + + Adult { + when age >= 18 and age < 65 + can use behaviors: [Work, Socialize, Train, Manage] + -> Elder when age >= 65 + } + + Elder { + when age >= 65 + can use behaviors: [Rest, Socialize, Mentor] + } +} +``` + +**This defines:** +- **States**: Baby, Child, Adolescent, Adult, Elder +- **Transitions**: age thresholds trigger state changes +- **Capabilities**: each state grants different behaviors + +### State Determines Capabilities + +**Behavior availability = Life Arc States + Location + Template** + +```storybook +Can Martha use TrainApprentice at Bakery? + + Check life arc states: + ✓ Human.Adult grants ability to Train + ✓ Baker.Master grants TrainApprentice + + Check location: + ✓ Bakery enables TrainApprentice + + → YES - all conditions met +``` + +**If Martha were Baker.Journeyman instead:** +```storybook +character Martha: Baker { + skill_level: 5, + life_arcs: { + Human: Adult, + Baker: Journeyman // Different state! + } +} + +Can Martha use TrainApprentice at Bakery? + + Check life arc states: + ✓ Human.Adult grants ability to Train + ✗ Baker.Journeyman does NOT grant TrainApprentice + + → NO - lacks capability from life arc state +``` + +### Multiple Concurrent State Machines + +Entities can be in multiple state machines simultaneously: + +```storybook +life_arc Human requires { age: Number } { + // Age-based progression +} + +life_arc Baker requires { skill_level: Number } { + // Skill-based progression +} + +life_arc Reputation requires { fame: Number } { + // Fame-based progression +} + +character Martha: Baker { + age: 34, + skill_level: 8, + fame: 85, + + life_arcs: { + Human: Adult, // State in age dimension + Baker: Master, // State in career dimension + Reputation: Famous // State in social dimension + } +} +``` + +**Each life arc is an independent state machine:** +- Human state machine: transitions based on age +- Baker state machine: transitions based on skill_level +- Reputation state machine: transitions based on fame + +**Available behaviors = union of all state capabilities:** +- From Human.Adult: Work, Train, Manage +- From Baker.Master: BakingWork, TrainApprentice +- From Reputation.Famous: Influence, NetworkGlobally + +### Locations Have State Too + +```storybook +life_arc Settlement requires { population: Number, development: Number } { + Village { + when population < 500 + enables behaviors: [Farming, Fishing] + -> Town when population >= 500 and development >= 3 + } + + Town { + when population >= 500 and population < 5000 + enables behaviors: [Trading, Crafting, Farming] + -> City when population >= 5000 and development >= 7 + } + + City { + when population >= 5000 + enables behaviors: [Trading, Manufacturing, Politics, Education] + } +} + +location TownSquare: SettlementTemplate { + population: 500, + development: 4, + + life_arcs: { + Settlement: Town // Current state + } +} +``` + +**TownSquare's state:** +- It's in the "Town" state (not Village, not City) +- It enables behaviors: Trading, Crafting, Farming +- When population reaches 5000 AND development reaches 7, it transitions to City state + +### Institutions Have State Too + +```storybook +life_arc Business requires { revenue: Number, reputation: Number } { + Startup { + when revenue < 10000 + enables behaviors: [Hustle, Experiment] + -> Established when revenue >= 10000 + } + + Established { + when revenue >= 10000 and revenue < 100000 + enables behaviors: [Operate, Expand] + -> Corporate when revenue >= 100000 + } + + Corporate { + when revenue >= 100000 + enables behaviors: [Operate, Expand, Franchise, Lobby] + } +} + +institution Bakery: Building { + revenue: 15000, + reputation: 75, + + life_arcs: { + Business: Established // Current state + } +} +``` + +### Bidirectional State Transitions + +**State machines are NOT necessarily forward-only.** + +Characters can progress forward, regress backward, or transition laterally based on field changes: + +```storybook +life_arc Baker requires { skill_level: Number, experience: Number } { + Apprentice { + when skill_level < 3 + can use behaviors: [Learn, AssistBaking] + -> Journeyman when skill_level >= 3 + } + + Journeyman { + when skill_level >= 3 and skill_level < 7 + can use behaviors: [BakingWork, ManageInventory] + -> Master when skill_level >= 7 // Progress forward + -> Apprentice when skill_level < 3 // Regress backward! + } + + Master { + when skill_level >= 7 + can use behaviors: [BakingWork, ManageInventory, TrainApprentice, InnovateTechniques] + -> Journeyman when skill_level < 7 // Can lose mastery! + } +} +``` + +**The `when` clause defines:** +- **State validity condition**: What must be true to be in this state +- **NOT a one-time check**: Re-evaluated whenever fields change + +**Examples of regression:** + +```storybook +character Martha: Baker { + skill_level: 8, + life_arcs: { Baker: Master } +} + +// Martha is Master Baker, then loses practice +action lose_practice(baker: Person) { + baker.skill_level -= 5 // Now skill_level = 3 +} + +lose_practice(Martha) + +// Runtime re-evaluates: +// 1. Is Martha still valid for Master? (requires skill_level >= 7) +// 3 >= 7? NO - state is invalid! +// 2. Check Master's transitions: +// -> Journeyman when skill_level < 7 +// 3 < 7? YES - transition! +// 3. Martha is now Journeyman + +// Martha's available behaviors change: +// Lost: TrainApprentice, InnovateTechniques +// Kept: BakingWork, ManageInventory +``` + +**Examples of recovery:** + +```storybook +// Later, Martha practices and improves +action practice_baking(baker: Person) { + baker.skill_level += 1 +} + +// Practice multiple times +practice_baking(Martha) // skill_level = 4 +practice_baking(Martha) // skill_level = 5 +practice_baking(Martha) // skill_level = 6 +practice_baking(Martha) // skill_level = 7 + +// After skill_level reaches 7: +// Runtime re-evaluates: +// 1. Check Journeyman's transitions: +// -> Master when skill_level >= 7 +// 7 >= 7? YES - transition! +// 2. Martha is Master again! +``` + +### State Changes = Mutations + +**Life arcs ARE the mutability mechanism:** + +1. **Actions modify field values:** +```storybook +action practice_baking(baker: Person) { + // Runtime implementation + baker.skill_level += 1 +} + +action lose_practice(baker: Person) { + // Runtime implementation + baker.skill_level -= 1 +} +``` + +2. **Modified values trigger state transitions (in ANY direction):** +```storybook +// Progression +// Before: Martha.skill_level = 6, Baker state = Journeyman +practice_baking(Martha) +// After: Martha.skill_level = 7 +// Transition: Journeyman -> Master (forward) + +// Regression +// Before: Martha.skill_level = 7, Baker state = Master +lose_practice(Martha) +lose_practice(Martha) +lose_practice(Martha) +// After: Martha.skill_level = 4 +// Transition: Master -> Journeyman (backward) +``` + +3. **New state grants/removes capabilities:** +```storybook +// After progression to Master: +// Gained: TrainApprentice, InnovateTechniques + +// After regression to Journeyman: +// Lost: TrainApprentice, InnovateTechniques +// Kept: BakingWork, ManageInventory +``` + +### Runtime State Re-evaluation + +**After ANY action that modifies fields:** + +```rust +impl Runtime { + fn execute_action(&mut self, action: Action) { + // 1. Execute action (mutates entity fields) + let entity_id = match &action { + Action::PracticeBaking { baker } => { + let character = self.get_character_mut(*baker); + character.skill_level += 1; + *baker + } + Action::LosePractice { baker } => { + let character = self.get_character_mut(*baker); + character.skill_level -= 1; + *baker + } + _ => { + // Handle other actions + return; + } + }; + + // 2. Re-evaluate ALL life arc states for this entity + self.update_life_arc_states(entity_id); + } + + fn update_life_arc_states(&mut self, entity_id: EntityId) { + let entity = self.get_character(entity_id); + let life_arcs = entity.life_arcs.clone(); + + for (arc_name, current_state) in &life_arcs { + let arc = self.get_life_arc(arc_name); + let state_def = arc.get_state(current_state); + + // Check if current state condition is still valid + if !self.evaluate_condition(entity_id, &state_def.condition) { + // State is invalid - find valid transition + for transition in &state_def.transitions { + if self.evaluate_condition(entity_id, &transition.condition) { + // Transition to new state + let entity = self.get_character_mut(entity_id); + entity.life_arcs.insert(arc_name.clone(), transition.to.clone()); + + // Log transition + println!( + "Entity {} transitioned: {}.{} -> {}.{}", + entity.name, arc_name, current_state, arc_name, transition.to + ); + + break; + } + } + } + } + } +} +``` + +**Re-evaluation algorithm:** +1. After action execution, check ALL life arcs for the affected entity +2. For each life arc, evaluate current state's `when` condition +3. If condition is FALSE, current state is invalid +4. Check state's transitions in order +5. Take first transition whose condition is TRUE +6. Update entity's life_arcs to new state +7. New state's capabilities are now available + +**Design principle:** State follows data. When field values change, states automatically transition to match the new reality. + +### Mental Model + +**Think of entities as:** +- **Data**: Fields with values (age, skill_level, reputation) +- **State**: Current position in life arc state machines +- **Capability**: Behaviors available based on state + location + template + +**Life arcs are NOT metadata - they ARE the state.** + +When you ask "What can Martha do?", you're asking: +1. What state is she in? (Human.Adult, Baker.Master) +2. Where is she? (Bakery) +3. What does her template grant? (Baker template) + +The answer is the intersection of capabilities from all three layers. + +--- + +--- + +## Type System Soundness + +### Type Theory Foundations + +Storybook uses a **hybrid type system** combining: +- **Nominal typing**: Templates and entities have explicit names and identity +- **Structural typing**: Life arc requirements use duck typing (any template with required fields) +- **Subtype polymorphism**: Template extension creates subtype relationships +- **Algebraic types**: Concepts and sub_concepts form sum types with pattern matching + +### Subtyping Relationship + +**Template extension creates subtyping:** + +```storybook +species Human { strength: Number = 10 } +template Person: Human { age: Number } +template Baker: Person { skill_level: Number } + +Type hierarchy: + Baker <: Person <: Human +``` + +**Liskov Substitution Principle:** +- Baker can be used wherever Person is expected (has all Person fields) +- Person can be used wherever Human is expected (has all Human fields) +- Subtyping flows from child to parent (upcast is implicit and safe) + +**Action parameter compatibility:** +```storybook +action greet(person: Person) + +character Martha: Baker +greet(Martha) // ✓ Valid - Baker <: Person (implicit upcast) + +action train_baker(baker: Baker) + +character Bob: Person +train_baker(Bob) // ✗ ERROR - Person Template > Species** + +```storybook +species Human { strength: Number = 10, speed: Number = 10 } +template Warrior: Human { strength: Number = 15 } +character Conan: Warrior { strength: 20 } + +Field lookup algorithm: + Conan.strength: + 1. Check character instance → 20 ✓ FOUND + 2. (not reached) + + Conan.speed: + 1. Check character instance → not found + 2. Check Warrior template → not found + 3. Check Human species → 10 ✓ FOUND +``` + +**Type invariance through chain:** +- Field types cannot change through inheritance +- If species defines `strength: Number`, template cannot override to `strength: Text` +- Only values/defaults can be overridden, not types + +### Life Arc Type Constraints + +**Life arcs use structural requirements (duck typing):** + +```storybook +life_arc Aging requires { age: Number, species: Species } + +// Works with ANY template that has these fields +``` + +**Compile-time validation:** +```storybook +template Person: Human { + age: Number, // ✓ has required field + name: Text, + // species inherited from Human ✓ has required field +} + +character Martha: Person { + life_arcs: { + Aging: Adult // ✓ Person has all required fields + } +} + +// Compiler checks: +// 1. Does Person have field 'age' of type Number? YES +// 2. Does Person have field 'species' of type Species? YES (inherited) +// 3. Are types exact match (not subtypes)? YES +// → VALID +``` + +**Unsoundness prevention:** +```storybook +template Robot { + age?: Number // Optional field +} + +life_arc Aging requires { age: Number } { + // Requires NON-optional age +} + +character R2D2: Robot { + life_arcs: { Aging: Adult } +} + +// ✗ TYPE ERROR: Aging requires age: Number (required) +// but Robot has age?: Number (optional) +// Required field cannot be optional in template +``` + +**Rule:** Life arc required fields MUST be non-optional in template. + +### Behavior Type Checking + +**Implicit self with template typing:** + +```storybook +behavior BakingWork { + then { + check_orders // Desugars to: check_orders(self) + bake(Bread) // Desugars to: bake(self, Bread) + } +} + +action check_orders(baker: Baker) +action bake(baker: Baker, item: Item) +``` + +**Type of implicit self:** +- `self` has the type of the entity's template +- Known at compile-time + +**Compatibility checking:** +```storybook +character Martha: Baker { + uses behaviors: [BakingWork] +} + +// Compiler validates: +// When Martha runs BakingWork: +// self: Baker (Martha's template) +// check_orders(self) → check_orders(Baker) ✓ +// bake(self, Bread) → bake(Baker, Item) ✓ +// → VALID + +character Bob: Person { + uses behaviors: [BakingWork] +} + +// Compiler validates: +// When Bob tries to run BakingWork: +// self: Person (Bob's template) +// check_orders(self) → check_orders(Person) +// But check_orders expects Baker +// Person = 7 // Entry condition + runtime assertion + can use behaviors: [InnovateTechniques] + } +} +``` + +**The `when` clause serves two purposes:** +1. **Entry condition**: Must be true to transition INTO this state +2. **Runtime assertion**: Should be true while IN this state + +**Potential inconsistency:** +```storybook +character Martha: Baker { + skill_level: 8, + life_arcs: { Baker: Master } // State says Master +} + +action lower_skill(baker: Baker) { + baker.skill_level -= 5 // Now skill_level = 3 +} + +// After action: Martha is in Master state, but skill_level < 7 +// State is inconsistent with data! +``` + +**Resolution - Hybrid approach:** + +**Compile-time (Storybook):** +Emit warnings when actions could invalidate state conditions: +``` +Warning: action 'lower_skill' modifies 'skill_level' which is used in + state condition for Baker.Master (requires skill_level >= 7). + Runtime should validate state before executing state-specific behaviors. +``` + +**Runtime (Implementation):** +Before executing behaviors that depend on state: +```rust +impl Runtime { + fn execute_behavior(&mut self, entity_id: EntityId, behavior: &Behavior) { + let character = self.get_character(entity_id); + + // Validate current state conditions + for (arc_name, current_state) in &character.life_arcs { + let arc = self.get_life_arc(arc_name); + let state_def = arc.get_state(current_state); + + if !self.evaluate_condition(entity_id, &state_def.condition) { + // State is inconsistent! + // Option A: Re-evaluate and transition to correct state + // Option B: Log warning and continue + // Option C: Throw error and reject behavior + // Runtime decides policy + } + } + + // Execute behavior actions... + } +} +``` + +**Rule:** State conditions are validated at entry (transition time) and SHOULD be validated at execution time (runtime's responsibility). + +### Type Checking Guarantees + +**Compile-time guarantees:** +✅ Template subtyping is safe (Baker <: Person) +✅ Field access through inheritance is valid +✅ Life arc structural requirements are satisfied +✅ Action parameters match expected types +✅ Behaviors are compatible with entity templates +✅ Initial life arc states satisfy entry conditions + +**Runtime responsibilities:** +⚠️ Validate state conditions before executing state-specific behaviors +⚠️ Handle state transitions when field values change +⚠️ Manage entity state consistency + +**The language guarantees type safety at compile-time. The runtime guarantees state consistency at execution-time.** + +### Formal Type Rules + +**Subtyping (transitive):** +``` +T extends S +─────────────── (SUB-EXTEND) +T <: S + +T <: S S <: R +─────────────── (SUB-TRANS) +T <: R +``` + +**Field access:** +``` +E : T T has field f : τ (through inheritance chain) +──────────────────────────────────────────────────── (FIELD-ACCESS) +E.f : τ +``` + +**Life arc compatibility:** +``` +T has fields {f1: τ1, ..., fn: τn} (required, non-optional) +L requires {f1: τ1, ..., fn: τn} +──────────────────────────────────────────────────── (LIFEARC-COMPAT) +T compatible with L +``` + +**Behavior validity:** +``` +B calls actions {a1(Self, ...), ..., an(Self, ...)} +E : T +∀i. T <: ParamType(ai, 0) (template is subtype of first param) +──────────────────────────────────────────────────── (BEHAVIOR-VALID) +E can use behavior B +``` + +**Action call:** +``` +a : (T1, T2, ..., Tn) → Unit +E : T T <: T1 +args : (T2, ..., Tn) +──────────────────────────────────────────────────── (ACTION-CALL) +a(E, args) : Unit +``` + +### Summary + +The type system is **sound** with these properties: +- **Progress**: Well-typed programs don't get stuck at compile-time +- **Type preservation**: Types are maintained through inheritance and execution +- **Memory safety**: No invalid field access or type confusion +- **Subtype safety**: Upcasting (child → parent) is safe and implicit + +The runtime must maintain **state consistency** by validating life arc conditions at execution time. + +--- + +## Future Considerations + +- **Exhaustiveness checking**: Ensure all variant combinations are covered in concept_comparisons +- **Default variants**: Support for catch-all patterns in comparisons +- **Type inference**: Automatic parent concept detection beyond prefix matching +- **Generic concepts**: Parameterized types for reusable patterns +- **Constraint validation**: Runtime validation of type constraints diff --git a/design.md b/docs/design.md similarity index 100% rename from design.md rename to docs/design.md diff --git a/examples/alice-in-wonderland/README.md b/examples/alice-in-wonderland/README.md deleted file mode 100644 index 4600421..0000000 --- a/examples/alice-in-wonderland/README.md +++ /dev/null @@ -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 diff --git a/examples/alice-in-wonderland/schema/beings.sb b/examples/alice-in-wonderland/schema/beings.sb deleted file mode 100644 index 14aa65a..0000000 --- a/examples/alice-in-wonderland/schema/beings.sb +++ /dev/null @@ -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. - --- -} diff --git a/examples/alice-in-wonderland/schema/templates.sb b/examples/alice-in-wonderland/schema/templates.sb deleted file mode 100644 index a57bb5e..0000000 --- a/examples/alice-in-wonderland/schema/templates.sb +++ /dev/null @@ -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 -} diff --git a/examples/alice-in-wonderland/storybook.toml b/examples/alice-in-wonderland/storybook.toml deleted file mode 100644 index 7bf510c..0000000 --- a/examples/alice-in-wonderland/storybook.toml +++ /dev/null @@ -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 diff --git a/examples/alice-in-wonderland/world/behaviors/wonderland_behaviors.sb b/examples/alice-in-wonderland/world/behaviors/wonderland_behaviors.sb deleted file mode 100644 index 6b17afa..0000000 --- a/examples/alice-in-wonderland/world/behaviors/wonderland_behaviors.sb +++ /dev/null @@ -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 - } - } -} diff --git a/examples/alice-in-wonderland/world/characters/alice.sb b/examples/alice-in-wonderland/world/characters/alice.sb deleted file mode 100644 index b39e0a2..0000000 --- a/examples/alice-in-wonderland/world/characters/alice.sb +++ /dev/null @@ -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. - --- - } -} diff --git a/examples/alice-in-wonderland/world/characters/caterpillar.sb b/examples/alice-in-wonderland/world/characters/caterpillar.sb deleted file mode 100644 index 30d7edb..0000000 --- a/examples/alice-in-wonderland/world/characters/caterpillar.sb +++ /dev/null @@ -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 - } - } -} diff --git a/examples/alice-in-wonderland/world/characters/cheshire_cat.sb b/examples/alice-in-wonderland/world/characters/cheshire_cat.sb deleted file mode 100644 index b680548..0000000 --- a/examples/alice-in-wonderland/world/characters/cheshire_cat.sb +++ /dev/null @@ -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 - } - } -} diff --git a/examples/alice-in-wonderland/world/characters/mad_tea_party.sb b/examples/alice-in-wonderland/world/characters/mad_tea_party.sb deleted file mode 100644 index a44398e..0000000 --- a/examples/alice-in-wonderland/world/characters/mad_tea_party.sb +++ /dev/null @@ -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 - } - } - } - } - } -} diff --git a/examples/alice-in-wonderland/world/characters/royal_court.sb b/examples/alice-in-wonderland/world/characters/royal_court.sb deleted file mode 100644 index f899e86..0000000 --- a/examples/alice-in-wonderland/world/characters/royal_court.sb +++ /dev/null @@ -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 - } - } -} diff --git a/examples/alice-in-wonderland/world/characters/white_rabbit.sb b/examples/alice-in-wonderland/world/characters/white_rabbit.sb deleted file mode 100644 index 50e84ff..0000000 --- a/examples/alice-in-wonderland/world/characters/white_rabbit.sb +++ /dev/null @@ -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 - } - } -} diff --git a/examples/alice-in-wonderland/world/institutions/wonderland_institutions.sb b/examples/alice-in-wonderland/world/institutions/wonderland_institutions.sb deleted file mode 100644 index 5696881..0000000 --- a/examples/alice-in-wonderland/world/institutions/wonderland_institutions.sb +++ /dev/null @@ -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). - --- -} diff --git a/examples/alice-in-wonderland/world/locations/wonderland_places.sb b/examples/alice-in-wonderland/world/locations/wonderland_places.sb deleted file mode 100644 index 352e93e..0000000 --- a/examples/alice-in-wonderland/world/locations/wonderland_places.sb +++ /dev/null @@ -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. - --- -} diff --git a/examples/alice-in-wonderland/world/relationships/wonderland_relationships.sb b/examples/alice-in-wonderland/world/relationships/wonderland_relationships.sb deleted file mode 100644 index 1063525..0000000 --- a/examples/alice-in-wonderland/world/relationships/wonderland_relationships.sb +++ /dev/null @@ -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 -} diff --git a/examples/alice-in-wonderland/world/schedules/wonderland_schedules.sb b/examples/alice-in-wonderland/world/schedules/wonderland_schedules.sb deleted file mode 100644 index be29347..0000000 --- a/examples/alice-in-wonderland/world/schedules/wonderland_schedules.sb +++ /dev/null @@ -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 - } - } -} diff --git a/install-zed-extension.sh b/install-zed-extension.sh deleted file mode 100755 index 621d577..0000000 --- a/install-zed-extension.sh +++ /dev/null @@ -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 "" diff --git a/test-extension.sb b/test-extension.sb deleted file mode 100644 index 8276432..0000000 --- a/test-extension.sb +++ /dev/null @@ -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 { - } -}