Created
April 26, 2026 04:44
-
-
Save rfielding/47cbec650bd9330e9bf55b2fd057633f to your computer and use it in GitHub Desktop.
Repository Wiki — generated by GitNexus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>go-ctl2 — Wiki</title> | |
| <script src="https://cdn.jsdelivr.net/npm/marked@11.0.0/marked.min.js"></script> | |
| <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script> | |
| <style> | |
| *{margin:0;padding:0;box-sizing:border-box} | |
| :root{ | |
| --bg:#ffffff;--sidebar-bg:#f8f9fb;--border:#e5e7eb; | |
| --text:#1e293b;--text-muted:#64748b;--primary:#2563eb; | |
| --primary-soft:#eff6ff;--hover:#f1f5f9;--code-bg:#f1f5f9; | |
| --radius:8px;--shadow:0 1px 3px rgba(0,0,0,.08); | |
| } | |
| body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; | |
| line-height:1.65;color:var(--text);background:var(--bg)} | |
| .layout{display:flex;min-height:100vh} | |
| .sidebar{width:280px;background:var(--sidebar-bg);border-right:1px solid var(--border); | |
| position:fixed;top:0;left:0;bottom:0;overflow-y:auto;padding:24px 16px; | |
| display:flex;flex-direction:column;z-index:10} | |
| .content{margin-left:280px;flex:1;padding:48px 64px;max-width:960px} | |
| .sidebar-header{margin-bottom:20px;padding-bottom:16px;border-bottom:1px solid var(--border)} | |
| .sidebar-title{font-size:16px;font-weight:700;color:var(--text);display:flex;align-items:center;gap:8px} | |
| .sidebar-title svg{flex-shrink:0} | |
| .sidebar-meta{font-size:11px;color:var(--text-muted);margin-top:6px} | |
| .nav-section{margin-bottom:2px} | |
| .nav-item{display:block;padding:7px 12px;border-radius:var(--radius);cursor:pointer; | |
| font-size:13px;color:var(--text);text-decoration:none;transition:all .15s; | |
| white-space:nowrap;overflow:hidden;text-overflow:ellipsis} | |
| .nav-item:hover{background:var(--hover)} | |
| .nav-item.active{background:var(--primary-soft);color:var(--primary);font-weight:600} | |
| .nav-item.overview{font-weight:600;margin-bottom:4px} | |
| .nav-children{padding-left:14px;border-left:1px solid var(--border);margin-left:12px} | |
| .nav-group-label{font-size:11px;font-weight:600;color:var(--text-muted); | |
| text-transform:uppercase;letter-spacing:.5px;padding:12px 12px 4px;user-select:none} | |
| .sidebar-footer{margin-top:auto;padding-top:16px;border-top:1px solid var(--border); | |
| font-size:11px;color:var(--text-muted);text-align:center} | |
| .content h1{font-size:28px;font-weight:700;margin-bottom:8px;line-height:1.3} | |
| .content h2{font-size:22px;font-weight:600;margin:32px 0 12px;padding-bottom:6px;border-bottom:1px solid var(--border)} | |
| .content h3{font-size:17px;font-weight:600;margin:24px 0 8px} | |
| .content h4{font-size:15px;font-weight:600;margin:20px 0 6px} | |
| .content p{margin:12px 0} | |
| .content ul,.content ol{margin:12px 0 12px 24px} | |
| .content li{margin:4px 0} | |
| .content a{color:var(--primary);text-decoration:none} | |
| .content a:hover{text-decoration:underline} | |
| .content blockquote{border-left:3px solid var(--primary);padding:8px 16px;margin:16px 0; | |
| background:var(--primary-soft);border-radius:0 var(--radius) var(--radius) 0; | |
| color:var(--text-muted);font-size:14px} | |
| .content code{font-family:'SF Mono',Consolas,'Courier New',monospace;font-size:13px; | |
| background:var(--code-bg);padding:2px 6px;border-radius:4px} | |
| .content pre{background:#1e293b;color:#e2e8f0;border-radius:var(--radius);padding:16px; | |
| overflow-x:auto;margin:16px 0} | |
| .content pre code{background:none;padding:0;font-size:13px;line-height:1.6;color:inherit} | |
| .content table{border-collapse:collapse;width:100%;margin:16px 0} | |
| .content th,.content td{border:1px solid var(--border);padding:8px 12px;text-align:left;font-size:14px} | |
| .content th{background:var(--sidebar-bg);font-weight:600} | |
| .content img{max-width:100%;border-radius:var(--radius)} | |
| .content hr{border:none;border-top:1px solid var(--border);margin:32px 0} | |
| .content .mermaid{margin:20px 0;text-align:center} | |
| .menu-toggle{display:none;position:fixed;top:12px;left:12px;z-index:20; | |
| background:var(--bg);border:1px solid var(--border);border-radius:var(--radius); | |
| padding:8px 12px;cursor:pointer;font-size:18px;box-shadow:var(--shadow)} | |
| @media(max-width:768px){ | |
| .sidebar{transform:translateX(-100%);transition:transform .2s} | |
| .sidebar.open{transform:translateX(0);box-shadow:2px 0 12px rgba(0,0,0,.1)} | |
| .content{margin-left:0;padding:24px 20px;padding-top:56px} | |
| .menu-toggle{display:block} | |
| } | |
| .empty-state{text-align:center;padding:80px 20px;color:var(--text-muted)} | |
| .empty-state h2{font-size:20px;margin-bottom:8px;border:none} | |
| </style> | |
| </head> | |
| <body> | |
| <button class="menu-toggle" id="menu-toggle" aria-label="Toggle menu">☰</button> | |
| <div class="layout"> | |
| <nav class="sidebar" id="sidebar"> | |
| <div class="sidebar-header"> | |
| <div class="sidebar-title"> | |
| <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 3h6a4 4 0 014 4v14a3 3 0 00-3-3H2z"/><path d="M22 3h-6a4 4 0 00-4 4v14a3 3 0 013-3h7z"/></svg> | |
| go-ctl2 | |
| </div> | |
| <div class="sidebar-meta" id="meta-info"></div> | |
| </div> | |
| <div id="nav-tree"></div> | |
| <div class="sidebar-footer">Generated by GitNexus</div> | |
| </nav> | |
| <main class="content" id="content"> | |
| <div class="empty-state"><h2>Loading…</h2></div> | |
| </main> | |
| </div> | |
| <script> | |
| var PAGES = {"core-logic":"# Core Logic\n\n# Core Logic Module Documentation\n\n## Overview\n\nThe **Core Logic** module is responsible for managing the runtime environment of actors, their states, transitions, and message passing. It implements a state machine model where actors can transition between states based on defined guards and actions. This module is crucial for simulating complex interactions in a concurrent system, allowing for the exploration of various actor behaviors and their interactions.\n\n## Key Components\n\n### 1. Types and Enums\n\n- **Kind**: An enumeration representing the type of a value (e.g., `KindSymbol`, `KindNumber`, `KindString`, etc.).\n- **Value**: A struct that encapsulates a value's kind, text representation, and any nested items.\n- **Actor**: Represents an entity in the system with its name, role, state data, and transitions.\n- **State**: Represents a state of an actor, including its transitions and guards.\n- **Transition**: Defines a transition from one state to another, including guards and actions.\n\n### 2. Runtime\n\nThe `Runtime` struct is the core of the module, managing the execution of actors and their interactions. It contains:\n\n- **Actors**: A list of all actors in the system.\n- **Mailboxes**: A mapping of actor names to their message queues.\n- **Step**: A counter for the number of execution steps taken.\n- **Dice**: A function for generating random numbers, used in probabilistic transitions.\n\n### 3. Functions\n\n#### Actor Management\n\n- **NewRuntime**: Initializes a new runtime with a list of actors.\n- **Tick**: Advances the simulation by one step, selecting an actor and executing its transition.\n- **StepActor**: Executes a single step for a specified actor, returning whether a transition was applied.\n\n#### State and Transition Handling\n\n- **CurrentState**: Retrieves the current state of an actor.\n- **StepActorDetailed**: Executes the detailed logic for stepping an actor, including evaluating guards and executing actions.\n- **validateTransitionNext**: Validates the next state after a transition to ensure it is declared.\n\n#### Message Passing\n\n- **Enqueue**: Adds a message to an actor's mailbox.\n- **DequeueMatching**: Retrieves a message from an actor's mailbox that matches a specified guard.\n\n#### Event Logging\n\n- **logEvent**: Records events that occur during execution, such as transitions and message sends/receives.\n- **EventCountSeries**: Generates a series of event counts for analysis.\n\n### 4. Guard and Action Functions\n\n- **GuardFunc**: A type for functions that determine if a transition can occur based on the current state and actor data.\n- **ActionFunc**: A type for functions that define actions to be executed during a transition.\n\n### 5. CTL and Mu Calculus\n\nThe module supports the specification and evaluation of temporal logic formulas using CTL (Computation Tree Logic) and Mu Calculus. Functions like `CompileCTL` and `CompileMu` are provided to parse and compile these formulas into internal representations.\n\n## Execution Flow\n\nThe execution flow of the Core Logic module can be summarized as follows:\n\n1. **Initialization**: The runtime is initialized with a set of actors.\n2. **Ticking**: The `Tick` function is called to advance the simulation.\n3. **Actor Selection**: An actor is randomly selected (or chosen via a custom function).\n4. **State Transition**: The selected actor's current state is evaluated, and applicable transitions are checked against their guards.\n5. **Action Execution**: If a transition is valid, its action is executed, and the actor's state is updated.\n6. **Event Logging**: Events are logged for transitions and message passing.\n\n```mermaid\ngraph TD;\n A[Runtime] -->|Manages| B[Actors]\n A -->|Handles| C[Mailboxes]\n A -->|Tracks| D[Steps]\n A -->|Logs| E[Events]\n B -->|Has| F[States]\n F -->|Defines| G[Transitions]\n G -->|Uses| H[Guards]\n G -->|Executes| I[Actions]\n```\n\n## Integration with the Codebase\n\nThe Core Logic module interacts with other parts of the codebase, such as:\n\n- **Server Module**: The runtime can be invoked from server requests to simulate actor behaviors based on user-defined models.\n- **Testing**: The module includes various test cases to ensure the correctness of actor transitions, message passing, and logic evaluations.\n- **Documentation Generation**: The module supports generating documentation for actor models and their behaviors, aiding in understanding and debugging.\n\n## Conclusion\n\nThe Core Logic module is a foundational component for simulating and managing actor-based systems. Its design allows for flexible state management, message passing, and the evaluation of complex logical conditions, making it suitable for a wide range of applications in concurrent programming and system modeling.","diagram-generation":"# Diagram Generation\n\n# Diagram Generation Module\n\nThe Diagram Generation module is responsible for generating visual representations of data using Mermaid syntax and creating XY plots from Go test data. It consists of two main scripts: `generate_diagram_sections.py` and `generate_xyplot.py`. This documentation outlines the purpose, functionality, and key components of each script, as well as their interactions.\n\n## Overview\n\n### Purpose\n\n- **`generate_diagram_sections.py`**: This script generates Markdown sections for diagrams defined in Mermaid files. It reads `.mmd` files from a specified directory, formats them into Markdown, and outputs the result to a specified file.\n \n- **`generate_xyplot.py`**: This script generates XY plots based on data emitted from Go tests. It retrieves plot data, formats it into Mermaid syntax, and outputs the results in a Markdown format.\n\n### Execution Flow\n\n```mermaid\ngraph TD;\n A[generate_diagram_sections.py] -->|calls| B[main()]\n B -->|reads| C[Mermaid files]\n B -->|writes| D[Markdown output]\n \n E[generate_xyplot.py] -->|calls| F[main()]\n F -->|loads| G[Go test manifest]\n F -->|loads| H[Plot data]\n F -->|writes| I[Markdown output]\n```\n\n## Key Components\n\n### 1. `generate_diagram_sections.py`\n\n#### Functions\n\n- **`title(name: str) -> str`**: Converts a given name by replacing underscores and hyphens with spaces and capitalizing each word.\n\n- **`main() -> int`**: The entry point of the script. It validates input arguments, reads Mermaid files, formats them into Markdown, and writes the output to a specified file.\n\n#### Usage\n\nTo run the script, use the following command:\n\n```bash\npython3 generate_diagram_sections.py <mermaid_dir> <out>\n```\n\n- `<mermaid_dir>`: Directory containing `.mmd` files.\n- `<out>`: Output Markdown file.\n\n### 2. `generate_xyplot.py`\n\n#### Functions\n\n- **`go_binary() -> str`**: Determines the path to the Go executable, checking for a Snap installation or using the system's PATH.\n\n- **`go_env() -> dict[str, str]`**: Sets up the environment for running Go commands, specifically defining a temporary GOCACHE.\n\n- **`load_manifest()`**: Executes a Go test to retrieve a manifest of plot data, returning it as a JSON object.\n\n- **`load_plot_data(name: str)`**: Loads specific plot data by executing a Go test with the provided name, returning the data as a JSON object.\n\n- **`format_number(value: float) -> str`**: Formats a number for display, ensuring it is presented in a user-friendly manner.\n\n- **`render_plot_mermaid(data: dict) -> str`**: Converts plot data into Mermaid syntax for rendering XY charts.\n\n- **`title(name: str) -> str`**: Similar to the function in `generate_diagram_sections.py`, it formats names for display.\n\n- **`main() -> int`**: The entry point of the script. It validates input arguments, loads the manifest and plot data, formats them into Markdown, and writes the output to a specified file.\n\n#### Usage\n\nTo run the script, use the following command:\n\n```bash\npython3 generate_xyplot.py <generated_dir> <sections_out>\n```\n\n- `<generated_dir>`: Directory where generated files will be stored.\n- `<sections_out>`: Output Markdown file for the XY plots.\n\n## Interactions with the Codebase\n\nBoth scripts are designed to work independently but can be used in conjunction to create comprehensive documentation that includes both diagrams and XY plots. The `generate_xyplot.py` script relies on Go test data, while `generate_diagram_sections.py` focuses on Mermaid files. \n\n### Dependencies\n\n- **Go**: The `generate_xyplot.py` script requires Go to be installed and accessible in the system's PATH.\n- **Mermaid**: The diagrams generated by `generate_diagram_sections.py` are based on Mermaid syntax, which should be supported in the Markdown rendering environment.\n\n## Conclusion\n\nThe Diagram Generation module provides essential functionality for visualizing data through diagrams and plots. By understanding the purpose and structure of each script, developers can effectively contribute to and extend the capabilities of this module.","documentation-generation":"# Documentation Generation\n\n# Documentation Generation Module\n\n## Overview\n\nThe **Documentation Generation** module is responsible for assembling documentation from various source snippets. It takes predefined sections of documentation and integrates them into a single output file, allowing for a streamlined process of generating comprehensive documentation for the codebase.\n\n## Purpose\n\nThe primary purpose of this module is to automate the documentation building process by combining different types of snippets (plot, language, and example) into a single document. This ensures that the documentation is consistent and up-to-date with the latest code changes.\n\n## Key Components\n\n### Main Function\n\nThe core of the module is the `main()` function, which orchestrates the documentation generation process. It performs the following tasks:\n\n1. **Argument Validation**: Checks if the correct number of command-line arguments are provided.\n2. **File Reading**: Reads the content of the documentation source and snippet files.\n3. **Content Replacement**: Replaces placeholders in the documentation source with the actual content from the snippets.\n4. **File Writing**: Writes the final assembled documentation to the specified output file.\n\n### Command-Line Interface\n\nThe module is executed from the command line with the following syntax:\n\n```bash\nbuild_doc.py <doc_src> <plot_snippets> <language_snippets> <example_snippets> <out>\n```\n\n- `<doc_src>`: Path to the main documentation source file.\n- `<plot_snippets>`: Path to the file containing plot snippets.\n- `<language_snippets>`: Path to the file containing language snippets.\n- `<example_snippets>`: Path to the file containing example snippets.\n- `<out>`: Path where the final documentation will be written.\n\n### Error Handling\n\nIf the number of command-line arguments is incorrect, the module raises a `SystemExit` with a usage message, preventing further execution.\n\n## Execution Flow\n\nThe execution flow of the module is straightforward, as it primarily consists of reading, processing, and writing files. Below is a simplified representation of the flow:\n\n```mermaid\ngraph TD;\n A[Start] --> B[Check Arguments]\n B -->|Valid| C[Read doc_src]\n B -->|Invalid| D[Exit with usage message]\n C --> E[Read plot_snippets]\n E --> F[Read language_snippets]\n F --> G[Read example_snippets]\n G --> H[Replace placeholders]\n H --> I[Write output to file]\n I --> J[End]\n```\n\n## How It Connects to the Codebase\n\nThis module is typically invoked as part of a build process or documentation generation pipeline. It can be integrated into CI/CD workflows to ensure that documentation is automatically updated whenever changes are made to the codebase. \n\nBy maintaining a clear structure for documentation snippets, developers can easily contribute to the documentation process by simply updating the relevant snippet files without needing to modify the main documentation source directly.\n\n## Conclusion\n\nThe Documentation Generation module is a crucial part of maintaining high-quality documentation in the codebase. By automating the assembly of documentation from various snippets, it reduces manual effort and helps ensure that the documentation remains accurate and comprehensive. Developers are encouraged to familiarize themselves with the command-line interface and the structure of the snippet files to effectively contribute to the documentation process.","other-docs":"# Other — docs\n\n# Other — docs Module Documentation\n\n## Overview\n\nThe **Other — docs** module is designed to provide a structured and visually appealing documentation framework for the actor-based model defined in the codebase. It encompasses styles, templates, and content that facilitate the generation of documentation, including diagrams and metrics, for the actor/message IR (Intermediate Representation) and its associated components.\n\n## Purpose\n\nThe primary purpose of this module is to:\n\n- Define a consistent dark theme for documentation using CSS.\n- Provide a Markdown structure for documenting the actor IR, control graphs, and temporal logic.\n- Enable the generation of diagrams using Mermaid to visualize the actor/message interactions and control flow.\n- Support the documentation build process, ensuring that the generated content is both readable and informative.\n\n## Key Components\n\n### 1. CSS Styles (`docs/dark.css`)\n\nThe CSS file defines a dark theme for the documentation, ensuring readability and aesthetic consistency. Key variables include:\n\n- `--bg`: Background color for the documentation.\n- `--text`: Text color for primary content.\n- `--link`: Color for hyperlinks.\n- `--panel`: Background color for panels and code blocks.\n\nThis styling enhances the user experience by providing a visually appealing interface for reading documentation.\n\n### 2. Documentation Structure (`docs/ir.md`)\n\nThe Markdown file serves as the main documentation for the actor IR, detailing its design, principles, and usage. Key sections include:\n\n- **Goal**: Outlines the intent behind the actor IR and its components.\n- **Audience**: Describes the target users and their expected interactions with the documentation.\n- **Design Principles**: Lists the foundational principles guiding the development of the actor IR.\n- **Core Model**: Provides an in-depth explanation of the actor, state, and transition concepts.\n- **Scheduling and Communication Semantics**: Details how actors interact and manage state transitions.\n- **Branching-Time Logic**: Explains the temporal logic used for model checking.\n- **Event Log and Metrics**: Describes how runtime events are logged and metrics are derived.\n\n### 3. Mermaid Diagrams\n\nThe module integrates Mermaid diagrams to visualize the control flow and interactions within the actor model. These diagrams are generated from the same source that defines the actor/message IR, ensuring consistency between the documentation and the underlying model.\n\n#### Example Mermaid Diagram\n\n```mermaid\nflowchart TD\n subgraph Client\n direction TB\n C_loop([loop]) -->|\"dice<0.5<br/>last = sleep\"| C_loop\n C_loop -->|\"dice>=0.5<br/>send req<br/>last = arrival\"| C_loop\n end\n\n subgraph Queue\n direction TB\n Q_wait([wait]) -->|\"req and count = 0<br/>count += 1<br/>elapsed = 0\"| Q_wait\n Q_wait -->|\"req and 0 < count < 5<br/>count += 1\"| Q_wait\n Q_wait -->|\"req and count = 5<br/>dropped_count += 1\"| Q_wait\n Q_wait -->|\"count > 0 and dice<0.5<br/>count -= 1<br/>last_departure = service-complete\"| Q_wait\n Q_wait -->|\"count > 0 and dice>=0.5<br/>last_departure = busy\"| Q_wait\n end\n\n C_loop -. arrival req .-> Q_wait\n```\n\n### 4. Build and Serve Documentation\n\nThe module includes a `Makefile` that provides commands for building and serving the documentation:\n\n- `make test`: Runs tests to ensure the integrity of the documentation.\n- `make docs`: Generates the documentation from Markdown and CSS sources.\n- `make serve-docs`: Serves the generated documentation over a local HTTP server for easy review.\n\n## Integration with the Codebase\n\nThe **Other — docs** module is tightly integrated with the actor/message IR implementation. The documentation reflects the current state of the codebase, ensuring that any changes in the actor model or its semantics are accurately represented in the documentation.\n\n### Workflow\n\n1. **Authoring**: Developers can write actor/message definitions in Lisp, which are then documented in Markdown.\n2. **Diagram Generation**: Mermaid diagrams are generated from the same definitions, providing a visual representation of the model.\n3. **Documentation Build**: The `Makefile` facilitates the building of the documentation, ensuring that all components are up-to-date and correctly formatted.\n4. **Review**: The served documentation can be reviewed locally, allowing for easy inspection and validation of the content.\n\n## Conclusion\n\nThe **Other — docs** module plays a crucial role in the overall architecture of the actor/message IR system. By providing a structured documentation framework, it enhances the usability and maintainability of the codebase, ensuring that developers can easily understand and contribute to the project. The integration of CSS styling, Markdown content, and Mermaid diagrams creates a cohesive and informative documentation experience.","other-go-mod":"# Other — go.mod\n\n# go.mod Module Documentation\n\n## Overview\n\nThe `go.mod` file is a crucial component of Go modules, which are the standard way to manage dependencies in Go projects. This specific `go.mod` file defines the module named `go-ctl2` and specifies that it is compatible with Go version 1.22. \n\n## Purpose\n\nThe primary purpose of the `go.mod` file is to:\n\n- Define the module's name.\n- Specify the Go version the module is compatible with.\n- Manage dependencies and their versions (though this file does not currently list any dependencies).\n\n## Structure\n\nThe `go.mod` file consists of the following key components:\n\n```go\nmodule go-ctl2\n\ngo 1.22\n```\n\n### Key Components\n\n1. **Module Declaration**:\n - The line `module go-ctl2` declares the name of the module. This name is used when importing the module in other Go files.\n\n2. **Go Version**:\n - The line `go 1.22` specifies that the module is intended to be used with Go version 1.22. This ensures compatibility and allows the Go toolchain to apply the correct rules and features associated with this version.\n\n## How It Works\n\nThe `go.mod` file serves as the entry point for Go's module system. When you run commands like `go build`, `go test`, or `go get`, the Go toolchain reads the `go.mod` file to understand the module's structure and dependencies. \n\n### Dependency Management\n\nWhile this `go.mod` file does not currently include any dependencies, it can be extended in the future to include them. Dependencies can be added using the `go get` command, which automatically updates the `go.mod` file to reflect the new dependencies and their versions.\n\n## Integration with the Codebase\n\nThe `go-ctl2` module can be imported into other Go files using the module name defined in the `go.mod` file. For example:\n\n```go\nimport \"go-ctl2\"\n```\n\nThis allows other packages to utilize the functionality provided by the `go-ctl2` module.\n\n## Future Considerations\n\nAs the project evolves, it is important to keep the `go.mod` file updated with any new dependencies that are introduced. This ensures that the module remains functional and compatible with the latest versions of its dependencies.\n\n## Conclusion\n\nThe `go.mod` file is a foundational element of the `go-ctl2` module, providing essential information about the module's identity and compatibility. Proper management of this file is crucial for maintaining the integrity and functionality of the Go project.","other-main-test-go":"# Other — main_test.go\n\n# main_test.go Module Documentation\n\n## Overview\n\nThe `main_test.go` module is a comprehensive test suite designed to validate the functionality of the core components of the application. It primarily focuses on testing the parsing and evaluation of expressions, the behavior of actors in a runtime environment, and the generation of documentation plots. This module ensures that the underlying logic of the application behaves as expected and adheres to the defined specifications.\n\n## Purpose\n\nThe primary purpose of this module is to provide a robust set of unit tests that cover various aspects of the application, including:\n\n- Expression parsing and evaluation.\n- Actor state transitions and message passing.\n- Error handling for invalid inputs.\n- Documentation generation for internal use.\n\n## Key Components\n\n### 1. Test Functions\n\nThe module contains several test functions, each targeting specific functionalities:\n\n- **TestEmitDocPlotDataForDocs**: Tests the generation of documentation plot data based on the specified mode and output path.\n- **TestReadAcceptsManyExpressions**: Validates that the `Read` function correctly parses a variety of input expressions, including symbols, numbers, strings, and lists.\n- **TestReadRejectsUnterminatedInput**: Ensures that the `Read` function returns an error for unterminated input.\n- **TestRuntimeMessageChainABC**: Tests the message-passing behavior between three actors (A, B, and C) in a runtime environment, verifying that messages are sent and received correctly.\n- **TestCompileActorAndRunMessageChainABC**: Compiles actor definitions and runs a message chain, checking the expected outcomes at each step.\n\n### 2. Data Structures\n\nThe tests utilize various data structures defined in the application, such as:\n\n- **Actor**: Represents an entity that can send and receive messages.\n- **State**: Defines the possible states an actor can be in.\n- **Transition**: Represents the transitions between states based on certain conditions.\n\n### 3. Error Handling\n\nThe module includes tests that ensure proper error handling for invalid inputs, such as:\n\n- Unterminated expressions.\n- Invalid actor definitions.\n- Incorrectly formatted messages.\n\n### 4. Documentation Generation\n\nThe `TestEmitDocPlotDataForDocs` function serves as an internal helper for generating documentation plots. It checks that the output is correctly formatted and written to the specified file.\n\n## Execution Flow\n\nThe execution flow of the tests is straightforward. Each test function is executed independently, and the results are reported back to the testing framework. The tests utilize assertions to verify that the actual outcomes match the expected results.\n\n```mermaid\ngraph TD;\n A[Test Functions] -->|calls| B[TestReadAcceptsManyExpressions]\n A -->|calls| C[TestRuntimeMessageChainABC]\n A -->|calls| D[TestEmitDocPlotDataForDocs]\n B -->|validates| E[Read Function]\n C -->|validates| F[Actor Message Passing]\n D -->|validates| G[Documentation Generation]\n```\n\n## Integration with the Codebase\n\nThe `main_test.go` module is tightly integrated with the core application logic, particularly the functions and types defined in `main.go`. The tests rely on the following key functions from the main application:\n\n- **Read**: Parses input expressions and returns their corresponding representations.\n- **NewRuntime**: Initializes a new runtime environment for actors.\n- **StepActor**: Advances the state of an actor based on its current state and transitions.\n\nBy ensuring that these core functions work as intended, the `main_test.go` module contributes to the overall reliability and maintainability of the codebase.\n\n## Conclusion\n\nThe `main_test.go` module is an essential part of the application, providing a comprehensive suite of tests that validate the core functionalities of expression parsing, actor behavior, and documentation generation. By maintaining a high level of test coverage, this module helps ensure that the application remains robust and reliable as it evolves.","other-makefile":"# Other — Makefile\n\n# Makefile Documentation\n\n## Overview\n\nThe Makefile in this module is designed to automate the documentation generation process for a Go-based project. It leverages tools like Pandoc and Mermaid to convert Markdown files into HTML and generate diagrams, respectively. This document outlines the key components, targets, and workflows defined in the Makefile.\n\n## Purpose\n\nThe primary purpose of this Makefile is to streamline the process of building documentation, running tests, and serving the documentation locally. It ensures that all necessary assets are generated and compiled into a cohesive format for easy access and readability.\n\n## Key Components\n\n### Variables\n\n- **PANDOC**: Specifies the command for Pandoc, used for converting Markdown to HTML.\n- **MMDC**: Points to the Mermaid CLI tool for generating SVG diagrams from Mermaid markdown files.\n- **GO**: Defines the Go command, checking for a specific installation path.\n- **GOCACHE**: Sets the Go cache directory.\n- **DOCS_DIR**: Directory containing documentation source files.\n- **BUILD_DIR**: Directory where the built documentation will reside.\n- **GENERATED_DIR**: Directory for generated assets like SVGs and snippets.\n- **MERMAID_DIR**: Directory containing Mermaid markdown files.\n- **CSS_FILE**: Path to the CSS file for styling the HTML output.\n- **DOC_SRC**: The main Markdown source file for documentation.\n\n### Targets\n\nThe Makefile defines several targets that can be invoked:\n\n- **all**: Default target that runs tests and builds documentation.\n- **test**: Executes Go tests across the project.\n- **docs**: Builds the documentation by generating the necessary Markdown and HTML files.\n- **diagrams**: Generates SVG diagrams from Mermaid markdown files.\n- **clean**: Cleans up the build and generated directories.\n- **serve-docs**: Serves the generated documentation locally on a specified address.\n\n### Execution Flow\n\n1. **Building Documentation**:\n - The `docs` target depends on `$(DOC_BUILD_SRC)` and `$(HTML_OUT)`.\n - `$(DOC_BUILD_SRC)` is generated by running a Python script that combines the main Markdown source with various snippets.\n - The final HTML output is created using Pandoc, which includes the generated Markdown and CSS.\n\n2. **Generating Diagrams**:\n - The `diagrams` target processes all `.mmd` files in the `MERMAID_DIR` and generates corresponding SVG files in the `GENERATED_DIR`.\n - If the Mermaid CLI (`mmdc`) is available, it is used to create the SVG; otherwise, a fallback SVG is generated with a preview message.\n\n3. **Generating Snippets**:\n - Snippets for plots, languages, and examples are generated by running specific Go commands that process the Go source files.\n\n### Directory Structure\n\n```mermaid\ngraph TD;\n A[Makefile] -->|calls| B[docs]\n A -->|calls| C[test]\n B -->|depends on| D[DOC_BUILD_SRC]\n B -->|depends on| E[HTML_OUT]\n D -->|generated by| F[build_doc.py]\n E -->|generated by| G[PANDOC]\n B -->|depends on| H[DOC_ASSETS]\n H -->|includes| I[PLOT_SNIPPETS]\n H -->|includes| J[LANGUAGE_SNIPPETS]\n H -->|includes| K[EXAMPLE_SNIPPETS]\n B -->|depends on| L[CSS_FILE]\n B -->|depends on| M[MERMAID_HEADER]\n B -->|depends on| N[MERMAID_SVG]\n```\n\n## Usage\n\nTo use this Makefile, navigate to the project directory in your terminal and run the following commands:\n\n- To build documentation and run tests:\n ```bash\n make\n ```\n\n- To generate only the documentation:\n ```bash\n make docs\n ```\n\n- To generate diagrams:\n ```bash\n make diagrams\n ```\n\n- To serve the documentation locally:\n ```bash\n make serve-docs\n ```\n\n- To clean up generated files:\n ```bash\n make clean\n ```\n\n## Conclusion\n\nThis Makefile serves as a crucial tool for automating the documentation process in a Go project. By understanding its structure and targets, developers can efficiently manage documentation generation, testing, and local serving, ensuring that the documentation remains up-to-date and accessible.","other-mermaid":"# Other — mermaid\n\n# Other — Mermaid Module Documentation\n\n## Overview\n\nThe **Other — Mermaid** module is designed to facilitate the visualization of various sequences and states in a system using the Mermaid syntax. This module provides a structured way to represent interactions between components, such as clients, relays, and servers, as well as the state transitions within these components. The diagrams generated from this module can be used for documentation, analysis, and communication of system behavior.\n\n## Purpose\n\nThe primary purpose of this module is to create clear and concise visual representations of system interactions and states. This is particularly useful for developers and stakeholders who need to understand the flow of messages and the state of different components in a system.\n\n## Key Components\n\n### Sequence Diagrams\n\nSequence diagrams illustrate the interactions between different participants over time. The module includes the following sequence diagrams:\n\n1. **A to B Sequence Diagram** (`a_to_b_sequence.mmd`):\n - **Participants**: Client, Relay, Server\n - **Flow**: The Client sends a `ping` message to the Relay, which then forwards the same message to the Server.\n\n ```mermaid\n sequenceDiagram\n participant Client\n participant Relay\n participant Server\n Client-->>Relay: message(type=ping)\n Relay-->>Server: message(type=ping)\n ```\n\n### Flowcharts\n\nFlowcharts depict the states and transitions of components in the system. The module includes the following flowcharts:\n\n1. **A to B State Flowchart** (`a_to_b_state.mmd`):\n - **Components**: Client, Relay, Server\n - **Flow**: The Client continuously sends `ping` messages to the Relay, which waits for messages and relays them to the Server, which remains idle until it receives a `ping`.\n\n ```mermaid\n flowchart TD\n subgraph Client\n direction TB\n C_loop([loop]) -->|\"sent = ping\"| C_loop\n end\n\n subgraph Relay\n direction TB\n subgraph R_relay[\"relay\"]\n direction TB\n R_wait([wait])\n end\n R_entry(( ))\n R_entry -->|\"recv msg\"| R_wait\n R_wait -->|\"send msg\"| R_entry\n end\n\n subgraph Server\n direction TB\n S_idle([idle]) -->|\"received = ping\"| S_idle\n end\n\n C_loop -. send ping .-> R_relay\n R_wait -. send ping .-> S_idle\n ```\n\n2. **MM1 5 Queue Flowchart** (`mm1_5_queue_flow.mmd`):\n - **Components**: Client, Queue\n - **Flow**: The Client can either send a request or sleep. If a request is sent, the Queue checks its count and either increments it or drops the request if the count reaches 5. The Queue also manages service completion and busy states.\n\n ```mermaid\n sequenceDiagram\n participant Client\n participant Queue\n Note over Client: dice branch\n alt arrival\n Client-->>Queue: req\n alt count < 5\n Queue->>Queue: count += 1\n else count = 5\n Queue->>Queue: dropped_count += 1\n end\n else sleep\n Client->>Client: last = sleep\n end\n Note over Queue: service branch when count > 0\n alt service-complete\n Queue->>Queue: count -= 1\n Queue->>Queue: last_departure = service-complete\n else busy\n Queue->>Queue: last_departure = busy\n end\n ```\n\n3. **MM1 5 Queue State Flowchart** (`mm1_5_queue_state.mmd`):\n - **Components**: Client, Queue\n - **Flow**: The Client loops, deciding to either send a request or sleep based on a random dice roll. The Queue manages requests and transitions based on its current count and service state.\n\n ```mermaid\n flowchart TD\n subgraph Client\n direction TB\n C_loop([loop]) -->|\"dice<0.5<br/>last = sleep\"| C_loop\n C_loop -->|\"dice>=0.5<br/>send req<br/>last = arrival\"| C_loop\n end\n\n subgraph Queue\n direction TB\n Q_wait([wait]) -->|\"req and count = 0<br/>count += 1<br/>elapsed = 0\"| Q_wait\n Q_wait -->|\"req and 0 < count < 5<br/>count += 1\"| Q_wait\n Q_wait -->|\"req and count = 5<br/>dropped_count += 1\"| Q_wait\n Q_wait -->|\"count > 0 and dice<0.5<br/>count -= 1<br/>last_departure = service-complete\"| Q_wait\n Q_wait -->|\"count > 0 and dice>=0.5<br/>last_departure = busy\"| Q_wait\n end\n\n C_loop -. arrival req .-> Q_wait\n ```\n\n## Integration with the Codebase\n\nThe **Other — Mermaid** module does not have any direct internal or external calls, making it a standalone component focused solely on generating visual representations. It can be integrated into documentation workflows or used in conjunction with other modules that require visual aids for understanding system behavior.\n\n## Conclusion\n\nThe **Other — Mermaid** module serves as a valuable tool for visualizing interactions and states within a system. By providing sequence diagrams and flowcharts, it enhances the clarity of system documentation and aids in the communication of complex behaviors among developers and stakeholders.","other-readme-md":"# Other — README.md\n\n# go-ctl2\n\n`go-ctl2` is a philosophy calculator based on Kripke semantics, designed to facilitate the modeling and verification of actor behaviors, state machines, and temporal requirements using a Lisp-based intermediate representation (IR). This module serves as a bridge between natural language requirements and formal verification, allowing developers to refine and validate models through interaction with a language model (LLM).\n\n## Purpose\n\nThe primary goal of `go-ctl2` is to enable users to create, inspect, and refine models that can be formally verified against specified requirements. By leveraging a Lisp-based IR, the module allows for expressive modeling of complex behaviors and interactions, ensuring that the requirements are not only generated but also rigorously checked.\n\n## Workflow Overview\n\nThe workflow for using `go-ctl2` consists of the following steps:\n\n1. **Model Creation**: The LLM generates a Lisp model that describes the desired behavior and requirements.\n2. **Compilation**: The model is compiled into an explicit transition system, which represents the states and transitions of the system.\n3. **Inspection**: Users can inspect the generated states, channel contents, diagrams, and CTL (Computation Tree Logic) claims.\n4. **Refinement**: Based on the inspection, users can reject or refine the model until the requirements are precise enough for verification.\n\n## Key Components\n\n### 1. Lisp Model\n\nThe Lisp model serves as the foundation for defining actor behaviors and system requirements. It allows for the specification of:\n\n- **Actor States**: Defined using constructs like `(in-state ActorName state)`.\n- **Mailbox Contents**: Specified with constructs such as `(mailbox-has ActorName '(message))`.\n\n### 2. Transition System\n\nThe transition system is generated from the Lisp model and represents the possible states and transitions of the system. This system is crucial for verifying the correctness of the model against the specified CTL assertions.\n\n### 3. CTL Assertions\n\nCTL assertions are used to express properties of the system that can be verified. These assertions focus on observable behaviors, such as:\n\n- State conditions: `(in-state Server done)`\n- Message conditions: `(mailbox-has Client '(event ...))`\n\n### 4. Inspection Tools\n\nThe module provides tools for inspecting the generated transition system, including:\n\n- **State Inspection**: View the current states of actors.\n- **Channel Inspection**: Examine the contents of message channels.\n- **Diagram Generation**: Visualize the state transitions and interactions.\n\n## Integration with the Codebase\n\n`go-ctl2` is designed to work seamlessly with other components of the codebase. The interaction with the LLM and the compilation process are abstracted, allowing developers to focus on refining their models without delving into the underlying implementation details.\n\n### Example Usage\n\nTo use `go-ctl2`, follow these steps:\n\n1. **Generate a Lisp Model**: Use the LLM to create a model.\n2. **Compile the Model**: Call the compilation function to generate the transition system.\n3. **Inspect the Model**: Utilize the inspection tools to review states and messages.\n4. **Refine as Necessary**: Adjust the model based on inspection results and recompile.\n\n## Conclusion\n\n`go-ctl2` provides a powerful framework for modeling and verifying actor-based systems using a formal approach. By combining the expressiveness of Lisp with the rigor of CTL, it enables developers to create precise models that can be validated against their requirements. For further details, refer to the generated documentation at [docs/build/ir.generated.md](docs/build/ir.generated.md).","other-server-go":"# Other — server.go\n\n# Other — server.go Module Documentation\n\n## Overview\n\nThe `server.go` module is responsible for serving a web application that interacts with a requirements modeling tool. It provides an HTTP server that handles various API endpoints for rendering models, managing chat interactions, and serving static assets. The module integrates with external language model providers (OpenAI and Anthropic) to enhance its capabilities.\n\n## Key Components\n\n### 1. HTTP Server\n\nThe core of the module is the HTTP server, which is initialized and started by the `serveWeb` function. It listens for incoming requests and routes them to appropriate handlers using a multiplexer created by `newServerMux`.\n\n```go\nfunc serveWeb(addr string) error {\n server := &http.Server{\n Addr: addr,\n Handler: newServerMux(),\n ReadHeaderTimeout: 5 * time.Second,\n }\n return server.ListenAndServe()\n}\n```\n\n### 2. Request Handlers\n\nThe module defines several request handlers that respond to specific API endpoints:\n\n- **Static Asset Handlers**: Serve static files like HTML, CSS, and JavaScript.\n- **API Handlers**: Handle requests for examples, providers, chat history, rendering, and chat interactions.\n\n#### Example Handlers\n\n- **handleIndex**: Serves the main HTML page.\n- **handleRender**: Processes rendering requests and returns Markdown and HTML interpretations.\n- **handleChat**: Manages chat interactions with the user and external LLMs.\n\n```go\nfunc handleIndex(w http.ResponseWriter, _ *http.Request) {\n data, err := webAppFS.ReadFile(\"webapp/index.html\")\n if err != nil {\n http.Error(w, err.Error(), http.StatusInternalServerError)\n return\n }\n w.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n _, _ = w.Write(data)\n}\n```\n\n### 3. Data Structures\n\nThe module uses several data structures to represent various entities:\n\n- **providerInfo**: Represents information about a language model provider.\n- **providerCatalog**: Contains a list of available providers and the default provider.\n- **chatRequest** and **chatResponse**: Structures for handling chat requests and responses.\n\n### 4. External Provider Integration\n\nThe module integrates with external LLM providers (OpenAI and Anthropic) to enhance its functionality. It checks for API keys and fetches available models from these providers.\n\n#### Example of Loading Providers\n\n```go\nfunc loadOpenAIProvider(ctx context.Context) providerInfo {\n _, available := lookupEnvLogged(\"OPENAI_API_KEY\")\n // Logic to fetch models from OpenAI\n}\n```\n\n### 5. History Management\n\nThe module manages chat history using functions to read, write, and clear history states. This allows users to maintain context across interactions.\n\n```go\nfunc readHistoryState() (historyState, error) {\n path := historyFilePath()\n data, err := os.ReadFile(path)\n // Logic to read and unmarshal history state\n}\n```\n\n## Execution Flow\n\nThe execution flow of the server can be visualized as follows:\n\n```mermaid\ngraph TD;\n A[Client Request] -->|HTTP Request| B[HTTP Server];\n B --> C[Request Handlers];\n C -->|Static Assets| D[Static File Handler];\n C -->|API Calls| E[API Handlers];\n E -->|Chat| F[Chat Provider];\n E -->|Render| G[Render Function];\n E -->|History| H[History Management];\n```\n\n## API Endpoints\n\n### Static Assets\n\n- `GET /`: Serves the main HTML page.\n- `GET /app.css`: Serves the application CSS.\n- `GET /app.js`: Serves the application JavaScript.\n\n### API Endpoints\n\n- `GET /api/examples`: Returns example payloads.\n- `GET /api/providers`: Returns the provider catalog.\n- `GET /api/history`: Retrieves chat history.\n- `PUT /api/history`: Updates chat history.\n- `DELETE /api/history`: Clears chat history.\n- `POST /api/render`: Renders a model based on the provided source.\n- `POST /api/chat`: Handles chat interactions with the user.\n\n## Error Handling\n\nThe module includes error handling mechanisms to ensure that appropriate HTTP status codes and error messages are returned to the client. Functions like `writeJSONError` are used to standardize error responses.\n\n```go\nfunc writeJSONError(w http.ResponseWriter, status int, err error) {\n w.WriteHeader(status)\n writeJSON(w, map[string]string{\"error\": err.Error()})\n}\n```\n\n## Conclusion\n\nThe `server.go` module is a crucial part of the application, providing a robust HTTP server that facilitates interaction with a requirements modeling tool. It integrates with external language models, manages chat history, and serves static assets, making it a comprehensive solution for users looking to work with requirements models in a web-based environment.","other":"# Other\n\n# Other Module Overview\n\nThe **Other** module serves as a comprehensive framework for the `go-ctl2` project, which focuses on modeling and verifying actor behaviors and state machines using Kripke semantics. This module integrates various components that work together to facilitate documentation generation, model interaction, and testing.\n\n## Purpose\n\nThe primary goal of the Other module is to provide a cohesive environment for:\n\n- Automating documentation generation through the [Makefile](makefile.md), which utilizes tools like Pandoc and Mermaid.\n- Structuring and presenting documentation for the actor-based model via the [docs](docs.md) module, ensuring a consistent and visually appealing format.\n- Enabling the creation and visualization of system interactions and states with the [Mermaid](mermaid.md) module, which enhances understanding of component relationships.\n- Managing dependencies and module configurations through the [go.mod](go.mod.md) file.\n- Validating core functionalities and behaviors of the application with the [main_test.go](main_test.go.md) test suite.\n- Serving a web application that interacts with a requirements modeling tool via the [server.go](server.go.md) module.\n\n## Key Workflows\n\n1. **Documentation Generation**: The [Makefile](makefile.md) automates the process of building documentation, which includes converting Markdown files into HTML and generating diagrams using the [Mermaid](mermaid.md) module. This ensures that all documentation is up-to-date and accessible.\n\n2. **Model Interaction**: The [server.go](server.go.md) module provides an HTTP server that facilitates interactions with the modeling tool, allowing users to render models and manage chat interactions. This server integrates with external language model providers to enhance functionality.\n\n3. **Testing and Validation**: The [main_test.go](main_test.go.md) module contains a suite of tests that validate the core components of the application, ensuring that the logic for parsing, evaluating expressions, and handling actor behaviors is functioning as expected.\n\n4. **Documentation Styling**: The [docs](docs.md) module defines a consistent theme and structure for the documentation, ensuring that all generated content adheres to a unified style, which is crucial for readability and usability.\n\n5. **Dependency Management**: The [go.mod](go.mod.md) file manages the module's dependencies and specifies compatibility with Go version 1.22, ensuring that the project remains maintainable and up-to-date with Go's module system.\n\nBy integrating these sub-modules, the Other module provides a robust environment for developing, documenting, and validating the `go-ctl2` project, enhancing both developer productivity and end-user experience.","overview":"# go-ctl2 — Wiki\n\n# go-ctl2\n\n`go-ctl2` is a Kripke philosophy calculator designed to model and verify actor behaviors and state machines using a Lisp-based intermediate representation (IR). The project facilitates a unique interaction with a conversational AI model, allowing users to define requirements, generate models, and engage in a dialogue to refine those models until they meet precise criteria for verification.\n\n## Architecture Overview\n\nThe architecture of `go-ctl2` is modular, consisting of several key components that work together to provide a seamless experience for modeling and verification. The core of the system is the **Core Logic** module, which manages the runtime environment for actors, their states, and message passing. The **Web Application** module serves as the user interface, enabling interactions with the AI model and visualizing outputs. Additionally, the **Documentation Generation** and **Diagram Generation** modules automate the creation of documentation and visual representations, respectively.\n\n### Key End-to-End Flows\n\n1. **Model Creation**: The user interacts with the Web Application to define a Lisp model, which is then processed by the Core Logic module.\n2. **Model Compilation**: The model is compiled into an explicit transition system, allowing for detailed inspection of states and transitions.\n3. **Verification**: Users can assert conditions over the model, such as checking mailbox contents or actor states, and refine the model based on feedback from the AI.\n4. **Documentation**: The Documentation Generation module compiles relevant documentation, while the Diagram Generation module creates visual representations of the model.\n\n### Mermaid Architecture Diagram\n\n```mermaid\ngraph TD;\n A[Web Application] -->|interacts with| B[Core Logic]\n B -->|compiles model| C[Other]\n C -->|generates docs| D[Documentation Generation]\n C -->|creates diagrams| E[Diagram Generation]\n B -->|sends messages| F[Actors]\n F -->|transitions states| B\n```\n\n## Getting Started\n\nTo set up the `go-ctl2` project, ensure you have Go 1.22 installed. Clone the repository and run the following command to install dependencies:\n\n```bash\ngo mod tidy\n```\n\nYou can then start the application by running:\n\n```bash\ngo run main.go\n```\n\nFor detailed information on each module, please refer to the following documentation:\n\n- [Core Logic](core-logic.md)\n- [Web Application](web-application.md)\n- [Documentation Generation](documentation-generation.md)\n- [Diagram Generation](diagram-generation.md)\n\nWelcome to the `go-ctl2` project! We encourage you to explore the modules and contribute to the ongoing development of this innovative tool.","web-application":"# Web Application\n\n# Web Application Module Documentation\n\n## Overview\n\nThe Web Application module serves as the frontend interface for the go-ctl2 chat application. It facilitates user interactions with a conversational AI model, allowing users to create conversations, send messages, and visualize outputs. The module is built using vanilla JavaScript and HTML, with a focus on dynamic rendering and user experience.\n\n## Key Components\n\n### State Management\n\nThe application maintains a global `state` object that tracks the following:\n\n- **providers**: List of available AI providers.\n- **examples**: Predefined examples for user reference.\n- **conversations**: Array of conversation objects, each containing messages and metadata.\n- **activeId**: ID of the currently active conversation.\n- **mermaid**: Reference to the Mermaid library for rendering diagrams.\n- **mathJaxReady**: Promise that resolves when MathJax is ready for rendering mathematical content.\n- **renderTimer**: Timer for scheduling rendering tasks.\n- **pendingChat**: Set of conversation IDs that are currently awaiting responses.\n\n### DOM Elements\n\nThe `els` object holds references to key DOM elements for easy access and manipulation:\n\n- `conversationList`: Container for displaying the list of conversations.\n- `conversationTitle`: Title of the active conversation.\n- `providerSelect`, `modelSelect`: Dropdowns for selecting AI providers and models.\n- `messages`: Container for displaying chat messages.\n- `chatForm`, `chatInput`: Form elements for user input.\n- `newConversation`, `wipeHistory`: Buttons for managing conversations.\n- `exampleSelect`, `loadExample`: Elements for loading predefined examples.\n- `renderStatus`: Displays the status of rendering operations.\n- `sourceEditor`, `renderOutput`: Areas for editing source code and displaying rendered output.\n\n### Initialization\n\nThe application initializes by calling the `init` function, which performs the following tasks:\n\n1. Binds event listeners to UI elements via `bindTabs` and `bindActions`.\n2. Loads providers and examples asynchronously.\n3. Loads existing conversations from the server.\n4. If no conversations exist, it creates a new one.\n5. Renders the conversation list and the active conversation.\n\n### Event Binding\n\nThe `bindActions` function sets up event listeners for user interactions:\n\n- **New Conversation**: Creates a new conversation and updates the UI.\n- **Wipe History**: Clears all conversations and resets the state.\n- **Provider and Model Selection**: Updates the active conversation's provider and model based on user selection.\n- **Load Example**: Loads a predefined example into the active conversation.\n- **Source Editor Input**: Updates the source code of the active conversation and schedules a render.\n- **Chat Form Submission**: Sends the user's message to the AI model.\n\n### Conversation Management\n\nConversations are managed through several key functions:\n\n- **addConversation**: Creates a new conversation object and adds it to the state.\n- **loadConversations**: Fetches stored conversations from the server and normalizes their structure.\n- **saveConversations**: Persists the current state of conversations to the server.\n- **wipeHistory**: Clears all conversation data from the state and server.\n\n### Rendering\n\nThe rendering process involves several functions that update the UI based on the current state:\n\n- **renderConversations**: Updates the conversation list in the UI.\n- **renderActiveConversation**: Displays the details of the currently active conversation.\n- **renderMessages**: Renders the messages of the active conversation, including user and assistant messages.\n- **renderInterpretation**: Sends the source code to the server for rendering and updates the output area.\n- **renderCachedInterpretation**: Displays the last rendered output or any errors that occurred during rendering.\n\n### Markdown and Rich Content Rendering\n\nThe module supports rendering of Markdown, Mermaid diagrams, and mathematical content using MathJax. Key functions include:\n\n- **renderMarkdown**: Converts Markdown text into HTML.\n- **renderMermaidBlocks**: Renders Mermaid diagrams from the source.\n- **renderMath**: Typesets mathematical expressions using MathJax.\n\n### Error Handling\n\nThe module includes error handling for network requests and rendering processes. Errors are displayed in the UI, allowing users to understand issues that arise during interactions.\n\n## Execution Flow\n\nThe following diagram illustrates the main execution flow of the Web Application module:\n\n```mermaid\ngraph TD;\n A[User Interaction] -->|Triggers| B[bindActions]\n B --> C[addConversation]\n B --> D[wipeHistory]\n B --> E[loadExample]\n B --> F[sendChat]\n F --> G[renderMessages]\n F --> H[renderInterpretation]\n H --> I[renderCachedInterpretation]\n I --> J[setRenderStatus]\n J --> K[renderOutput]\n K --> L[renderMarkdown]\n K --> M[renderMermaidBlocks]\n K --> N[renderMath]\n```\n\n## Conclusion\n\nThe Web Application module is a comprehensive frontend solution for interacting with the go-ctl2 conversational AI. It effectively manages state, handles user input, and renders dynamic content, providing a seamless user experience. Developers can extend this module by adding new features or improving existing functionalities, leveraging the structured approach to state management and rendering."}; | |
| var TREE = [{"name":"Core Logic","slug":"core-logic","files":["main.go"]},{"name":"Diagram Generation","slug":"diagram-generation","files":["scripts/generate_diagram_sections.py","scripts/generate_xyplot.py"]},{"name":"Documentation Generation","slug":"documentation-generation","files":["scripts/build_doc.py"]},{"name":"Web Application","slug":"web-application","files":["webapp/app.js","webapp/app.css","webapp/index.html"]},{"name":"Other","slug":"other","files":[],"children":[{"name":"Other — Makefile","slug":"other-makefile","files":["Makefile"]},{"name":"Other — README.md","slug":"other-readme-md","files":["README.md"]},{"name":"Other — docs","slug":"other-docs","files":["docs/dark.css","docs/ir.md","docs/mermaid-config.json","docs/mermaid-header.html"]},{"name":"Other — mermaid","slug":"other-mermaid","files":["docs/mermaid/a_to_b_sequence.mmd","docs/mermaid/a_to_b_state.mmd","docs/mermaid/mm1_5_queue_flow.mmd","docs/mermaid/mm1_5_queue_state.mmd"]},{"name":"Other — go.mod","slug":"other-go-mod","files":["go.mod"]},{"name":"Other — main_test.go","slug":"other-main-test-go","files":["main_test.go"]},{"name":"Other — server.go","slug":"other-server-go","files":["server.go"]}]}]; | |
| var META = {"fromCommit":"2f96363d8e59921ad52b7e32e37e31499752b118","generatedAt":"2026-04-26T04:38:18.142Z","model":"gpt-4o-mini","moduleFiles":{"Core Logic":["main.go"],"Diagram Generation":["scripts/generate_diagram_sections.py","scripts/generate_xyplot.py"],"Documentation Generation":["scripts/build_doc.py"],"Web Application":["webapp/app.js","webapp/app.css","webapp/index.html"],"Other":["Makefile","README.md","docs/dark.css","docs/ir.md","docs/mermaid-config.json","docs/mermaid-header.html","docs/mermaid/a_to_b_sequence.mmd","docs/mermaid/a_to_b_state.mmd","docs/mermaid/mm1_5_queue_flow.mmd","docs/mermaid/mm1_5_queue_state.mmd","go.mod","main_test.go","server.go"],"Other — Makefile":["Makefile"],"Other — README.md":["README.md"],"Other — docs":["docs/dark.css","docs/ir.md","docs/mermaid-config.json","docs/mermaid-header.html"],"Other — mermaid":["docs/mermaid/a_to_b_sequence.mmd","docs/mermaid/a_to_b_state.mmd","docs/mermaid/mm1_5_queue_flow.mmd","docs/mermaid/mm1_5_queue_state.mmd"],"Other — go.mod":["go.mod"],"Other — main_test.go":["main_test.go"],"Other — server.go":["server.go"]},"moduleTree":[{"name":"Core Logic","slug":"core-logic","files":["main.go"]},{"name":"Diagram Generation","slug":"diagram-generation","files":["scripts/generate_diagram_sections.py","scripts/generate_xyplot.py"]},{"name":"Documentation Generation","slug":"documentation-generation","files":["scripts/build_doc.py"]},{"name":"Web Application","slug":"web-application","files":["webapp/app.js","webapp/app.css","webapp/index.html"]},{"name":"Other","slug":"other","files":[],"children":[{"name":"Other — Makefile","slug":"other-makefile","files":["Makefile"]},{"name":"Other — README.md","slug":"other-readme-md","files":["README.md"]},{"name":"Other — docs","slug":"other-docs","files":["docs/dark.css","docs/ir.md","docs/mermaid-config.json","docs/mermaid-header.html"]},{"name":"Other — mermaid","slug":"other-mermaid","files":["docs/mermaid/a_to_b_sequence.mmd","docs/mermaid/a_to_b_state.mmd","docs/mermaid/mm1_5_queue_flow.mmd","docs/mermaid/mm1_5_queue_state.mmd"]},{"name":"Other — go.mod","slug":"other-go-mod","files":["go.mod"]},{"name":"Other — main_test.go","slug":"other-main-test-go","files":["main_test.go"]},{"name":"Other — server.go","slug":"other-server-go","files":["server.go"]}]}]}; | |
| (function() { | |
| var activePage = 'overview'; | |
| document.addEventListener('DOMContentLoaded', function() { | |
| mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'loose' }); | |
| renderMeta(); | |
| renderNav(); | |
| document.getElementById('menu-toggle').addEventListener('click', function() { | |
| document.getElementById('sidebar').classList.toggle('open'); | |
| }); | |
| if (location.hash && location.hash.length > 1) { | |
| activePage = decodeURIComponent(location.hash.slice(1)); | |
| } | |
| navigateTo(activePage); | |
| }); | |
| function renderMeta() { | |
| if (!META) return; | |
| var el = document.getElementById('meta-info'); | |
| var parts = []; | |
| if (META.generatedAt) { | |
| parts.push(new Date(META.generatedAt).toLocaleDateString()); | |
| } | |
| if (META.model) parts.push(META.model); | |
| if (META.fromCommit) parts.push(META.fromCommit.slice(0, 8)); | |
| el.textContent = parts.join(' \u00b7 '); | |
| } | |
| function renderNav() { | |
| var container = document.getElementById('nav-tree'); | |
| var html = '<div class="nav-section">'; | |
| html += '<a class="nav-item overview" data-page="overview" href="#overview">Overview</a>'; | |
| html += '</div>'; | |
| if (TREE.length > 0) { | |
| html += '<div class="nav-group-label">Modules</div>'; | |
| html += buildNavTree(TREE); | |
| } | |
| container.innerHTML = html; | |
| container.addEventListener('click', function(e) { | |
| var target = e.target; | |
| while (target && !target.dataset.page) { target = target.parentElement; } | |
| if (target && target.dataset.page) { | |
| e.preventDefault(); | |
| navigateTo(target.dataset.page); | |
| } | |
| }); | |
| } | |
| function buildNavTree(nodes) { | |
| var html = ''; | |
| for (var i = 0; i < nodes.length; i++) { | |
| var node = nodes[i]; | |
| html += '<div class="nav-section">'; | |
| html += '<a class="nav-item" data-page="' + escH(node.slug) + '" href="#' + encodeURIComponent(node.slug) + '">' + escH(node.name) + '</a>'; | |
| if (node.children && node.children.length > 0) { | |
| html += '<div class="nav-children">' + buildNavTree(node.children) + '</div>'; | |
| } | |
| html += '</div>'; | |
| } | |
| return html; | |
| } | |
| function escH(s) { | |
| var d = document.createElement('div'); | |
| d.textContent = s; | |
| return d.innerHTML; | |
| } | |
| function navigateTo(page) { | |
| activePage = page; | |
| location.hash = encodeURIComponent(page); | |
| var items = document.querySelectorAll('.nav-item'); | |
| for (var i = 0; i < items.length; i++) { | |
| if (items[i].dataset.page === page) { | |
| items[i].classList.add('active'); | |
| } else { | |
| items[i].classList.remove('active'); | |
| } | |
| } | |
| var contentEl = document.getElementById('content'); | |
| var md = PAGES[page]; | |
| if (!md) { | |
| contentEl.innerHTML = '<div class="empty-state"><h2>Page not found</h2><p>' + escH(page) + '.md does not exist.</p></div>'; | |
| return; | |
| } | |
| contentEl.innerHTML = marked.parse(md); | |
| // Rewrite .md links to hash navigation | |
| var links = contentEl.querySelectorAll('a[href]'); | |
| for (var i = 0; i < links.length; i++) { | |
| var href = links[i].getAttribute('href'); | |
| if (href && href.endsWith('.md') && href.indexOf('://') === -1) { | |
| var slug = href.replace(/\.md$/, ''); | |
| links[i].setAttribute('href', '#' + encodeURIComponent(slug)); | |
| (function(s) { | |
| links[i].addEventListener('click', function(e) { | |
| e.preventDefault(); | |
| navigateTo(s); | |
| }); | |
| })(slug); | |
| } | |
| } | |
| // Convert mermaid code blocks into mermaid divs | |
| var mermaidBlocks = contentEl.querySelectorAll('pre code.language-mermaid'); | |
| for (var i = 0; i < mermaidBlocks.length; i++) { | |
| var pre = mermaidBlocks[i].parentElement; | |
| var div = document.createElement('div'); | |
| div.className = 'mermaid'; | |
| div.textContent = mermaidBlocks[i].textContent; | |
| pre.parentNode.replaceChild(div, pre); | |
| } | |
| try { mermaid.run({ querySelector: '.mermaid' }); } catch(e) {} | |
| window.scrollTo(0, 0); | |
| document.getElementById('sidebar').classList.remove('open'); | |
| } | |
| })(); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment