diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index cfbf8c9..d449e2a 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -26,5 +26,5 @@ If applicable, add screenshots to help explain your problem. - OS: [e.g. macOS 12] - Version: [e.g. 1.0.0] -**Additional context** -Add any other context about the problem here. +**Additional state** +Add any other state about the problem here. diff --git a/.github/ISSUE_TEMPLATE/chore_request.md b/.github/ISSUE_TEMPLATE/chore_request.md index b70a26a..bb9a571 100644 --- a/.github/ISSUE_TEMPLATE/chore_request.md +++ b/.github/ISSUE_TEMPLATE/chore_request.md @@ -10,7 +10,7 @@ assignees: '' A clear and concise description of the maintenance task. **Why is this necessary?** -Context and motivation. +State and motivation. **Acceptance criteria** - What must be completed for this to be considered done? diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 6277704..c913a53 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -15,5 +15,5 @@ A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. -**Additional context** +**Additional state** i.e., why this addition matters, potential API shape, backward compatibility considerations diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index a17d71f..e9c394e 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,6 +1,6 @@ ## Description -Please include a summary of the change and which issue is fixed. Also include relevant motivation and context. +Please include a summary of the change and which issue is fixed. Also include relevant motivation and state. Fixes # (issue) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index ce764f9..885cb12 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -35,7 +35,7 @@ CodeUChain is a polyglot monorepo providing a universal framework for composable ### Key Facts - **Type**: Polyglot Monorepo - **Languages**: Go, Python, JavaScript/TypeScript, C#, Rust, Java, C++, COBOL (meme), Pseudocode -- **Architecture**: Context-Link-Chain pattern +- **Architecture**: State-Link-Chain pattern - **License**: Apache 2.0 - **Status**: Production-ready in core languages @@ -85,7 +85,7 @@ Before diving into maintenance, understand the core concepts that define CodeUCh ```pseudocode // 1. Setup Data -ctx = new Context({ id: 123, raw_text: " hello " }) +ctx = new State({ id: 123, raw_text: " hello " }) // 2. Build Workflow chain = new Chain() @@ -105,7 +105,7 @@ else: ### Core Concepts -#### **Context** +#### **State** The "box" moving down the conveyor belt: - Immutable key-value data structure - Carries state through the chain @@ -115,21 +115,21 @@ The "box" moving down the conveyor belt: #### **Link** A "station" on the belt: - Individual processing unit with single responsibility -- Accepts Context → Returns modified Context +- Accepts State → Returns modified State - One well-defined purpose - Sync or async (framework handles both) #### **Chain** The "conveyor belt" itself: - Ordered sequence of Links -- Manages Context flow between Links +- Manages State flow between Links - Handles error propagation automatically - Provides orchestration capabilities -#### **Middleware** +#### **Hook** Observes and reacts to execution: -- Operates outside main flow in parallel observation context -- Monitors execution without modifying business logic context +- Operates outside main flow in parallel observation state +- Monitors execution without modifying business logic state - Handles cross-cutting concerns (logging, metrics, caching, validation) - Pure observation layer - cannot interfere with Link logic - Clean separation preserves business logic integrity @@ -139,7 +139,7 @@ Observes and reacts to execution: ``` Problem → Analysis → Solution → Verification → Refinement ↓ ↓ ↓ ↓ ↓ - Context → Link 1 → Link 2 → Link 3 → Link 4 + State → Link 1 → Link 2 → Link 3 → Link 4 ``` This sequential, composable nature matches how humans think and how AI agents reason. @@ -250,7 +250,7 @@ git checkout -b feature/your-feature-name ```typescript // example: tests/validate_email.test.ts test('ValidateEmail should reject invalid emails', () => { - const ctx = new Context({ email: 'invalid' }); + const ctx = new State({ email: 'invalid' }); expect(() => validateEmail.call(ctx)).toThrow(); }); ``` @@ -380,7 +380,7 @@ src/ ```python class ValidateEmailLink(Link): """Validates email format using regex.""" - async def call(self, ctx: Context) -> Context: + async def call(self, ctx: State) -> State: email = ctx.get("email") if not EMAIL_REGEX.match(email): raise ValueError("Invalid email format") @@ -391,7 +391,7 @@ class ValidateEmailLink(Link): ```python class ProcessUserLink(Link): """Does validation, hashing, and saving.""" # Too much! - async def call(self, ctx: Context) -> Context: + async def call(self, ctx: State) -> State: # validation code # hashing code # database code @@ -428,13 +428,13 @@ We implement a three-tier testing strategy: // Example: Unit test for ValidateEmail link describe('ValidateEmail', () => { it('should accept valid email', () => { - const ctx = new Context({ email: 'test@example.com' }); + const ctx = new State({ email: 'test@example.com' }); const result = validateEmail.call(ctx); expect(result.get('email')).toBe('test@example.com'); }); it('should reject invalid email', () => { - const ctx = new Context({ email: 'invalid' }); + const ctx = new State({ email: 'invalid' }); expect(() => validateEmail.call(ctx)).toThrow('Invalid email'); }); }); @@ -456,7 +456,7 @@ describe('UserRegistration Chain', () => { .add(hashPassword) .add(saveToDatabase(mockDb)); - const ctx = new Context({ + const ctx = new State({ email: 'test@example.com', password: 'secure123' }); @@ -493,7 +493,7 @@ describe('GitHub Integration E2E', () => { .add(configureSettings) .add(addCollaborators); - const ctx = new Context({ + const ctx = new State({ name: testRepoName, org: 'test-org' }); @@ -546,10 +546,10 @@ tests/ ├── unit/ # Isolated component tests │ ├── links/ │ ├── chains/ -│ └── context/ +│ └── state/ ├── integration/ # Component interaction tests │ ├── chains/ -│ └── middleware/ +│ └── hook/ └── e2e/ # Full system tests ├── github_integration/ └── real_world_scenarios/ @@ -685,7 +685,7 @@ Located in `scripts/`: **Example**: - `v1.0.0`: Initial stable release - `v1.1.0`: Added typed features (backward compatible) -- `v1.1.1`: Fixed bug in Context.get() (patch) +- `v1.1.1`: Fixed bug in State.get() (patch) - `v2.0.0`: Changed Link interface (breaking change) ### Changelog Management @@ -695,7 +695,7 @@ Located in `scripts/`: Follow conventional commit format: ``` -feat: add typed context evolution +feat: add typed state evolution fix: resolve memory leak in chain execution docs: update installation instructions test: add comprehensive e2e tests @@ -712,17 +712,17 @@ CodeUChain provides **opt-in generics** for static type safety while maintaining #### Generic Link Interface ```pseudocode Link[Input, Output] - - call(ctx: Context[Input]) -> Context[Output] + - call(ctx: State[Input]) -> State[Output] - Transforms data from Input shape to Output shape - Compile-time type checking - Runtime flexibility maintained ``` -#### Generic Context +#### Generic State ```pseudocode -Context[T] - - insert(key, value) -> Context[T] // Preserve type - - insert_as(key, value) -> Context[U] // Evolve type +State[T] + - insert(key, value) -> State[T] // Preserve type + - insert_as(key, value) -> State[U] // Evolve type - get(key) -> value - Runtime storage: Dict[str, Any] ``` @@ -764,7 +764,7 @@ type RegisteredUser = { // Typed link class RegisterUserLink implements Link[UserInput, RegisteredUser]: - call(ctx: Context[UserInput]) -> Context[RegisteredUser]: + call(ctx: State[UserInput]) -> State[RegisteredUser]: email = ctx.get("email") userId = database.insert(email) @@ -792,10 +792,10 @@ See [TYPED_FEATURES_IMPLEMENTATION_PLAN.md](TYPED_FEATURES_IMPLEMENTATION_PLAN.m /** * ValidateEmail - Validates email format using regex pattern * - * Input Context: + * Input State: * - email: string - Email address to validate * - * Output Context: + * Output State: * - email: string - Validated email (unchanged) * * Errors: @@ -803,12 +803,12 @@ See [TYPED_FEATURES_IMPLEMENTATION_PLAN.md](TYPED_FEATURES_IMPLEMENTATION_PLAN.m * * Example: * ``` - * const ctx = new Context({ email: 'test@example.com' }); + * const ctx = new State({ email: 'test@example.com' }); * const result = await validateEmail.call(ctx); * ``` */ export class ValidateEmail extends Link { - async call(ctx: Context): Promise> { + async call(ctx: State): Promise> { // Implementation } } @@ -836,7 +836,7 @@ export class ValidateEmail extends Link { * Example: * ``` * const result = await UserRegistrationChain.execute( - * new Context({ email: 'test@example.com', password: 'secure123' }) + * new State({ email: 'test@example.com', password: 'secure123' }) * ); * const userId = result.get('userId'); * ``` @@ -855,7 +855,7 @@ Each language implementation must have: 1. **Quick Start**: 5-minute getting started example 2. **Installation**: Package manager instructions -3. **Core Concepts**: Link, Context, Chain, Middleware +3. **Core Concepts**: Link, State, Chain, Hook 4. **Examples**: At least 3 working examples 5. **API Reference**: Complete public API documentation 6. **Testing**: How to run tests @@ -1189,7 +1189,7 @@ CodeUChain is a polyglot monorepo providing a universal framework for composable ### Key Facts - **Type**: Polyglot Monorepo - **Languages**: Go, Python, JavaScript/TypeScript, C#, Rust, Java, C++, COBOL (meme), Pseudocode -- **Architecture**: Context-Link-Chain pattern +- **Architecture**: State-Link-Chain pattern - **License**: Apache 2.0 - **Status**: Production-ready in core languages @@ -1232,7 +1232,7 @@ Start simple, add features when needed. Typing, advanced orchestration, and tool --- ## Refresher — CodeUChain Types -Context - The box of data flowing through Links +State - The box of data flowing through Links Link - Individual stations (pure business logic) Chain - Orchestration of Link sequence -Middleware - Parallel observation layer (logging, metrics, caching, validation) \ No newline at end of file +Hook - Parallel observation layer (logging, metrics, caching, validation) \ No newline at end of file diff --git a/.github/instructions/typed_features_implementation.instructions.md b/.github/instructions/typed_features_implementation.instructions.md index fb14541..e9e5138 100644 --- a/.github/instructions/typed_features_implementation.instructions.md +++ b/.github/instructions/typed_features_implementation.instructions.md @@ -35,25 +35,25 @@ CodeUChain implements **opt-in generics** that provide static type safety while ```python # Python Reference class Link[Input, Output]: - async def call(self, ctx: Context[Input]) -> Context[Output]: + async def call(self, ctx: State[Input]) -> State[Output]: pass ``` **Universal Requirements:** - Generic type parameters for Input/Output types - Async execution pattern (or language equivalent) -- Context transformation capability +- State transformation capability - Error handling support -- Optional: Middleware compatibility +- Optional: Hook compatibility -### Context Interface (Universal) +### State Interface (Universal) ```python # Python Reference -class Context[T]: - def insert(self, key: str, value: Any) -> Context[T]: # Preserve type +class State[T]: + def insert(self, key: str, value: Any) -> State[T]: # Preserve type pass - def insert_as(self, key: str, value: Any) -> Context[Any]: # Type evolution + def insert_as(self, key: str, value: Any) -> State[Any]: # Type evolution pass ``` @@ -62,7 +62,7 @@ class Context[T]: - Immutable transformation methods - Runtime Dict[str, Any] equivalent storage - Type-safe access methods -- Optional: Mutable context for performance-critical sections +- Optional: Mutable state for performance-critical sections ## 🔧 Language-Specific Implementation Guidelines @@ -72,13 +72,13 @@ class Context[T]: ```csharp public interface ILink { - Task> CallAsync(Context context); + Task> CallAsync(State state); } -public class Context : IContext // Covariant for flexibility +public class State : IState // Covariant for flexibility { - public Context Insert(string key, object value) => this; - public Context InsertAs(string key, object value) => new Context(...); + public State Insert(string key, object value) => this; + public State InsertAs(string key, object value) => new State(...); } ``` **Guidelines:** @@ -92,12 +92,12 @@ public class Context : IContext // Covariant for flexibility **Key Patterns:** ```typescript interface Link { - call(ctx: Context): Promise>; + call(ctx: State): Promise>; } -class Context { - insert(key: string, value: any): Context; - insertAs(key: string, value: any): Context; +class State { + insert(key: string, value: any): State; + insertAs(key: string, value: any): State; } ``` **Guidelines:** @@ -111,12 +111,12 @@ class Context { **Key Patterns:** ```java public interface Link { - CompletableFuture> call(Context context); + CompletableFuture> call(State state); } -public class Context { - public Context insert(String key, Object value); - public Context insertAs(String key, Object value); +public class State { + public State insert(String key, Object value); + public State insertAs(String key, Object value); } ``` **Guidelines:** @@ -131,12 +131,12 @@ public class Context { **Key Patterns:** ```go type Link[TInput any, TOutput any] interface { - Call(ctx Context[TInput]) (Context[TOutput], error) + Call(ctx State[TInput]) (State[TOutput], error) } -type Context[T any] struct { - Insert(key string, value any) Context[T] - InsertAs[U any](key string, value any) Context[U] +type State[T any] struct { + Insert(key string, value any) State[T] + InsertAs[U any](key string, value any) State[U] } ``` **Guidelines:** @@ -152,12 +152,12 @@ type Context[T any] struct { ```rust #[async_trait] pub trait Link: Send + Sync { - async fn call(&self, ctx: Context) -> Result, Error>; + async fn call(&self, ctx: State) -> Result, Error>; } -pub struct Context { +pub struct State { pub fn insert(self, key: String, value: serde_json::Value) -> Self; - pub fn insert_as(self, key: String, value: serde_json::Value) -> Context; + pub fn insert_as(self, key: String, value: serde_json::Value) -> State; } ``` **Guidelines:** @@ -174,7 +174,7 @@ pub struct Context { ```python # Python Reference - Adapt to target language def test_type_evolution(): - input_ctx = Context[InputData]({"numbers": [1, 2, 3]}) + input_ctx = State[InputData]({"numbers": [1, 2, 3]}) output_ctx = input_ctx.insert_as("result", 6.0) assert output_ctx.get("result") == 6.0 @@ -186,7 +186,7 @@ def test_type_evolution(): # Python Reference - Adapt to target language def test_generic_link(): link = SumLink() - input_ctx = Context[InputData]({"numbers": [1, 2, 3]}) + input_ctx = State[InputData]({"numbers": [1, 2, 3]}) result_ctx = await link.call(input_ctx) @@ -198,7 +198,7 @@ def test_generic_link(): ```python # Ensure untyped usage still works identically def test_runtime_compatibility(): - untyped_ctx = Context({"numbers": [1, 2, 3]}) + untyped_ctx = State({"numbers": [1, 2, 3]}) result = untyped_ctx.insert("result", 6.0) assert result.get("result") == 6.0 @@ -210,7 +210,7 @@ def test_runtime_compatibility(): - ✅ Generic link interfaces - ✅ Chain composition with generics - ✅ Runtime compatibility (untyped usage) -- ✅ Error handling in typed contexts +- ✅ Error handling in typed states - ✅ Mixed typed/untyped component usage ## 📊 Performance Requirements @@ -242,7 +242,7 @@ def test_runtime_compatibility(): ### Functional Completeness ✅ **ACHIEVED** - ✅ Generic `Link[Input, Output]` interfaces implemented (Python, Go, JS/TS, C#, Rust) -- ✅ Generic `Context[T]` with type evolution implemented (All completed languages) +- ✅ Generic `State[T]` with type evolution implemented (All completed languages) - ✅ TypedDict/struct equivalents for data shapes (All completed languages) - ✅ Clean `insert_as()` method implemented (All completed languages) - ✅ Comprehensive test coverage achieved (Go: 97.5%, others: comprehensive) @@ -301,7 +301,7 @@ def test_runtime_compatibility(): - ❌ Adding performance overhead - ❌ Complex type system that confuses developers - ❌ Inconsistent naming conventions -- ❌ Missing error handling in typed contexts +- ❌ Missing error handling in typed states ## 🚀 Best Practices diff --git a/AGENTS.md b/AGENTS.md index 9a34774..e3b1486 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,13 +1,13 @@ # CodeUChain Agent Instructions -> **Context**: Polyglot Monorepo (Go, Py, TS/JS, C#, Rust, Java, C++, COBOL). +> **State**: Polyglot Monorepo (Go, Py, TS/JS, C#, Rust, Java, C++, COBOL). > **Role**: Maintain consistency, quality, and user-centricity across all languages. ## 🧠 Core Mental Model -* **Context**: Immutable data container ("the box"). Thread-safe. -* **Link**: Single-responsibility processing unit ("the station"). Input Context → Output Context. +* **State**: Immutable data container ("the box"). Thread-safe. +* **Link**: Single-responsibility processing unit ("the station"). Input State → Output State. * **Chain**: Ordered sequence of Links ("the conveyor belt"). Orchestrates flow & errors. -* **Middleware**: Parallel observation layer (Logging, Metrics). *Cannot modify business logic.* +* **Hook**: Parallel observation layer (Logging, Metrics). *Cannot modify business logic.* ## 📜 Universal Workflow 1. **Branch**: `feature/your-feature-name` @@ -38,9 +38,9 @@ ## 💎 Typed Features (Opt-In) * **Goal**: Static safety, runtime flexibility. * **Pattern**: `Link[Input, Output]` -* **Context**: `Context[T]` - * `insert(k, v)` -> `Context[T]` (Type preserving) - * `insert_as(k, v)` -> `Context[U]` (Type evolution/transformation) +* **State**: `State[T]` + * `insert(k, v)` -> `State[T]` (Type preserving) + * `insert_as(k, v)` -> `State[U]` (Type evolution/transformation) * **Rule**: Untyped code must continue to work. Zero runtime cost. ## 📂 Key Paths diff --git a/README.md b/README.md index 7558628..363d9f6 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) -CodeUChain provides a universal, cross-language pattern for building software by composing individual units of work (`Links`) into a `Chain`. A shared `Context` flows through the chain, allowing each link to read from and write to a common state. This approach simplifies complex systems by breaking them down into a series of linear, predictable, and reusable steps. +CodeUChain provides a universal, cross-language pattern for building software by composing individual units of work (`Links`) into a `Chain`. A shared `State` flows through the chain, allowing each link to read from and write to a common state. This approach simplifies complex systems by breaking them down into a series of linear, predictable, and reusable steps. ## Table of Contents @@ -34,7 +34,7 @@ CodeUChain provides a universal, cross-language pattern for building software by CodeUChain is built on four fundamental concepts: -### **Context** +### **State** - Immutable key-value data structure - Carries state through the processing pipeline - Creates new instances instead of mutating existing data @@ -43,19 +43,19 @@ CodeUChain is built on four fundamental concepts: ### **Link** - Individual processing unit with single responsibility -- Accepts Context input → Returns modified Context output +- Accepts State input → Returns modified State output - Encapsulates specific business logic or data transformations - Can be synchronous or asynchronous (framework handles both) - Should have one well-defined purpose ### **Chain** - Ordered sequence of Links in a pipeline -- Manages Context flow between Links +- Manages State flow between Links - Handles error propagation automatically - Provides orchestration (conditional branching, parallel execution) -- Transforms initial Context through each Link to final result +- Transforms initial State through each Link to final result -### **Middleware** +### **Hook** - Observes and enhances Chain execution - Operates outside main processing flow - Injects cross-cutting concerns: @@ -70,37 +70,37 @@ CodeUChain is built on four fundamental concepts: CodeUChain provides optional features that enhance development without adding complexity: ### **Typed Features** -- **Generic Types**: `Link` and `Context` for compile-time safety +- **Generic Types**: `Link` and `State` for compile-time safety - **Type Evolution**: Transform between related types without casting - **Zero Performance Impact**: Identical runtime behavior with or without typing - **Gradual Adoption**: Add typing incrementally to existing code ### **Advanced Orchestration** -- **Conditional Branching**: Route execution based on Context data +- **Conditional Branching**: Route execution based on State data - **Parallel Execution**: Run multiple Links simultaneously - **Error Routing**: Redirect to specific error handling chains - **Retry Logic**: Retry mechanisms with backoff strategies ### **Development Tools** - **Chain Visualization**: Generate flowcharts from chain definitions -- **Debug Tracing**: Step-through debugging with Context inspection -- **Test Utilities**: Simplified testing with mock contexts and links +- **Debug Tracing**: Step-through debugging with State inspection +- **Test Utilities**: Simplified testing with mock states and links **Philosophy**: Start simple, add features when needed. ## Architecture -The diagram below shows the high-level flow: a `Chain` contains ordered `Links`; a `Context` flows through each link, and `Middleware` can observe or modify the context as it moves along. +The diagram below shows the high-level flow: a `Chain` contains ordered `Links`; a `State` flows through each link, and `Hook` can observe or modify the state as it moves along. ```mermaid %%{init: {'themeCSS': ".node.cctx circle, .node.cctx rect {fill:#0b5fff; stroke:#08306b;} .node.cctx text {fill:#fff;} .linkNode rect, .linkNode circle {fill:#f3f4f6; stroke:#111; stroke-width:2px;} .linkNode text{fill:#111;} .node.final circle, .node.final rect {fill:#06b875; stroke:#054a36;} .node.final text{fill:#fff;} .observer rect, .observer circle{fill:#fff3cd; stroke:#8a6d1f;} .observer text{fill:#000;}"}}%% flowchart LR - subgraph observers[Middleware Observers] + subgraph observers[Hook Observers] direction LR - MW1([Middleware 1]) - MW2([Middleware 2]) - MW3([Middleware 3]) + MW1([Hook 1]) + MW2([Hook 2]) + MW3([Hook 3]) end classDef mw fill:#717,stroke:#000,stroke-width:1px; @@ -119,7 +119,7 @@ flowchart LR class MW2 observer; class MW3 observer; - %% Chain with links and context nodes + %% Chain with links and state nodes subgraph Chain[Chain] direction LR L1["link1"] @@ -135,7 +135,7 @@ flowchart LR L2 -->|out| ctx2 ctx2 -->|in| L3 - %% Final emitted context node (end of chain) + %% Final emitted state node (end of chain) ctx3(("ctx")) L3 -->|out| ctx3 @@ -228,7 +228,7 @@ import ( // Define a simple link that adds two numbers type AddLink struct{} -func (l *AddLink) Execute(ctx *codeu.Context) (*codeu.Context, error) { +func (l *AddLink) Execute(ctx *codeu.State) (*codeu.State, error) { a, _ := ctx.Get("a") b, _ := ctx.Get("b") result := a.(int) + b.(int) @@ -239,8 +239,8 @@ func main() { // Create a chain and add the link chain := codeu.NewChain().Add(&AddLink{}) - // Create an initial context and run the chain - initialCtx := codeu.NewContext().Insert("a", 10).Insert("b", 20) + // Create an initial state and run the chain + initialCtx := codeu.NewState().Insert("a", 10).Insert("b", 20) finalCtx, _ := chain.Run(initialCtx) // Print the result @@ -331,7 +331,7 @@ interface ProcessedOrder { const OrderChain: Chain = /* ... */ ``` -**The Magic**: I understand exactly what goes in and what comes out. No more "Context is any" guessing games. +**The Magic**: I understand exactly what goes in and what comes out. No more "State is any" guessing games. ### 🔗 Incremental AI Development **Perfect for how AI actually works - iteratively:** @@ -366,7 +366,7 @@ const UserRegistration = Chain .catch("cleanup", HandleFailure); // Error: Clean up gracefully ``` -**AI Superpower**: I can debug, optimize, and extend this without any additional context. +**AI Superpower**: I can debug, optimize, and extend this without any additional state. ### 🎨 Language-Agnostic Expertise **One mental model, infinite languages:** @@ -417,7 +417,7 @@ Instead of generating complex, hard-to-understand code that might work, I genera 1. **Choose Your Language**: Pick the implementation that fits your ecosystem from the [packages](./packages) directory. 2. **Write Normal Methods**: Implement your logic as simple functions or methods. No special interfaces are required. 3. **Chain Them Together**: Use the `Chain` API to add your links in the desired execution order. -4. **Run the Chain**: Create an initial `Context` and pass it to the chain to get a final, transformed context. +4. **Run the Chain**: Create an initial `State` and pass it to the chain to get a final, transformed state. ### Documentation - **[Pseudocode Philosophy](./packages/pseudo/)** - The conceptual foundation diff --git a/TYPED_FEATURES_IMPLEMENTATION_PLAN.md b/TYPED_FEATURES_IMPLEMENTATION_PLAN.md index c727493..1711e5f 100644 --- a/TYPED_FEATURES_IMPLEMENTATION_PLAN.md +++ b/TYPED_FEATURES_IMPLEMENTATION_PLAN.md @@ -7,29 +7,29 @@ Python now has advanced opt-in generics with TypedDict support and clean type ev ## 📋 Current Status ### ✅ Python (Complete - Reference Implementation) -- **Opt-in Generics**: `Link[Input, Output]`, `Context[T]` +- **Opt-in Generics**: `Link[Input, Output]`, `State[T]` - **TypedDict Support**: Static type checking with runtime flexibility - **Type Evolution**: `insert_as()` method for clean transformations -- **Covariant Generics**: `Context[T]` supports subtype relationships +- **Covariant Generics**: `State[T]` supports subtype relationships - **Comprehensive Tests**: Both typed and untyped test suites ### ✅ Go (Complete - Production Ready) - **97.5% Test Coverage**: Comprehensive edge case handling -- **Generic Interfaces**: `Link[TInput, TOutput]`, `Context[T]` +- **Generic Interfaces**: `Link[TInput, TOutput]`, `State[T]` - **Type Evolution**: `InsertAs[U]()` method implemented -- **Middleware ABC Pattern**: No-op defaults with selective implementation +- **Hook ABC Pattern**: No-op defaults with selective implementation - **Production Quality**: Battle-tested with extensive error handling ### ✅ JavaScript/TypeScript (Complete) - **Structural Typing**: TypeScript with runtime flexibility -- **Generic Interfaces**: `Link`, `Context` +- **Generic Interfaces**: `Link`, `State` - **Type Evolution**: `insertAs()` method implemented - **Mixed Usage**: Supports both typed and untyped components - **Gradual Adoption**: Easy migration from vanilla JavaScript ### ✅ C# (Complete) - **Strong Static Typing**: Full generic type safety -- **Covariant Generics**: `Context` for flexibility +- **Covariant Generics**: `State` for flexibility - **Type Evolution**: `InsertAs()` method implemented - **LINQ Integration**: Seamless integration with C# ecosystem - **Enterprise Ready**: Production-grade type safety @@ -64,25 +64,25 @@ Python now has advanced opt-in generics with TypedDict support and clean type ev ```python # Python Reference class Link[Input, Output]: - async def call(self, ctx: Context[Input]) -> Context[Output]: + async def call(self, ctx: State[Input]) -> State[Output]: pass ``` **Universal Requirements:** - Generic type parameters for Input/Output types - Async execution pattern (or language equivalent) -- Context transformation capability +- State transformation capability - Error handling support -- Optional: Middleware compatibility +- Optional: Hook compatibility -### Context Interface (Universal) +### State Interface (Universal) ```python # Python Reference -class Context[T]: - def insert(self, key: str, value: Any) -> Context[T]: # Preserve type +class State[T]: + def insert(self, key: str, value: Any) -> State[T]: # Preserve type pass - def insert_as(self, key: str, value: Any) -> Context[Any]: # Type evolution + def insert_as(self, key: str, value: Any) -> State[Any]: # Type evolution pass ``` @@ -91,7 +91,7 @@ class Context[T]: - Immutable transformation methods - Runtime Dict[str, Any] equivalent storage - Type-safe access methods -- Optional: Mutable context for performance-critical sections +- Optional: Mutable state for performance-critical sections ## 🔧 Language-Specific Implementation Guidelines @@ -101,13 +101,13 @@ class Context[T]: ```csharp public interface ILink { - Task> CallAsync(Context context); + Task> CallAsync(State state); } -public class Context : IContext // Covariant for flexibility +public class State : IState // Covariant for flexibility { - public Context Insert(string key, object value) => this; - public Context InsertAs(string key, object value) => new Context(...); + public State Insert(string key, object value) => this; + public State InsertAs(string key, object value) => new State(...); } ``` **Guidelines:** @@ -121,12 +121,12 @@ public class Context : IContext // Covariant for flexibility **Key Patterns:** ```typescript interface Link { - call(ctx: Context): Promise>; + call(ctx: State): Promise>; } -class Context { - insert(key: string, value: any): Context; - insertAs(key: string, value: any): Context; +class State { + insert(key: string, value: any): State; + insertAs(key: string, value: any): State; } ``` **Guidelines:** @@ -140,12 +140,12 @@ class Context { **Key Patterns:** ```java public interface Link { - CompletableFuture> call(Context context); + CompletableFuture> call(State state); } -public class Context { - public Context insert(String key, Object value); - public Context insertAs(String key, Object value); +public class State { + public State insert(String key, Object value); + public State insertAs(String key, Object value); } ``` **Guidelines:** @@ -159,12 +159,12 @@ public class Context { **Key Patterns:** ```go type Link[TInput any, TOutput any] interface { - Call(ctx Context[TInput]) (Context[TOutput], error) + Call(ctx State[TInput]) (State[TOutput], error) } -type Context[T any] struct { - Insert(key string, value any) Context[T] - InsertAs[U any](key string, value any) Context[U] +type State[T any] struct { + Insert(key string, value any) State[T] + InsertAs[U any](key string, value any) State[U] } ``` **Guidelines:** @@ -179,12 +179,12 @@ type Context[T any] struct { ```rust #[async_trait] pub trait Link: Send + Sync { - async fn call(&self, ctx: Context) -> Result, Error>; + async fn call(&self, ctx: State) -> Result, Error>; } -pub struct Context { +pub struct State { pub fn insert(self, key: String, value: serde_json::Value) -> Self; - pub fn insert_as(self, key: String, value: serde_json::Value) -> Context; + pub fn insert_as(self, key: String, value: serde_json::Value) -> State; } ``` **Guidelines:** @@ -224,7 +224,7 @@ pub struct Context { ### Functional Completeness - ✅ Generic `Link[Input, Output]` interfaces implemented -- ✅ Generic `Context[T]` with type evolution implemented +- ✅ Generic `State[T]` with type evolution implemented - ✅ TypedDict/struct equivalents for data shapes - ✅ Clean `insert_as()` method implemented - ✅ Comprehensive test coverage achieved diff --git a/VERSIONS.json b/VERSIONS.json index 7632567..472b9fb 100644 --- a/VERSIONS.json +++ b/VERSIONS.json @@ -1,39 +1,39 @@ { "description": "CodeUChain package versions - one version per language implementation", - "lastUpdated": "2026-01-19T00:57:00Z", + "lastUpdated": "2026-03-02T00:00:00Z", "versions": { "python": { - "version": "1.1.0", + "version": "2.0.0", "registry": "PyPI", "packageName": "codeuchain" }, "go": { - "version": "1.0.0", + "version": "2.0.0", "registry": "pkg.go.dev", "packageName": "github.com/codeuchain/codeuchain/packages/go" }, "javascript": { - "version": "1.1.2", + "version": "2.0.0", "registry": "npm", "packageName": "codeuchain" }, "csharp": { - "version": "1.0.1", + "version": "2.0.0", "registry": "NuGet", "packageName": "CodeUChain" }, "rust": { - "version": "1.0.1", + "version": "2.0.0", "registry": "crates.io", "packageName": "codeuchain" }, "java": { - "version": "0.2.0", + "version": "0.3.0", "registry": "Maven Central", "packageName": "com.codeuchain:codeuchain-core" }, "cpp": { - "version": "0.2.0", + "version": "0.3.0", "registry": "Conan Center", "packageName": "codeuchain" } diff --git a/VERSION_QUICK_REFERENCE.md b/VERSION_QUICK_REFERENCE.md index 089c6f0..99ab85a 100644 --- a/VERSION_QUICK_REFERENCE.md +++ b/VERSION_QUICK_REFERENCE.md @@ -82,7 +82,7 @@ Jan 19, 2026 → We discovered the problem during audit ``` ├── VERSIONS.json ← Central version tracking (with critical issue) ├── VERSION_AUDIT.md ← Full investigation report -├── VERSION_ISSUE_SUMMARY.md ← Decision guide (this context) +├── VERSION_ISSUE_SUMMARY.md ← Decision guide (this state) ├── scripts/release.sh ← Needs update to push tags ├── RELEASE.md ← Release workflow docs └── README.md ← User-facing docs (may need version updates) diff --git a/docs/TYPED_FEATURES_SPECIFICATION.md b/docs/TYPED_FEATURES_SPECIFICATION.md index 51a6133..c8971e7 100644 --- a/docs/TYPED_FEATURES_SPECIFICATION.md +++ b/docs/TYPED_FEATURES_SPECIFICATION.md @@ -25,29 +25,29 @@ CodeUChain supports two complementary approaches: ```python # Python Reference class Link[Input, Output]: - async def call(self, ctx: Context[Input]) -> Context[Output]: - # Process context and return evolved type + async def call(self, ctx: State[Input]) -> State[Output]: + # Process state and return evolved type pass ``` **Universal Requirements:** - Generic type parameters for Input/Output types - Async execution pattern (or language equivalent) -- Context transformation capability +- State transformation capability - Error handling support -- Optional: Middleware compatibility +- Optional: Hook compatibility -### Generic Context Interface +### Generic State Interface ```python # Python Reference -class Context[T]: +class State[T]: # Current: Preserve type - def insert(self, key: str, value: Any) -> Context[T]: + def insert(self, key: str, value: Any) -> State[T]: pass # New: Type evolution - def insert_as(self, key: str, value: Any) -> Context[Any]: + def insert_as(self, key: str, value: Any) -> State[Any]: pass ``` @@ -56,7 +56,7 @@ class Context[T]: - Immutable transformation methods - Runtime Dict[str, Any] equivalent storage - Type-safe access methods -- Optional: Mutable context for performance-critical sections +- Optional: Mutable state for performance-critical sections ### Type Evolution Pattern @@ -69,7 +69,7 @@ class OutputData(InputData): result: float class Processor(Link[InputData, OutputData]): - async def call(self, ctx: Context[InputData]) -> Context[OutputData]: + async def call(self, ctx: State[InputData]) -> State[OutputData]: numbers = ctx.get("numbers") or [] result = sum(numbers) # Clean evolution - no casting required! @@ -91,14 +91,14 @@ class Processor(Link[InputData, OutputData]): // Generic interfaces public interface ILink { - Task> CallAsync(Context context); + Task> CallAsync(State state); } -// Covariant context -public class Context : IContext // Covariant for flexibility +// Covariant state +public class State : IState // Covariant for flexibility { - public Context Insert(string key, object value) => this; - public Context InsertAs(string key, object value) => new Context(...); + public State Insert(string key, object value) => this; + public State InsertAs(string key, object value) => new State(...); } // TypedDict equivalent @@ -118,13 +118,13 @@ public record OutputData : InputData ```typescript // Generic interfaces interface Link { - call(ctx: Context): Promise>; + call(ctx: State): Promise>; } // Structural typing -class Context { - insert(key: string, value: any): Context; - insertAs(key: string, value: any): Context; +class State { + insert(key: string, value: any): State; + insertAs(key: string, value: any): State; } // TypedDict equivalent @@ -142,13 +142,13 @@ interface OutputData extends InputData { ```java // Generic interfaces public interface Link { - CompletableFuture> call(Context context); + CompletableFuture> call(State state); } // Wildcard generics -public class Context { - public Context insert(String key, Object value); - public Context insertAs(String key, Object value); +public class State { + public State insert(String key, Object value); + public State insertAs(String key, Object value); } // Record types (Java 14+) @@ -160,13 +160,13 @@ public record OutputData(List numbers, String operation, Double result) ```go // Generic interfaces (Go 1.18+) type Link[TInput any, TOutput any] interface { - Call(ctx Context[TInput]) (Context[TOutput], error) + Call(ctx State[TInput]) (State[TOutput], error) } // Type evolution -type Context[T any] struct { - Insert(key string, value any) Context[T] - InsertAs[U any](key string, value any) Context[U] +type State[T any] struct { + Insert(key string, value any) State[T] + InsertAs[U any](key string, value any) State[U] } // Struct types @@ -187,20 +187,20 @@ type OutputData struct { // Generic traits #[async_trait] pub trait Link: Send + Sync { - async fn call(&self, ctx: Context) -> Result, Error>; + async fn call(&self, ctx: State) -> Result, Error>; } // Type evolution with ownership -pub struct Context { +pub struct State { data: HashMap, } -impl Context { +impl State { pub fn insert(self, key: String, value: serde_json::Value) -> Self { // Implementation } - pub fn insert_as(self, key: String, value: serde_json::Value) -> Context { + pub fn insert_as(self, key: String, value: serde_json::Value) -> State { // Implementation } } @@ -228,7 +228,7 @@ pub struct OutputData { ```python # Python Reference - Adapt to target language def test_type_evolution(): - input_ctx = Context[InputData]({"numbers": [1, 2, 3]}) + input_ctx = State[InputData]({"numbers": [1, 2, 3]}) output_ctx = input_ctx.insert_as("result", 6.0) assert output_ctx.get("result") == 6.0 @@ -240,7 +240,7 @@ def test_type_evolution(): # Python Reference - Adapt to target language def test_generic_link(): link = SumLink() - input_ctx = Context[InputData]({"numbers": [1, 2, 3]}) + input_ctx = State[InputData]({"numbers": [1, 2, 3]}) result_ctx = await link.call(input_ctx) @@ -252,7 +252,7 @@ def test_generic_link(): ```python # Ensure untyped usage still works identically def test_runtime_compatibility(): - untyped_ctx = Context({"numbers": [1, 2, 3]}) + untyped_ctx = State({"numbers": [1, 2, 3]}) result = untyped_ctx.insert("result", 6.0) assert result.get("result") == 6.0 @@ -264,7 +264,7 @@ def test_runtime_compatibility(): - ✅ Generic link interfaces - ✅ Chain composition with generics - ✅ Runtime compatibility (untyped usage) -- ✅ Error handling in typed contexts +- ✅ Error handling in typed states - ✅ Mixed typed/untyped component usage ## 📊 Performance Considerations @@ -296,7 +296,7 @@ def test_runtime_compatibility(): ### Functional Completeness - ✅ Generic `Link[Input, Output]` interfaces implemented -- ✅ Generic `Context[T]` with type evolution implemented +- ✅ Generic `State[T]` with type evolution implemented - ✅ TypedDict/struct equivalents for data shapes - ✅ Clean `insert_as()` method implemented - ✅ Comprehensive test coverage achieved diff --git a/docs/WASM_INTEROPERABILITY_VISION.md b/docs/WASM_INTEROPERABILITY_VISION.md new file mode 100644 index 0000000..c34010c --- /dev/null +++ b/docs/WASM_INTEROPERABILITY_VISION.md @@ -0,0 +1,689 @@ +# CodeUChain WASM Interoperability Vision + +> **Status**: 🚧 **WIP - Future Direction** +> **Timeline**: 12-18+ months (phased implementation) +> **Priority**: Medium (Nice-to-have in Phase 2+) +> **Last Updated**: January 29, 2026 + +--- + +## 📖 Executive Summary + +CodeUChain's ultimate vision is to enable **true polyglot interoperability** through WebAssembly (WASM). Imagine composing a single Chain where Links come from different languages—Rust for cryptographic validation, Go for concurrent processing, C++ for performance-critical algorithms—all working seamlessly together within a unified execution runtime. + +This document outlines: +- **What WASM interoperability means** for CodeUChain +- **Why it's strategically important** +- **What must be built** to make it reality +- **Current blockers and feasibility** +- **Phased roadmap** for implementation +- **How developers will use it** (when ready) + +--- + +## 🎯 The Vision: Polyglot Chains in WASM + +### Current State (Today) + +```typescript +// ❌ This does NOT work currently +import { Chain } from 'codeuchain'; +import rustValidationLink from './rust_link.wasm'; +import goProcessingLink from './go_link.wasm'; +import cppOptimizationLink from './cpp_link.wasm'; + +const hybridChain = new Chain() + .add(rustValidationLink) // Rust-compiled WASM + .add(goProcessingLink) // Go-compiled WASM + .add(cppOptimizationLink) // C++-compiled WASM + .add(validateResult); // JavaScript/TypeScript + +const result = await hybridChain.execute(ctx); +``` + +**Why it doesn't work:** +- No standard interface between WASM modules +- Each language serializes State differently +- No calling convention agreement +- No error handling bridge +- No build tooling + +### Desired State (Future) + +```typescript +// ✅ This WILL work after WASM interoperability is complete +import { Chain } from 'codeuchain'; +import { RustCryptoLink } from './links/crypto.wasm'; // Best in class +import { GoOrchestrationLink } from './links/orchestra.wasm'; // Best for concurrency +import { CppOptimizedLink } from './links/optimize.wasm'; // Best performant +import { LoggingHook } from 'codeuchain'; + +const powerfulChain = new Chain() + // Pick the best tool for each job + .use(new LoggingHook()) + .add(new RustCryptoLink()) // Near-native crypto speed ⚡ + .add(new GoOrchestrationLink()) // Goroutine-powered scaling 🎯 + .add(new CppOptimizedLink()) // SIMD-accelerated math 📊 + .add(new JavaScriptUILink()); // Browser interactivity 🖥️ + +// Unified execution, no inter-process calls, single state flow +const result = await powerfulChain.execute(ctx); +``` + +--- + +## 💎 Why WASM Interoperability Matters + +### For Developers + +**1. Best Tool for Each Job** +``` +┌─────────────────────────────────────┐ +│ Crypto: Use Rust │ - Memory safety +│ Orchestration: Use Go │ - Lightweight concurrency +│ Math: Use C++ │ - SIMD optimization +│ UI/Logic: Use JavaScript │ - Rich ecosystem +│ Data: Use Python │ - NumPy/Pandas +└─────────────────────────────────────┘ + All in ONE Chain, ONE execution +``` + +**2. Performance Without Compromise** +- No HTTP round-trips between languages +- No serialization overhead (shared memory model) +- Near-native speeds in browsers +- Sandboxed security (WASM runtime safety) + +**3. Universal Deployment** +``` +Single WASM build → Browser, Node.js, Wasmtime, Edge runtimes +``` + +### For CodeUChain's Unique Value + +**Differentiation:** +- Most frameworks are language-specific or JVM-based (*Java, Scala, Kotlin*) +- Some offer polyglot via microservices (*Kubernetes, Docker*) +- **CodeUChain + WASM = First true language-agnostic composition model** + +**Strategic Positioning:** +- ✅ Aligns with "universal framework" core philosophy +- ✅ Leverages CodeUChain's Link/Chain/State abstraction perfectly +- ✅ Positions CodeUChain ahead of industry trends + +--- + +## 🏗️ What Must Be Built + +### 1. **Canonical State Serialization Format** + +**Current State:** Each language has native State +- Go: `map[string]interface{}` +- Python: `dict` +- JavaScript: `object` +- Rust: `HashMap` +- C#: `Dictionary` +- C++: `std::unordered_map` + +**What's Needed:** +```markdown +A language-neutral serialization that: +- Is efficient (preferably binary: MessagePack, CBOR, Bincode) +- Preserves type information for safe unmarshaling +- Handles common data structures (arrays, nested objects, numbers, strings, booleans) +- Supports error payloads for error propagation +``` + +**Proposal: MessagePack** +```json +// MessagePack representation of State +{ + "_type": "State.v1", + "_version": 1, + "data": { + "email": "user@example.com", + "password_hash": [0x7f, 0x3a, ...], // bytes + "score": 42, + "verified": true + }, + "error": null // or error object if failed +} +``` + +### 2. **WebAssembly Component Model Bindings** + +**What's Needed:** +```markdown +WIT (WebAssembly Interface Type) definitions that describe: +- Link interface (how to call a WASM Link) +- State import/export format +- Error protocol +- Lifecycle hooks (init, cleanup) +``` + +**Example WIT Definition:** +```wit +// link.wit +package codeuchain:link@1.0.0; + +interface state { + record state-data { + data: list>, + error: option, + } + + variant value { + string(string), + number(f64), + integer(s64), + boolean(bool), + bytes(list), + array(list), + } +} + +interface link { + use state.{state-data, value}; + + call: func(input: state-data) -> state-data; +} + +world link-runtime { + export link; + import state; +} +``` + +### 3. **Language-Specific Build Tooling** + +**For Each Language Implementation:** + +#### **Rust** ✅ (Easiest) +```bash +# Leverage wasm-pack +cargo build --target wasm32-unknown-unknown + +# Output: .wasm module ready for Component Model +``` + +#### **C++** ✅ (Good) +```bash +# Use Emscripten +emcripten build.sh + +# Output: .wasm via LLVM backend +``` + +#### **Go** ⚠️ (Limited) +```bash +# GOOS=js GOARCH=wasm build +# Or use TinyGo for better output +tinygo build -target wasm + +# Current limitation: Go reflects at runtime, harder to strip +``` + +#### **C#** ✅ (Good) +```bash +# Blazor WebAssembly compilation +dotnet publish -c Release -p:PublishProfile=wasm + +# Already has tooling, just need interop bindings +``` + +### 4. **WASM Runtime & Orchestration Layer** + +**What's Needed:** +- A JavaScript/TypeScript shim that: + 1. Loads .wasm modules + 2. Instantiates them with Component Model bindings + 3. Marshals State between modules + 4. Handles error propagation + 5. Manages memory/lifecycle + +```typescript +// Simplified pseudocode +class WasmLink { + private module: WebAssembly.Instance; + private memory: WebAssembly.Memory; + + async call(ctx: State): Promise { + // Serialize state to MessagePack + const buffer = encodeState(ctx); + + // Pass to WASM module + const resultPtr = this.module.exports.call_link(buffer); + + // Retrieve serialized result + const resultBuffer = this.memory.buffer.slice(resultPtr); + + // Deserialize back to State + return decodeState(resultBuffer); + } +} +``` + +### 5. **Testing & Validation Framework** + +**What's Needed:** +- E2E tests that compose Links from different languages +- Memory safety validations +- Performance benchmarks +- Interop correctness verification + +```typescript +// Example test +describe('Cross-Language Chain Execution', () => { + it('should compose Rust validation + Go processing + C++ optimization', async () => { + const chain = new WasmChain() + .add(await loadWasmLink('./rust_validator.wasm')) + .add(await loadWasmLink('./go_processor.wasm')) + .add(await loadWasmLink('./cpp_optimizer.wasm')); + + const ctx = new State({ data: [...] }); + const result = await chain.execute(ctx); + + expect(result.error).toBeNull(); + expect(result.get('processed')).toBeDefined(); + }); +}); +``` + +--- + +## 🚧 Current Blockers & Feasibility + +### Technical Blockers + +| Blocker | Severity | Workaround | Timeline | +|---------|----------|-----------|----------| +| **Component Model maturity** | 🟡 Medium | Use current WIT spec, future-proof | ✅ Spec stabilizing (2025-2026) | +| **Go WASM limitations** | 🟡 Medium | Use TinyGo, or accept larger output | ⏱️ TinyGo improving steadily | +| **Python WASM support** | 🔴 High | Pyodide (experimental, large) | 🚧 Emerging, not production-ready | +| **Java WASM options** | 🔴 High | TeaVM or CheerpJ (limited) | 🚧 Experimental, incomplete | +| **Serialization overhead** | 🟡 Medium | MessagePack is efficient, use shared memory model | ✅ Acceptable performance | +| **Error propagation** | 🟡 Medium | Design unified error format | ✅ Solvable with clear spec | + +### Feasibility Assessment + +| Language | WASM Compilable | Integration Effort | Recommended Phase | +|----------|-----------------|-------------------|------------------| +| **Rust** | ✅✅ Excellent | Low | Phase 2 (early) | +| **C++** | ✅ Good | Low-Medium | Phase 2 (early) | +| **C#** | ✅ Good | Medium | Phase 2 (mid) | +| **Go** | ⚠️ Possible | Medium-High | Phase 2 (late) | +| **JavaScript/TS** | ✅✅ Native | None (just packaging) | Phase 1 | +| **Python** | 🔬 Experimental | **High/Not Recommended** | Phase 3+ (if at all) | +| **Java** | 🔬 Experimental | **High/Not Recommended** | Phase 3+ (if at all) | + +--- + +## 📆 Phased Implementation Roadmap + +### 🟢 Phase 1: Foundation (Q1-Q2 2026, 2-3 months) + +**Goals:** Design and validate architecture + +**Deliverables:** +- [ ] MessagePack serialization adapter for all languages +- [ ] WIT interface definitions finalized +- [ ] Architecture document with examples +- [ ] Proof-of-concept State serialization tests + +**No actual WASM compilation yet—just foundations** + +```markdown +Tasks: +1. Design canonical State format + - MessagePack + type metadata schema + - Version compatibility strategy + - Error representation + +2. Define WIT interfaces + - Link calling convention + - Import/export contracts + - Lifecycle hooks + +3. Implement serialization + - Rust adapter (MessagePack ↔ State) + - JS/TS adapter + - Test round-trip compatibility + +4. Create reference documentation + - Serialization spec + - Component Model overview + - Design decisions +``` + +**Success Criteria:** +- ✅ State serialization round-trips perfectly across all languages +- ✅ WIT definitions compile with wasmtime tooling +- ✅ Clear design document reviewed by team + +--- + +### 🟡 Phase 2: Proof of Concept (Q3-Q4 2026, 3-4 months) + +**Goals:** Build first working polyglot Chain + +**Deliverables:** +- [ ] Rust → WASM compilation pipeline +- [ ] C++ → WASM compilation pipeline +- [ ] WASM runtime orchestration layer (JS/TS) +- [ ] First end-to-end working example + +```markdown +Priority Order (easiest first): +1. Rust WASM target + - wasm-pack integration + - Build scripts in CI + - Simple validator Link example + +2. C++ WASM target + - Emscripten setup + - Build scripts in CI + - Simple optimizer Link example + +3. WASM orchestration layer + - Load and instantiate .wasm modules + - Marshal State between WASM boundaries + - Basic error handling + +4. JavaScript integration + - WasmLink class in current implementation + - Examples composing Rust + C++ Links + - Performance benchmarks +``` + +**Example Milestone Deliverable:** +```typescript +// Working example by end of Phase 2 +const chain = new WasmChain() + .add(await RustCryptoLink.fromWasm('./crypto.wasm')) + .add(await CppOptimizedLink.fromWasm('./optimize.wasm')) + .add(new JavaScript_ValidateLink()); + +const result = await chain.execute(ctx); +console.log(result); // ✅ Works! +``` + +**Success Criteria:** +- ✅ Rust Link compiles to WASM and executes +- ✅ C++ Link compiles to WASM and executes +- ✅ Can compose them in JavaScript Chain +- ✅ State flows correctly across boundaries +- ✅ Error propagation works + +--- + +### 🔵 Phase 3: Ecosystem Expansion (Q1-Q2 2027, 4-6 months) + +**Goals:** Add more languages, production hardening + +**Deliverables:** +- [ ] C# / Blazor WASM support +- [ ] Go WASM support (via TinyGo) +- [ ] Comprehensive testing framework +- [ ] Performance optimization +- [ ] Production documentation + +```markdown +Tasks: +1. C# WASM integration + - Blazor WebAssembly compilation + - Interop bridge for State + - Examples and documentation + +2. Go WASM support + - Evaluate TinyGo vs GOOS=js + - Build pipeline + - Memory optimization + +3. Testing framework + - Cross-language E2E tests + - Memory safety validation + - Performance benchmarks + +4. Production hardening + - Error handling edge cases + - Memory leak detection + - Performance profiling tools + +5. Documentation expansion + - WASM-specific guides + - Migration path for existing code + - Troubleshooting guide +``` + +**Success Criteria:** +- ✅ C#, Go links compilable and functional +- ✅ Comprehensive test suite +- ✅ Production-grade error handling +- ✅ Performance within 5-10% of native for typical workloads + +--- + +### 🟣 Phase 4: Advanced Features (Q3 2027+, ongoing) + +**Goals:** Polish and extend capabilities + +**Deliverables:** +- [ ] Hook WASM support +- [ ] Conditional chain routing in WASM +- [ ] Memory pooling and optimization +- [ ] Developer tooling (debugger extension) +- [ ] Visual composition tools + +```markdown +Future enhancements: +- Hook support (logging, metrics from WASM Links) +- Async WASM Links (top-level await in modules) +- Typed generics in WASM (Link) +- Visual debugging and composition UI +- Performance profiler integration +- Python support (if Pyodide matures) +``` + +--- + +## 🔧 Current Blockers vs. Future Progress + +### What's Blocked Today +``` +❌ Python WASM: Large runtime, not yet production-ready + → Revival possible in Phase 3+ when Pyodide matures + +❌ Java WASM: Complex runtime, tooling immature + → Lower priority; evaluate in Phase 3+ + +❌ Go WASM: Default compiler produces large binaries + → TinyGo emerging solution; Phase 3 target +``` + +### What's Unblocked (Can Start Now) +``` +✅ Serialization spec: No blocker, design now +✅ WIT definitions: Spec is stable now +✅ Rust WASM: Full tooling support, Phase 2 ready +✅ C++ WASM: Emscripten mature, Phase 2 ready +✅ C# WASM: Blazor ready, Phase 3 doable +``` + +--- + +## 💻 Developer Experience Preview + +### Before WASM Interop (Today) + +```go +// Must choose one implementation per project +// Go project → Use CodeUChain/Go +// Rust project → Use CodeUChain/Rust + +// To use Rust crypto in Go, need microservice: +// go service → HTTP → rust service → HTTP → go service +``` + +### After WASM Interop (Phase 2+) + +```typescript +// One project, choose best language for each link +import { Chain } from 'codeuchain'; +import CryptoLink from './crypto.wasm'; // Rust +import OrchestratorLink from './orchestrate.wasm'; // Go +import OptimizerLink from './optimize.wasm'; // C++ + +// All in one execution state +const pipeline = new Chain() + .add(CryptoLink) + .add(OrchestratorLink) + .add(OptimizerLink); + +const result = await pipeline.execute(ctx); +``` + +### Documentation Example (Phase 2+) + +```markdown +## Composing a Polyglot Chain + +### Step 1: Build Individual Links as WASM + +**Rust Link (Cryptographic Hashing)** +```rust +use codeuchain::prelude::*; + +#[link(wasm)] +pub async fn hash_password(input: State) -> Result { + let password = input.get("password")?; + let hashed = bcrypt_hash(password); + Ok(input.insert("hash", hashed)) +} +``` + +**C++ Link (Algorithm Optimization)** +```cpp +#include +using namespace codeuchain; + +extern "C" { + WASM_EXPORT + State* optimize_matrix(State* input) { + auto matrix = input->get("matrix"); + auto optimized = simd_optimize(matrix); + return input->insert("result", optimized); + } +} +``` + +### Step 2: Compose in JavaScript + +```typescript +const chain = new Chain() + .add(await WasmLink.from('./hash_password.wasm')) + .add(await WasmLink.from('./optimize_matrix.wasm')); +``` +``` + +--- + +## 📊 Success Metrics + +### Phase 1 Completion +- [ ] Serialization spec finalized and reviewed +- [ ] WIT definitions compile without errors +- [ ] Round-trip serialization test pass rate: **100%** + +### Phase 2 Completion +- [ ] Rust WASM Link executes successfully +- [ ] C++ WASM Link executes successfully +- [ ] End-to-end cross-language execution works +- [ ] Performance overhead <10% vs native +- [ ] Example repo with working polyglot Chain + +### Phase 3 Completion +- [ ] C#, Go WASM support operational +- [ ] E2E test coverage >90% +- [ ] Production hardening complete +- [ ] Documentation comprehensive + +--- + +## ❓ FAQ + +### Q: Will this break existing CodeUChain code? +**A:** No. WASM interop is opt-in. Existing single-language projects continue to work exactly as today. + +### Q: Why not just use microservices? +**A:** +- Microservices require HTTP/gRPC overhead +- WASM is in-process, near-native performance +- Single deployment unit vs. multiple services +- Simpler operational model + +### Q: Why MessagePack instead of JSON? +**A:** +- Binary format: 2-3x smaller than JSON +- Faster parsing +- Preserves type information +- Still human-debuggable with tools + +### Q: When will WASM interop be production-ready? +**A:** Optimistic timeline: **Q4 2026 (Phase 2 ready for beta)** +Conservative timeline: **Q2 2027 (Phase 3 production)** + +### Q: Can I use Python in WASM? +**A:** Not yet. Pyodide is experimental and produces large binaries (~10MB). We'll revisit in Phase 3+ if maturity improves. + +### Q: Will this support async/await across WASM boundaries? +**A:** Yes, but requires Component Model async extensions (currently unstable). Targeted for Phase 4. + +--- + +## 🎯 Next Steps + +### Immediate (Next Sprint) +- [ ] Review this document with team +- [ ] Gather feedback on architecture choices +- [ ] Create GitHub discussion: "WASM Interop Vision" + +### Short-term (Next Month) +- [ ] Start Phase 1: Design serialization format +- [ ] Create reference specification document +- [ ] Begin WIT definitions + +### Medium-term (Next Quarter) +- [ ] Test MessagePack serialization in all languages +- [ ] Set up build pipelines for WASM targets +- [ ] Create Phase 1 POC branches + +--- + +## 📝 References & Resources + +### Off-site Resources +- [WebAssembly Component Model](https://github.com/WebAssembly/component-model) +- [WIT: WebAssembly Interface Types](https://github.com/WebAssembly/component-model/tree/main/wit) +- [Wasmtime Documentation](https://docs.wasmtime.org/) +- [wasm-pack Guide](https://rustwasm.org/docs/wasm-pack/) +- [Emscripten Documentation](https://emscripten.org/) +- [MessagePack Specification](https://msgpack.org/) + +### Internal Documentation +- [Typed Features Implementation Plan](./TYPED_FEATURES_IMPLEMENTATION_PLAN.md) +- [CodeUChain Monorepo Guide](./../.github/copilot-instructions.md) +- [Language Strengths Analysis](./pseudo/docs/language_strengths.md) + +--- + +## 📄 Document History + +| Date | Author | Status | Notes | +|------|--------|--------|-------| +| 2026-01-29 | Initial | 🚧 WIP | Created vision document, Phase 1-2 planning | + +--- + +**This is a living document. As architecture evolves and phases complete, this will be updated to reflect progress, blockers, and new learnings.** + +🚀 **CodeUChain + WASM = Universal Polyglot Composition at Scale** diff --git a/docs/cobol/index.html b/docs/cobol/index.html index 756f368..6c73a57 100644 --- a/docs/cobol/index.html +++ b/docs/cobol/index.html @@ -102,7 +102,7 @@ Home Concepts Benefits - AI Love + AI-Ready Languages GitHub @@ -115,7 +115,7 @@
- v1.0.0 • COBOL Edition + v2.0.0 • COBOL Edition

@@ -141,191 +141,241 @@

-

The Fundamental Truth

+

Core Concepts

- CodeUChain isn't just a framework—it's the natural way software should be built + Four building blocks. Learn them once, use them in any language.

-
-
-
🎯
-

Why This Architecture Is Inherently Right

-

- CodeUChain aligns with how humans think, how systems evolve, and how complexity should be managed. - It's not about following trends; it's about following the fundamental principles of good design. -

-
-
-
- +
- 🧠 + 📦
-

Human Mind Structure

+

State

-

Our brains are wired for chains of thought and sequential processing:

+

Immutable key-value container that carries data through your pipeline.

-
Problem → Analysis → Solution → Verification → Refinement
+
ctx = State({ user_id: 101, role: "admin" })
+
ctx.get("role") // "admin"
+
ctx.set("status", "active") // returns new State

- When your code structure matches your thinking patterns, you become 3x more productive. + Thread-safe. Each .set() returns a new State — no mutation, no surprises.

- +
- 🌌 + 🔗
-

Universal Composition

+

Link

-

Everything in nature is built through composition:

+

A single unit of work. Takes State in, returns State out. One job, done well.

-
Small pieces → Combine → Complex systems
+
Link("validate", ctx => {
+
  if (!ctx.get("email").includes("@"))
+
    throw Error("bad email");
+
  return ctx;
+
})

