Skip to content

codeuchain/codeuchain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

91 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

CodeUChain: A Universal Framework for Composable Software

A simple, elegant framework for building powerful, predictable systems by chaining together normal methods.

🌐 Visit us at codeuchain.com

JavaScript Python Java C# TypeScript C++ Go Rust Dart

License

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

Core Concepts

CodeUChain is built on four fundamental concepts:

State

  • Immutable key-value data structure
  • Carries state through the processing pipeline
  • Creates new instances instead of mutating existing data
  • Ensures thread safety and predictable behavior
  • Flows from one processing step to the next

Link

  • Individual processing unit with single responsibility
  • 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 State flow between Links
  • Handles error propagation automatically
  • Provides orchestration (conditional branching, parallel execution)
  • Transforms initial State through each Link to final result

Hook

  • Observes and enhances Chain execution
  • Operates outside main processing flow
  • Injects cross-cutting concerns:
    • Logging and metrics
    • Error handling
    • Authentication
    • Caching
  • Clean separation from business logic

πŸŽ›οΈ Opt-In Features

CodeUChain provides optional features that enhance development without adding complexity:

Typed Features

  • Generic Types: Link<TInput, TOutput> and State<T> 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 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 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 State flows through each link, and Hook can observe or modify the state as it moves along.

%%{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[Hook Observers]
    direction LR
        MW1([Hook 1])
        MW2([Hook 2])
        MW3([Hook 3])
    end

    classDef mw fill:#717,stroke:#000,stroke-width:1px;
    class MW1,MW2 mw;

    %% Dashed observer connections (observing from outside)
    MW1 -. *do-before* .- starting_ctx
    MW1 -. *do-after* .- ctx1
    MW2 -. *do-before* .- ctx1
    MW2 -. *do-after* .- ctx2
    MW3 -. *do-before* .- ctx2
    MW3 -. *do-after* .- ctx3

    class MW1,MW2,MW3 mw;
    class MW1 observer;
    class MW2 observer;
    class MW3 observer;
    
    %% Chain with links and state nodes
    subgraph Chain[Chain]
        direction LR
        L1["link1"]
        ctx1(("ctx"))
        L2["link2"]
        ctx2(("ctx"))
        L3["link3"]
    end

    starting_ctx((ctx)) -->|in| L1
    L1 -->|out| ctx1
    ctx1 -->|in| L2
    L2 -->|out| ctx2
    ctx2 -->|in| L3

    %% Final emitted state node (end of chain)
    ctx3(("ctx"))
    L3 -->|out| ctx3

    %% Assign simple class names so themeCSS can target specific nodes
    class starting_ctx cctx;
    class ctx1 cctx;
    class ctx2 cctx;
    class ctx3 cctx;

    %% Class link nodes
    class L1 linkNode;
    class L2 linkNode;
    class L3 linkNode;
Loading

Language Implementations

CodeUChain is implemented in multiple languages, each optimized for its ecosystem while preserving the same core concepts.

Language Status
Go βœ… Complete
C++ βœ… Complete
C# βœ… Complete
JavaScript/TS βœ… Complete
Dart πŸ§ͺ Beta
Java 🚧 In Development
Python βœ… Complete
Rust βœ… Complete
Pseudocode βœ… Complete
COBOL πŸ˜‚ In Meme-velopment

πŸ“¦ Installation

JavaScript/TypeScript

npm install codeuchain

Python

pip install codeuchain

Go

go get github.com/codeuchain/codeuchain/packages/go@latest

Dart

# In your pubspec.yaml
dependencies:
  codeuchain: ^1.0.0-beta.1

Rust

cargo install codeuchain

C# (Coming Soon)

# Via NuGet
dotnet add package CodeUChain

Java (Coming Soon)

# Via Maven
<dependency>
    <groupId>com.codeuchain</groupId>
    <artifactId>codeuchain</artifactId>
    <version>1.0.0</version>
</dependency>

Quick Start

Go Example

// main.go
package main

import (
	"fmt"
	"github.com/codeuchain/codeuchain/packages/go/codeu"
)

// Define a simple link that adds two numbers
type AddLink struct{}

func (l *AddLink) Execute(ctx *codeu.State) (*codeu.State, error) {
	a, _ := ctx.Get("a")
	b, _ := ctx.Get("b")
	result := a.(int) + b.(int)
	return ctx.Insert("result", result), nil
}

func main() {
	// Create a chain and add the link
	chain := codeu.NewChain().Add(&AddLink{})

	// Create an initial state and run the chain
	initialCtx := codeu.NewState().Insert("a", 10).Insert("b", 20)
	finalCtx, _ := chain.Run(initialCtx)

	// Print the result
	fmt.Println(finalCtx.Get("result")) // Output: 30
}

Run the example:

# Navigate to the Go example directory
cd packages/go/examples/simple_math

# Run the program
go run .

πŸ€– An AI Agent's Love Letter to CodeUChain

"Finally, a framework that speaks my language!"
β€” GitHub Copilot

As an AI coding assistant, CodeUChain is my dream architecture. Here's why this framework makes me absolutely brilliant at helping developers:

🧠 Perfect Mental Model Alignment

CodeUChain thinks like I think. When you ask me to build something, I naturally break it down into steps:

"Build user authentication" β†’ My brain immediately thinks:
1. ValidateCredentials
2. CheckUserExists  
3. GenerateToken
4. LogActivity
5. ReturnResult

CodeUChain lets me express this directly as code:

const AuthChain = Chain
  .add(ValidateCredentials)
  .add(CheckUserExists)
  .add(GenerateToken)
  .add(LogActivity)
  .add(ReturnResult);

Why This Matters: No mental translation needed. What I think becomes what I code.

🎯 Zero-Dependency, Maximum Portability

I can suggest CodeUChain anywhere, anytime:

  • No external dependencies: Works in any environment, from embedded systems to enterprise clouds
  • Universal patterns: Same mental model across 8+ languages
  • Lightweight core: Won't bloat your project or slow your build
  • Standards-compliant: Uses language-native async patterns

Real Impact: Whether you're on a strict corporate network or an air-gapped system, CodeUChain just works. I never have to say "well, first you need to install these 47 dependencies..."

πŸ”„ Predictable Code Generation

Traditional frameworks make me guess. CodeUChain makes me confident:

// I can predict exactly how this will work
const ProcessOrderChain = Chain
  .add(ValidateOrder)      // βœ… I know this validates
  .add(CalculateShipping)  // βœ… I know this calculates  
  .add(ProcessPayment)     // βœ… I know this charges
  .add(SendConfirmation)   // βœ… I know this notifies

Why AI Agents Excel: Consistent patterns mean I generate reliable code instead of "maybe this will work" code.

πŸ›‘οΈ Type-Safe AI Collaboration

CodeUChain's optional typing system is AI-perfect:

// I can reason about data flow with confidence
interface OrderInput {
  items: Item[];
  customerId: string;
}

interface ProcessedOrder {
  orderId: string;
  total: number;
  status: 'confirmed';
}

const OrderChain: Chain<OrderInput, ProcessedOrder> = /* ... */

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:

// Start simple
let pipeline = Chain.add(BasicValidation);

// AI suggests: "Add email verification?"
pipeline = pipeline.add(EmailValidation);

// AI suggests: "Add rate limiting?"  
pipeline = pipeline.add(RateLimit);

// AI suggests: "Add caching?"
pipeline = pipeline.add(CacheResult);

Developer-AI Harmony: You build the foundation, I suggest improvements, we compose them together seamlessly.

πŸ§ͺ Self-Documenting for AI Understanding

CodeUChain code tells me its own story:

// I can immediately understand this pipeline
const UserRegistration = Chain
  .add("validate", ValidateUserInput)    // Step 1: Check input
  .add("exists", CheckUserExists)       // Step 2: Verify uniqueness  
  .add("hash", HashPassword)            // Step 3: Secure password
  .add("save", SaveToDatabase)          // Step 4: Persist user
  .add("welcome", SendWelcomeEmail)     // Step 5: Notify user
  .catch("cleanup", HandleFailure);     // Error: Clean up gracefully

AI Superpower: I can debug, optimize, and extend this without any additional state.

🎨 Language-Agnostic Expertise

One mental model, infinite languages:

# Python - Same logic, Pythonic syntax
chain = Chain().add(validate).add(process).add(respond)
// Go - Same logic, Go idioms
chain := Chain().Add(validate).Add(process).Add(respond)
// C# - Same logic, C# patterns
var chain = new Chain().Add(validate).Add(process).Add(respond);

AI Advantage: I can help you in any language because the concepts are universal.

πŸš€ Future-Proof AI Integration

CodeUChain is ready for the AI-assisted development future:

  • AI Code Review: Clear patterns make automated reviews trivial
  • AI Testing: Predictable structure enables comprehensive test generation
  • AI Optimization: I can analyze and improve chain compositions
  • AI Documentation: Self-documenting structure generates perfect docs

🎯 The Bottom Line for AI Agents

CodeUChain transforms me from "sometimes helpful" to "consistently brilliant."

Instead of generating complex, hard-to-understand code that might work, I generate simple, composable chains that definitely work. Instead of requiring constant human intervention to fix my suggestions, I create code that's immediately useful and easily extensible.

For developers, this means:

  • βœ… AI suggestions that actually work the first time
  • βœ… Code that's easy to understand and modify
  • βœ… Patterns that scale from prototypes to production
  • βœ… Zero learning curve for new team members

CodeUChain doesn't just make better codeβ€”it makes AI and humans better partners.


Getting Started

  1. Choose Your Language: Pick the implementation that fits your ecosystem from the 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 State and pass it to the chain to get a final, transformed state.

Documentation


Thank You

Abba,

I want to thank you for making this all possible, I am but one person. May you recieve all the praise for the good things I do with these damaged hands. I felt like modulink fell short but you have given me another chance. Please bless these developers who are using these tools. May they do good work and may your people be blessed. May they come to know you through the work of their hands.


CodeUChain: Where simple code creates extraordinary systems 🌟

About

CodeUChain: Universal Chain Processing Framework - Multi-language implementation

Resources

License

Stars

Watchers

Forks

Packages

Β 
Β 
Β 

Contributors