> ## Documentation Index
> Fetch the complete documentation index at: https://docs.astrakairo.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# How Kairo Works: A Developer's Tour of Every Command

> A developer-friendly walkthrough of every Kairo command: what it does, how it works, and when to reach for it. Read top-to-bottom or jump to the construct you're debugging.

This page is the "show me how the language actually works" guide. For every construct in Kairo v0.1, you get a plain-English answer to two questions: **what does this command do?** and **how does it work under the hood?** It's meant to be read like a tour, not a spec.

<Info>
  Looking for the exhaustive spec-style entries (syntax, prerequisites, thread-safety, opcodes)? See the [Command Catalog](/reference/command-catalog). This page focuses on intuition and mechanics.
</Info>

<Tip>
  Every example here compiles under Kairo v0.1. If something says "reserved" or "deferred," the keyword exists but the runtime behavior isn't ratified yet.
</Tip>

## How to read this page

Each entry follows the same shape:

* **What it does** — the one-sentence job of the construct.
* **How it works** — what actually happens when Forge sees it or Pulse runs it.
* **Example** — the smallest snippet that shows the mechanic.

Jump to a section:

<CardGroup cols={2}>
  <Card title="Project structure" icon="folder-tree" href="#project-structure">
    `module`, `import`, `.ak` files, `kairo.toml`
  </Card>

  <Card title="Visibility" icon="eye" href="#visibility">
    `public`, `internal`, `private`
  </Card>

  <Card title="Types" icon="shapes" href="#type-declarations">
    `value`, `object`, `contract`, `enum`
  </Card>

  <Card title="Members & callables" icon="function" href="#members-and-callables">
    fields, properties, `func`, `init`
  </Card>

  <Card title="Bindings & control flow" icon="route" href="#bindings-and-control-flow">
    `let`, `var`, `if`, `match`, `return`
  </Card>

  <Card title="Async" icon="bolt" href="#async">
    `async func`, `await`
  </Card>

  <Card title="Types & literals" icon="quote-left" href="#type-system-and-literals">
    `T?`, `null`, `Text`, numeric literals
  </Card>

  <Card title="Operators" icon="calculator" href="#operators">
    boolean, equality, comparison, arithmetic, `=`
  </Card>

  <Card title="Construction" icon="hammer" href="#construction">
    value construction, object construction
  </Card>

  <Card title="Error handling" icon="triangle-exclamation" href="#error-handling">
    `Result<T, E>`, `.success`, `.failure`, inspection
  </Card>

  <Card title="Collections & generics" icon="layer-group" href="#collections-and-generics">
    `List`, `Set`, `Map`, type parameters, constraints
  </Card>

  <Card title="Runtime" icon="play" href="#runtime">
    entrypoint, `Pulse.Console`
  </Card>
</CardGroup>

***

## Project structure

### `module`

**What it does.** Names the logical module a file belongs to.

**How it works.** Forge reads the `module` line as the authoritative identity for the file. File paths are a hint for humans, but they do not define meaning. One `module` per file, PascalCase segments separated by dots.

```kairo theme={null}
module Sales.Orders
```

### `import`

**What it does.** Pulls another module into the current file's scope.

**How it works.** Forge resolves the module name against package metadata. There are no wildcards, so what you import is exactly what you get. Imports go after `module` and before declarations.

```kairo theme={null}
module Demo.App

import Astra.Data
import Pulse.Console
```

### `import ... as`

**What it does.** Imports a module under a local alias.

**How it works.** The alias is a file-local rename for readability. It doesn't create a new module identity, and it must be unique within the file's imports.

```kairo theme={null}
import Astra.Net.Http as Http
```

### `import type`

**What it does.** Imports a specific type instead of a whole module.

**How it works.** Forge is strict about the distinction between a module and a type. `import type` tells the compiler you want the type, so it never has to guess.

```kairo theme={null}
import type Astra.Data.Database
```

### `.ak` source file

**What it does.** Holds Kairo source code.