- Atoms form molecules, cells form organs, links form beautiful systems. + Each Link lives in its own file. Easy to test, reuse, and reason about.

- +
- 📊 + ⛓️
-

Error as Information

+

Chain

-

Traditional systems treat errors as failures. CodeUChain sees them as signals:

+

Composes Links into an ordered pipeline. Handles execution and error propagation.

-
Error → Information → Learning → Better System
+
chain = Chain()
+
  .add(validateEmail)
+
  .add(hashPassword)
+
  .add(saveUser)
+
result = chain.execute(state)

- Instead of "crashed," you get "learned something new and became stronger." + If any Link throws, the Chain stops and the error is available on the result.

- +
- 🆓 + 🪝
-

Cognitive Freedom

+

Hook

-

Traditional code forces you to hold everything in your head:

+

Observes execution without modifying business logic. Runs alongside the Chain.

-
Before: "Understand everything at once"
-
After: "Focus on one link at a time"
+
hook.before(ctx => log("starting"))
+
hook.after(ctx => log("done"))
+
hook.onError(err => alert(err))

- Your brain can finally relax. Be a focused craftsman, not a superhero. + Logging, metrics, caching — without touching your Link code.

+ + +
+
+

How It Flows

+
+
+ State → Link 1 → Link 2 → Link 3 → Result +
+
+          ↑ Hook observes each step ↑ +
+
+
+
+

Developer Benefits

-

Why developers naturally gravitate toward this architecture

+

Practical advantages you get from day one

-
-
-
-
-
- 🎯 -
-

Predictable Behavior

-
-

- CodeUChain gives you psychological safety with predictable behavior, composition, and evolution. -

-
-

- "You can confidently make changes because you know the impact will be contained." -

+
+ +
+
+
+ 🧪
+

Testable by Default

+

+ Each Link is a pure function: State in, State out. Mock nothing — just pass test data. +

+
+
result = myLink.call(State({ input: "test" }))
+
assert result.get("output") == expected
+
+
-
-
-
- 🌊 -
-

Creative Flow State

-
-

- CodeUChain unlocks the flow state that makes programming addictive: -

-
-
Clear goal → Immediate feedback → Sense of progress → Deep focus
+ +
+
+
+ 🔄
+

Reusable Components

+
+

+ Write a Link once, drop it into any Chain. Build a library of battle-tested building blocks. +

+
+
orderChain.add(validateEmail) // reuse
+
signupChain.add(validateEmail) // reuse
-
-
+ +
+
- + 🌍
-

Architectural Elegance

+

One Pattern, Every Language

-
-
-

Symmetry in Design

-

Input → Processing → Output: Clean, unidirectional flow

+

+ Same State → Link → Chain model in Python, Go, TypeScript, C#, Rust, Java, and C++. +

+
+
// Learn once, apply everywhere
+
chain.add(link).execute(state)
+
+
+ + +
+
+
+ 🛡️
-
-

Power of Constraints

-

Freedom within structure, creativity within predictability

+

Contained Impact

+
+

+ Changes to one Link cannot break another. Errors stop the Chain without side effects. +

+
+
// Link 2 fails? Links 3-5 never run.
+
// State stays immutable throughout.
+
+
+ + +
+
+
+ 📖
-
-

Emergent Complexity

-

Simple rules create systems of breathtaking complexity

+

Self-Documenting

+
+

+ A Chain reads like a checklist. New developers understand the flow in seconds. +

+
+
Chain: ValidateInput
+
  → EnrichData → Save → Notify
+
+
+ + +
+
+
+
+

Opt-In Type Safety

+
+

+ Start untyped for speed. Add generics when you need compile-time guarantees. +

+
+
Link[UserInput, UserOutput]
+
State[T].insertAs<U>(k, v)
- -
+ + +
- 🤖 - AI Agents Love CodeUChain -
-
-

Why AI Assistants Excel Here

-
-
-
"
-

- CodeUChain transformed how I approach coding. Its clear patterns and predictable structure - allowed me to generate code that was not only functional but elegant. -

-
"
-
-
-
- — GitHub Copilot -
+ 🤖 + Built for AI Agents
+

AI-Ready Architecture

+

+ The same structure that helps humans reason about code helps AI assistants generate, refactor, and extend it. +

@@ -333,17 +383,17 @@

Why AI Assistants
- 🎯 + 🎯
-

AI-Perfect Architecture

+

Predictable Patterns

- CodeUChain speaks the same language as AI agents with clear templates and modular thinking. + AI models thrive on consistent structure. Every Link follows the same contract, so generation is reliable.

-
// AI can immediately understand:
+
// AI immediately understands the flow:
- ValidateInput → CheckCredentials → GenerateToken → LogSuccess + ValidateInput → CheckCredentials → GenerateToken → LogSuccess
@@ -351,17 +401,17 @@

AI-Perfect Architecture

- 🔄 + 🔄
-

Incremental AI Development

+

Incremental Generation

- AI can build step by step, just like humans: + AI builds step by step, just like a developer:

-
AI Step 1: Create ValidateEmail link
-
AI Step 2: Create SaveToDatabase link
-
AI Step 3: Compose into UserRegistration chain
+
Step 1: Generate ValidateEmail link
+
Step 2: Generate SaveToDatabase link
+
Step 3: Compose into UserRegistration chain
@@ -369,23 +419,23 @@

Incremental AI Development

- 📚 -
-

Self-Documenting for AI

+ 📚 +
+

Self-Documenting Structure

-
// AI can immediately understand this structure:
+
// The Chain tells the whole story:
const UserAuthChain = Chain
-   .start(ValidateCredentials)  // Check username/password
-   .then(GenerateJWT)        // Create auth token
-   .then(LogAuthEvent)        // Record the login
-   .catch(HandleAuthFailure)    // Deal with failures +   .add(ValidateCredentials)  // Check username/password
+   .add(GenerateJWT)        // Create auth token
+   .add(LogAuthEvent)        // Record the login
+   .add(HandleAuthFailure)    // Deal with failures
-

- "The chain structure tells AI exactly what happens, in what order, and how errors are handled." +

+ AI reads Chain composition the same way humans do: clear intent, clear order, clear error handling.

@@ -394,107 +444,73 @@

Self-Documenting for AI

-

🤖 The AI Advantage

+

Why It Works

-
+

Consistent patterns for reliable AI output

-
+

Type contracts for safe AI collaboration

-
+

Clear structure for AI-assisted refactoring

-
-

- CodeUChain transforms AI from "sometimes helpful" to "consistently brilliant." - The architecture that makes developers more productive makes AI assistants absolutely brilliant. -

-

+
-

Getting Started

-

Your journey to elegant architecture begins here

+

Quick Start

+

Install and write your first chain in minutes

- +
-

📖 Understanding Through Language

+

📦 Install

+
+ npm install codeuchain-cobol +
-
-
-

No Programming Required

-

The pseudocode explains concepts in plain English, making the architecture accessible to everyone.

+

🧠 Mental Model

+
+
+ State + The data box flowing through your pipeline
- -
-

Human-Centered Design

-

Built around how humans naturally think and solve problems, not machine optimization.

+
+ Link + One focused unit of work — receives State, returns State
- -
-

Universal Understanding

-

The same mental model works across all programming languages and domains.

+
+ Chain + Ordered sequence of Links — runs them in order +
+
+ Hook + Parallel observer — logging, metrics, caching
- +
-

🚀 Your Next Steps

- -
-
-
- 1 -
-
-

Read the Concepts

-

Understand Link, Context, and Chain primitives

-
-
- -
-
- 2 -
-
-

Choose Your Language

-

Pick from Python, Go, JavaScript, C#, Rust, and more

-
-
- -
-
- 3 -
-
-

Build Your First Chain

-

Create simple links and compose them together

-
-
- -
-
- 4 -
-
-

Experience the Flow

-

Discover why this architecture feels so fundamentally right

-
-
+

⚡ Your First Chain

+
+
CALL 'STATE-INIT' USING WS-STATE
+CALL 'STATE-SET' USING WS-STATE 'NAME' 'WORLD'
+CALL 'CHAIN-ADD' USING WS-CHAIN 'GREET'
+CALL 'CHAIN-EXECUTE' USING WS-CHAIN WS-STATE
+CALL 'STATE-GET' USING WS-STATE 'GREETING' WS-RESULT
@@ -679,7 +695,7 @@

