Skip to content

Repository files navigation

Kōdo Logo

Kōdo

The programming language designed for AI agents — transparent for humans.

Status: AlphaLicense: MITVersion: v1.13.0Tests: 2800+ passingSelf-hosted: lexer + parserCoverage: pending


Why Kōdo?

AI agents are writing more and more production code. But the languages they write in were designed decades ago, for humans typing at keyboards. The result: ambiguous code, no correctness guarantees, no way to trace which agent wrote what, and no enforcement that safety-critical code was actually reviewed.

Kōdo is the first compiled language designed from scratch for AI agents to write, reason about, and maintain software — while remaining fully transparent and auditable by humans. It's not a framework, a linter, or a set of conventions bolted onto an existing language. It's a new language where the problems of AI-generated code are solved at the grammar level.

If your team uses AI agents to generate or maintain code, Kōdo gives you what no other language does: contract verification via SMT solver, compiler-enforced authorship tracking, and intent-driven code generation.

The Problem with AI + Existing Languages

ProblemWhat happens todayWhat Kōdo does
No correctness guaranteesAI generates code that "looks right" but has subtle bugsContracts (requires/ensures) verified by Z3 SMT solver at compile time
No authorship trackingYou can't tell which agent wrote which function@authored_by, @confidence, @reviewed_by — compiler-enforced
No trust enforcementLow-quality AI code ships without reviewCode below 0.8 confidence won't compile without human sign-off
Ambiguous semanticsAI hallucinates APIs, misunderstands ownershipZero-ambiguity LL(1) grammar, linear ownership (own/ref), no implicit conversions
Boilerplate generationAI generates repetitive glue code that rotsIntent blocks: declare what, compiler generates how
Opaque modulesAI generates code without explaining purposeMandatory meta blocks — every module is self-describing
Useless error messagesCompiler errors are for humans, not agentsStructured JSON errors with machine-applicable fix patches, Levenshtein suggestions
No repair loopAgent gets an error, guesses the fixkodoc fix applies patches automatically — agent reads error, applies fix, recompiles

What Makes Kōdo Different

1. Compiler-as-Reviewer: Trust Policies for AI Code

No other language tracks AI vs. human authorship with compiler enforcement. In Kōdo, every function can declare who wrote it, how confident the agent was, and whether a human reviewed it. The compiler uses this to reject unsafe AI code before it ships.

// High confidence — compiles without review
@authored_by(agent:"claude")
@confidence(0.95)fnadd(a:Int,b:Int) -> Int{return a + b
}// Low confidence — won't compile without human sign-off
@authored_by(agent:"claude")
@confidence(0.5)
@reviewed_by(human:"rafael")
fn experimental(a:Int, b:Int) -> Int{
return a * b
}// Security-sensitive — won't compile without contracts
@security_sensitive
fn safe_divide(a:Int, b:Int) -> Intrequires{ b != 0}{return a / b
}

Confidence propagation is transitive: if function A (confidence 0.95) calls function B (confidence 0.5), A's effective confidence drops to 0.5. You can't hide low-quality code behind a high-confidence wrapper. kodoc confidence-report visualizes the entire call graph with effective confidence scores.

Enforced policies:

  • @confidence below 0.8 → @reviewed_by(human: "...") required, or compilation fails (E0260)
  • @security_sensitive → at least one requires/ensures contract required (E0262)
  • min_confidence in module meta → all functions must meet the threshold (E0261)

2. Contracts as Grammar — Verified by Z3 Before Code Runs

Contracts aren't comments, decorators, or type annotations — they're part of the language syntax, verified by the Z3 SMT solver at compile time. The compiler doesn't just catch type errors; it catches logical errors.

fnsafe_divide(a:Int,b:Int) -> Intrequires{ b != 0}{return a / b
}fnclamp(value:Int,min:Int,max:Int) -> Intrequires{ min <= max }{if value < min {return min }if value > max {return max }return value
}

Why this matters for AI agents: an agent doesn't just generate code — it generates code with mathematical proof of correctness. When an agent writes requires { b != 0 }, the compiler verifies it at every call site. Bugs that would survive code review in other languages are caught at compile time.

3. Error Messages Designed for Machines (and Humans)

In most languages, error messages are formatted for humans. AI agents have to parse free-text output, guess what went wrong, and hope their fix is right. Kōdo's compiler is designed for agent consumption:

# Structured JSON with machine-applicable patches
kodoc check file.ko --json-errors
{
"code": "E0201",
"message": "undefined type `conter`",
"suggestion": "did you mean `counter`?",
"fix_patch": {
"description": "rename to closest match",
"start_offset": 42,
"end_offset": 48,
"replacement": "counter"
}
}
# Automatic error correction — no guessing
kodoc fix file.ko