**How it works.** Forge treats every `.ak` file under `src/` as compilable input, and files under `tests/` as test input. Each file must belong to a package with a `kairo.toml`.

### `kairo.toml`

**What it does.** Declares the package: its name, kind, version, dependencies, and runtime settings.

**How it works.** Forge reads `kairo.toml` before touching any source. It's the single source of truth for package identity and the application entrypoint.

```toml theme={null}
[package]
name = "Demo.App"
version = "0.1.0.0"
kind = "application"

[application]
entry = "Demo.App.main"

[runtime]
target = "pulse"
```

***

## Visibility

### `public`

**What it does.** Exposes a declaration outside its package.

**How it works.** Forge tracks a `public` declaration in the package's exported API. Anything not marked stays inside the package.

```kairo theme={null}
public value CustomerId {
    value: Text
}
```

### `internal`

**What it does.** Restricts a declaration to the same package.

**How it works.** `internal` is the default. You rarely need to type it; it exists so you can be explicit when you want to.

### `private`

**What it does.** Restricts a declaration to its declaring type or file.

**How it works.** Where you write `private` controls the scope: inside a type, it's type-private; at file scope, it's file-private.

```kairo theme={null}
public object Customer {
    public var name: Text

    private func validateName(name: Text): Bool {
        return name != ""
    }
}
```

***

## Type declarations

### `value`

**What it does.** Declares a value type: a fact-shaped, immutable-by-default piece of data.

**How it works.** Values have no identity. Two `Money` values with the same amount and currency are the same thing. Value members can only store other value-like types, which keeps object references from leaking into your fact model.

```kairo theme={null}
public value Money {
    amount: Decimal
    currency: Text
}
```

### `object`

**What it does.** Declares an object type: a participant with identity and lifecycle.

**How it works.** Objects have identity, so two `Customer`s with the same name are still different customers. `init` runs once at construction. `var` members can change after that; immutable members cannot.

```kairo theme={null}
public object Customer {
    public id: CustomerId
    public var name: Text

    public init(id: CustomerId, name: Text) {
        this.id = id
        this.name = name
    }
}
```

### `contract`

**What it does.** Declares a capability that other types can promise to satisfy.

**How it works.** A contract lists required methods and properties. It never provides bodies or stored fields. When a type conforms, Forge checks the shape matches.

```kairo theme={null}
public contract Named {
    name: Text
}
```

### Contract conformance `:`

**What it does.** Declares that a value or object satisfies one or more contracts.

**How it works.** Forge verifies the required members are present with matching signatures. Conformance is always explicit in v0.1, never inferred.

```kairo theme={null}
public object Customer : Named {
    public id: CustomerId
    public var name: Text

    public init(id: CustomerId, name: Text) {
        this.id = id
        this.name = name
    }
}
```

### `enum`

**What it does.** Declares a finite, named set of cases.

**How it works.** Each case is a distinct value of the enum type. Use enums for status, mode, or workflow state so `match` can branch on them.

```kairo theme={null}
public enum OrderStatus {
    Draft
    Submitted
    Paid
    Cancelled
}
```

***

## Members and callables

### Member field

**What it does.** Stores data on a value or object.

**How it works.** Members are immutable by default. Add `var` only when the field genuinely needs to change over an object's lifetime. Value members must be value-like.

```kairo theme={null}
public object Customer {
    public id: CustomerId
    public var name: Text
}
```

### Computed property

**What it does.** Declares a property whose value is calculated on read (and optionally written on set).

**How it works.** You write an explicit `get` and, if needed, `set(value: Type)`. Kairo does not auto-generate getters or setters in v0.1, so the behavior is always visible in code.

```kairo theme={null}
public object Customer {
    public var firstName: Text
    public var lastName: Text

    public fullName: Text {
        get {
            return firstName + " " + lastName
        }
    }
}
```

### `func`

**What it does.** Declares a function.

**How it works.** At module level, `func` is a free function. Inside a type, it's an instance method. Omitting the return type means "returns nothing."

```kairo theme={null}
public func calculateTotal(order: Order): Money {
    return order.total
}
```

### Instance method