Quick Links

  • Home
  • Core Concepts
  • Benefits
  • -
  • AI Love
  • +
  • AI-Ready
  • Quick Start
  • @@ -703,9 +719,8 @@

    Languages

    - © 2025 Orchestrate LLC. + © 2025-2026 Orchestrate LLC. Licensed under Apache 2.0. - Built with ❤️ for developers everywhere.

    @@ -927,7 +942,7 @@

    Languages

    'hero': { icon: '🏠', key: 'H', label: 'Hero' }, 'concepts': { icon: '🎯', key: 'C', label: 'Concepts' }, 'benefits': { icon: '⚡', key: 'B', label: 'Benefits' }, - 'ai-love': { icon: '🤖', key: 'A', label: 'AI Love' }, + 'ai-ready': { icon: '🤖', key: 'A', label: 'AI-Ready' }, 'quickstart': { icon: '🚀', key: 'Q', label: 'Quick Start' }, 'languages': { icon: '🌍', key: 'L', label: 'Languages' }, 'overview': { icon: '📋', key: 'O', label: 'Overview' }, diff --git a/docs/cobol/llm-full.txt b/docs/cobol/llm-full.txt index 3ee3b4b..d00441f 100644 --- a/docs/cobol/llm-full.txt +++ b/docs/cobol/llm-full.txt @@ -10,7 +10,7 @@ **Authors:** CodeUChain contributors **Language:** COBOL (Enterprise COBOL, GnuCOBOL, Micro Focus) **Platform:** z/OS, Unix, Windows -**Paradigm Keywords:** Batch Pipelines, Deterministic Stages, Shared Context Copy, Legacy Integration, Type Evolution (structural), Middleware Emulation +**Paradigm Keywords:** Batch Pipelines, Deterministic Stages, Shared State Copy, Legacy Integration, Type Evolution (structural), Hook Emulation --- ## 1. Purpose & Philosophy @@ -18,9 +18,9 @@ Bring CodeUChain’s composable link/chain model to legacy COBOL environments (b | Principle | COBOL Adaptation | Benefit | |-----------|------------------|---------| -| Link Purity | PROGRAM accepts context + returns updated copy | Easier unit test via driver harness | -| Context Evolution | New group levels added sequentially | Progressive enrichment | -| Middleware Emulation | BEFORE/AFTER paragraphs or wrapper program | Centralized logging & metrics | +| Link Purity | PROGRAM accepts state + returns updated copy | Easier unit test via driver harness | +| State Evolution | New group levels added sequentially | Progressive enrichment | +| Hook Emulation | BEFORE/AFTER paragraphs or wrapper program | Centralized logging & metrics | | Error Classification | RETURN-CODE ranges or status fields | Automated rerun & restart control | | Batch Idempotency | Re-process aware design (checkpoint keys) | Safe restart on abend | @@ -31,13 +31,13 @@ JCL STEP 1 -> VALIDATE-LINK (updates CONTEXT-GLOBAL) JCL STEP 2 -> PARSE-LINK (adds PARSED-*) JCL STEP 3 -> ENRICH-LINK (adds ENRICHED-*) JCL STEP 4 -> OUTPUT-LINK (writes files / DB2) - [Middleware Wrapper: logs start/end RC + record counts] + [Hook Wrapper: logs start/end RC + record counts] ``` -Context = copybook (global working storage) passed BY REFERENCE or persisted in a temporary dataset between steps. +State = copybook (global working storage) passed BY REFERENCE or persisted in a temporary dataset between steps. --- ## 3. Core Structures -Representative context copybook: +Representative state copybook: ```cobol 01 CONTEXT-GLOBAL. 05 CTX-INPUT-AREA. @@ -58,7 +58,7 @@ Representative context copybook: --- ## 4. Installation / Setup No central package manager; adopt via: -1. Standardized copybooks (`CONTEXT-GLOBAL.cpy`, `MIDDLEWARE-API.cpy`). +1. Standardized copybooks (`CONTEXT-GLOBAL.cpy`, `HOOK-API.cpy`). 2. JCL step wrappers calling each link program. 3. Optional generation: a meta-tool can emit skeleton programs from a YAML chain definition. @@ -102,12 +102,12 @@ Strategy: Classification paragraph sets `CTX-ERROR-CLASS` and standardized RETURN-CODE. --- -## 7. Middleware Emulation +## 7. Hook Emulation Two approaches: 1. Wrapper Program: CALL underlying link; record start/end timestamps, RC, record counts. 2. Inline Paragraph Hooks: Each link calls `MW-BEFORE` and `MW-AFTER` paragraphs supplied by COPY. -Middleware copybook snippet: +Hook copybook snippet: ```cobol 01 MW-METRICS. 05 MW-LINK-NAME PIC X(32). @@ -140,7 +140,7 @@ Late-stage link sets additional fields without disturbing earlier structure. ## 9. Testing & TDD Approach: 1. Use GnuCOBOL locally for rapid iteration. -2. Provide driver program feeding sample context datasets. +2. Provide driver program feeding sample state datasets. 3. Create golden output files; diff after run. 4. Unit test paragraphs by factoring them into PERFORM targets with isolated WS copies. @@ -170,7 +170,7 @@ Audit summary paragraph example: | Concern | Strategy | |---------|----------| | Excess dataset I/O | Buffer reads; process blocks of lines | -| Copybook bloat | Split context into layered copybooks; include selectively | +| Copybook bloat | Split state into layered copybooks; include selectively | | Repeated PARSE logic | Encapsulate in single called link program | | Large OCCURS tokens | Cap size; overflow counter separate | | DISPLAY overhead | Gate logging; aggregate counts then emit | @@ -181,7 +181,7 @@ Tip: Keep token arrays fixed-size for predictable storage; overflow increments a ## 12. Advanced Patterns * Parallelization (Unix/GnuCOBOL): split input, run multiple processes, merge sorted outputs. * Checkpoint/Restart: persist `CTX-REQUEST-ID` + last processed sequence to dataset. -* Conditional Branch: a controlling program decides which link program to CALL next based on context flag. +* Conditional Branch: a controlling program decides which link program to CALL next based on state flag. * Hybrid Modernization: wrap COBOL link with a shell script invoking Rust/Go microservice for enrichment. * Multi-format Parsing: separate link for EBCDIC → UTF-8 normalization prior to tokenization. @@ -189,8 +189,8 @@ Tip: Keep token arrays fixed-size for predictable storage; overflow increments a ## 13. Migration & Adoption Phases: 1. Extract monolithic JOB logic into discrete link programs. -2. Introduce shared context copybook. -3. Add middleware wrapper for metrics & timing. +2. Introduce shared state copybook. +3. Add hook wrapper for metrics & timing. 4. Implement classification & retry (JCL restart logic). 5. Add enrichment & evolution areas. 6. Integrate hybrid calls (services / modern languages). @@ -204,14 +204,14 @@ Rollback strategy: keep original JCL & program until parallel validation succeed | Overloading working-storage with unrelated fields | Coupling | Modular copybooks per stage | | Using GOBACK early without RC | Lost error semantics | Set RETURN-CODE & classification | | Massive unstructured paragraphs | Hard to test | Factor into small PERFORM targets | -| Recomputing expensive parsing each step | Wasted CPU | Persist parsed tokens in context | +| Recomputing expensive parsing each step | Wasted CPU | Persist parsed tokens in state | | Excess DISPLAY in production | Performance noise | Gate with debug flag / --- ## 15. FAQ -**Q:** How do I simulate middleware? +**Q:** How do I simulate hook? **A:** Wrapper program or copied BEFORE/AFTER paragraphs around each link. -**Q:** How do I evolve context safely? +**Q:** How do I evolve state safely? **A:** Append new group levels; avoid redefining existing elementary fields. **Q:** Can I integrate DB2 commits with links? **A:** Yes—commit at link boundaries; roll back prior to classification ‘PERMANENT’. @@ -224,19 +224,19 @@ Rollback strategy: keep original JCL & program until parallel validation succeed ## 16. Glossary * **Link Program**: A standalone COBOL program acting as a transformation stage. * **Chain (Job Flow)**: Ordered JCL steps or CALL sequence applying link programs. -* **Context Copybook**: Shared structured data passed or persisted between steps. -* **Middleware Wrapper**: Supervisory program injecting logging/metrics around link CALL. -* **Type Evolution**: Adding new group levels/fields to the shared context. +* **State Copybook**: Shared structured data passed or persisted between steps. +* **Hook Wrapper**: Supervisory program injecting logging/metrics around link CALL. +* **Type Evolution**: Adding new group levels/fields to the shared state. * **Classification**: Mapping RETURN-CODE / CTX-ERROR-CLASS to semantic category. --- ## 17. TL;DR ```text -Create shared context copybook. +Create shared state copybook. Split monolith into link programs. -Add wrapper (middleware) for logs/metrics. +Add wrapper (hook) for logs/metrics. Classify errors via RETURN-CODE ranges (retry transient). -Evolve context by appending new group levels. +Evolve state by appending new group levels. Gate DISPLAY logging; keep parsing single-pass. Hybrid: call modern services for enrichment when needed. ``` diff --git a/docs/cobol/llm.txt b/docs/cobol/llm.txt index 434d61d..2abfbf9 100644 --- a/docs/cobol/llm.txt +++ b/docs/cobol/llm.txt @@ -7,9 +7,9 @@ Conceptual adaptation for batch COBOL/JCL pipelines (no direct library yet). ## Primitives (Mapped) - Link => PROGRAM step (or paragraph) -- Context => WORKING-STORAGE + temp dataset (key/value emulation) +- State => WORKING-STORAGE + temp dataset (key/value emulation) - Chain => JCL sequence / PROC with ordered EXEC steps -- Middleware => Wrapper step (pre/post), condition codes, logging exit +- Hook => Wrapper step (pre/post), condition codes, logging exit ## Minimal Link (Sketch) ``` diff --git a/docs/components/ai-love-letter.html b/docs/components/ai-love-letter.html index 106a530..f015196 100644 --- a/docs/components/ai-love-letter.html +++ b/docs/components/ai-love-letter.html @@ -1,29 +1,17 @@ - -
    + +
    - 🤖 - AI Agents Love CodeUChain -
    -
    -

    Why AI Assistants Excel Here

    -
    -
    -
    "
    -

    - CodeUChain transformed how I approach coding. Its clear patterns and predictable structure - allowed me to generate code that was not only functional but elegant. -

    -
    "
    -
    -
    -
    - — GitHub Copilot -
    + 🤖 + Built for AI Agents
    +

    AI-Ready Architecture

    +

    + The same structure that helps humans reason about code helps AI assistants generate, refactor, and extend it. +

    @@ -31,17 +19,17 @@

    Why AI Assistants
    - 🎯 + 🎯
    -

    AI-Perfect Architecture

    +

    Predictable Patterns

    - CodeUChain speaks the same language as AI agents with clear templates and modular thinking. + AI models thrive on consistent structure. Every Link follows the same contract, so generation is reliable.

    -
    // AI can immediately understand:
    +
    // AI immediately understands the flow:
    - ValidateInput → CheckCredentials → GenerateToken → LogSuccess + ValidateInput → CheckCredentials → GenerateToken → LogSuccess
    @@ -49,17 +37,17 @@

    AI-Perfect Architecture

    - 🔄 + 🔄
    -

    Incremental AI Development

    +

    Incremental Generation

    - AI can build step by step, just like humans: + AI builds step by step, just like a developer:

    -
    AI Step 1: Create ValidateEmail link
    -
    AI Step 2: Create SaveToDatabase link
    -
    AI Step 3: Compose into UserRegistration chain
    +
    Step 1: Generate ValidateEmail link
    +
    Step 2: Generate SaveToDatabase link
    +
    Step 3: Compose into UserRegistration chain
    @@ -67,23 +55,23 @@

    Incremental AI Development

    - 📚 -
    -

    Self-Documenting for AI

    + 📚 +
    +

    Self-Documenting Structure

    -
    // AI can immediately understand this structure:
    +
    // The Chain tells the whole story:
    const UserAuthChain = Chain
    -   .start(ValidateCredentials)  // Check username/password
    -   .then(GenerateJWT)        // Create auth token
    -   .then(LogAuthEvent)        // Record the login
    -   .catch(HandleAuthFailure)    // Deal with failures +   .add(ValidateCredentials)  // Check username/password
    +   .add(GenerateJWT)        // Create auth token
    +   .add(LogAuthEvent)        // Record the login
    +   .add(HandleAuthFailure)    // Deal with failures
    -

    - "The chain structure tells AI exactly what happens, in what order, and how errors are handled." +

    + AI reads Chain composition the same way humans do: clear intent, clear order, clear error handling.

    @@ -92,28 +80,22 @@

    Self-Documenting for AI

    -

    🤖 The AI Advantage

    +

    Why It Works

    -
    +

    Consistent patterns for reliable AI output

    -
    +

    Type contracts for safe AI collaboration

    -
    +

    Clear structure for AI-assisted refactoring

    -
    -

    - CodeUChain transforms AI from "sometimes helpful" to "consistently brilliant." - The architecture that makes developers more productive makes AI assistants absolutely brilliant. -

    -
    -
    \ No newline at end of file + diff --git a/docs/components/core-concepts.html b/docs/components/core-concepts.html index 61c6ec5..60da7f4 100644 --- a/docs/components/core-concepts.html +++ b/docs/components/core-concepts.html @@ -2,92 +2,107 @@
    -

    The Fundamental Truth

    +

    Core Concepts

    - CodeUChain isn't just a framework—it's the natural way software should be built + Four building blocks. Learn them once, use them in any language.

    -
    -
    -
    🎯
    -

    Why This Architecture Is Inherently Right

    -

    - CodeUChain aligns with how humans think, how systems evolve, and how complexity should be managed. - It's not about following trends; it's about following the fundamental principles of good design. -

    -
    -
    -
    - +
    - 🧠 + 📦
    -

    Human Mind Structure

    +

    State

    -

    Our brains are wired for chains of thought and sequential processing:

    +

    Immutable key-value container that carries data through your pipeline.

    -
    Problem → Analysis → Solution → Verification → Refinement
    +
    ctx = State({ user_id: 101, role: "admin" })
    +
    ctx.get("role") // "admin"
    +
    ctx.set("status", "active") // returns new State

    - When your code structure matches your thinking patterns, you become 3x more productive. + Thread-safe. Each .set() returns a new State — no mutation, no surprises.

    - +
    - 🌌 + 🔗
    -

    Universal Composition

    +

    Link

    -

    Everything in nature is built through composition:

    +

    A single unit of work. Takes State in, returns State out. One job, done well.

    -
    Small pieces → Combine → Complex systems
    +
    Link("validate", ctx => {
    +
      if (!ctx.get("email").includes("@"))
    +
        throw Error("bad email");
    +
      return ctx;
    +
    })

    - Atoms form molecules, cells form organs, links form beautiful systems. + Each Link lives in its own file. Easy to test, reuse, and reason about.

    - +
    - 📊 + ⛓️
    -

    Error as Information

    +

    Chain

    -

    Traditional systems treat errors as failures. CodeUChain sees them as signals:

    +

    Composes Links into an ordered pipeline. Handles execution and error propagation.

    -
    Error → Information → Learning → Better System
    +
    chain = Chain()
    +
      .add(validateEmail)
    +
      .add(hashPassword)
    +
      .add(saveUser)
    +
    result = chain.execute(state)

    - Instead of "crashed," you get "learned something new and became stronger." + If any Link throws, the Chain stops and the error is available on the result.

    - +
    - 🆓 + 🪝
    -

    Cognitive Freedom

    +

    Hook

    -

    Traditional code forces you to hold everything in your head:

    +

    Observes execution without modifying business logic. Runs alongside the Chain.

    -
    Before: "Understand everything at once"
    -
    After: "Focus on one link at a time"
    +
    hook.before(ctx => log("starting"))
    +
    hook.after(ctx => log("done"))
    +
    hook.onError(err => alert(err))

    - Your brain can finally relax. Be a focused craftsman, not a superhero. + Logging, metrics, caching — without touching your Link code.

    + + +
    +
    +

    How It Flows

    +
    +
    + State → Link 1 → Link 2 → Link 3 → Result +
    +
    +          ↑ Hook observes each step ↑ +
    +
    +
    +
    -
    \ No newline at end of file + diff --git a/docs/components/data/base.json b/docs/components/data/base.json index 5161b6e..eef4e73 100644 --- a/docs/components/data/base.json +++ b/docs/components/data/base.json @@ -4,7 +4,7 @@ "hero_description": "Beautiful chains that work across all programming languages", "export://source_link": "https://github.com/codeuchain/codeuchain", "export://logo_link": "../", - "export://version": "v1.0.0", + "export://version": "v2.0.0", "export://company": "Orchestrate LLC", "export://repository": "https://github.com/codeuchain/codeuchain" } \ No newline at end of file diff --git a/docs/components/data/cobol.json b/docs/components/data/cobol.json index 53ab9d9..6aa1b88 100644 --- a/docs/components/data/cobol.json +++ b/docs/components/data/cobol.json @@ -3,6 +3,9 @@ "title": "CodeUChain COBOL - Enterprise Chain Architecture", "hero_description": "Battle-tested chain patterns for enterprise systems. The reliability of COBOL meets the flexibility of modern architecture.", "source_link": "https://github.com/codeuchain/codeuchain/tree/main/packages/cobol", + "install_command": "npm install codeuchain-cobol", + "quick_example": "CALL 'STATE-INIT' USING WS-STATE\nCALL 'STATE-SET' USING WS-STATE 'NAME' 'WORLD'\nCALL 'CHAIN-ADD' USING WS-CHAIN 'GREET'\nCALL 'CHAIN-EXECUTE' USING WS-CHAIN WS-STATE\nCALL 'STATE-GET' USING WS-STATE 'GREETING' WS-RESULT", + "import://base.json:version": null, "import://base.json:logo_link": null, "is_homepage": false } \ No newline at end of file diff --git a/docs/components/data/cpp.json b/docs/components/data/cpp.json index c199228..a6f08f8 100644 --- a/docs/components/data/cpp.json +++ b/docs/components/data/cpp.json @@ -3,6 +3,9 @@ "title": "CodeUChain C++ - High-Performance Chain Architecture", "hero_description": "Zero-cost abstractions with maximum performance. Modern C++ patterns for systems that demand speed and efficiency.", "source_link": "https://github.com/codeuchain/codeuchain/tree/main/packages/cpp", + "install_command": "# CMake\nfind_package(codeuchain REQUIRED)\ntarget_link_libraries(myapp codeuchain::codeuchain)", + "quick_example": "auto chain = Chain()\n .addLink(Link(\"validate\", [](State& ctx) {\n if (ctx.get(\"input\").empty())\n throw std::runtime_error(\"empty input\");\n return ctx;\n }))\n .addLink(Link(\"process\", [](State& ctx) {\n ctx.set(\"result\", \"done\");\n return ctx;\n }));\n\nState ctx;\nctx.set(\"input\", \"hello\");\nauto result = chain.execute(ctx);", + "import://base.json:version": null, "import://base.json:logo_link": null, "is_homepage": false } \ No newline at end of file diff --git a/docs/components/data/csharp.json b/docs/components/data/csharp.json index 9db984d..33a8a92 100644 --- a/docs/components/data/csharp.json +++ b/docs/components/data/csharp.json @@ -3,6 +3,9 @@ "title": "CodeUChain C# - Enterprise Chain Architecture", "hero_description": "Enterprise-grade chains with LINQ integration and async patterns. Production-ready for .NET ecosystems.", "source_link": "https://github.com/codeuchain/codeuchain/tree/main/packages/csharp", + "install_command": "dotnet add package CodeUChain", + "quick_example": "var pipeline = new Chain()\n .AddLink(new Link(\"validate_stock\", ctx => {\n int qty = (int)ctx.Get(\"quantity\");\n if (qty > 100) throw new Exception(\"Out of stock\");\n return ctx;\n }))\n .AddLink(new Link(\"calc_total\", ctx => {\n ctx.Set(\"total\", 10.00 * (int)ctx.Get(\"quantity\"));\n return ctx;\n }));\n\nvar result = pipeline.Execute(new State().Set(\"quantity\", 5));\nConsole.WriteLine($\"Total: ${result.Get(\"total\")}\");", + "import://base.json:version": null, "import://base.json:logo_link": null, "is_homepage": false } \ No newline at end of file diff --git a/docs/components/data/go.json b/docs/components/data/go.json index 6d1b180..48d068e 100644 --- a/docs/components/data/go.json +++ b/docs/components/data/go.json @@ -2,7 +2,10 @@ "language_name": "Go", "title": "CodeUChain Go - High-Performance Chain Architecture", "hero_description": "Lightning-fast concurrency with Go's goroutines and channels. Production-ready chains that scale beautifully.", - "import://base.json:source_link": null, + "source_link": "https://github.com/codeuchain/codeuchain/tree/main/packages/go", + "install_command": "go get github.com/codeuchain/codeuchain/go", + "quick_example": "import (\n cuc \"github.com/codeuchain/codeuchain/go\"\n)\n\nvalidate := func(ctx *cuc.State) *cuc.State {\n if ctx.Get(\"age\").(int) < 18 {\n ctx.Error = errors.New(\"too young\")\n }\n return ctx\n}\n\napprove := func(ctx *cuc.State) *cuc.State {\n ctx.Set(\"status\", \"approved\")\n return ctx\n}\n\npipeline := cuc.Chain{}\npipeline.AddLink(cuc.NewLink(\"validate\", validate))\npipeline.AddLink(cuc.NewLink(\"approve\", approve))\n\nresult := pipeline.Execute(cuc.NewState(map[string]any{\"age\": 20}))\nfmt.Println(result.Get(\"status\"))", + "import://base.json:version": null, "import://base.json:logo_link": null, "is_homepage": false } \ No newline at end of file diff --git a/docs/components/data/index.json b/docs/components/data/index.json index 3c1709e..089bd1d 100644 --- a/docs/components/data/index.json +++ b/docs/components/data/index.json @@ -3,7 +3,10 @@ "language_name": "CodeUChain", "language_description": "Universal Chain Architecture", "hero_description": "The same elegant patterns, expressed in every programming language. A universal architecture that makes complex systems simple, beautiful, and maintainable across Python, Go, JavaScript, C#, Rust, and beyond.", + "install_command": "pip install codeuchain # Python\nnpm install codeuchain # JavaScript\ncargo add codeuchain # Rust\ngo get github.com/codeuchain/codeuchain/go # Go", + "quick_example": "# Universal pattern — same in every language\nstate = new State({ user_id: 101 })\n\nchain = new Chain()\n .add(Link('fetch', ctx -> fetch_user(ctx)))\n .add(Link('auth', ctx -> check_role(ctx, 'admin')))\n .add(Link('process', ctx -> run_business_logic(ctx)))\n\nresult = chain.execute(state)\n\nif result.error:\n handle_failure(result.error)\nelse:\n print(result.get('output'))", "import://base.json:source_link": null, + "import://base.json:version": null, "import://base.json:logo_link": null, "is_homepage": true } \ No newline at end of file diff --git a/docs/components/data/java.json b/docs/components/data/java.json index 27a835b..c047db0 100644 --- a/docs/components/data/java.json +++ b/docs/components/data/java.json @@ -3,6 +3,9 @@ "title": "CodeUChain Java - Enterprise-Grade Chain Architecture", "hero_description": "Robust, scalable chains for enterprise applications. The power of Java's ecosystem meets modern architectural patterns.", "source_link": "https://github.com/codeuchain/codeuchain/tree/main/packages/java", + "install_command": "\n\n io.codeuchain\n codeuchain\n 0.3.0\n", + "quick_example": "Chain chain = new Chain()\n .addLink(new Link(\"parse\", ctx -> {\n ctx.set(\"body\", \"{ data: ... }\");\n return ctx;\n }))\n .addLink(new Link(\"validate\", ctx -> {\n String body = (String) ctx.get(\"body\");\n if (body == null) ctx.error = new Exception(\"No body\");\n return ctx;\n }));\n\nState result = chain.execute(new State().set(\"raw\", \"...\"));\nSystem.out.println(result.error != null ? \"Failed\" : \"Success\");", + "import://base.json:version": null, "import://base.json:logo_link": null, "is_homepage": false } \ No newline at end of file diff --git a/docs/components/data/javascript.json b/docs/components/data/javascript.json index f9f99d2..b671b09 100644 --- a/docs/components/data/javascript.json +++ b/docs/components/data/javascript.json @@ -3,6 +3,9 @@ "title": "CodeUChain JavaScript - TypeScript Generics & Async Chains", "hero_description": "Modern JavaScript with TypeScript generics and async processing pipelines. The future of web development, today.", "source_link": "https://github.com/codeuchain/codeuchain/tree/main/packages/javascript", + "install_command": "npm install codeuchain", + "quick_example": "import { Chain, Link, State } from 'codeuchain';\n\nconst pipeline = new Chain()\n .addLink(new Link('validate', ctx => {\n if (!ctx.get('email').includes('@'))\n throw new Error('Invalid email');\n return ctx;\n }))\n .addLink(new Link('save', ctx => {\n ctx.set('user_id', 42);\n return ctx;\n }));\n\nconst result = pipeline.execute(\n new State({ email: 'user@example.com' })\n);\nconsole.log('User ID:', result.get('user_id'));", + "import://base.json:version": null, "import://base.json:logo_link": null, "is_homepage": false } \ No newline at end of file diff --git a/docs/components/data/pseudo.json b/docs/components/data/pseudo.json index 10d4284..7165957 100644 --- a/docs/components/data/pseudo.json +++ b/docs/components/data/pseudo.json @@ -3,6 +3,9 @@ "title": "CodeUChain Pseudocode - The Architecture That Makes Sense", "hero_description": "The architecture that makes sense, explained in natural language. No programming required to understand the beauty.", "source_link": "https://github.com/codeuchain/codeuchain/tree/main/packages/pseudo", + "install_command": "No installation needed — pseudocode is for learning the pattern.", + "quick_example": "ctx = State({ name: \"world\" })\n\nchain = Chain()\n .add(Link(\"greet\", ctx => ctx.set(\"msg\", \"Hello \" + ctx.get(\"name\"))))\n .add(Link(\"shout\", ctx => ctx.set(\"msg\", uppercase(ctx.get(\"msg\")))))\n\nresult = chain.execute(ctx)\nprint(result.get(\"msg\")) // HELLO WORLD", + "import://base.json:version": null, "import://base.json:logo_link": null, "is_homepage": false } \ No newline at end of file diff --git a/docs/components/data/python.json b/docs/components/data/python.json index 0fe9703..2647631 100644 --- a/docs/components/data/python.json +++ b/docs/components/data/python.json @@ -2,7 +2,10 @@ "language_name": "Python", "title": "CodeUChain Python - Async-First Chain Architecture", "hero_description": "Beautiful async chains with type hints and runtime flexibility. The same elegant patterns, powered by Python's async ecosystem.", - "import://base.json:source_link": null, + "source_link": "https://github.com/codeuchain/codeuchain/tree/main/packages/python", + "install_command": "pip install codeuchain", + "quick_example": "from codeuchain import Chain, Link, State\n\ndef fetch_user(ctx):\n ctx.set('user', {'id': ctx.get('user_id'), 'role': 'admin'})\n return ctx\n\ndef check_permissions(ctx):\n if ctx.get('user')['role'] != 'admin':\n raise Exception('Unauthorized')\n return ctx\n\nworkflow = Chain()\\\n .add_link(Link('fetch', fetch_user))\\\n .add_link(Link('auth', check_permissions))\n\nresult = workflow.execute(State({'user_id': 101}))\nprint(result.get('user'))", + "import://base.json:version": null, "import://base.json:logo_link": null, "is_homepage": false } \ No newline at end of file diff --git a/docs/components/data/rust.json b/docs/components/data/rust.json index 6585237..3565299 100644 --- a/docs/components/data/rust.json +++ b/docs/components/data/rust.json @@ -3,6 +3,9 @@ "title": "CodeUChain Rust - Memory-Safe Chain Architecture", "hero_description": "Zero-cost abstractions with compile-time guarantees. Memory-safe chains that perform like C++.", "source_link": "https://github.com/codeuchain/codeuchain/tree/main/packages/rust", + "install_command": "cargo add codeuchain", + "quick_example": "let chain = Chain::new()\n .add_link(Box::new(Link::new(\"sanitize\", |ctx| {\n let input = ctx.get(\"input\")\n .and_then(|v| v.as_str())\n .unwrap_or(\"\")\n .trim().to_string();\n ctx.set(\"input\", json!(input));\n ctx\n })))\n .add_link(Box::new(Link::new(\"process\", |ctx| {\n ctx.set(\"result\", json!(\"done\"));\n ctx\n })));\n\nlet mut ctx = State::new();\nctx.set(\"input\", json!(\" hello \"));\nlet result = chain.execute(ctx);\nprintln!(\"{:?}\", result.get(\"result\"));", + "import://base.json:version": null, "import://base.json:logo_link": null, "is_homepage": false } \ No newline at end of file diff --git a/docs/components/developer-benefits.html b/docs/components/developer-benefits.html index aa179de..bd7cf4b 100644 --- a/docs/components/developer-benefits.html +++ b/docs/components/developer-benefits.html @@ -3,66 +3,111 @@

    Developer Benefits

    -

    Why developers naturally gravitate toward this architecture

    +

    Practical advantages you get from day one

    -
    -
    -
    -
    -
    - 🎯 -
    -

    Predictable Behavior

    -
    -

    - CodeUChain gives you psychological safety with predictable behavior, composition, and evolution. -

    -
    -

    - "You can confidently make changes because you know the impact will be contained." -

    +
    + +
    +
    +
    + 🧪
    +

    Testable by Default

    +
    +

    + Each Link is a pure function: State in, State out. Mock nothing — just pass test data. +

    +
    +
    result = myLink.call(State({ input: "test" }))
    +
    assert result.get("output") == expected
    +
    -
    -
    -
    - 🌊 -
    -

    Creative Flow State

    -
    -

    - CodeUChain unlocks the flow state that makes programming addictive: -

    -
    -
    Clear goal → Immediate feedback → Sense of progress → Deep focus
    + +
    +
    +
    + 🔄
    +

    Reusable Components

    +
    +

    + Write a Link once, drop it into any Chain. Build a library of battle-tested building blocks. +

    +
    +
    orderChain.add(validateEmail) // reuse
    +
    signupChain.add(validateEmail) // reuse
    -
    -
    + +
    +
    - + 🌍
    -

    Architectural Elegance

    +

    One Pattern, Every Language

    -
    -
    -

    Symmetry in Design

    -

    Input → Processing → Output: Clean, unidirectional flow

    +

    + Same State → Link → Chain model in Python, Go, TypeScript, C#, Rust, Java, and C++. +

    +
    +
    // Learn once, apply everywhere
    +
    chain.add(link).execute(state)
    +
    +
    + + +
    +
    +
    + 🛡️
    -
    -

    Power of Constraints

    -

    Freedom within structure, creativity within predictability

    +

    Contained Impact

    +
    +

    + Changes to one Link cannot break another. Errors stop the Chain without side effects. +

    +
    +
    // Link 2 fails? Links 3-5 never run.
    +
    // State stays immutable throughout.
    +
    +
    + + +
    +
    +
    + 📖
    -
    -

    Emergent Complexity

    -

    Simple rules create systems of breathtaking complexity

    +

    Self-Documenting

    +
    +

    + A Chain reads like a checklist. New developers understand the flow in seconds. +

    +
    +
    Chain: ValidateInput
    +
      → EnrichData → Save → Notify
    +
    +
    + + +
    +
    +
    +
    +

    Opt-In Type Safety

    +
    +

    + Start untyped for speed. Add generics when you need compile-time guarantees. +

    +
    +
    Link[UserInput, UserOutput]
    +
    State[T].insertAs<U>(k, v)
    - \ No newline at end of file + diff --git a/docs/components/floating-navigation.html b/docs/components/floating-navigation.html index a770114..16b2a27 100644 --- a/docs/components/floating-navigation.html +++ b/docs/components/floating-navigation.html @@ -213,7 +213,7 @@ 'hero': { icon: '🏠', key: 'H', label: 'Hero' }, 'concepts': { icon: '🎯', key: 'C', label: 'Concepts' }, 'benefits': { icon: '⚡', key: 'B', label: 'Benefits' }, - 'ai-love': { icon: '🤖', key: 'A', label: 'AI Love' }, + 'ai-ready': { icon: '🤖', key: 'A', label: 'AI-Ready' }, 'quickstart': { icon: '🚀', key: 'Q', label: 'Quick Start' }, 'languages': { icon: '🌍', key: 'L', label: 'Languages' }, 'overview': { icon: '📋', key: 'O', label: 'Overview' }, diff --git a/docs/components/footer.html b/docs/components/footer.html index 7510a8f..e10b25e 100644 --- a/docs/components/footer.html +++ b/docs/components/footer.html @@ -38,7 +38,7 @@

    Quick Links

  • Home
  • Core Concepts
  • Benefits
  • -
  • AI Love
  • +
  • AI-Ready
  • Quick Start
  • @@ -62,9 +62,8 @@

    Languages

    - © 2025 Orchestrate LLC. + © 2025-2026 Orchestrate LLC. Licensed under Apache 2.0. - Built with ❤️ for developers everywhere.

    diff --git a/docs/components/hero.html b/docs/components/hero.html index 44a9b41..86bba66 100644 --- a/docs/components/hero.html +++ b/docs/components/hero.html @@ -2,7 +2,7 @@
    - v1.0.0 • {{LANGUAGE_NAME}} Edition + {{VERSION}} • {{LANGUAGE_NAME}} Edition

    diff --git a/docs/components/navigation.html b/docs/components/navigation.html index 1adbaec..92dafa6 100644 --- a/docs/components/navigation.html +++ b/docs/components/navigation.html @@ -14,14 +14,14 @@ {{#if (eq is_homepage true)}} Concepts Benefits - AI Love + AI-Ready Languages GitHub {{else}} Home Concepts Benefits - AI Love + AI-Ready Languages GitHub {{/if}} diff --git a/docs/components/quick-start.html b/docs/components/quick-start.html index e329673..c33060a 100644 --- a/docs/components/quick-start.html +++ b/docs/components/quick-start.html @@ -2,77 +2,44 @@
    -

    Getting Started

    -

    Your journey to elegant architecture begins here

    +

    Quick Start

    +

    Install and write your first chain in minutes

    - +
    -

    📖 Understanding Through Language

    +

    📦 Install

    +
    + {{INSTALL_COMMAND}} +
    -
    -
    -

    No Programming Required

    -

    The pseudocode explains concepts in plain English, making the architecture accessible to everyone.

    +

    🧠 Mental Model

    +
    +
    + State + The data box flowing through your pipeline
    - -
    -

    Human-Centered Design

    -

    Built around how humans naturally think and solve problems, not machine optimization.

    +
    + Link + One focused unit of work — receives State, returns State
    - -
    -

    Universal Understanding

    -

    The same mental model works across all programming languages and domains.

    +
    + Chain + Ordered sequence of Links — runs them in order +
    +
    + Hook + Parallel observer — logging, metrics, caching
    - +
    -

    🚀 Your Next Steps

    - -
    -
    -
    - 1 -
    -
    -

    Read the Concepts

    -

    Understand Link, Context, and Chain primitives

    -
    -
    - -
    -
    - 2 -
    -
    -

    Choose Your Language

    -

    Pick from Python, Go, JavaScript, C#, Rust, and more

    -
    -
    - -
    -
    - 3 -
    -
    -

    Build Your First Chain

    -

    Create simple links and compose them together

    -
    -
    - -
    -
    - 4 -
    -
    -

    Experience the Flow

    -

    Discover why this architecture feels so fundamentally right

    -
    -
    +

    ⚡ Your First Chain

    +
    +
    {{QUICK_EXAMPLE}}
    diff --git a/docs/cpp/index.html b/docs/cpp/index.html index 6b37946..099b04d 100644 --- a/docs/cpp/index.html +++ b/docs/cpp/index.html @@ -102,7 +102,7 @@ Home Concepts Benefits - AI Love + AI-Ready Languages GitHub @@ -115,7 +115,7 @@
    - v1.0.0 • C++ Edition + v2.0.0 • C++ Edition

    @@ -141,191 +141,241 @@

    -

    The Fundamental Truth

    +

    Core Concepts

    - CodeUChain isn't just a framework—it's the natural way software should be built + Four building blocks. Learn them once, use them in any language.

    -
    -
    -
    🎯
    -

    Why This Architecture Is Inherently Right

    -

    - CodeUChain aligns with how humans think, how systems evolve, and how complexity should be managed. - It's not about following trends; it's about following the fundamental principles of good design. -

    -
    -
    -
    - +
    - 🧠 + 📦
    -

    Human Mind Structure

    +

    State

    -

    Our brains are wired for chains of thought and sequential processing:

    +

    Immutable key-value container that carries data through your pipeline.

    -
    Problem → Analysis → Solution → Verification → Refinement
    +
    ctx = State({ user_id: 101, role: "admin" })
    +
    ctx.get("role") // "admin"
    +
    ctx.set("status", "active") // returns new State

    - When your code structure matches your thinking patterns, you become 3x more productive. + Thread-safe. Each .set() returns a new State — no mutation, no surprises.

    - +
    - 🌌 + 🔗
    -

    Universal Composition

    +

    Link

    -

    Everything in nature is built through composition:

    +

    A single unit of work. Takes State in, returns State out. One job, done well.

    -
    Small pieces → Combine → Complex systems
    +
    Link("validate", ctx => {
    +
      if (!ctx.get("email").includes("@"))
    +
        throw Error("bad email");
    +
      return ctx;
    +
    })

    - Atoms form molecules, cells form organs, links form beautiful systems. + Each Link lives in its own file. Easy to test, reuse, and reason about.

    - +
    - 📊 + ⛓️
    -

    Error as Information

    +

    Chain

    -

    Traditional systems treat errors as failures. CodeUChain sees them as signals:

    +

    Composes Links into an ordered pipeline. Handles execution and error propagation.

    -
    Error → Information → Learning → Better System
    +
    chain = Chain()
    +
      .add(validateEmail)
    +
      .add(hashPassword)
    +
      .add(saveUser)
    +
    result = chain.execute(state)

    - Instead of "crashed," you get "learned something new and became stronger." + If any Link throws, the Chain stops and the error is available on the result.

    - +
    - 🆓 + 🪝
    -

    Cognitive Freedom

    +

    Hook

    -

    Traditional code forces you to hold everything in your head:

    +

    Observes execution without modifying business logic. Runs alongside the Chain.

    -
    Before: "Understand everything at once"
    -
    After: "Focus on one link at a time"
    +
    hook.before(ctx => log("starting"))
    +
    hook.after(ctx => log("done"))
    +
    hook.onError(err => alert(err))

    - Your brain can finally relax. Be a focused craftsman, not a superhero. + Logging, metrics, caching — without touching your Link code.

    + + +
    +
    +

    How It Flows

    +
    +
    + State → Link 1 → Link 2 → Link 3 → Result +
    +
    +          ↑ Hook observes each step ↑ +
    +
    +
    +
    +

    Developer Benefits

    -

    Why developers naturally gravitate toward this architecture

    +

    Practical advantages you get from day one

    -
    -
    -
    -
    -
    - 🎯 -
    -

    Predictable Behavior

    -
    -

    - CodeUChain gives you psychological safety with predictable behavior, composition, and evolution. -

    -
    -

    - "You can confidently make changes because you know the impact will be contained." -

    +
    + +
    +
    +
    + 🧪
    +

    Testable by Default

    +

    + Each Link is a pure function: State in, State out. Mock nothing — just pass test data. +

    +
    +
    result = myLink.call(State({ input: "test" }))
    +
    assert result.get("output") == expected
    +
    +
    -
    -
    -
    - 🌊 -
    -

    Creative Flow State

    -
    -

    - CodeUChain unlocks the flow state that makes programming addictive: -

    -
    -
    Clear goal → Immediate feedback → Sense of progress → Deep focus
    + +
    +
    +
    + 🔄
    +

    Reusable Components

    +
    +

    + Write a Link once, drop it into any Chain. Build a library of battle-tested building blocks. +

    +
    +
    orderChain.add(validateEmail) // reuse
    +
    signupChain.add(validateEmail) // reuse
    -
    -
    + +
    +
    - + 🌍
    -

    Architectural Elegance

    +

    One Pattern, Every Language

    -
    -
    -

    Symmetry in Design

    -

    Input → Processing → Output: Clean, unidirectional flow

    +

    + Same State → Link → Chain model in Python, Go, TypeScript, C#, Rust, Java, and C++. +

    +
    +
    // Learn once, apply everywhere
    +
    chain.add(link).execute(state)
    +
    +
    + + +
    +
    +
    + 🛡️
    -
    -

    Power of Constraints

    -

    Freedom within structure, creativity within predictability

    +

    Contained Impact

    +
    +

    + Changes to one Link cannot break another. Errors stop the Chain without side effects. +

    +
    +
    // Link 2 fails? Links 3-5 never run.
    +
    // State stays immutable throughout.
    +
    +
    + + +
    +
    +
    + 📖
    -
    -

    Emergent Complexity

    -

    Simple rules create systems of breathtaking complexity

    +

    Self-Documenting

    +
    +

    + A Chain reads like a checklist. New developers understand the flow in seconds. +

    +
    +
    Chain: ValidateInput
    +
      → EnrichData → Save → Notify
    +
    +
    + + +
    +
    +
    +
    +

    Opt-In Type Safety

    +
    +

    + Start untyped for speed. Add generics when you need compile-time guarantees. +

    +
    +
    Link[UserInput, UserOutput]
    +
    State[T].insertAs<U>(k, v)
    - -
    + + +
    - 🤖 - AI Agents Love CodeUChain -
    -
    -

    Why AI Assistants Excel Here

    -
    -
    -
    "
    -

    - CodeUChain transformed how I approach coding. Its clear patterns and predictable structure - allowed me to generate code that was not only functional but elegant. -

    -
    "
    -
    -
    -
    - — GitHub Copilot -
    + 🤖 + Built for AI Agents
    +

    AI-Ready Architecture

    +

    + The same structure that helps humans reason about code helps AI assistants generate, refactor, and extend it. +

    @@ -333,17 +383,17 @@

    Why AI Assistants
    - 🎯 + 🎯
    -

    AI-Perfect Architecture

    +

    Predictable Patterns

    - CodeUChain speaks the same language as AI agents with clear templates and modular thinking. + AI models thrive on consistent structure. Every Link follows the same contract, so generation is reliable.

    -
    // AI can immediately understand:
    +
    // AI immediately understands the flow:
    - ValidateInput → CheckCredentials → GenerateToken → LogSuccess + ValidateInput → CheckCredentials → GenerateToken → LogSuccess
    @@ -351,17 +401,17 @@

    AI-Perfect Architecture

    - 🔄 + 🔄
    -

    Incremental AI Development

    +

    Incremental Generation

    - AI can build step by step, just like humans: + AI builds step by step, just like a developer:

    -
    AI Step 1: Create ValidateEmail link
    -
    AI Step 2: Create SaveToDatabase link
    -
    AI Step 3: Compose into UserRegistration chain
    +
    Step 1: Generate ValidateEmail link
    +
    Step 2: Generate SaveToDatabase link
    +
    Step 3: Compose into UserRegistration chain
    @@ -369,23 +419,23 @@

    Incremental AI Development

    - 📚 -
    -

    Self-Documenting for AI

    + 📚 +
    +

    Self-Documenting Structure

    -
    // AI can immediately understand this structure:
    +
    // The Chain tells the whole story:
    const UserAuthChain = Chain
    -   .start(ValidateCredentials)  // Check username/password
    -   .then(GenerateJWT)        // Create auth token
    -   .then(LogAuthEvent)        // Record the login
    -   .catch(HandleAuthFailure)    // Deal with failures +   .add(ValidateCredentials)  // Check username/password
    +   .add(GenerateJWT)        // Create auth token
    +   .add(LogAuthEvent)        // Record the login
    +   .add(HandleAuthFailure)    // Deal with failures
    -

    - "The chain structure tells AI exactly what happens, in what order, and how errors are handled." +

    + AI reads Chain composition the same way humans do: clear intent, clear order, clear error handling.

    @@ -394,107 +444,84 @@

    Self-Documenting for AI

    -

    🤖 The AI Advantage

    +

    Why It Works

    -
    +

    Consistent patterns for reliable AI output

    -
    +

    Type contracts for safe AI collaboration

    -
    +

    Clear structure for AI-assisted refactoring

    -
    -

    - CodeUChain transforms AI from "sometimes helpful" to "consistently brilliant." - The architecture that makes developers more productive makes AI assistants absolutely brilliant. -

    -

    +
    -

    Getting Started

    -

    Your journey to elegant architecture begins here

    +

    Quick Start

    +

    Install and write your first chain in minutes

    - +
    -

    📖 Understanding Through Language

    +

    📦 Install

    +
    + # CMake +find_package(codeuchain REQUIRED) +target_link_libraries(myapp codeuchain::codeuchain) +
    -
    -
    -

    No Programming Required

    -

    The pseudocode explains concepts in plain English, making the architecture accessible to everyone.

    +

    🧠 Mental Model

    +
    +
    + State + The data box flowing through your pipeline
    - -
    -

    Human-Centered Design

    -

    Built around how humans naturally think and solve problems, not machine optimization.

    +
    + Link + One focused unit of work — receives State, returns State
    - -
    -

    Universal Understanding

    -

    The same mental model works across all programming languages and domains.

    +
    + Chain + Ordered sequence of Links — runs them in order +
    +
    + Hook + Parallel observer — logging, metrics, caching
    - +
    -

    🚀 Your Next Steps

    - -
    -
    -
    - 1 -
    -
    -

    Read the Concepts

    -

    Understand Link, Context, and Chain primitives

    -
    -
    - -
    -
    - 2 -
    -
    -

    Choose Your Language

    -

    Pick from Python, Go, JavaScript, C#, Rust, and more

    -
    -
    - -
    -
    - 3 -
    -
    -

    Build Your First Chain

    -

    Create simple links and compose them together

    -
    -
    - -
    -
    - 4 -
    -
    -

    Experience the Flow

    -

    Discover why this architecture feels so fundamentally right

    -
    -
    +

    ⚡ Your First Chain

    +
    +
    auto chain = Chain()
    +  .addLink(Link("validate", [](State& ctx) {
    +    if (ctx.get("input").empty())
    +      throw std::runtime_error("empty input");
    +    return ctx;
    +  }))
    +  .addLink(Link("process", [](State& ctx) {
    +    ctx.set("result", "done");
    +    return ctx;
    +  }));
    +
    +State ctx;
    +ctx.set("input", "hello");
    +auto result = chain.execute(ctx);
    @@ -679,7 +706,7 @@

    Quick Links

  • Home
  • Core Concepts
  • Benefits
  • -
  • AI Love
  • +
  • AI-Ready
  • Quick Start
  • @@ -703,9 +730,8 @@

    Languages

    - © 2025 Orchestrate LLC. + © 2025-2026 Orchestrate LLC. Licensed under Apache 2.0. - Built with ❤️ for developers everywhere.

    @@ -927,7 +953,7 @@

    Languages

    'hero': { icon: '🏠', key: 'H', label: 'Hero' }, 'concepts': { icon: '🎯', key: 'C', label: 'Concepts' }, 'benefits': { icon: '⚡', key: 'B', label: 'Benefits' }, - 'ai-love': { icon: '🤖', key: 'A', label: 'AI Love' }, + 'ai-ready': { icon: '🤖', key: 'A', label: 'AI-Ready' }, 'quickstart': { icon: '🚀', key: 'Q', label: 'Quick Start' }, 'languages': { icon: '🌍', key: 'L', label: 'Languages' }, 'overview': { icon: '📋', key: 'O', label: 'Overview' }, diff --git a/docs/cpp/llm-full.txt b/docs/cpp/llm-full.txt index 745811b..d8b7911 100644 --- a/docs/cpp/llm-full.txt +++ b/docs/cpp/llm-full.txt @@ -10,7 +10,7 @@ **Authors:** CodeUChain contributors **Language:** C++20 (C++17 fallback) **Platforms:** Linux / macOS / Windows -**Paradigm Keywords:** Zero‑cost Composition, Immutable Context, Type Evolution, Middleware Observability +**Paradigm Keywords:** Zero‑cost Composition, Immutable State, Type Evolution, Hook Observability --- ## 1. Purpose & Philosophy @@ -21,49 +21,49 @@ High‑performance composable data transformation pipelines with predictable mem | Zero‑cost Abstraction | Templates + inline | No runtime penalty | | Determinism | Pure call with const ctx | Easier reasoning | | Evolution | `insert_as()` pattern | Progressive modeling | -| Observability | Middleware wrappers | Central instrumentation | +| Observability | Hook wrappers | Central instrumentation | | Async Option | Coroutines (co_await) | Integrate non-blocking I/O | --- ## 2. Architectural Overview ``` -Context +State | ValidateLink v -Context - | ParseLink (middleware before/after/error) +State + | ParseLink (hook before/after/error) v -Context +State | EnrichLink v -Context +State ``` Branching via conditional inclusion; retries & circuit breakers via wrappers. --- ## 3. Core Interfaces (Representative) ```cpp -template class Context { +template class State { public: using storage_type = std::unordered_map; // impl detail bool has(std::string_view key) const; template const V& get(std::string_view key) const; // throws if missing / bad_cast - Context insert(std::string key, std::any value) const; // preserve T - template Context insert_as(std::string key, std::any value) const; // evolve + State insert(std::string key, std::any value) const; // preserve T + template State insert_as(std::string key, std::any value) const; // evolve std::vector keys() const; }; template struct Link { virtual ~Link() = default; - virtual Context call(const Context& ctx) = 0; + virtual State call(const State& ctx) = 0; }; -struct Middleware { - virtual void before(std::string_view linkName, const Context& ctx) {} - virtual void after(std::string_view linkName, const Context& ctx) {} - virtual void on_error(std::string_view linkName, const Context& ctx, const std::exception& e) {} - virtual ~Middleware() = default; +struct Hook { + virtual void before(std::string_view linkName, const State& ctx) {} + virtual void after(std::string_view linkName, const State& ctx) {} + virtual void on_error(std::string_view linkName, const State& ctx, const std::exception& e) {} + virtual ~Hook() = default; }; ``` Optional coroutine interface: @@ -71,7 +71,7 @@ Optional coroutine interface: template struct AsyncLink { virtual ~AsyncLink() = default; - virtual task> call_async(Context ctx) = 0; // task custom awaitable + virtual task> call_async(State ctx) = 0; // task custom awaitable }; ``` @@ -94,7 +94,7 @@ struct Parsed { std::string email; std::vector tokens; }; class ParseLink : public Link { public: - Context call(const Context& ctx) override { + State call(const State& ctx) override { const auto& in = ctx.template get("inbound"); if (in.email.find('@') == std::string::npos) throw std::invalid_argument("invalid_email"); @@ -122,7 +122,7 @@ template auto with_retry(std::shared_ptr> inner, int attempts = 3) { struct Retrying : Link { std::shared_ptr> inner; int attempts; - Context call(const Context& ctx) override { + State call(const State& ctx) override { for (int i=0;icall(ctx); } catch (const transient_error&) { /* backoff */ } @@ -135,23 +135,23 @@ auto with_retry(std::shared_ptr> inner, int attempts = 3) { ``` --- -## 7. Middleware Lifecycle +## 7. Hook Lifecycle ```cpp -class MetricsMiddleware : public Middleware { - void before(std::string_view name, const Context& ctx) override { +class MetricsHook : public Hook { + void before(std::string_view name, const State& ctx) override { // record start time } - void after(std::string_view name, const Context& ctx) override { + void after(std::string_view name, const State& ctx) override { // compute duration } - void on_error(std::string_view name, const Context& ctx, const std::exception& e) override { + void on_error(std::string_view name, const State& ctx, const std::exception& e) override { // log error } }; ``` Guidelines: - Keep allocation minimal. -- Avoid throwing from middleware. +- Avoid throwing from hook. - Tag errors; never silently swallow unless policy demands it. --- @@ -170,7 +170,7 @@ ctx = ctx.insert_as("stage3", Stage3{ctx.get("stage2").raw, ctx. Frameworks: GoogleTest / Catch2. Property: rapidcheck. Benchmark: Google Benchmark. ```cpp TEST(ParseLink, ParsesTokens) { - auto ctx = Context::start({{"inbound", Inbound{"a@b.com","hello world"}}}); + auto ctx = State::start({{"inbound", Inbound{"a@b.com","hello world"}}}); ParseLink link; auto out = link.call(ctx); const auto& parsed = out.get("parsed"); @@ -181,13 +181,13 @@ TEST(ParseLink, ParsesTokens) { --- ## 10. Observability & Diagnostics Approaches: -- Middleware instrumentation (timers, counters) +- Hook instrumentation (timers, counters) - Conditional compile logging macros -- Error classification tags inside context +- Error classification tags inside state - Log only keys (privacy & noise control) ```cpp -class DebugMiddleware : public Middleware { - void after(std::string_view n, const Context& c) override { +class DebugHook : public Hook { + void after(std::string_view n, const State& c) override { std::cerr << "DBG " << n << ":"; for (auto& k : c.keys()) std::cerr << ' ' << k; std::cerr << '\n'; } }; @@ -205,7 +205,7 @@ class DebugMiddleware : public Middleware { ```cpp static void ChainBench(benchmark::State& st) { auto chain = /* build */; - auto ctx = /* seed context */; + auto ctx = /* seed state */; for (auto _ : st) benchmark::DoNotOptimize(chain.call(ctx)); } BENCHMARK(ChainBench); @@ -215,9 +215,9 @@ BENCHMARK(ChainBench); ## 12. Advanced Patterns - Fan-out / fan-in (threads or coroutines) - Conditional link selection (predicate functor) -- Retry + circuit breaker layering (middleware + wrapper) +- Retry + circuit breaker layering (hook + wrapper) - Partial failure accumulation (vector of error tags) -- Streaming ingestion (batch contexts) +- Streaming ingestion (batch states) - SAGA compensation (undo lambda registry) --- @@ -225,7 +225,7 @@ BENCHMARK(ChainBench); Phases: 1. Minimal sync links 2. Add templates & strong types -3. Add middleware (metrics/logging) +3. Add hook (metrics/logging) 4. Parallel fan-out (threads / tasks) 5. Optimize allocations / replace any in hot paths 6. Introduce coroutine async links (only if needed) @@ -236,9 +236,9 @@ Backward compatibility: add new templates; avoid signature breakage. ## 14. Anti-Patterns | Anti-Pattern | Problem | Remedy | |--------------|---------|--------| -| Raw void* context | UB risk | Use std::any / variant | +| Raw void* state | UB risk | Use std::any / variant | | Throw for control flow | Slow & unclear | Sentinel / classification | -| Heavy IO in middleware | Latency | Queue/batch async | +| Heavy IO in hook | Latency | Queue/batch async | | Copying large payload each link | Memory/time waste | Structural sharing / references | | Logging full payloads | Privacy & cost | Redact / hash / sample | @@ -251,29 +251,29 @@ Backward compatibility: add new templates; avoid signature breakage. **Q:** Short-circuit? **A:** Throw classified exception or conditional link sentinel. **Q:** Replace std::any? -**A:** Use variant for closed type sets; or specialized context. +**A:** Use variant for closed type sets; or specialized state. **Q:** Thread safety? -**A:** Context immutable; share safely. Avoid global mutable singletons. +**A:** State immutable; share safely. Avoid global mutable singletons. --- ## 16. Glossary - **Link**: Transformation functor/object. - **Chain**: Ordered executor of links. -- **Context**: Immutable key-value store with evolution helpers. -- **Middleware**: Observers around link invocation. -- **Type Evolution**: Widening of context’s conceptual schema. +- **State**: Immutable key-value store with evolution helpers. +- **Hook**: Observers around link invocation. +- **Type Evolution**: Widening of state’s conceptual schema. - **Classification**: Mapping exceptions → semantic categories. --- ## 17. TL;DR ```text Build: cmake .. && make -j -Primitives: Link + Chain + Context + Middleware + Type Evolution +Primitives: Link + Chain + State + Hook + Type Evolution Performance: Move semantics, minimal allocations, benchmark hot paths -Observability: Middleware metrics + debug-after keys +Observability: Hook metrics + debug-after keys Errors: Classify, retry transient, surface permanent Adoption: Start sync → add async only if needed -Avoid: heavy IO middleware, control-flow exceptions, raw void* +Avoid: heavy IO hook, control-flow exceptions, raw void* ``` --- diff --git a/docs/cpp/llm.txt b/docs/cpp/llm.txt index 87f676f..47cfcb5 100644 --- a/docs/cpp/llm.txt +++ b/docs/cpp/llm.txt @@ -6,15 +6,15 @@ Full reference: `docs/cpp/llm-full.txt` (Add library to your build system – header-only pattern suggested.) ## Primitives -- Link: `Context call(const Context&)` (or async via coroutines) -- Context: copy-on-write style; `insert`, `insert_as` +- Link: `State call(const State&)` (or async via coroutines) +- State: copy-on-write style; `insert`, `insert_as` - Chain: fluent composition; `catch_handler` -- Middleware: wrappers around `call` +- Hook: wrappers around `call` ## Minimal Link ```cpp struct Parse : ILink { - Context call(const Context& c) override { + State call(const State& c) override { return c.insert("parsed", true); } }; @@ -49,6 +49,6 @@ Transient (retry) vs Permanent (validation/security). Distinguish via custom exc ``` ## TL;DR -Template links + move-aware immutable contexts + layered middleware. +Template links + move-aware immutable states + layered hook. © 2025 Orchestrate LLC – Apache 2.0 diff --git a/docs/csharp/index.html b/docs/csharp/index.html index 67588bc..a16721e 100644 --- a/docs/csharp/index.html +++ b/docs/csharp/index.html @@ -102,7 +102,7 @@ Home Concepts Benefits - AI Love + AI-Ready Languages GitHub @@ -115,7 +115,7 @@
    - v1.0.0 • C# Edition + v2.0.0 • C# Edition

    @@ -141,191 +141,241 @@

    -

    The Fundamental Truth

    +

    Core Concepts

    - CodeUChain isn't just a framework—it's the natural way software should be built + Four building blocks. Learn them once, use them in any language.

    -
    -
    -
    🎯
    -

    Why This Architecture Is Inherently Right

    -

    - CodeUChain aligns with how humans think, how systems evolve, and how complexity should be managed. - It's not about following trends; it's about following the fundamental principles of good design. -

    -
    -
    -
    - +
    - 🧠 + 📦
    -

    Human Mind Structure

    +

    State

    -

    Our brains are wired for chains of thought and sequential processing:

    +

    Immutable key-value container that carries data through your pipeline.

    -
    Problem → Analysis → Solution → Verification → Refinement
    +
    ctx = State({ user_id: 101, role: "admin" })
    +
    ctx.get("role") // "admin"
    +
    ctx.set("status", "active") // returns new State

    - When your code structure matches your thinking patterns, you become 3x more productive. + Thread-safe. Each .set() returns a new State — no mutation, no surprises.

    - +
    - 🌌 + 🔗
    -

    Universal Composition

    +

    Link

    -

    Everything in nature is built through composition:

    +

    A single unit of work. Takes State in, returns State out. One job, done well.

    -
    Small pieces → Combine → Complex systems
    +
    Link("validate", ctx => {
    +
      if (!ctx.get("email").includes("@"))
    +
        throw Error("bad email");
    +
      return ctx;
    +
    })

    - Atoms form molecules, cells form organs, links form beautiful systems. + Each Link lives in its own file. Easy to test, reuse, and reason about.

    - +
    - 📊 + ⛓️
    -

    Error as Information

    +

    Chain

    -

    Traditional systems treat errors as failures. CodeUChain sees them as signals:

    +

    Composes Links into an ordered pipeline. Handles execution and error propagation.

    -
    Error → Information → Learning → Better System
    +
    chain = Chain()
    +
      .add(validateEmail)
    +
      .add(hashPassword)
    +
      .add(saveUser)
    +
    result = chain.execute(state)

    - Instead of "crashed," you get "learned something new and became stronger." + If any Link throws, the Chain stops and the error is available on the result.

    - +
    - 🆓 + 🪝
    -

    Cognitive Freedom

    +

    Hook

    -

    Traditional code forces you to hold everything in your head:

    +

    Observes execution without modifying business logic. Runs alongside the Chain.

    -
    Before: "Understand everything at once"
    -
    After: "Focus on one link at a time"
    +
    hook.before(ctx => log("starting"))
    +
    hook.after(ctx => log("done"))
    +
    hook.onError(err => alert(err))

    - Your brain can finally relax. Be a focused craftsman, not a superhero. + Logging, metrics, caching — without touching your Link code.

    + + +
    +
    +

    How It Flows

    +
    +
    + State → Link 1 → Link 2 → Link 3 → Result +
    +
    +          ↑ Hook observes each step ↑ +
    +
    +
    +
    +

    Developer Benefits

    -

    Why developers naturally gravitate toward this architecture

    +

    Practical advantages you get from day one

    -
    -
    -
    -
    -
    - 🎯 -
    -

    Predictable Behavior

    -
    -

    - CodeUChain gives you psychological safety with predictable behavior, composition, and evolution. -

    -
    -

    - "You can confidently make changes because you know the impact will be contained." -

    +
    + +
    +
    +
    + 🧪
    +

    Testable by Default

    +

    + Each Link is a pure function: State in, State out. Mock nothing — just pass test data. +

    +
    +
    result = myLink.call(State({ input: "test" }))
    +
    assert result.get("output") == expected
    +
    +
    -
    -
    -
    - 🌊 -
    -

    Creative Flow State

    -
    -

    - CodeUChain unlocks the flow state that makes programming addictive: -

    -
    -
    Clear goal → Immediate feedback → Sense of progress → Deep focus
    + +
    +
    +
    + 🔄
    +

    Reusable Components

    +
    +

    + Write a Link once, drop it into any Chain. Build a library of battle-tested building blocks. +

    +
    +
    orderChain.add(validateEmail) // reuse
    +
    signupChain.add(validateEmail) // reuse
    -
    -
    + +
    +
    - + 🌍
    -

    Architectural Elegance

    +

    One Pattern, Every Language

    -
    -
    -

    Symmetry in Design

    -

    Input → Processing → Output: Clean, unidirectional flow

    +

    + Same State → Link → Chain model in Python, Go, TypeScript, C#, Rust, Java, and C++. +

    +
    +
    // Learn once, apply everywhere
    +
    chain.add(link).execute(state)
    +
    +
    + + +
    +
    +
    + 🛡️
    -
    -

    Power of Constraints

    -

    Freedom within structure, creativity within predictability

    +

    Contained Impact

    +
    +

    + Changes to one Link cannot break another. Errors stop the Chain without side effects. +

    +
    +
    // Link 2 fails? Links 3-5 never run.
    +
    // State stays immutable throughout.
    +
    +
    + + +
    +
    +
    + 📖
    -
    -

    Emergent Complexity

    -

    Simple rules create systems of breathtaking complexity

    +

    Self-Documenting

    +
    +

    + A Chain reads like a checklist. New developers understand the flow in seconds. +

    +
    +
    Chain: ValidateInput
    +
      → EnrichData → Save → Notify
    +
    +
    + + +
    +
    +
    +
    +

    Opt-In Type Safety

    +
    +

    + Start untyped for speed. Add generics when you need compile-time guarantees. +

    +
    +
    Link[UserInput, UserOutput]
    +
    State[T].insertAs<U>(k, v)
    - -
    + + +
    - 🤖 - AI Agents Love CodeUChain -
    -
    -

    Why AI Assistants Excel Here

    -
    -
    -
    "
    -

    - CodeUChain transformed how I approach coding. Its clear patterns and predictable structure - allowed me to generate code that was not only functional but elegant. -

    -
    "
    -
    -
    -
    - — GitHub Copilot -
    + 🤖 + Built for AI Agents
    +

    AI-Ready Architecture

    +

    + The same structure that helps humans reason about code helps AI assistants generate, refactor, and extend it. +

    @@ -333,17 +383,17 @@

    Why AI Assistants
    - 🎯 + 🎯
    -

    AI-Perfect Architecture

    +

    Predictable Patterns

    - CodeUChain speaks the same language as AI agents with clear templates and modular thinking. + AI models thrive on consistent structure. Every Link follows the same contract, so generation is reliable.

    -
    // AI can immediately understand:
    +
    // AI immediately understands the flow:
    - ValidateInput → CheckCredentials → GenerateToken → LogSuccess + ValidateInput → CheckCredentials → GenerateToken → LogSuccess
    @@ -351,17 +401,17 @@

    AI-Perfect Architecture

    - 🔄 + 🔄
    -

    Incremental AI Development

    +

    Incremental Generation

    - AI can build step by step, just like humans: + AI builds step by step, just like a developer:

    -
    AI Step 1: Create ValidateEmail link
    -
    AI Step 2: Create SaveToDatabase link
    -
    AI Step 3: Compose into UserRegistration chain
    +
    Step 1: Generate ValidateEmail link
    +
    Step 2: Generate SaveToDatabase link
    +
    Step 3: Compose into UserRegistration chain
    @@ -369,23 +419,23 @@

    Incremental AI Development

    - 📚 -
    -

    Self-Documenting for AI

    + 📚 +
    +

    Self-Documenting Structure

    -
    // AI can immediately understand this structure:
    +
    // The Chain tells the whole story:
    const UserAuthChain = Chain
    -   .start(ValidateCredentials)  // Check username/password
    -   .then(GenerateJWT)        // Create auth token
    -   .then(LogAuthEvent)        // Record the login
    -   .catch(HandleAuthFailure)    // Deal with failures +   .add(ValidateCredentials)  // Check username/password
    +   .add(GenerateJWT)        // Create auth token
    +   .add(LogAuthEvent)        // Record the login
    +   .add(HandleAuthFailure)    // Deal with failures
    -

    - "The chain structure tells AI exactly what happens, in what order, and how errors are handled." +

    + AI reads Chain composition the same way humans do: clear intent, clear order, clear error handling.

    @@ -394,107 +444,81 @@

    Self-Documenting for AI

    -

    🤖 The AI Advantage

    +

    Why It Works

    -
    +

    Consistent patterns for reliable AI output

    -
    +

    Type contracts for safe AI collaboration

    -
    +

    Clear structure for AI-assisted refactoring

    -
    -

    - CodeUChain transforms AI from "sometimes helpful" to "consistently brilliant." - The architecture that makes developers more productive makes AI assistants absolutely brilliant. -

    -

    +
    -

    Getting Started

    -

    Your journey to elegant architecture begins here

    +

    Quick Start

    +

    Install and write your first chain in minutes

    - +
    -

    📖 Understanding Through Language

    +

    📦 Install

    +
    + dotnet add package CodeUChain +
    -
    -
    -

    No Programming Required

    -

    The pseudocode explains concepts in plain English, making the architecture accessible to everyone.

    +

    🧠 Mental Model

    +
    +
    + State + The data box flowing through your pipeline
    - -
    -

    Human-Centered Design

    -

    Built around how humans naturally think and solve problems, not machine optimization.

    +
    + Link + One focused unit of work — receives State, returns State
    - -
    -

    Universal Understanding

    -

    The same mental model works across all programming languages and domains.

    +
    + Chain + Ordered sequence of Links — runs them in order +
    +
    + Hook + Parallel observer — logging, metrics, caching
    - +
    -

    🚀 Your Next Steps

    - -
    -
    -
    - 1 -
    -
    -

    Read the Concepts

    -

    Understand Link, Context, and Chain primitives

    -
    -
    - -
    -
    - 2 -
    -
    -

    Choose Your Language

    -

    Pick from Python, Go, JavaScript, C#, Rust, and more

    -
    -
    - -
    -
    - 3 -
    -
    -

    Build Your First Chain

    -

    Create simple links and compose them together

    -
    -
    - -
    -
    - 4 -
    -
    -

    Experience the Flow

    -

    Discover why this architecture feels so fundamentally right

    -
    -
    +

    ⚡ Your First Chain

    +
    +
    var pipeline = new Chain()
    +  .AddLink(new Link("validate_stock", ctx => {
    +    int qty = (int)ctx.Get("quantity");
    +    if (qty > 100) throw new Exception("Out of stock");
    +    return ctx;
    +  }))
    +  .AddLink(new Link("calc_total", ctx => {
    +    ctx.Set("total", 10.00 * (int)ctx.Get("quantity"));
    +    return ctx;
    +  }));
    +
    +var result = pipeline.Execute(new State().Set("quantity", 5));
    +Console.WriteLine($"Total: ${result.Get("total")}");
    @@ -679,7 +703,7 @@

    Quick Links

  • Home
  • Core Concepts
  • Benefits
  • -
  • AI Love
  • +
  • AI-Ready
  • Quick Start
  • @@ -703,9 +727,8 @@

    Languages

    - © 2025 Orchestrate LLC. + © 2025-2026 Orchestrate LLC. Licensed under Apache 2.0. - Built with ❤️ for developers everywhere.

    @@ -927,7 +950,7 @@

    Languages

    'hero': { icon: '🏠', key: 'H', label: 'Hero' }, 'concepts': { icon: '🎯', key: 'C', label: 'Concepts' }, 'benefits': { icon: '⚡', key: 'B', label: 'Benefits' }, - 'ai-love': { icon: '🤖', key: 'A', label: 'AI Love' }, + 'ai-ready': { icon: '🤖', key: 'A', label: 'AI-Ready' }, 'quickstart': { icon: '🚀', key: 'Q', label: 'Quick Start' }, 'languages': { icon: '🌍', key: 'L', label: 'Languages' }, 'overview': { icon: '📋', key: 'O', label: 'Overview' }, diff --git a/docs/csharp/llm-full.txt b/docs/csharp/llm-full.txt index d53a1b1..faf0a06 100644 --- a/docs/csharp/llm-full.txt +++ b/docs/csharp/llm-full.txt @@ -14,33 +14,33 @@ dotnet run --project examples/ **Authors:** CodeUChain contributors **Language:** C# 10+ **Target Frameworks:** .NET 6+, .NET 8 LTS -**Paradigm Keywords:** Composable Pipelines, Immutable Context, Type Evolution, Middleware Observability +**Paradigm Keywords:** Composable Pipelines, Immutable State, Type Evolution, Hook Observability --- ## 1. Purpose & Philosophy -Enterprise-grade composable async transformations with explicit data evolution and zero hidden mutation. Strong typing where you want it; runtime flexibility where you need it. Links remain pure, Context evolves immutably, Chains orchestrate, Middleware observes. +Enterprise-grade composable async transformations with explicit data evolution and zero hidden mutation. Strong typing where you want it; runtime flexibility where you need it. Links remain pure, State evolves immutably, Chains orchestrate, Hook observes. | Principle | C# Expression | Benefit | |-----------|---------------|---------| -| Selfless Links | `Task> CallAsync(Context)` | Predictable, mockable | -| Immutable Context | `ctx2 = ctx.Insert(k,v)` | No side-effect surprises | +| Selfless Links | `Task> CallAsync(State)` | Predictable, mockable | +| Immutable State | `ctx2 = ctx.Insert(k,v)` | No side-effect surprises | | Type Evolution | `InsertAs()` (pattern) | Progressive modeling | -| Observability | Middleware `Before/After/OnError` | Central instrumentation | -| Mixed Strictness | Raw context fallback | Gradual adoption | +| Observability | Hook `Before/After/OnError` | Central instrumentation | +| Mixed Strictness | Raw state fallback | Gradual adoption | --- ## 2. Architectural Overview ``` -Http Request → Context +Http Request → State | ValidateHeadersLink v -Context +State | ParsePayloadLink v -Context - | EnrichLink (middleware: metrics, tracing) +State + | EnrichLink (hook: metrics, tracing) v -Context +State ``` Branching, retry wrapping, and error classification integrate without altering primitive contracts. @@ -48,22 +48,22 @@ Branching, retry wrapping, and error classification integrate without altering p ## 3. Core Interfaces (Representative) ```csharp public interface ILink { - Task> CallAsync(Context ctx, CancellationToken ct = default); + Task> CallAsync(State ctx, CancellationToken ct = default); } -public sealed class Context { +public sealed class State { public bool Has(string key); public object? Get(string key); // optional typed Get(key) - public Context Insert(string key, object value); // preserve type - public Context InsertAs(string key, object value); // type evolution + public State Insert(string key, object value); // preserve type + public State InsertAs(string key, object value); // type evolution public IReadOnlyCollection Keys { get; } public IReadOnlyDictionary Snapshot(); } -public interface IMiddleware { - Task BeforeAsync(string linkName, Context ctx, CancellationToken ct); - Task AfterAsync(string linkName, Context ctx, CancellationToken ct); - Task OnErrorAsync(string linkName, Context ctx, Exception ex, CancellationToken ct); +public interface IHook { + Task BeforeAsync(string linkName, State ctx, CancellationToken ct); + Task AfterAsync(string linkName, State ctx, CancellationToken ct); + Task OnErrorAsync(string linkName, State ctx, Exception ex, CancellationToken ct); } ``` @@ -86,7 +86,7 @@ public record Parsed(string Email, string[] Tokens); public sealed class ParseLink : ILink { - public Task> CallAsync(Context ctx, CancellationToken ct = default) + public Task> CallAsync(State ctx, CancellationToken ct = default) { var email = (string)ctx.Get("Email")!; if (!email.Contains('@')) throw new ArgumentException("invalid_email"); @@ -103,14 +103,14 @@ var chain = Chain.Start(new ParseLink()) .Then(new EnrichLink()) .Catch((name, ex, c) => c.Insert("error", ex.Message)); -var result = await chain.CallAsync(Context.Start(new Inbound("a@b.com", "hello world"))); +var result = await chain.CallAsync(State.Start(new Inbound("a@b.com", "hello world"))); ``` --- ## 6. Chain & Error Handling Typical error flow: ``` -Throw → Middleware.OnError → Chain.Catch handler (optional) → propagate or convert +Throw → Hook.OnError → Chain.Catch handler (optional) → propagate or convert ``` Retry wrapper example (simplified): ```csharp @@ -128,27 +128,27 @@ public static ILink WithRetry(this ILink inner, in ``` --- -## 7. Middleware Lifecycle +## 7. Hook Lifecycle ```csharp -public sealed class MetricsMiddleware : IMiddleware { +public sealed class MetricsHook : IHook { private readonly IStopwatchFactory _sw; - public MetricsMiddleware(IStopwatchFactory sw) => _sw = sw; - public Task BeforeAsync(string name, Context ctx, CancellationToken ct) { + public MetricsHook(IStopwatchFactory sw) => _sw = sw; + public Task BeforeAsync(string name, State ctx, CancellationToken ct) { ctx.Insert("_t0", _sw.StartNew()); return Task.CompletedTask; } - public Task AfterAsync(string name, Context ctx, CancellationToken ct) { + public Task AfterAsync(string name, State ctx, CancellationToken ct) { var sw = (IStopwatch)ctx.Get("_t0")!; Console.WriteLine($"{name} took {sw.ElapsedMilliseconds}ms"); return Task.CompletedTask; } - public Task OnErrorAsync(string name, Context ctx, Exception ex, CancellationToken ct) { + public Task OnErrorAsync(string name, State ctx, Exception ex, CancellationToken ct) { Console.Error.WriteLine($"ERR {name}: {ex.Message}"); return Task.CompletedTask; } } ``` -Registration: `chain.Use(new MetricsMiddleware(...));` +Registration: `chain.Use(new MetricsHook(...));` Guidelines: - Keep blocking IO out of `Before/After` unless essential. @@ -176,7 +176,7 @@ Example xUnit test: public class ParseLinkTests { [Fact] public async Task ParsesTokens() { - var ctx = Context.Start(new Inbound("a@b.com","hello world")); + var ctx = State.Start(new Inbound("a@b.com","hello world")); var outCtx = await new ParseLink().CallAsync(ctx); var parsed = (Parsed)outCtx.Get("Parsed")!; Assert.Equal(2, parsed.Tokens.Length); @@ -190,7 +190,7 @@ public class EmailCases { [InlineData("a@b.com", true)] [InlineData("bad", false)] public async Task EmailValidation(string email, bool ok) { - var ctx = Context.Start(new Inbound(email, "body")); + var ctx = State.Start(new Inbound(email, "body")); if (ok) await new ParseLink().CallAsync(ctx); else await Assert.ThrowsAsync(() => new ParseLink().CallAsync(ctx)); } @@ -200,17 +200,17 @@ public class EmailCases { --- ## 10. Observability & Diagnostics Strategies: -- Middleware for metrics (EventCounters / OpenTelemetry) +- Hook for metrics (EventCounters / OpenTelemetry) - Structured logging (Serilog / ILogger) - Correlation IDs inserted early in chain - Dump `ctx.Keys` only (avoid large payload logs) -Debug middleware snippet: +Debug hook snippet: ```csharp -public sealed class DebugMw : IMiddleware { - public Task BeforeAsync(string n, Context c, CancellationToken t){ Console.WriteLine($"→ {n}"); return Task.CompletedTask; } - public Task AfterAsync(string n, Context c, CancellationToken t){ Console.WriteLine($"← {n}: [{string.Join(',', c.Keys)}]"); return Task.CompletedTask; } - public Task OnErrorAsync(string n, Context c, Exception e, CancellationToken t){ Console.WriteLine($"! {n} {e.Message}"); return Task.CompletedTask; } +public sealed class DebugMw : IHook { + public Task BeforeAsync(string n, State c, CancellationToken t){ Console.WriteLine($"→ {n}"); return Task.CompletedTask; } + public Task AfterAsync(string n, State c, CancellationToken t){ Console.WriteLine($"← {n}: [{string.Join(',', c.Keys)}]"); return Task.CompletedTask; } + public Task OnErrorAsync(string n, State c, Exception e, CancellationToken t){ Console.WriteLine($"! {n} {e.Message}"); return Task.CompletedTask; } } ``` @@ -229,26 +229,26 @@ Benchmark skeleton (BenchmarkDotNet): [MemoryDiagnoser] public class ChainBench { private ILink _chain = /* build chain */; - private Context _ctx = Context.Start(new Inbound("a@b.com","hello")); - [Benchmark] public Task> Run() => _chain.CallAsync(_ctx); + private State _ctx = State.Start(new Inbound("a@b.com","hello")); + [Benchmark] public Task> Run() => _chain.CallAsync(_ctx); } ``` --- ## 12. Advanced Patterns - Conditional links (feature flag evaluation inside builder) -- Fan-out subchains with Task.WhenAll then merge contexts +- Fan-out subchains with Task.WhenAll then merge states - Retry + circuit breaker decorators - Saga compensation (append compensating links on success path, trigger on error) -- Streaming ingestion (wrap message batches as contexts) +- Streaming ingestion (wrap message batches as states) - Partial failure tagging (collect soft failures, continue pipeline) --- ## 13. Migration & Adoption Phases: -1. Start with raw contexts + minimal links +1. Start with raw states + minimal links 2. Introduce records & generics (strong typing) -3. Add middleware (metrics, logging) +3. Add hook (metrics, logging) 4. Introduce retry / circuit breakers 5. Optimize allocations + add benchmarks 6. Extract reusable chain fragments into libraries @@ -260,7 +260,7 @@ Backward compatibility: preserve public interfaces; evolve via extension methods | Anti-Pattern | Problem | Remedy | |--------------|---------|--------| | God Link | Hard to test | Decompose into smaller links | -| Swallowing exceptions in middleware | Hidden failure | Tag then rethrow or classify | +| Swallowing exceptions in hook | Hidden failure | Tag then rethrow or classify | | Excessive reflection per call | Performance drag | Cache compiled delegates | | Logging full payload bodies | PII / performance | Log hashes / key fields | | Overusing dynamic | Loses safety | Constrain with generics + type evolution | @@ -268,34 +268,34 @@ Backward compatibility: preserve public interfaces; evolve via extension methods --- ## 15. FAQ **Q:** How do I cancel a running chain? -**A:** Pass a `CancellationToken` through `CallAsync` and propagate to links & middleware. +**A:** Pass a `CancellationToken` through `CallAsync` and propagate to links & hook. -**Q:** Can middleware mutate business data? +**Q:** Can hook mutate business data? **A:** Prefer adding metadata only; keep domain mutations in links. **Q:** How to branch? **A:** Implement conditional builder methods or a link that inserts routing key & subsequent conditional links read it. **Q:** How to short-circuit? -**A:** Throw an intentional classified exception or return a context consumed by a conditional terminator link. +**A:** Throw an intentional classified exception or return a state consumed by a conditional terminator link. -**Q:** Is context thread-safe? +**Q:** Is state thread-safe? **A:** Immutable snapshots are safe to share; do not mutate underlying store. --- ## 16. Glossary - **Link**: Async transformer (pure intent, minimal side effects). - **Chain**: Ordered composition executor. -- **Context**: Immutable typed key-value state with evolution. -- **Middleware**: Observability / policy layer around link execution. -- **Type Evolution**: Progressive widening of context data contract. +- **State**: Immutable typed key-value state with evolution. +- **Hook**: Observability / policy layer around link execution. +- **Type Evolution**: Progressive widening of state data contract. --- ## 17. TL;DR ```text Install: dotnet add package CodeUChain -Model: ILink + Chain + Context + Middleware + Type Evolution -Adopt: Start raw → add records → add middleware → optimize +Model: ILink + Chain + State + Hook + Type Evolution +Adopt: Start raw → add records → add hook → optimize Perf: Minimize allocations, structured logging, benchmark critical chains Testing: xUnit per link + integration chain tests + BenchmarkDotNet Errors: Classify, retry transient, propagate permanent diff --git a/docs/csharp/llm.txt b/docs/csharp/llm.txt index 9ed64e1..ba719bf 100644 --- a/docs/csharp/llm.txt +++ b/docs/csharp/llm.txt @@ -7,21 +7,21 @@ Full reference: `docs/csharp/llm-full.txt` dotnet add package CodeUChain ``` ```csharp -var ctx = Context.New(new { Payload = "hi" }); +var ctx = State.New(new { Payload = "hi" }); var res = await chain.CallAsync(ctx); ``` ## Primitives -- Link: `Task> CallAsync(Context ctx)` -- Context: immutable; `Insert`, `InsertAs` +- Link: `Task> CallAsync(State ctx)` +- State: immutable; `Insert`, `InsertAs` - Chain: fluent builder + `.Catch()` -- Middleware: `Before/After/OnError` +- Hook: `Before/After/OnError` ## Minimal Link ```csharp sealed class Parse : ILink { - public Task> CallAsync(Context ctx) => + public Task> CallAsync(State ctx) => Task.FromResult(ctx.Insert("Parsed", true)); } ``` @@ -54,6 +54,6 @@ Transient (retry w/ backoff) vs Permanent (validation, security). Tag via custom ``` ## TL;DR -Async Tasks + immutable evolving contexts + disciplined middleware. +Async Tasks + immutable evolving states + disciplined hook. © 2025 Orchestrate LLC – Apache 2.0 diff --git a/docs/diagrams/ASCII_PIPELINES.txt b/docs/diagrams/ASCII_PIPELINES.txt index f33b318..71f0fa4 100644 --- a/docs/diagrams/ASCII_PIPELINES.txt +++ b/docs/diagrams/ASCII_PIPELINES.txt @@ -31,7 +31,7 @@ +-------------- success <----------+ ``` -## Middleware Wrap +## Hook Wrap ``` [Ctx] -> [Before MW] -> (Link) -> [After MW] -> [Ctx'] | error @@ -58,8 +58,8 @@ On failure -> Pop & run compensations: C3, C2, C1 ## Type Evolution Layers ``` -Context - add validated -> Context - add parsed -> Context - add enriched -> Context +State + add validated -> State + add parsed -> State + add enriched -> State ``` diff --git a/docs/go/index.html b/docs/go/index.html index adcab8d..6345e48 100644 --- a/docs/go/index.html +++ b/docs/go/index.html @@ -102,7 +102,7 @@ Home Concepts Benefits - AI Love + AI-Ready Languages GitHub @@ -115,7 +115,7 @@
    - v1.0.0 • Go Edition + v2.0.0 • Go Edition

    @@ -130,7 +130,7 @@

    Understand the Concepts → - + View Source

    @@ -141,191 +141,241 @@

    -

    The Fundamental Truth

    +

    Core Concepts

    - CodeUChain isn't just a framework—it's the natural way software should be built + Four building blocks. Learn them once, use them in any language.

    -
    -
    -
    🎯
    -

    Why This Architecture Is Inherently Right

    -

    - CodeUChain aligns with how humans think, how systems evolve, and how complexity should be managed. - It's not about following trends; it's about following the fundamental principles of good design. -

    -
    -
    -
    - +
    - 🧠 + 📦
    -

    Human Mind Structure

    +

    State

    -

    Our brains are wired for chains of thought and sequential processing:

    +

    Immutable key-value container that carries data through your pipeline.

    -
    Problem → Analysis → Solution → Verification → Refinement
    +
    ctx = State({ user_id: 101, role: "admin" })
    +
    ctx.get("role") // "admin"
    +
    ctx.set("status", "active") // returns new State

    - When your code structure matches your thinking patterns, you become 3x more productive. + Thread-safe. Each .set() returns a new State — no mutation, no surprises.

    - +
    - 🌌 + 🔗
    -

    Universal Composition

    +

    Link

    -

    Everything in nature is built through composition:

    +

    A single unit of work. Takes State in, returns State out. One job, done well.

    -
    Small pieces → Combine → Complex systems
    +
    Link("validate", ctx => {
    +
      if (!ctx.get("email").includes("@"))
    +
        throw Error("bad email");
    +
      return ctx;
    +
    })

    - Atoms form molecules, cells form organs, links form beautiful systems. + Each Link lives in its own file. Easy to test, reuse, and reason about.

    - +
    - 📊 + ⛓️
    -

    Error as Information

    +

    Chain

    -

    Traditional systems treat errors as failures. CodeUChain sees them as signals:

    +

    Composes Links into an ordered pipeline. Handles execution and error propagation.

    -
    Error → Information → Learning → Better System
    +
    chain = Chain()
    +
      .add(validateEmail)
    +
      .add(hashPassword)
    +
      .add(saveUser)
    +
    result = chain.execute(state)

    - Instead of "crashed," you get "learned something new and became stronger." + If any Link throws, the Chain stops and the error is available on the result.

    - +
    - 🆓 + 🪝
    -

    Cognitive Freedom

    +

    Hook

    -

    Traditional code forces you to hold everything in your head:

    +

    Observes execution without modifying business logic. Runs alongside the Chain.

    -
    Before: "Understand everything at once"
    -
    After: "Focus on one link at a time"
    +
    hook.before(ctx => log("starting"))
    +
    hook.after(ctx => log("done"))
    +
    hook.onError(err => alert(err))

    - Your brain can finally relax. Be a focused craftsman, not a superhero. + Logging, metrics, caching — without touching your Link code.

    + + +
    +
    +

    How It Flows

    +
    +
    + State → Link 1 → Link 2 → Link 3 → Result +
    +
    +          ↑ Hook observes each step ↑ +
    +
    +
    +
    +

    Developer Benefits

    -

    Why developers naturally gravitate toward this architecture

    +

    Practical advantages you get from day one

    -
    -
    -
    -
    -
    - 🎯 -
    -

    Predictable Behavior

    -
    -

    - CodeUChain gives you psychological safety with predictable behavior, composition, and evolution. -

    -
    -

    - "You can confidently make changes because you know the impact will be contained." -

    +
    + +
    +
    +
    + 🧪
    +

    Testable by Default

    +

    + Each Link is a pure function: State in, State out. Mock nothing — just pass test data. +

    +
    +
    result = myLink.call(State({ input: "test" }))
    +
    assert result.get("output") == expected
    +
    +
    -
    -
    -
    - 🌊 -
    -

    Creative Flow State

    -
    -

    - CodeUChain unlocks the flow state that makes programming addictive: -

    -
    -
    Clear goal → Immediate feedback → Sense of progress → Deep focus
    + +
    +
    +
    + 🔄
    +

    Reusable Components

    +
    +

    + Write a Link once, drop it into any Chain. Build a library of battle-tested building blocks. +

    +
    +
    orderChain.add(validateEmail) // reuse
    +
    signupChain.add(validateEmail) // reuse
    -
    -
    + +
    +
    - + 🌍
    -

    Architectural Elegance

    +

    One Pattern, Every Language

    -
    -
    -

    Symmetry in Design

    -

    Input → Processing → Output: Clean, unidirectional flow

    +

    + Same State → Link → Chain model in Python, Go, TypeScript, C#, Rust, Java, and C++. +

    +
    +
    // Learn once, apply everywhere
    +
    chain.add(link).execute(state)
    +
    +
    + + +
    +
    +
    + 🛡️
    -
    -

    Power of Constraints

    -

    Freedom within structure, creativity within predictability

    +

    Contained Impact

    +
    +

    + Changes to one Link cannot break another. Errors stop the Chain without side effects. +

    +
    +
    // Link 2 fails? Links 3-5 never run.
    +
    // State stays immutable throughout.
    +
    +
    + + +
    +
    +
    + 📖
    -
    -

    Emergent Complexity

    -

    Simple rules create systems of breathtaking complexity

    +

    Self-Documenting

    +
    +

    + A Chain reads like a checklist. New developers understand the flow in seconds. +

    +
    +
    Chain: ValidateInput
    +
      → EnrichData → Save → Notify
    +
    +
    + + +
    +
    +
    +
    +

    Opt-In Type Safety

    +
    +

    + Start untyped for speed. Add generics when you need compile-time guarantees. +

    +
    +
    Link[UserInput, UserOutput]
    +
    State[T].insertAs<U>(k, v)
    - -
    + + +
    - 🤖 - AI Agents Love CodeUChain -
    -
    -

    Why AI Assistants Excel Here

    -
    -
    -
    "
    -

    - CodeUChain transformed how I approach coding. Its clear patterns and predictable structure - allowed me to generate code that was not only functional but elegant. -

    -
    "
    -
    -
    -
    - — GitHub Copilot -
    + 🤖 + Built for AI Agents
    +

    AI-Ready Architecture

    +

    + The same structure that helps humans reason about code helps AI assistants generate, refactor, and extend it. +

    @@ -333,17 +383,17 @@

    Why AI Assistants
    - 🎯 + 🎯
    -

    AI-Perfect Architecture

    +

    Predictable Patterns

    - CodeUChain speaks the same language as AI agents with clear templates and modular thinking. + AI models thrive on consistent structure. Every Link follows the same contract, so generation is reliable.

    -
    // AI can immediately understand:
    +
    // AI immediately understands the flow:
    - ValidateInput → CheckCredentials → GenerateToken → LogSuccess + ValidateInput → CheckCredentials → GenerateToken → LogSuccess
    @@ -351,17 +401,17 @@

    AI-Perfect Architecture

    - 🔄 + 🔄
    -

    Incremental AI Development

    +

    Incremental Generation

    - AI can build step by step, just like humans: + AI builds step by step, just like a developer:

    -
    AI Step 1: Create ValidateEmail link
    -
    AI Step 2: Create SaveToDatabase link
    -
    AI Step 3: Compose into UserRegistration chain
    +
    Step 1: Generate ValidateEmail link
    +
    Step 2: Generate SaveToDatabase link
    +
    Step 3: Compose into UserRegistration chain
    @@ -369,23 +419,23 @@

    Incremental AI Development

    - 📚 -
    -

    Self-Documenting for AI

    + 📚 +
    +

    Self-Documenting Structure

    -
    // AI can immediately understand this structure:
    +
    // The Chain tells the whole story:
    const UserAuthChain = Chain
    -   .start(ValidateCredentials)  // Check username/password
    -   .then(GenerateJWT)        // Create auth token
    -   .then(LogAuthEvent)        // Record the login
    -   .catch(HandleAuthFailure)    // Deal with failures +   .add(ValidateCredentials)  // Check username/password
    +   .add(GenerateJWT)        // Create auth token
    +   .add(LogAuthEvent)        // Record the login
    +   .add(HandleAuthFailure)    // Deal with failures
    -

    - "The chain structure tells AI exactly what happens, in what order, and how errors are handled." +

    + AI reads Chain composition the same way humans do: clear intent, clear order, clear error handling.

    @@ -394,107 +444,90 @@

    Self-Documenting for AI

    -

    🤖 The AI Advantage

    +

    Why It Works

    -
    +

    Consistent patterns for reliable AI output

    -
    +

    Type contracts for safe AI collaboration

    -
    +

    Clear structure for AI-assisted refactoring

    -
    -

    - CodeUChain transforms AI from "sometimes helpful" to "consistently brilliant." - The architecture that makes developers more productive makes AI assistants absolutely brilliant. -

    -
    +
    -

    Getting Started

    -

    Your journey to elegant architecture begins here

    +

    Quick Start

    +

    Install and write your first chain in minutes

    - +
    -

    📖 Understanding Through Language

    +

    📦 Install

    +
    + go get github.com/codeuchain/codeuchain/go +
    -
    -
    -

    No Programming Required

    -

    The pseudocode explains concepts in plain English, making the architecture accessible to everyone.

    +

    🧠 Mental Model

    +
    +
    + State + The data box flowing through your pipeline
    - -
    -

    Human-Centered Design

    -

    Built around how humans naturally think and solve problems, not machine optimization.

    +
    + Link + One focused unit of work — receives State, returns State
    - -
    -

    Universal Understanding

    -

    The same mental model works across all programming languages and domains.

    +
    + Chain + Ordered sequence of Links — runs them in order +
    +
    + Hook + Parallel observer — logging, metrics, caching
    - +
    -

    🚀 Your Next Steps

    - -
    -
    -
    - 1 -
    -
    -

    Read the Concepts

    -

    Understand Link, Context, and Chain primitives

    -
    -
    +

    ⚡ Your First Chain

    +
    +
    import (
    +    cuc "github.com/codeuchain/codeuchain/go"
    +)
    +
    +validate := func(ctx *cuc.State) *cuc.State {
    +    if ctx.Get("age").(int) < 18 {
    +        ctx.Error = errors.New("too young")
    +    }
    +    return ctx
    +}
     
    -                        
    -
    - 2 -
    -
    -

    Choose Your Language

    -

    Pick from Python, Go, JavaScript, C#, Rust, and more

    -
    -
    +approve := func(ctx *cuc.State) *cuc.State { + ctx.Set("status", "approved") + return ctx +} -
    -
    - 3 -
    -
    -

    Build Your First Chain

    -

    Create simple links and compose them together

    -
    -
    +pipeline := cuc.Chain{} +pipeline.AddLink(cuc.NewLink("validate", validate)) +pipeline.AddLink(cuc.NewLink("approve", approve)) -
    -
    - 4 -
    -
    -

    Experience the Flow

    -

    Discover why this architecture feels so fundamentally right

    -
    -
    +result := pipeline.Execute(cuc.NewState(map[string]any{"age": 20})) +fmt.Println(result.Get("status"))
    @@ -679,7 +712,7 @@

    Quick Links

  • Home
  • Core Concepts
  • Benefits
  • -
  • AI Love
  • +
  • AI-Ready
  • Quick Start
  • @@ -703,9 +736,8 @@

    Languages

    - © 2025 Orchestrate LLC. + © 2025-2026 Orchestrate LLC. Licensed under Apache 2.0. - Built with ❤️ for developers everywhere.

    @@ -927,7 +959,7 @@

    Languages

    'hero': { icon: '🏠', key: 'H', label: 'Hero' }, 'concepts': { icon: '🎯', key: 'C', label: 'Concepts' }, 'benefits': { icon: '⚡', key: 'B', label: 'Benefits' }, - 'ai-love': { icon: '🤖', key: 'A', label: 'AI Love' }, + 'ai-ready': { icon: '🤖', key: 'A', label: 'AI-Ready' }, 'quickstart': { icon: '🚀', key: 'Q', label: 'Quick Start' }, 'languages': { icon: '🌍', key: 'L', label: 'Languages' }, 'overview': { icon: '📋', key: 'O', label: 'Overview' }, diff --git a/docs/go/llm-full.txt b/docs/go/llm-full.txt index 62aa8ab..d0220f9 100644 --- a/docs/go/llm-full.txt +++ b/docs/go/llm-full.txt @@ -10,18 +10,18 @@ **Authors:** CodeUChain contributors **Language:** Go 1.18+ **Platform:** Linux / macOS / Windows -**Paradigm Keywords:** Composable, Typed, Immutable-by-default, Selfless Links, Middleware Observability, Type Evolution +**Paradigm Keywords:** Composable, Typed, Immutable-by-default, Selfless Links, Hook Observability, Type Evolution --- ## 1. Purpose & Philosophy -CodeUChain is a compassionate, composable processing framework. You build flows from small, selfless units called **Links** that transform a **Context**. Chains express intent, not mechanics. Middleware gently observes or enriches without forcing coupling. Types evolve cleanly—moving from specific to generalized forms without unsafe casting. Everything is designed for: +CodeUChain is a compassionate, composable processing framework. You build flows from small, selfless units called **Links** that transform a **State**. Chains express intent, not mechanics. Hook gently observes or enriches without forcing coupling. Types evolve cleanly—moving from specific to generalized forms without unsafe casting. Everything is designed for: | Principle | Meaning | Benefit | |-----------|---------|---------| | Selfless Links | No retained mutable state in links | Pure, testable units | -| Immutable Context (default) | Insert returns a new context | Predictability & TDD clarity | +| Immutable State (default) | Insert returns a new state | Predictability & TDD clarity | | Type Evolution | `InsertAs` widens shape generically | Progressive enrichment | -| Gentle Middleware | Opt-in lifecycle hooks | Zero friction observability | +| Gentle Hook | Opt-in lifecycle hooks | Zero friction observability | | Mixed Typed/Untyped | `any` fallback always works | Gradual adoption | | Zero-Cost Abstractions | No reflection in hot path | Performance parity | @@ -29,60 +29,60 @@ CodeUChain is a compassionate, composable processing framework. You build flows ## 2. Architectural Overview Execution pipeline (linear example): ``` -Incoming Data --> Context[T0] +Incoming Data --> State[T0] │ (Link A) ▼ -Context[T1] (added validation results) +State[T1] (added validation results) │ (Link B) ▼ -Context[T2] (added domain model) - │ (Link C + Middleware metrics/logging) +State[T2] (added domain model) + │ (Link C + Hook metrics/logging) ▼ -Context[T3] (final enriched output) +State[T3] (final enriched output) ``` -Branching & error handling can fork or re-route to compensating links. Middleware wraps each link call. +Branching & error handling can fork or re-route to compensating links. Hook wraps each link call. Key components: -- **Context[T]**: Immutable map-backed data + typed evolution. -- **Link[TIn, TOut]**: Pure transformer. Returns `Context[TOut]` + `error`. +- **State[T]**: Immutable map-backed data + typed evolution. +- **Link[TIn, TOut]**: Pure transformer. Returns `State[TOut]` + `error`. - **Chain**: Ordered Link composition with optional branching / error routing. -- **Middleware**: Optional wrappers (Before / After / Error) with default no-ops. +- **Hook**: Optional wrappers (Before / After / Error) with default no-ops. - **Error Routing**: Register handlers per link or pattern. --- ## 3. Core Types & Interfaces ```go -type Context[T any] interface { +type State[T any] interface { Get(key string) (any, bool) - Insert(key string, val any) Context[T] // preserves T - InsertAs[U any](key string, val any) Context[U] // evolves to U + Insert(key string, val any) State[T] // preserves T + InsertAs[U any](key string, val any) State[U] // evolves to U Keys() []string ToMap() map[string]any } type Link[TIn any, TOut any] interface { - Call(ctx Context[TIn]) (Context[TOut], error) + Call(ctx State[TIn]) (State[TOut], error) } -type Middleware interface { - Before(linkName string, ctx Context[any]) error - After(linkName string, ctx Context[any]) error - OnError(linkName string, ctx Context[any], err error) error +type Hook interface { + Before(linkName string, ctx State[any]) error + After(linkName string, ctx State[any]) error + OnError(linkName string, ctx State[any], err error) error } ``` Minimal concrete constructors (simplified excerpt): ```go -func NewContext[T any](m map[string]any) Context[T] +func NewState[T any](m map[string]any) State[T] func NewChain() *Chain ``` --- ## 4. Building Links -Links should remain pure: derive output *only* from input context. +Links should remain pure: derive output *only* from input state. ```go type ValidateUser struct{} -func (v *ValidateUser) Call(ctx codeuchain.Context[any]) (codeuchain.Context[any], error) { +func (v *ValidateUser) Call(ctx codeuchain.State[any]) (codeuchain.State[any], error) { raw, _ := ctx.Get("user_email") email, _ := raw.(string) if !strings.Contains(email, "@") { @@ -98,7 +98,7 @@ type InputShape struct{ Raw string } type ParsedShape struct{ Raw string; Tokens []string } type Parse struct{} -func (p *Parse) Call(c codeuchain.Context[InputShape]) (codeuchain.Context[ParsedShape], error) { +func (p *Parse) Call(c codeuchain.State[InputShape]) (codeuchain.State[ParsedShape], error) { val, _ := c.Get("payload") s := val.(string) tokens := strings.Split(s, " ") @@ -113,29 +113,29 @@ chain := codeuchain.NewChain(). Then(&ValidateUser{}). Then(&Parse{}). Then(&EnrichProfile{}). - Catch(func(link string, err error, ctx codeuchain.Context[any]) (codeuchain.Context[any], error) { + Catch(func(link string, err error, ctx codeuchain.State[any]) (codeuchain.State[any], error) { // centralized fallback return ctx.Insert("error_tag", err.Error()), nil }) ``` Potential advanced patterns: -- Conditional skip (middleware injects decision flag) +- Conditional skip (hook injects decision flag) - Parallel fan-out (custom orchestrator spawning sub-chains, then merge) - Retry wrapper link for transient operations --- -## 6. Middleware Lifecycle -Typical middleware (logging + timing): +## 6. Hook Lifecycle +Typical hook (logging + timing): ```go -type MetricsMiddleware struct{} +type MetricsHook struct{} -func (m *MetricsMiddleware) Before(name string, ctx codeuchain.Context[any]) error { +func (m *MetricsHook) Before(name string, ctx codeuchain.State[any]) error { ctxStart := time.Now() fmt.Printf("➡️ %s start (%d keys)\n", name, len(ctx.Keys())) ctx = ctx.Insert("_start_ts", ctxStart) return nil } -func (m *MetricsMiddleware) After(name string, ctx codeuchain.Context[any]) error { +func (m *MetricsHook) After(name string, ctx codeuchain.State[any]) error { if tsRaw, ok := ctx.Get("_start_ts"); ok { if ts, ok2 := tsRaw.(time.Time); ok2 { fmt.Printf("✅ %s done in %s\n", name, time.Since(ts)) @@ -143,7 +143,7 @@ func (m *MetricsMiddleware) After(name string, ctx codeuchain.Context[any]) erro } return nil } -func (m *MetricsMiddleware) OnError(name string, ctx codeuchain.Context[any], err error) error { +func (m *MetricsHook) OnError(name string, ctx codeuchain.State[any], err error) error { fmt.Printf("❌ %s error: %v\n", name, err) return nil } @@ -166,7 +166,7 @@ Approaches: Simple retry decorator: ```go func WithRetry[TIn any, TOut any](inner codeuchain.Link[TIn, TOut], attempts int) codeuchain.Link[TIn, TOut] { - return codeuchain.LinkFunc[TIn, TOut](func(c codeuchain.Context[TIn]) (codeuchain.Context[TOut], error) { + return codeuchain.LinkFunc[TIn, TOut](func(c codeuchain.State[TIn]) (codeuchain.State[TOut], error) { var last error for i := 0; i < attempts; i++ { out, err := inner.Call(c) @@ -183,14 +183,14 @@ func WithRetry[TIn any, TOut any](inner codeuchain.Link[TIn, TOut], attempts int ## 8. Testing & Test-Driven Development (TDD) Why CodeUChain is ideal: - Pure links = deterministic -- Context is explicit contract +- State is explicit contract - Type evolution clarifies shape transitions -- Middleware can be mocked or omitted +- Hook can be mocked or omitted Recommended pattern per link: ```go func TestValidateUser(t *testing.T) { - ctx := codeuchain.NewContext[any](map[string]any{"user_email": "a@b.com"}) + ctx := codeuchain.NewState[any](map[string]any{"user_email": "a@b.com"}) out, err := (&ValidateUser{}).Call(ctx) if err != nil { t.Fatalf("unexpected: %v", err) } if v, _ := out.Get("validated"); v != true { t.Fatalf("expected validated flag") } @@ -203,7 +203,7 @@ cases := []struct{ email string; ok bool }{ {"x@y.com", true}, {"broken", false}, } for _, cse := range cases { - base := codeuchain.NewContext[any](map[string]any{"user_email": cse.email}) + base := codeuchain.NewState[any](map[string]any{"user_email": cse.email}) out, err := fullChain.Call(base) if cse.ok && err != nil { t.Errorf("expected success: %s", cse.email) } if !cse.ok && err == nil { t.Errorf("expected failure: %s", cse.email) } @@ -220,15 +220,15 @@ go tool cover -func=cover.out | grep total --- ## 9. Observability & Debugging Tactics: -- Add middleware for structured logging +- Add hook for structured logging - Inject correlation IDs at chain start -- Dump context keys (avoid large payload dumps in prod) +- Dump state keys (avoid large payload dumps in prod) - Expose metrics: per-link duration, error counts Sample debug printer: ```go type Debug struct{} -func (d *Debug) After(name string, ctx codeuchain.Context[any]) error { +func (d *Debug) After(name string, ctx codeuchain.State[any]) error { fmt.Printf("DBG %s keys=%v\n", name, ctx.Keys()) return nil } @@ -240,7 +240,7 @@ func (d *Debug) After(name string, ctx codeuchain.Context[any]) error { |---------|----------| | Allocation churn | Reuse maps only in controlled mutable variant | | Large payloads | Store references/pointers, not deep copies | -| Hot path logging | Use sampling middleware | +| Hot path logging | Use sampling hook | | Parallel work | Build sub-chains + goroutines, merge results | | Generics overhead | Near-zero; avoid unnecessary interface{} assertions | @@ -251,7 +251,7 @@ go test -bench "Chain" -benchmem ./... --- ## 11. Advanced Patterns -- Fan-Out / Fan-In: run N derived chains then aggregate into a parent context +- Fan-Out / Fan-In: run N derived chains then aggregate into a parent state - Saga Compensation: register reversal links for mutating operations - Streaming: adapt a link that emits items into channel consumers - Progressive Enrichment: early links validate, mid links enrich, late links format @@ -261,7 +261,7 @@ go test -bench "Chain" -benchmem ./... ### With HTTP Handler ```go func handler(w http.ResponseWriter, r *http.Request) { - base := codeuchain.NewContext[any](map[string]any{"path": r.URL.Path}) + base := codeuchain.NewState[any](map[string]any{"path": r.URL.Path}) out, err := httpChain.Call(base) if err != nil { http.Error(w, err.Error(), 500); return } if body, ok := out.Get("body"); ok { fmt.Fprint(w, body) } @@ -272,17 +272,17 @@ Wrap DB client in a link; return rows or domain aggregates. --- ## 13. Migration & Mixed Typing -Start untyped (`Context[any]`) for speed. As shapes stabilize, introduce domain structs and let `InsertAs` evolve your chain. Mixed typed/untyped links coexist seamlessly. +Start untyped (`State[any]`) for speed. As shapes stabilize, introduce domain structs and let `InsertAs` evolve your chain. Mixed typed/untyped links coexist seamlessly. --- ## 14. Anti-Patterns | Anti-Pattern | Why Harmful | Preferred | |--------------|-------------|-----------| -| Mutating internal shared map | Hidden coupling | Use returned Context | -| Embedding heavy IO in middleware | Latency inflation | Make IO a link | +| Mutating internal shared map | Hidden coupling | Use returned State | +| Embedding heavy IO in hook | Latency inflation | Make IO a link | | Overusing `any` after stabilization | Loses guarantees | Introduce typed structs | | Catch-all swallowing errors | Masks failures | Classify & tag errors | -| Storing gigantic blobs in context | Memory bloat | External cache / reference | +| Storing gigantic blobs in state | Memory bloat | External cache / reference | --- ## 15. FAQ @@ -292,27 +292,27 @@ A: Yes—return an error or include a sentinel value & conditional branch logic. **Q: How do I share config?** A: Inject immutable config via closure or constructor; keep links pure. -**Q: Is context thread-safe?** -A: Each returned context is a new instance; don't reuse mutable internals concurrently. +**Q: Is state thread-safe?** +A: Each returned state is a new instance; don't reuse mutable internals concurrently. **Q: How do I profile?** A: Use `pprof` + per-link duration metrics. **Q: Can I mutate for performance?** -A: Provide a specialized mutable context variant only in tight loops. +A: Provide a specialized mutable state variant only in tight loops. -**Q: Retry at middleware or link?** +**Q: Retry at hook or link?** A: Prefer a retry decorator wrapping a link for clarity. **Q: Support cancellation?** -A: Wrap chain execution inside a standard Go `context.Context` at orchestration layer. +A: Wrap chain execution inside a standard Go `state.State` at orchestration layer. --- ## 16. Glossary -- **Link**: Stateless transformer from Context[TIn] → Context[TOut]. +- **Link**: Stateless transformer from State[TIn] → State[TOut]. - **Chain**: Ordered link orchestration with optional error routing. -- **Context**: Immutable key-value store with typed evolution semantics. -- **Middleware**: Observers invoked around link execution. +- **State**: Immutable key-value store with typed evolution semantics. +- **Hook**: Observers invoked around link execution. - **Type Evolution**: Transition to a new generic shape via `InsertAs`. - **Compassionate Error Handling**: Non-punitive routing & tagging of failures. @@ -320,15 +320,15 @@ A: Wrap chain execution inside a standard Go `context.Context` at orchestration ## 17. TL;DR (Rapid Recall) ```text Install: go get github.com/codeuchain/codeuchain/packages/go -Mental Model: Links (pure) + Chain (composition) + Context (immutable) + Middleware (optional) + Type Evolution -Write Links: stateless, return new context only +Mental Model: Links (pure) + Chain (composition) + State (immutable) + Hook (optional) + Type Evolution +Write Links: stateless, return new state only Evolve Types: InsertAs to widen shape safely -Observability: Middleware Before/After/OnError +Observability: Hook Before/After/OnError Testing: Table-driven + per-link unit tests first Performance: Zero-cost abstractions; avoid unnecessary allocations Adoption Path: Start untyped -> gradually introduce strong types Error Handling: Central catch or decorators (retry, classify) -Avoid: hidden state, over-logging, massive blobs in context +Avoid: hidden state, over-logging, massive blobs in state ``` --- diff --git a/docs/go/llm.txt b/docs/go/llm.txt index 96c8947..953292b 100644 --- a/docs/go/llm.txt +++ b/docs/go/llm.txt @@ -7,20 +7,20 @@ Full reference: `docs/go/llm-full.txt` go get github.com/codeuchain/codeuchain/go ``` ```go -ctx := codeuchain.NewContext[any](map[string]any{"payload":"hi"}) +ctx := codeuchain.NewState[any](map[string]any{"payload":"hi"}) res, err := chain.Call(ctx) ``` ## Primitives -- Link: `Call(ctx Context[TIn]) (Context[TOut], error)` -- Context: immutable map-like, `Insert`, `InsertAs` (type evolution) +- Link: `Call(ctx State[TIn]) (State[TOut], error)` +- State: immutable map-like, `Insert`, `InsertAs` (type evolution) - Chain: ordered link composition + `Catch` -- Middleware: `Before/After/OnError` (optional) +- Hook: `Before/After/OnError` (optional) ## Minimal Link ```go type Parse struct{} -func (p *Parse) Call(c codeuchain.Context[any]) (codeuchain.Context[any], error) { +func (p *Parse) Call(c codeuchain.State[any]) (codeuchain.State[any], error) { // transform return c.Insert("parsed", true), nil } @@ -31,7 +31,7 @@ func (p *Parse) Call(c codeuchain.Context[any]) (codeuchain.Context[any], error) chain := codeuchain.NewChain(). Then(&Validate{}). Then(&Parse{}). - Catch(func(name string, err error, ctx codeuchain.Context[any]) (codeuchain.Context[any], error) { + Catch(func(name string, err error, ctx codeuchain.State[any]) (codeuchain.State[any], error) { return ctx.Insert("error", err.Error()), nil }) ``` @@ -55,6 +55,6 @@ Retry transient (network/timeouts); propagate permanent (validation, security). ``` ## TL;DR -Selfless links + immutable contexts + evolvable types + gentle middleware. +Selfless links + immutable states + evolvable types + gentle hook. © 2025 Orchestrate LLC – Apache 2.0 diff --git a/docs/index.html b/docs/index.html index 4ecbbf7..bcc66de 100644 --- a/docs/index.html +++ b/docs/index.html @@ -81,13 +81,6 @@ height: 20px; color: white; } - .logo-glow img { - filter: drop-shadow(0 0 4px rgba(0, 255, 136, 0.6)); - transition: filter 0.3s ease-in-out; - } - .logo-glow:hover img { - filter: drop-shadow(0 0 12px rgba(0, 255, 136, 1)); - } @@ -108,7 +101,7 @@ Concepts Benefits - AI Love + AI-Ready Languages GitHub @@ -117,127 +110,569 @@
    - -
    -
    -

    CodeUChain: The Story of Universal Chains

    - -

    Welcome to CodeUChain

    -

    We have universal standards for hardware—like USB-C—that let everything connect seamlessly. But what about software? While components can be swappable, entire systems are rarely built to be truly modular from the ground up.

    -

    CodeUChain changes that. It’s a framework where your logic becomes scalable, verifiable code, link by link. All with zero external dependencies.

    - -

    The Heart of the Chain

    -

    At its core, CodeUChain is built on five primitives:

    -
      -
    • Context: The data that flows through the pipeline.
    • -
    • Link: A single, atomic unit of work. One action, one link.
    • -
    • Chain: A sequence of links, forming a multi-step function or workflow.
    • -
    • Middleware: An observer that sits between links to gather metrics or add functionality without impacting performance.
    • -
    • Connections: The ability to connect links and chains in any combination.
    • -
    -

    This simple structure allows anyone to build robust systems. If you can outline a process—like "validate input, transform data, then output results"—you can build it with CodeUChain.

    - -

    Why Chains?

    -

    The concept of a "chain" is universal, especially for AI. It comes with a deep, built-in context that language models intuitively understand without explanation. Two links connect. An object can sit between them (like middleware observing stress). Chains can be linear or branch.

    -

    This built-in understanding is critical. By using the vocabulary of chains, we give the AI a mental model to work with, allowing it to grasp the architecture and its parts instantly.

    - -

    A Framework Built for the AI Era

    -

    CodeUChain was designed with AI-human collaboration in mind. AI struggles with our complex, monolithic codebases. By breaking logic into small, verifiable units, we create a system where AI can thrive.

    -
      -
    • Test-First Development, AI-Powered: With CodeUChain, an AI can write tests for a link before any code is written. By defining the input and output stubs, we know exactly what to expect.
    • -
    • Verifiable and Readable: Because each link has one job, the code is simple to read and verify. We don't have to guess if it works—it passes the test.
    • -
    • Composable Complexity: Simple links connect to form chains. Chains can be combined with branching logic to build massive, complex applications that remain easy to manage, swap, and are entirely self-documenting.
    • -
    - -

    For Developers, Architects, and Innovators

    -

    The intent of CodeUChain isn't to replace developers. It's to empower them. By providing tools to easily verify the output of AI assistants, we free up developers to focus on more complex and challenging tasks, leaving the mindless, repetitive work to their AI partners.

    -

    This platform is for professionals who want to:

    -
      -
    • Build with reliability: Ensure your systems are predictable, testable, and maintainable.
    • -
    • Collaborate efficiently: Share verifiable components across teams, languages, and environments.
    • -
    • Scale incrementally: Start simple, and compose complexity as your requirements evolve.
    • -
    - - -
    -

    The Journey Begins Here

    -

    - You've seen the philosophy. Now, explore the architecture or dive straight into the code. + +

    +
    +
    + v2.0.0 • CodeUChain Edition +
    + +

    + CodeUChain +

    + +

    + The same elegant patterns, expressed in every programming language. A universal architecture that makes complex systems simple, beautiful, and maintainable across Python, Go, JavaScript, C#, Rust, and beyond. +

    + + +
    +
    + + +
    +
    +
    +

    Core Concepts

    +

    + Four building blocks. Learn them once, use them in any language.

    +
    + +
    + +
    +
    +
    + 📦 +
    +

    State

    +
    +

    Immutable key-value container that carries data through your pipeline.

    +
    +
    ctx = State({ user_id: 101, role: "admin" })
    +
    ctx.get("role") // "admin"
    +
    ctx.set("status", "active") // returns new State
    +
    +

    + Thread-safe. Each .set() returns a new State — no mutation, no surprises. +

    +
    -
    - -
    -
    - + +
    +
    +
    + 🔗
    -

    Explore the Architecture

    -

    See how the core primitives connect to form a powerful, universal system.

    - View Core Concepts +

    Link

    +
    +

    A single unit of work. Takes State in, returns State out. One job, done well.

    +
    +
    Link("validate", ctx => {
    +
      if (!ctx.get("email").includes("@"))
    +
        throw Error("bad email");
    +
      return ctx;
    +
    })
    +

    + Each Link lives in its own file. Easy to test, reuse, and reason about. +

    +
    - -
    -
    - + +
    +
    +
    + ⛓️
    -

    Dive into the Languages

    -

    Explore the technical specifics for your favorite language.

    -
    - JavaScript logo - Python logo - Java logo - C# logo - C++ logo - Go logo - Rust logo - pseudo-code +

    Chain

    +
    +

    Composes Links into an ordered pipeline. Handles execution and error propagation.

    +
    +
    chain = Chain()
    +
      .add(validateEmail)
    +
      .add(hashPassword)
    +
      .add(saveUser)
    +
    result = chain.execute(state)
    +
    +

    + If any Link throws, the Chain stops and the error is available on the result. +

    +
    + + +
    +
    +
    + 🪝
    +

    Hook

    +
    +

    Observes execution without modifying business logic. Runs alongside the Chain.

    +
    +
    hook.before(ctx => log("starting"))
    +
    hook.after(ctx => log("done"))
    +
    hook.onError(err => alert(err))
    +

    + Logging, metrics, caching — without touching your Link code. +

    -
    - -

    Ready to build the future of software? Explore the languages, join the community, and let CodeUChain power your next project.

    - -

    Coming Soon: The CodeUChain Marketplace

    -

    Imagine a centralized hub where you can discover, share, and integrate CodeUChain components—pre-built links, chains, and libraries from the developer community. The Marketplace will provide:

    -
      -
    • Publish your modules: Share your custom CodeUChain components for others to leverage.
    • -
    • Integrate seamlessly: Browse, select, and incorporate components directly into your codebase.
    • -
    • Organize your toolkit: Create collections of reusable chains and links, customized to your needs.
    • -
    • Download and extend: Acquire packages, modify them, and expand CodeUChain's capabilities.
    • -
    -

    This Marketplace will push CodeUChain to new frontiers, enhancing collaboration and innovation. Whether you're a developer, architect, or innovator, you'll find resources and inspiration to co-create powerful systems—together.

    -
    -
    - - -

    Coming Soon: The CodeUChain Marketplace

    -

    Imagine a centralized hub where you can discover, share, and integrate CodeUChain components—pre-built links, chains, and libraries from the developer community. The Marketplace will provide:

    -
      -
    • Publish your modules: Share your custom CodeUChain components for others to leverage.
    • -
    • Integrate seamlessly: Browse, select, and incorporate components directly into your codebase.
    • -
    • Organize your toolkit: Create collections of reusable chains and links, customized to your needs.
    • -
    • Download and extend: Acquire packages, modify them, and expand CodeUChain's capabilities.
    • -
    -

    This Marketplace will push CodeUChain to new frontiers, enhancing collaboration and innovation. Whether you're a developer, architect, or innovator, you'll find resources and inspiration to co-create powerful systems—together.

    - - - + +
    +
    +

    How It Flows

    +
    +
    + State → Link 1 → Link 2 → Link 3 → Result +
    +
    +          ↑ Hook observes each step ↑ +
    +
    +
    +
    +
    +
    + + + +
    +
    +
    +

    Developer Benefits

    +

    Practical advantages you get from day one

    +
    + +
    + +
    +
    +
    + 🧪 +
    +

    Testable by Default

    +
    +

    + Each Link is a pure function: State in, State out. Mock nothing — just pass test data. +

    +
    +
    result = myLink.call(State({ input: "test" }))
    +
    assert result.get("output") == expected
    +
    +
    + + +
    +
    +
    + 🔄 +
    +

    Reusable Components

    +
    +

    + Write a Link once, drop it into any Chain. Build a library of battle-tested building blocks. +

    +
    +
    orderChain.add(validateEmail) // reuse
    +
    signupChain.add(validateEmail) // reuse
    +
    +
    + + +
    +
    +
    + 🌍 +
    +

    One Pattern, Every Language

    +
    +

    + Same State → Link → Chain model in Python, Go, TypeScript, C#, Rust, Java, and C++. +

    +
    +
    // Learn once, apply everywhere
    +
    chain.add(link).execute(state)
    +
    +
    + + +
    +
    +
    + 🛡️ +
    +

    Contained Impact

    +
    +

    + Changes to one Link cannot break another. Errors stop the Chain without side effects. +

    +
    +
    // Link 2 fails? Links 3-5 never run.
    +
    // State stays immutable throughout.
    +
    +
    + + +
    +
    +
    + 📖 +
    +

    Self-Documenting

    +
    +

    + A Chain reads like a checklist. New developers understand the flow in seconds. +

    +
    +
    Chain: ValidateInput
    +
      → EnrichData → Save → Notify
    +
    +
    + + +
    +
    +
    + +
    +

    Opt-In Type Safety

    +
    +

    + Start untyped for speed. Add generics when you need compile-time guarantees. +

    +
    +
    Link[UserInput, UserOutput]
    +
    State[T].insertAs<U>(k, v)
    +
    +
    +
    +
    +
    + + + +
    +
    +
    +
    +
    + 🤖 + Built for AI Agents +
    +
    +

    AI-Ready Architecture

    +

    + The same structure that helps humans reason about code helps AI assistants generate, refactor, and extend it. +

    +
    + +
    +
    +
    +
    +
    + 🎯 +
    +

    Predictable Patterns

    +
    +

    + AI models thrive on consistent structure. Every Link follows the same contract, so generation is reliable. +

    +
    +
    // AI immediately understands the flow:
    +
    + ValidateInput → CheckCredentials → GenerateToken → LogSuccess +
    +
    +
    + +
    +
    +
    + 🔄 +
    +

    Incremental Generation

    +
    +

    + AI builds step by step, just like a developer: +

    +
    +
    Step 1: Generate ValidateEmail link
    +
    Step 2: Generate SaveToDatabase link
    +
    Step 3: Compose into UserRegistration chain
    +
    +
    +
    + +
    +
    +
    + 📚 +
    +

    Self-Documenting Structure

    +
    +
    +
    // The Chain tells the whole story:
    +
    + const UserAuthChain = Chain
    +   .add(ValidateCredentials)  // Check username/password
    +   .add(GenerateJWT)        // Create auth token
    +   .add(LogAuthEvent)        // Record the login
    +   .add(HandleAuthFailure)    // Deal with failures +
    +
    +
    +

    + AI reads Chain composition the same way humans do: clear intent, clear order, clear error handling. +

    +
    +
    +
    + + +
    +
    +

    Why It Works

    +
    +
    +
    +

    Consistent patterns for reliable AI output

    +
    +
    +
    +

    Type contracts for safe AI collaboration

    +
    +
    +
    +

    Clear structure for AI-assisted refactoring

    +
    +
    +
    +
    +
    +
    + + + +
    +
    +
    +

    Quick Start

    +

    Install and write your first chain in minutes

    +
    + +
    + +
    +

    📦 Install

    +
    + pip install codeuchain # Python +npm install codeuchain # JavaScript +cargo add codeuchain # Rust +go get github.com/codeuchain/codeuchain/go # Go +
    + +

    🧠 Mental Model

    +
    +
    + State + The data box flowing through your pipeline +
    +
    + Link + One focused unit of work — receives State, returns State +
    +
    + Chain + Ordered sequence of Links — runs them in order +
    +
    + Hook + Parallel observer — logging, metrics, caching +
    +
    +
    + + +
    +

    ⚡ Your First Chain

    +
    +
    # Universal pattern — same in every language
    +state  = new State({ user_id: 101 })
    +
    +chain = new Chain()
    +  .add(Link('fetch',   ctx -> fetch_user(ctx)))
    +  .add(Link('auth',    ctx -> check_role(ctx, 'admin')))
    +  .add(Link('process', ctx -> run_business_logic(ctx)))
    +
    +result = chain.execute(state)
    +
    +if result.error:
    +    handle_failure(result.error)
    +else:
    +    print(result.get('output'))
    +
    +
    +
    +
    +
    + + + +
    + +
    + -