What the compiler gives agents:

  • Unique error codes (E0001–E0699) with structured JSON — no regex parsing needed
  • Levenshtein-based suggestions — "did you mean counter?" for typos (E0201)
  • Machine-applicable fix patches — byte offsets + replacement text, apply without interpreting prose
  • kodoc fix — applies all patches automatically, creating a compile→fix→recompile loop
  • Complete explanationskodoc explain E0240 gives full context for any error code

This creates a closed-loop repair cycle: agent writes code → compiler returns structured error → agent applies fix patch → recompile. No ambiguity, no guessing.

4. Intent-Driven Programming

Declare what you want. The compiler generates how.

module intent_demo{
meta {purpose:"Demonstrates intent-driven programming in Kōdo",version:"1.0.0"}
intent console_app{greeting:"Hello from intent-driven Kōdo!"}}

No main(), no boilerplate. The intent block is a declaration of intent — the compiler expands it into concrete code at the AST level with full type checking. Think of it as a semantic macro, not a text substitution.

Why this matters for AI agents: less generated code = fewer bugs. The agent declares intent ("I want a console app that prints X") and the compiler guarantees the implementation is correct. Inspect what any intent generates with kodoc intent-explain.

5. Linear Ownership — Correct by Construction

Kōdo enforces linear ownership at the type level. Every value has exactly one owner. When a value is moved, it cannot be used again. Borrow with ref to share without transferring ownership. Use mut for exclusive mutable access — no other borrows may coexist.