**What it does.** Declares behavior owned by an instance of a type.

**How it works.** Inside a `value`, `this` is immutable. Inside an `object`, `this` refers to the identity-bearing instance and can mutate `var` members.

```kairo theme={null}
public object Customer {
    public var name: Text

    public func rename(newName: Text) {
        this.name = newName
    }
}
```

### `type func`

**What it does.** Declares a function owned by the type itself, not an instance.

**How it works.** No `this`; you call it through the type name. Great for named factories and type-scoped helpers.

```kairo theme={null}
public value EmailAddress {
    value: Text

    public type func create(value: Text): EmailAddress {
        return EmailAddress {
            value: value
        }
    }
}
```

### `init`

**What it does.** Initializes an object.

**How it works.** `init` runs once, assigns required immutable members, and cannot return a value. Kairo v0.1 allows exactly one primary `init` per object, so there is no overload resolution to reason about.

```kairo theme={null}
public init(id: CustomerId, name: Text) {
    this.id = id
    this.name = name
}
```

***

## Bindings and control flow

### `let`

**What it does.** Binds an immutable local.

**How it works.** Kairo infers the type when the initializer makes it obvious. The binding can't be reassigned.

```kairo theme={null}
let name: Text = "Pete"
let active = true
```

### `var`

**What it does.** Declares a mutable local or mutable member.

**How it works.** Local `var` requires an explicit type in v0.1. Mutability is always something you opt into, never a hidden default.

```kairo theme={null}
var count: Int32 = 0
count = count + 1
```

### `this`

**What it does.** Refers to the current value or object instance.

**How it works.** Only valid inside instance methods and object `init`. Free functions and `type func` do not have a `this`.

### `return`

**What it does.** Exits the current function or method, optionally with a value.

**How it works.** The returned expression must match the declared return type. Functions without a return type must return nothing.

```kairo theme={null}
public func answer(): Int32 {
    return 42
}
```

### `if / else`

**What it does.** Branches on a boolean condition.

**How it works.** The condition must be `Bool`. Kairo has no truthy or falsy coercions, so `if customer` will not compile; you write `if customer != null`.

```kairo theme={null}
if customer.name == "" {
    return 1
} else {
    return 0
}
```

### `match`

**What it does.** Branches on a pattern.

**How it works.** Statement `match` uses block arms. Expression `match` uses `Pattern => value` arms and must be exhaustive (use `else` as the fallback). Supported patterns in v0.1 are literals, enum cases, `null`, type names, and `else`.

```kairo theme={null}
let label: Text = match status {
    Draft => "Draft"
    Submitted => "Submitted"
    Paid => "Paid"
    else => "Unknown"
}
```

### `for` and `while` (reserved)

**What they do.** Nothing yet. Both keywords are reserved in v0.1.

**How it works.** Loop semantics are deferred until the next ratified stage. Use `match` or recursion patterns for now, or wait for the loop model to land.

***

## Async

### `async func`

**What it does.** Declares a function whose execution can suspend.

**How it works.** The language shape is frozen: `async` is part of the signature, so a caller can see suspension might happen. The async runtime is deferred, so today `async` is mostly a signal to Forge and future Pulse builds.

```kairo theme={null}
public async func fetchCustomer(id: CustomerId): Customer {
    return await CustomerApi.get(id)
}
```

### `await`

**What it does.** Marks a visible suspension point at a call site.

**How it works.** `await` waits for the awaited work to complete. It does not unwrap a `Result` and it does not spawn background work. It is only legal inside `async func`.

```kairo theme={null}
let customer = await fetchCustomer(customerId)
```

***

## Type system and literals

### Nullable type `T?`

**What it does.** Says "this holds a `T` or `null`."

**How it works.** Nullability is part of the type. `Customer` and `Customer?` are different types, and Forge will not let you assign `null` to a non-nullable slot. Nested nullables like `T??` are not part of v0.1.

```kairo theme={null}
public func findCustomer(id: CustomerId): Customer? {
    return null
}
```

### `null`

**What it does.** Represents "no value" for a nullable target.

**How it works.** `null` is only legal where the target type is nullable. It's the way you say "absent" without inventing sentinel values.

### `true` / `false`

**What they do.** Literal `Bool` values.

**How it works.** Booleans are strict. There is no truthy or falsy, no zero-equals-false rule.

### `Text` literal

**What it does.** Creates a `Text` value.

**How it works.** Kairo uses `Text` as the core textual type instead of `String`. Wrap in double quotes.

```kairo theme={null}
let message: Text = "Customer updated"
```

### Numeric literal

**What it does.** Represents a number.

**How it works.** Integer literals default to `Int64`. Fractional literals default to `Decimal`, because business math should be exact. `Float64` requires explicit typing or conversion. Overflow at compile time is an error, not a truncation.

```kairo theme={null}
let count: Int64 = 100
let price: Decimal = 125.50
```

***

## Operators

### Boolean operators

**What they do.** `not`, `and`, `or` on `Bool` values.

**How it works.** Kairo uses words instead of symbols so boolean logic reads like a sentence. Both operands must be `Bool`.

```kairo theme={null}
if not isValid or hasExpired {
    return false
}
```

### Equality operators

**What they do.** `==` and `!=` compare compatible values.

**How it works.** Custom equality rules are not part of v0.1, so equality is what the type declares by structure.

### Comparison operators

**What they do.** `<`, `<=`, `>`, `>=` on ordered types.

**How it works.** Operands must already be comparable and compatible. Kairo does not silently promote across numeric families.

### Arithmetic operators

**What they do.** `+`, `-`, `*`, `/`. `+` also concatenates `Text`.

**How it works.** No hidden numeric promotion. Add `Decimal` to `Decimal`, not `Decimal` to `Int64`.

```kairo theme={null}
let subtotal: Decimal = 100.00
let tax: Decimal = 10.00
let total: Decimal = subtotal + tax
```

### Assignment `=`

**What it does.** Assigns to a mutable target.

**How it works.** Only legal on `var` locals and `var` members. `let` bindings and immutable members are permanent after construction.

***

## Construction

### Value construction

**What it does.** Builds a value from its fields.

**How it works.** You write the type name followed by a field block. Every required field must be supplied exactly once.

```kairo theme={null}
let total = Money {
    amount: 125.50
    currency: "AUD"
}
```

### Object construction

**What it does.** Builds an object through its `init`.

**How it works.** You call the type like a function, but arguments must be named. There is no hidden default constructor for objects with required members.

```kairo theme={null}
let customer = Customer(
    id: customerId,
    name: "Pete"
)
```

***

## Error handling

### `Result<T, E>`

**What it does.** Represents an outcome that can be either a success with a `T` or an expected failure with an `E`.

**How it works.** `Result` is part of the Kairo Core prelude, so no import is needed. Expected business failures return `Result.failure`. Unexpected explosions become faults, which are a different category and are not wrapped in `Result`.

```kairo theme={null}
public func createEmail(value: Text): Result<EmailAddress, EmailFailure> {
    if value == "" {
        return Result.failure(EmailFailure.Empty)
    }

    return Result.success(EmailAddress {
        value: value
    })
}
```

### `Result.success`

**What it does.** Builds a successful `Result`.

**How it works.** The payload must be assignment-compatible with the declared success type. In v0.1 the surrounding context must supply the expected `Result<T, E>` type.

### `Result.failure`

**What it does.** Builds a failed `Result` for an expected business failure.

**How it works.** The failure payload must be value-like, so error types are safe to pass around and inspect.

### Result inspection

**What it does.** Reads a `Result` without destructuring.

**How it works.** Use `result.isSuccess` or `result.isFailure` to branch, then read `result.value` on success or `result.error` on failure. Reading the wrong side is a runtime fault, so always branch first.

```kairo theme={null}
let result = createEmail("pete@example.com")

match result.isSuccess {
    true {
        let email = result.value
        Pulse.Console.out.writeLine(email.value)
    }

    false {
        let failure = result.error
        Pulse.Console.error.writeLine("Could not create email")
    }
}
```

***

## Collections and generics

### `List<T>`

**What it does.** An immutable ordered collection.

**How it works.** `List<T>` is value-like only when `T` is value-like. You cannot store a list of objects as a value member.

### `Set<T>`

**What it does.** An immutable collection of unique values.

**How it works.** Same value-likeness rule as `List<T>`. Mutable set semantics are deferred.

### `Map<K, V>`

**What it does.** An immutable key-value collection.

**How it works.** Value-like only when both `K` and `V` are value-like. `Map<CustomerId, Customer>` is not a value if `Customer` is an object.

```kairo theme={null}
public value ExchangeRates {
    rates: Map<Text, Decimal>
}
```

### Generic type parameter

**What it does.** Parameterizes a declaration by another type.

**How it works.** You declare `T` in angle brackets on the type or contract. Callers supply the concrete type. Generic values may not store unconstrained parameters as value members in v0.1.

```kairo theme={null}
public contract Formatter<T> {
    func format(value: T): Text
}
```

### Generic contract constraint

**What it does.** Requires a type parameter to satisfy a contract.

**How it works.** Written as `T: ContractName`. Only contract constraints are supported in v0.1; multiple or non-contract constraints are deferred.

```kairo theme={null}
public contract Formatter<T: Displayable> {
    func format(value: T): Text
}
```

***

## Runtime

### Application entrypoint

**What it does.** Tells Pulse where to start executing your application.

**How it works.** Pulse reads `[application].entry` from `kairo.toml` and calls that module-level function. The function must be `public`. Nothing about filenames matters. Supported return types are `Int32` or `Result<Int32, E>`.

```toml theme={null}
[application]
entry = "Demo.App.main"
```

```kairo theme={null}
module Demo.App

public func main(): Result<Int32, AppFailure> {
    return Result.success(42)
}
```

### `Pulse.Console.out.write`

**What it does.** Writes to standard output without a newline.

**How it works.** This is a runtime service call, not a language keyword. You must `import Pulse.Console` and call it explicitly, so console I/O is always visible in code.

### `Pulse.Console.out.writeLine`

**What it does.** Writes to standard output and appends a newline.

**How it works.** Same rules as `write`. This is the workhorse for printing lines from a Kairo program.

```kairo theme={null}
import Pulse.Console

public func main(): Int32 {
    Pulse.Console.out.writeLine("Kairo is running")
    return 0
}
```

### `Pulse.Console.error.write` / `.writeLine`

**What they do.** Write to standard error, without or with a newline.

**How it works.** Routing to stderr is always explicit; Kairo will not silently redirect stdout to stderr based on content or exit code.

```kairo theme={null}
import Pulse.Console

public func main(): Int32 {
    Pulse.Console.error.writeLine("Something went wrong")
    return 1
}
```

***

## What's deliberately not here yet

These features have a place reserved in the language but do not have ratified runtime behavior in v0.1:

* Loop semantics for `for` and `while`
* Async runtime execution and task spawning
* Destructuring patterns and guards inside `match`
* Fault catching and recovery syntax
* Constructor overloading and delegation
* Extension methods and overload resolution
* Multiple or non-contract generic constraints
* Mutable collection model
* Broad numeric promotion rules

When the ratification for each of these lands, this page and the [Command Catalog](/reference/command-catalog) will grow with it.

## Next steps

<CardGroup cols={2}>
  <Card title="Command Catalog" icon="book" href="/reference/command-catalog">
    The full spec-style reference: syntax, prerequisites, thread-safety, and opcodes for every construct.
  </Card>

  <Card title="Quickstart" icon="rocket" href="/quickstart">
    Write, build, and run your first Kairo application end-to-end.
  </Card>

  <Card title="Language syntax" icon="code" href="/language/syntax">
    A deeper look at module and file structure.
  </Card>

  <Card title="Error handling" icon="triangle-exclamation" href="/language/error-handling">
    How `Result` and faults fit together in real programs.
  </Card>
</CardGroup>