fnconsume(own s:String){println(s)}fnborrow(ref s:String){println(s)}fnmain(){let msg:String = "hello"
borrow(msg)// OK — msg is borrowed, still usable
borrow(msg)// OK — msg is still ownedconsume(msg)// OK — msg is moved to consume// println(msg) // E0240: use-after-move}

Copy semantics for primitives:Int, Bool, Float, Byte are implicitly copied — only compound types (structs, strings) enforce move semantics. This eliminates false positives without sacrificing safety.

Why this matters for AI agents: agents frequently generate code with aliasing bugs, dangling references, and use-after-free. Kōdo catches these at compile time with clear, structured error messages that the agent can fix automatically.

6. Self-Describing Modules

Every Kōdo module must include a meta block. The compiler rejects code without it.

module payments{
meta {purpose:"Process recurring subscription payments",version:"2.1.0"}// ...}

AI agents and humans can understand any module's purpose without reading the implementation. Self-documentation isn't optional — it's enforced at the grammar level.


A Complete Language

Kōdo isn't just annotations on top of another language — it's a full compiled language with native binary output via Cranelift:

CategoryFeatures
Type systemInt, Float64, Bool, String, structs, enums, tuples ((Int, String)), generics with monomorphization and trait bounds (<T: Ord + Display>), dyn Trait (dynamic dispatch with vtables), local type inference, no implicit conversions
Pattern matchingExhaustive match on enums with destructuring, short variant patterns (Ok(v), Some(v) without enum prefix)
TestingBuilt-in test blocks, describe grouping with setup/teardown, @skip/@todo/@timeout annotations, @property + forall property-based testing with basic shrinking, kodoc generate-tests for contract-driven stub generation, kodoc test --json for agent consumption
ClosuresLambda lifting, capture analysis with ownership tracking (E0281–E0283), higher-order functions, (Int) -> Int types
OwnershipLinear ownership (own/ref/mut), Copy semantics for primitives, use-after-move (E0240), borrow-escapes-scope (E0241), move-while-borrowed (E0242), mut-borrow-while-ref-borrowed (E0245), ref-borrow-while-mut-borrowed (E0246), double-mut-borrow (E0247), assign-through-ref (E0248), closure capture ownership (E0281–E0283), atomic reference counting (thread-safe automatic deallocation)
Contractsrequires/ensures verified by Z3 SMT solver, runtime fallback, recoverable mode, module-level invariant blocks
Agent traceability@authored_by, @confidence, @reviewed_by, transitive confidence propagation, min_confidence threshold
Error repairMachine-applicable FixPatch in JSON, multi-step RepairPlan for complex errors, kodoc fix for auto-correction, Levenshtein suggestions for typos
Error handlingOption<T> and Result<T, E> in the prelude, ? operator for Result propagation — no null, no exceptions
Bare constructorsOk(v), Err(e), Some(v), and None work without Result::/Option:: prefix — desugared by the type checker and MIR lowering into existing enum variant representation
String interpolationf"Hello {name}!" — f-strings desugar to concatenation with automatic to_string
Inherent impl blocksimpl Point { fn distance(self) ... } — methods on structs without requiring a trait
Iterators & functionalIterator protocol for List<T>, String, Map<K,V>, Set<T>; functional combinators (map, filter, fold, reduce, count, any, all); functional pipelines
Standard libraryabs, min, max, clamp, string methods (length, contains, split, trim, to_upper, to_lower, substring, concat, index_of, replace, lines, parse_int), List<T> (push, get, pop, remove, set, slice, sort, join), Map<K,V> (Int and String keys), Set<T> (add, contains, remove, union, intersection, difference), methods on Option<T> and Result<T,E>, generic method dispatch, File I/O (file_read, file_write, file_append, file_delete, file_exists, dir_list, dir_exists), HTTP client (http_get, http_post returning Result<String, String>), HTTP server (http_server_new, http_server_recv, http_request_method/path/body, http_respond), JSON (json_parse, json_get_string, json_get_int, json_free, json_new_object, json_set_string/int/bool, json_stringify), CLI (args, readln, exit), Math (sqrt, pow, sin, cos, log, floor, ceil, round, rand_int), Regex (regex_match, regex_find, regex_replace)
Visibilitypub fn, pub struct — declarations are private by default, pub makes them accessible from other modules
Multi-fileimport module_name across .ko files, selective imports (import math { add, Point }), qualified calls (math.add(1, 2))
ConcurrencyGreen threads with M:N work-stealing scheduler, spawn on green threads (64KB stacks), async/await with Future<T>, parallel {} with OS threads, generic Channel<T> for any type, actor with state and message passing, cooperative yield points at loops and calls, --threads=N configuration
Developer toolsInteractive REPL (kodoc repl) with full compile-and-execute pipeline and persistent history (~/.kodo_history); LSP server with diagnostics, hover (full annotations), goto-definition (functions, variables, params, structs, enums), find-references (with include_declaration), contract-aware completions (31 builtins), and code actions from FixPatch; VSCode extension for seamless editor integration; Neovim plugin with syntax highlighting, indentation, and LSP support (setup guide); tree-sitter grammar for advanced syntax highlighting (tree-sitter-kodo); MCP server (kodo-mcp) with 7 tools including kodo.annotate for agent-driven contract inference via JSON-RPC over stdio; kodoc annotate --ai for LLM-assisted contract suggestion; JSON error output; kodoc explain for any error code; kodoc audit for consolidated trust reports
Package managerkodoc init (scaffold project with kodo.toml + src/main.ko), kodoc add (git or path dependencies), kodoc remove, kodoc update (re-resolve and update kodo.lock)
Build artifactsCompilation certificates (.ko.cert.json) with SHA-256 hashes, per-function confidence scores, per-function contract status (static_verified/runtime_only/no_contracts), and contract verification stats

Performance

BenchmarkKōdo (Inkwell)Kōdo (Cranelift)RustGoPython
fib(35)0.029s0.035s0.04s0.09s0.87s
sum 10M0.020s0.022s0.00s0.08s0.48s

Kōdo with the Inkwell (LLVM) backend is faster than Rust on recursive workloads and 4x faster than Go on tight loops. Concurrency-aware yield analysis skips overhead for pure functions — no unnecessary scheduling in computational code.

Two backends: Cranelift (default, fast compilation) and Inkwell (LLVM C API, --release flag, maximum runtime performance).


Quick Start

Option A: Download Pre-Built Binary

Download the latest release from the Releases page:

# macOS (Apple Silicon)
curl -L https://github.com/rfunix/kodo/releases/latest/download/kodoc-macos-aarch64 -o kodoc
# Linux (x86_64)
curl -L https://github.com/rfunix/kodo/releases/latest/download/kodoc-linux-x86_64 -o kodoc
chmod +x kodoc
sudo mv kodoc /usr/local/bin/

Option B: Build from Source

Prerequisites:Rust toolchain (1.91+) and a C linker (cc).

git clone https://github.com/rfunix/kodo.git
cd kodo
make install

This builds in release mode and installs kodoc to ~/.kodo/bin/. Add to your PATH:

echo'export PATH="$HOME/.kodo/bin:$PATH"'>>~/.zshrc
source~/.zshrc

Verify:

kodoc --version

Hello World

Create hello.ko:

module hello {
meta {purpose:"My first Kōdo program",version:"0.1.0",author:"Your Name"}fnmain(){println("Hello, World!")}}

Compile and run:

kodoc build hello.ko -o hello
./hello

Or try the interactive REPL:

kodoc repl
# kōdo> println("Hello from the REPL!")# kōdo> let x: Int = 2 + 3# kōdo> fn double(n: Int) -> Int { return n * 2 }# kōdo> double(x)

Examples

The examples/ directory contains 150 compilable programs:

Core Language

FileWhat it demonstrates
hello.koMinimal hello world
fibonacci.koRecursive functions
while_loop.koLoops and mutable variables
structs.koStruct definition and field access
struct_params.koStructs as function parameters and return values
enums.koEnum types and pattern matching
enum_params.koEnums as function parameters
expressions.koArithmetic and boolean expressions
for_loop.koFor loop iteration
optional_sugar.koOptional syntactic sugar (?., ??)
break_continue.koBreak and continue in loops
type_errors.koDemonstrates type error messages
type_inference.koLocal type inference for let bindings

Type System

FileWhat it demonstrates
generics.koGeneric enum types
generic_fn.koGeneric functions with monomorphization
option_demo.koOption<T> — no null values
result_demo.koResult<T, E> — explicit error handling
result_bare_constructors.koBare Ok/Err/Some/None constructors without Result::/Option:: prefix
try_operator.koResult pattern matching for error handling
flow_typing.koFlow-sensitive type narrowing
traits.koTrait definitions and static dispatch
generic_bounds.koGeneric trait bounds (<T: Ord>)
sorted_list.koBounded generics with sorted collections
advanced_traits.koAdvanced trait patterns
associated_types.koAssociated types in traits
methods.koInherent impl blocks — struct methods
tuples.koTuple types, literals, indexing, and destructuring

Functions & Closures

FileWhat it demonstrates
closures.koClosures and direct closure calls
closures_functional.koHigher-order functions and indirect calls
float_math.koFloat64 arithmetic operations
string_concat_operator.koString concatenation with + operator
string_interpolation.koF-string interpolation (f"Hello {name}")
stdlib_demo.koStandard library: abs, min, max, clamp
regex_demo.koRegex builtins: regex_match, regex_find, regex_replace

Contracts, Ownership & AI Traceability

FileWhat it demonstrates
contracts.koBasic contract syntax
contracts_demo.koRuntime contract checking (requires/ensures)
contracts_verified.koStatically verified contracts via Z3
contracts_smt_demo.koSMT solver contract verification demo
smt_verified.koSMT contract verification
recoverable_contracts.koRecoverable contract mode (--contracts=recoverable)
ownership.koLinear ownership with own/ref, move semantics for structs
borrow_rules.koBorrow rules: multiple ref borrows, mut exclusivity
move_semantics.koMove semantics, Copy vs non-Copy types
copy_semantics.koImplicit Copy for primitives vs move for compounds
confidence_demo.koTransitive confidence propagation through call graph
agent_traceability.ko@authored_by, @confidence, @reviewed_by, @security_sensitive
refinement_types.koRefinement types with requires constraints
refinement_smt.koSMT-verified refinement types
struct_predicates.koStruct field predicates in contracts
memory_management.koReference counting for heap-allocated values
module_invariant.koModule-level invariant blocks for global properties
visibility.kopub/private visibility for functions and structs

Intent System

FileWhat it demonstrates
intent_demo.koIntent-driven programming (console_app)
intent_math.koMath module intent resolver
intent_composed.koMultiple intents composed in one module
intent_http.koHTTP intent resolver
intent_database.koDatabase intent resolver
intent_json_api.koJSON API intent resolver
intent_cache.koCache intent resolver
intent_queue.koQueue intent resolver
intent_cli.koCLI tool intent resolver
intent_http_server.koHTTP server intent resolver
intent_file_processor.koFile processor intent resolver
intent_worker.koWorker loop intent resolver

Collections & I/O

FileWhat it demonstrates
list_demo.koList<T>list_new, list_push, list_get, list_length, list_contains
map_demo.koMap<K,V>map_new, map_insert, map_get, map_contains_key, map_length
set_operations.koSet<T>Set::new, add, contains, remove, length, union, intersection, difference
map_string_string.koMap<String, String> — generic map with String keys and values
map_string_int.koMap<String, Int> — generic map with String keys
map_int_string.koMap<Int, String> — generic map with String values
string_demo.koString methods including split, trim, to_upper, substring
for_in.koFor-in loops over List<T> collections
file_io_demo.koFile I/O: file_exists, file_read, file_write
http_client.koHTTP GET with Result<String, String>
time_env.koTime functions and environment variables
cli_args.koReading command-line arguments with args()
json_builder.koJSON construction: json_new_object, json_set_*, json_stringify
math_demo.koExtended math: rand_int
http_api.koHTTP server with JSON responses via tiny_http

Iterators, Functional Combinators & Methods

FileWhat it demonstrates
iterator_basic.koBasic iterator protocol
iterator_list.koIterating over List<T>
iterator_string.koIterating over String characters
iterator_map.koIterating over Map<K,V> entries
iterator_map_filter.komap and filter combinators on iterators
iterator_fold.kofold combinator for aggregation
functional_pipeline.koFunctional pipelines with chained combinators (map/filter/fold/count/any/all)
enum_methods.koMethods on Option<T> and Result<T,E> enum types
generic_method_dispatch.koGeneric method dispatch on parameterized types

Real-World Examples

FileWhat it demonstrates
todo_app.koAgent-built task manager with @authored_by, @confidence, forced @reviewed_by, contracts
config_validator.koConfig validation with refinement types (Port, MaxConns), @security_sensitive, module invariant
health_checker.koHealth checker with file_exists, fold aggregation, --json-errors for agent consumption
url_shortener.koURL shortener with @security_sensitive, contracts, Map<Int,Int> lookup
word_counter.koWord counter demonstrating ref borrowing (E0240 prevention), for-in over .split()
audit_log/Multi-file audit log: 15+ features (contracts, refinement types, agent traceability, functional pipelines, enums, pattern matching, multi-file imports)
self_hosted_lexer/Self-hosted lexer: a Kodo tokenizer written in Kodo itself — proves language expressiveness for compiler work

Concurrency & Multi-File

Note:spawn with captured variables, actor with state/message passing, parallel blocks, channels, and async/await with thread pool runtime are fully working.

FileWhat it demonstrates
async_demo.koasync fn / await — real green-thread concurrency
async_real_demo.koTwo concurrent async tasks, both awaited
async_real.koCooperative spawn syntax preview
async_tasks.koSpawn with captured variables
concurrency_demo.koConcurrency patterns
actors.koActor state and message passing
actor_demo.koActor demonstration
parallel_blocks.koStructured concurrency with parallel blocks
channels.koInter-thread communication with channels
channel_string.koGeneric typed channels
parallel_demo.koStructured concurrency with parallel {} and async runtime
qualified_imports.koQualified imports (math.add(1, 2))
selective_imports.koSelective imports (import { add } from math)
send_sync_demo.koSend/Sync bounds for thread safety
multi_file/Multi-file compilation with imports

Vericoding Benchmark

The bench/vericoding/ directory contains 20 formally verified programs equivalent to the AlgoVeri benchmark (77 algorithms in Dafny/Verus/Lean). Each task has:

  • A JSON spec with description, signature, and expected output
  • A Kōdo solution with requires/ensures contracts verified by Z3
cd bench/vericoding && ./run.sh --verbose # run all 20 tasks
./run.sh --json # JSON output for CI

Result: 20/20 tasks passing (100% success rate).


Compiler Architecture

Source (.ko)
│
▼
┌─────────────┐
│ kodo_lexer │ Token stream (logos-based DFA)
└──────┬──────┘
▼
┌─────────────┐
│ kodo_parser │ AST (hand-written recursive descent, LL(1))
└──────┬──────┘
▼
┌─────────────┐
│ kodo_types │ Type checking (no inference across modules)
└──────┬──────┘
▼
┌──────────────────┐
│ kodo_contracts │ Z3 SMT verification (static) + runtime fallback
└──────┬───────────┘
▼
┌────────────────┐
│ kodo_resolver │ Intent expansion (intent blocks → concrete code)
└──────┬─────────┘
▼
┌──────────────┐
│ kodo_desugar │ Syntactic desugaring (for loops, optional sugar)
└──────┬───────┘
▼
┌─────────────┐
│ kodo_mir │ Mid-level IR (CFG, basic blocks)
└──────┬──────┘
▼
┌─────────────────┐
│ MIR Optimizer │ Constant folding, DCE, copy propagation
└──────┬──────────┘
▼
┌──────────────┐
│ kodo_codegen │ Native binary (Cranelift)
└──────────────┘

13 crates in a Rust workspace. Zero circular dependencies. Zero clippy warnings.


Documentation


Contributing

See CONTRIBUTING.md for development guidelines.

cargo fmt --all # Format
cargo clippy --workspace -- -D warnings # Lint
cargo test --workspace # Test
make ui-test # Run UI tests
make validate-docs # Validate documentation examples
make validate-everything # Run ALL validation phases (fmt, clippy, test, ui-test, docs, examples, CLI)

License

MIT

About

Kōdo (コード) — A compiled programming language designed for AI agents to write, reason about, and maintain software

Resources

Code of conduct

Contributing

Security policy

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages