core

package module
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2026 License: EUPL-1.2, EUPL-1.2 Imports: 57 Imported by: 0

README

CoreGO

Dependency injection, service lifecycle, permission, and message-passing for Go.

import "dappco.re/go/core"

CoreGO is the foundation layer for the Core ecosystem. It gives you:

  • one container: Core
  • one input shape: Options
  • one output shape: Result
  • one command tree: Command
  • one message bus: ACTION, QUERY + named Action callables
  • one permission gate: Entitled
  • one collection primitive: Registry[T]

Quick Example

package main

import "dappco.re/go/core"

func main() {
    c := core.New(
        core.WithOption("name", "agent-workbench"),
        core.WithService(cache.Register),
        core.WithServiceLock(),
    )
    c.Run()
}

Core Surfaces

Surface Purpose
Core Central container and access point
Service Managed lifecycle component
Command Path-based executable operation
Action Named callable with panic recovery + entitlement
Task Composed sequence of Actions
Registry[T] Thread-safe named collection
Process Managed execution (Action sugar)
API Remote streams (protocol handlers)
Entitlement Permission check result
Data Embedded filesystem mounts
Drive Named transport handles
Fs Local filesystem (sandboxable)
Config Runtime settings and feature flags

Install

go get dappco.re/go/core

Requires Go 1.26 or later.

Test

go test ./...    # 483 tests, 84.7% coverage

Docs

The authoritative API contract is docs/RFC.md (21 sections).

License

EUPL-1.2

Documentation

Overview

Named action system for the Core framework. Actions are the atomic unit of work — named, registered, invokable, and inspectable. The Action registry IS the capability map.

Register a named action:

c.Action("git.log", func(ctx Context, opts core.Options) core.Result {
    dir := opts.String("dir")
    return c.Process().RunIn(ctx, dir, "git", "log")
})

Invoke by name:

r := c.Action("git.log").Run(ctx, core.NewOptions(
    core.Option{Key: "dir", Value: "/path/to/repo"},
))

Check capability:

if c.Action("process.run").Exists() { ... }

List all:

names := c.Actions()  // ["process.run", "agentic.dispatch", ...]

Remote communication primitive for the Core framework. API manages named streams to remote endpoints. The transport protocol (HTTP, WebSocket, SSE, MCP, TCP) is handled by protocol handlers registered by consumer packages.

Drive is the phone book (WHERE to connect). API is the phone (HOW to connect).

Usage:

// Configure endpoint
c.Drive().New(core.NewOptions(
    core.Option{Key: "name", Value: "charon"},
    core.Option{Key: "transport", Value: "http://10.69.69.165:9101/mcp"},
))

// Open stream
s := c.API().Stream("charon")
if s.OK { stream := s.Value.(Stream) }

// Remote Action dispatch
r := c.API().Call("charon", "agentic.status", opts)

AX-shaped assertions for the Core test framework.

The Assert* family records a non-fatal failure; the Require* family records and stops the test. Both wrap testing.TB so helpers compose across Test, Benchmark, and Fuzz contexts.

Output format

Default is the AX one-line key=value shape — minimalist, grep-able, AI-readable:

fs_test.go:144: AssertEqual want="hello" got="world"
fs_test.go:147: AssertNoError got=open foo: no such file or directory

Set core.AssertVerbose = true (e.g. in TestMain or a setup hook) to switch to the multi-line "standard output" format more familiar from testify and human-driven test triage:

fs_test.go:144: AssertEqual failed
    want: "hello"
    got:  "world"

The flag is global to the test process. Pass = silent in either mode (Go test default).

Usage

core.AssertEqual(t, "expected", actual)
core.AssertTrue(t, result.OK)
core.AssertNoError(t, err)
core.AssertContains(t, []string{"a", "b"}, "a")
core.RequireNoError(t, c.Fs().Write(p, "data").Error())

Optional trailing string args are joined into a context suffix on the failure line.

Cli is the CLI surface layer for the Core command tree.

c := core.New(core.WithOption("name", "myapp")).Value.(*Core)
c.Command("deploy", core.Command{Action: handler})
c.Cli().Run()

AX-10 CLI test assertions for the Core framework.

CLITest declares a single binary scenario; AssertCLI dispatches it through c.Process() (so the Core must register a "process.run" service — typically dappco.re/go-process). AssertCLIs runs a table-driven set of cases under sub-tests.

Pair these with `tests/cli/{path}/Taskfile.yaml` per AX-10 — the Taskfile drives the `go test` invocation and the CLITest values describe the binary behaviour fixtures.

Command is a DTO representing an executable operation. Commands don't know if they're root, child, or nested — the tree structure comes from composition via path-based registration.

Register a command:

c.Command("deploy", func(opts core.Options) core.Result {
    return core.Result{"deployed", true}
})

Register a nested command:

c.Command("deploy/to/homelab", handler)

Description is an i18n key — derived from path if omitted:

"deploy"             → "cmd.deploy.description"
"deploy/to/homelab"  → "cmd.deploy.to.homelab.description"

Context primitives — re-exports of Go's standard context package as Core types, so consumers never need to write `import "context"`.

ctx, cancel := core.WithTimeout(core.Background(), 5*core.Second)
defer cancel()
r := c.Action("git.log").Run(ctx, opts)

Data is the embedded/stored content system for core packages. Packages mount their embedded content here and other packages read from it by path.

Mount a package's assets:

c.Data().New(core.NewOptions(
    core.Option{Key: "name", Value: "brain"},
    core.Option{Key: "source", Value: brainFS},
    core.Option{Key: "path", Value: "prompts"},
))

Read from any mounted path:

content := c.Data().ReadString("brain/coding.md")
entries := c.Data().List("agent/flow")

Extract a template directory:

c.Data().Extract("agent/workspace/default", "/tmp/ws", data)

Built-in introspection actions — the capability map made queryable. Every Core answers these three (entitlement-gated at Run like any other action), so an agent can walk a mesh of Core apps discovering what each one can do:

r := c.API("codex").Discover()                       // remote peer
r = c.Action("core.actions").Run(ctx, core.NewOptions()) // local

With the colon law, discovery composes: register a Drive handle for a peer and c.Action("peer:core.actions") resolves transparently.

Drive is the resource handle registry for transport connections. Packages register their transport handles (API, MCP, SSH, VPN) and other packages access them by name.

Register a transport:

c.Drive().New(core.NewOptions(
    core.Option{Key: "name", Value: "api"},
    core.Option{Key: "transport", Value: "https://api.lthn.ai"},
))
c.Drive().New(core.NewOptions(
    core.Option{Key: "name", Value: "ssh"},
    core.Option{Key: "transport", Value: "ssh://claude@10.69.69.165"},
))
c.Drive().New(core.NewOptions(
    core.Option{Key: "name", Value: "mcp"},
    core.Option{Key: "transport", Value: "mcp://mcp.lthn.sh"},
))

Retrieve a handle:

api := c.Drive().Get("api")

Embedded assets for the Core framework.

Embed provides scoped filesystem access for go:embed and any FS. Also includes build-time asset packing (AST scanner + compressor) and template-based directory extraction.

Usage (mount):

sub, _ := core.Mount(myFS, "lib/persona")
content, _ := sub.ReadString("secops/developer.md")

Usage (extract):

core.Extract(fsys, "/tmp/workspace", data)

Usage (pack):

refs, _ := core.ScanAssets([]string{"main.go"})
source, _ := core.GeneratePack(refs)

Encoding helpers for the Core framework. Wraps encoding/hex so consumers can use core primitives for common byte-string encodings.

Permission primitive for the Core framework. Entitlement answers "can [subject] do [action] with [quantity]?" Default: everything permitted (trusted conclave). With go-entitlements: checks workspace packages, features, usage, boosts. With commerce-matrix: checks entity hierarchy, lock cascade.

Usage:

e := c.Entitled("process.run")           // boolean gate
e := c.Entitled("social.accounts", 3)    // quantity check
if e.Allowed { proceed() }
if e.NearLimit(0.8) { showUpgradePrompt() }

Registration:

c.SetEntitlementChecker(myChecker)
c.SetUsageRecorder(myRecorder)

Formatting and printing primitives — re-exports of Go's fmt package as Core helpers, so consumers never need to write `import "fmt"`. SPOR file for fmt: every Sprintf/Sprint/Println/Print in core/go and downstream packages routes through here.

core.Println("agent", agent.Name, "ready")
msg := core.Sprintf("%s connected on %d", host, port)

Sandboxed local filesystem I/O for the Core framework.

System information registry for the Core framework. Read-only key-value store of environment facts, populated once at init. Env is environment. Config is ours.

System keys:

core.Env("OS")        // "darwin"
core.Env("ARCH")      // "arm64"
core.Env("GO")        // "go1.26"
core.Env("DS")        // "/" (directory separator)
core.Env("PS")        // ":" (path list separator)
core.Env("HOSTNAME")  // "cladius"
core.Env("USER")      // "snider"
core.Env("PID")       // "12345"
core.Env("NUM_CPU")   // "10"

Directory keys:

core.Env("DIR_HOME")      // "/Users/snider"
core.Env("DIR_CONFIG")    // "~/Library/Application Support"
core.Env("DIR_CACHE")     // "~/Library/Caches"
core.Env("DIR_DATA")      // "~/Library" (platform-specific)
core.Env("DIR_TMP")       // "/tmp"
core.Env("DIR_CWD")       // current working directory
core.Env("DIR_DOWNLOADS") // "~/Downloads"
core.Env("DIR_CODE")      // "~/Code"

Timestamp keys:

core.Env("CORE_START")  // "2026-03-22T14:30:00Z"

Integer conversion helpers for the Core framework. Wraps strconv so consumers don't import it directly.

Base I/O primitives for the Core framework.

Re-exports stdlib io interfaces and the EOF sentinel as core types so consumer packages declare Reader/Writer parameters via core without importing io directly. Bundle size is unaffected by aliases — they resolve to the same underlying types — but the AX-6 import-line cost drops to zero for typed-parameter use.

Usage:

func handle(r core.Reader, w core.Writer) error { ... }

if errors.Is(err, core.EOF) { ... }

n := core.Copy(dst, src)
if !n.OK { return n }

Iterator primitives — re-exports of Go's iter package as Core types, so consumers never need to write `import "iter"`. Sequences yielded by core helpers (Fs.WalkSeq, Slice generators, etc.) all use these aliases.

for path := range c.Fs().WalkSeq(root) {
    Println(path)
}

JSON helpers for the Core framework. Wraps encoding/json so consumers don't import it directly. Same guardrail pattern as string.go wraps strings.

Usage:

data := core.JSONMarshal(myStruct)
if data.OK { json := data.Value.([]byte) }

r := core.JSONUnmarshal(jsonBytes, &target)
if !r.OK { /* handle error */ }

Structured logging for the Core framework.

core.SetLevel(core.LevelDebug)
core.Info("server started", "port", 8080)
core.Error("failed to connect", "err", err)

Language Server Protocol implementation for the Core framework.

LSPServe starts a JSON-RPC-over-stdio Language Server that surfaces the same drift signals as tests/cli/imports, tests/cli/naming, and tests/cli/test_imports — but as inline editor diagnostics. Editors (VS Code, Zed) and AI agents (Claude Code, Codex) connect over stdio and receive textDocument/publishDiagnostics on every save, closing the feedback loop from "fail at CI" to "fail at keystroke".

Architecture

The server core handles LSP plumbing — message framing, method dispatch, document state. Diagnostic-producing logic lives in pluggable DiagnosticSource functions registered via LSPRegisterDiagnostic. The default registration includes test-imports, result-shape, SPOR, and AX-7 drift sources.

Wire protocol

LSP messages frame on stdin/stdout as:

Content-Length: N\r\n
\r\n
{ JSON-RPC body }

The body uses jsonrpc 2.0. core/go ships zero stdlib LSP deps; JSON marshalling routes through core.JSONMarshal/Unmarshal.

Usage

c := core.New()
core.LSPServe(core.Background())  // blocks until stdin closes

Editor integration: point the LSP client at the binary and use stdio transport. No port, no socket — straight pipes.

Network primitives for the Core framework.

Re-exports stdlib net types and provides Result-shape constructors for the common Dial / Listen / ParseIP patterns. Consumer packages reach IP/Conn/Listener types via core without importing net directly.

Higher-level HTTP machinery lives alongside Stream in api.go (see HTTPGet / HTTPServer / HTTPClient). What's here is the lower layer — TCP/UDP/Unix sockets, IP parsing, and the connection interfaces HTTP and other protocols build on top of.

Usage:

addr := core.ParseIP("192.0.2.1")
if addr == nil { return core.E("bad", "invalid IP", nil) }

conn := core.NetDial("tcp", "10.0.0.1:8080")
if !conn.OK { return conn }
defer conn.Value.(core.Conn).Close()

a, b := core.NetPipe()  // in-memory test connection pair

Core primitives: Option, Options, Result.

Options is the universal input type. Result is the universal output type. All Core operations accept Options and return Result.

opts := core.NewOptions(
    core.Option{Key: "name", Value: "brain"},
    core.Option{Key: "path", Value: "prompts"},
)
r := c.Drive().New(opts)
if !r.OK { log.Fatal(r.Error()) }

Base OS primitives for the Core framework.

Re-exports stdlib os value types and the standard streams so consumer packages declare FileMode parameters and reach Stdin/Stdout/Stderr without importing os directly.

File operations live on c.Fs() (sandbox-aware). Environment lookups live on core.Env. Process control lives on c.Process() / go-process. What's here is the connecting tissue: types, constants, and the canonical stdio streams that boundary code can't avoid.

Usage:

func writeMode(p string, mode core.FileMode) { ... }

core.WriteString(core.Stderr(), "diagnostic\n")

if mode.Perm()&core.ModePerm == 0o600 { ... }

OS-aware filesystem path operations for the Core framework. Uses Env("DS") for the separator and Core string primitives for path manipulation. filepath imported only for PathGlob.

Path anchors relative segments to DIR_HOME:

core.Path("Code", ".core")     // "/Users/snider/Code/.core"
core.Path("/tmp", "workspace") // "/tmp/workspace"
core.Path()                    // "/Users/snider"

Path component helpers:

core.PathBase("/Users/snider/Code/core")  // "core"
core.PathDir("/Users/snider/Code/core")   // "/Users/snider/Code"
core.PathExt("main.go")                   // ".go"

Process is the Core primitive for managed execution. Methods emit via named Actions — actual execution is handled by whichever service registers the "process.*" actions (typically go-process).

If go-process is NOT registered, all methods return Result{OK: false}. This is permission-by-registration: no handler = no capability.

Usage:

r := c.Process().Run(ctx, "git", "log", "--oneline")
if r.OK { output := r.Value.(string) }

r := c.Process().RunIn(ctx, "/path/to/repo", "go", "test", "./...")

Permission model:

// Full Core — process registered:
c := core.New(core.WithService(process.Register))
c.Process().Run(ctx, "git", "log")  // works

// Sandboxed Core — no process:
c := core.New()
c.Process().Run(ctx, "git", "log")  // Result{OK: false}

Reflection primitives — re-exports of Go's standard reflect package as Core types, so consumers never need to write `import "reflect"`. Reflection is a low-level tool; reach for it only when generic constraints and type switches genuinely cannot express the operation.

if core.TypeOf(v).Kind() == core.KindStruct { ... }

Compiled regular expression primitive for the Core framework. Wraps stdlib regexp with the Result-shape error pattern.

Usage:

r := core.Regex(`\d+`)
if !r.OK { return r }
rx := r.Value.(*Regex)

rx.MatchString("foo123bar")     // true
rx.FindString("hello 42 world") // "42"
rx.FindAllString("a1 b2 c3", -1) // ["1","2","3"]
rx.ReplaceAllString("a1b2", "X") // "aXbX"
rx.Split("a,b,,c", -1)          // ["a","b","","c"]

Thread-safe named collection primitive for the Core framework. Registry[T] is the universal brick — all named registries (services, commands, actions, drives, data) embed this type.

Usage:

r := core.NewRegistry[*MyService]()
r.Set("brain", brainSvc)
r.Get("brain")              // Result{brainSvc, true}
r.Has("brain")              // true
r.Names()                   // []string{"brain"} (insertion order)
r.Each(func(name string, svc *MyService) { ... })
r.Lock()                    // fully frozen — no more writes
r.Seal()                    // no new keys, updates to existing OK

Three lock modes:

Open   (default) — anything goes
Sealed — no new keys, existing keys CAN be updated
Locked — fully frozen, no writes at all

Result ergonomics — methods and free functions that collapse the common Result-handling patterns into one-liners. Result itself is defined in options.go alongside Options as a Core primitive; this file extends it with the call-site helpers.

user := core.MustCast[*User](c.Drive().Get(opts))
timeout := core.HTTPGet(url).Or(defaultResp)

Return[T] — the typed twin of Result for leaf functions with one concrete return type. Flat: a direct Value OR an error, with Err as the discriminant. Result stays the universal bus type; Return[T] gives compile-time typing at call boundaries so consumers never type-assert.

The law (see PLAN-v0.12.0.md W1-3):

  1. Anything crossing a type-erasing boundary — IPC, registries, Actions, Tasks, RegistryOf — returns Result. No exceptions.

  2. Leaf functions with one concrete struct-shaped return may declare Return[T].

  3. Scalars use Result and its typed getters, never lifted into Return. One symbol never offers both shapes.

    func UserByName(name string) core.Return[*User] { return core.ReturnFrom(lookup(name)) } u := UserByName("snider").Log("svc.Auth", "lookup failed").Or(guest)

SQL database primitive for the Core framework.

Re-exports stdlib database/sql types and provides a Result-shape Open. Consumer packages declare DB / Tx / Rows / Stmt parameters via core without importing database/sql directly.

Driver registration stays the canonical Go pattern — import the driver package for its init-time side effect:

import _ "github.com/mattn/go-sqlite3"
r := core.SQLOpen("sqlite3", "file:./data.db?_pragma=journal_mode(WAL)")
if !r.OK { return r }
db := r.Value.(*DB)
defer db.Close()

ErrNoRows is the canonical sentinel for "no row matched" queries.

if core.Is(err, core.ErrNoRows) { /* not found */ }

Text templating primitive for the Core framework.

Re-exports stdlib text/template types and provides Result-shape constructors for Compile / Parse / Execute. Consumer packages declare Template / FuncMap parameters via core without importing text/template directly.

Usage:

r := core.NewTemplate("greeting").Parse("Hello {{.Name}}!")
if !r.OK { return r }
tmpl := r.Value.(*Template)

var buf bytes.Buffer
er := core.ExecuteTemplate(tmpl, &buf, map[string]string{"Name": "Snider"})
if !er.OK { return er }

AX-shaped test framework for the Core ecosystem.

The framework is split across three production files for AX-3 path-as-documentation:

  • test.go — Go-runner aliases (T/TB/B/F) + AnError sentinel. The single SPOR import of the testing package.
  • assert.go — Assert*/Require* family + AssertVerbose flag. The minimalist-by-default failure-output engine.
  • cli_assert.go — CLITest/AssertCLI/AssertCLIs for AX-10 binary validation through c.Process().

Test files use a single dot-import — `. "dappco.re/go"` — and the runner picks them up by signature because *T is type-identical to *testing.T. No `import "testing"` line in any consumer file.

package mypkg_test

import . "dappco.re/go"

func TestRepository_Sync_Good(t *T) {
    r := svc.SyncRepository("agent", "/srv/repos/agent")
    AssertTrue(t, r.OK)
    AssertEqual(t, "synced", r.Value.(string))
}

Pass = silent (Go test default). Fail emits the AX one-line shape by default; flip core.AssertVerbose=true for the testify-style multi-line format. See assert.go for the full helper catalogue.

Unicode rune helpers for the Core framework. Wraps unicode so consumers don't import it directly.

URL helpers for the Core framework. Wraps net/url so consumers can use core primitives for URL parsing and escaping.

User identity primitives — re-exports of Go's os/user package as Core types, so consumers never need to write `import "os/user"`. Used by filesystem path resolution (~ expansion) and log identity.

r := core.UserCurrent()
if r.OK { homeDir := r.Value.(*core.User).HomeDir }
Example (OpenFileNoFollow)

Example_openFileNoFollow refuses to open a symlinked final path component through `O_NOFOLLOW`. The flag carries a real symlink-refusal semantic only on unix — it is 0 (a no-op) on Windows, so this example is built only under !windows, matching os_nofollow_unix.go's own build tag.

NOTE: this cannot be named ExampleO_NOFOLLOW — go vet's example-association parser splits an Example name on its FIRST underscore and treats the head as the target identifier, so ExampleO_NOFOLLOW resolves to "O" (unknown) and go vet — and `go test`'s automatic pre-test vet subset — hard-fails the whole package build with "refers to unknown identifier: O" (same failure mode as SHA3_256, confirmed with a standalone repro). Any exported identifier containing an underscore is unnameable as a symbol-attached Example under Go's own naming grammar; the package-level leading-underscore form used here is the only mechanism that stays vet-clean.

dir := TempDir()
target := PathJoin(dir, "real.log")
link := PathJoin(dir, "current.log")
WriteFile(target, []byte("ready"), 0o600)
Symlink(target, link)
defer Remove(target)
defer Remove(link)

r := OpenFile(link, O_CREATE|O_EXCL|O_NOFOLLOW|O_WRONLY, 0o600)
Println(r.OK)
Output:
false
Example (Sha3_256)

Example_sha3_256 hashes a byte payload with SHA3-256 for Ethereum-compatible digest work. SHA3 and Keccak helpers cover Ethereum-compatible digest inputs without direct crypto imports.

NOTE: this cannot be named ExampleSHA3_256 — go vet's example-association parser splits an Example name on its FIRST underscore and treats the head as the target identifier, so ExampleSHA3_256 resolves to "SHA3" (unknown) and go vet — and `go test`'s automatic pre-test vet subset — hard-fails the whole package build with "refers to unknown identifier: SHA3". Confirmed with a standalone repro. Any exported identifier containing an underscore (SHA3_256, SHA3_256Hex) is unnameable as a symbol-attached Example under Go's own naming grammar; the package-level leading-underscore form used here is the only mechanism that stays vet-clean.

sum := SHA3_256([]byte("hello"))
Println(HexEncode(sum[:])[:16])
Output:
3338be694f50c5f3
Example (Sha3_256Hex)

Example_sha3_256Hex hashes a byte payload and renders SHA3-256 hex for Ethereum-compatible digest work. SHA3 and Keccak helpers cover Ethereum-compatible digest inputs without direct crypto imports.

NOTE: see Example_sha3_256 — ExampleSHA3_256Hex has the same go-vet-breaking shape.

Println(SHA3_256Hex([]byte("hello"))[:16])
Output:
3338be694f50c5f3

Index

Examples

Constants

View Source
const (
	MethodGet     = http.MethodGet
	MethodHead    = http.MethodHead
	MethodPost    = http.MethodPost
	MethodPut     = http.MethodPut
	MethodPatch   = http.MethodPatch
	MethodDelete  = http.MethodDelete
	MethodConnect = http.MethodConnect
	MethodOptions = http.MethodOptions
	MethodTrace   = http.MethodTrace
)

HTTP method constants. Re-exported from net/http so consumers reach methods through core without importing net/http.

r := core.NewHTTPRequest(core.MethodPost, target, body)
View Source
const (
	StatusOK                  = http.StatusOK
	StatusCreated             = http.StatusCreated
	StatusAccepted            = http.StatusAccepted
	StatusNoContent           = http.StatusNoContent
	StatusBadRequest          = http.StatusBadRequest
	StatusUnauthorized        = http.StatusUnauthorized
	StatusForbidden           = http.StatusForbidden
	StatusNotFound            = http.StatusNotFound
	StatusMethodNotAllowed    = http.StatusMethodNotAllowed
	StatusConflict            = http.StatusConflict
	StatusGone                = http.StatusGone
	StatusUnprocessableEntity = http.StatusUnprocessableEntity
	StatusTooManyRequests     = http.StatusTooManyRequests
	StatusInternalServerError = http.StatusInternalServerError
	StatusNotImplemented      = http.StatusNotImplemented
	StatusBadGateway          = http.StatusBadGateway
	StatusServiceUnavailable  = http.StatusServiceUnavailable
	StatusGatewayTimeout      = http.StatusGatewayTimeout
)

HTTP status code constants. Re-exported from net/http for consumers that build Lethean HTTP handlers without importing the stdlib package.

if r.StatusCode == core.StatusOK { return r }
core.HTTPError(w, "missing field", core.StatusBadRequest)
View Source
const (
	LSPSeverityError       = 1
	LSPSeverityWarning     = 2
	LSPSeverityInformation = 3
	LSPSeverityHint        = 4
)

LSPDiagnosticSeverity values match LSP spec — Error=1, Warning=2, Information=3, Hint=4. Drift signals default to Warning so they surface inline without blocking edit-time iteration.

View Source
const (
	ModeDir        = os.ModeDir
	ModeAppend     = os.ModeAppend
	ModeExclusive  = os.ModeExclusive
	ModeTemporary  = os.ModeTemporary
	ModeSymlink    = os.ModeSymlink
	ModeDevice     = os.ModeDevice
	ModeNamedPipe  = os.ModeNamedPipe
	ModeSocket     = os.ModeSocket
	ModeSetuid     = os.ModeSetuid
	ModeSetgid     = os.ModeSetgid
	ModeCharDevice = os.ModeCharDevice
	ModeSticky     = os.ModeSticky
	ModeIrregular  = os.ModeIrregular
	ModeType       = os.ModeType
	ModePerm       = os.ModePerm // 0o777 — Unix permission bits
)

File mode bits exposed at core scope. These are the same values as os.ModeDir etc., re-exported so consumers don't need to import os.

mode := core.ModeDir | core.ModePerm
if mode&core.ModeDir != 0 { core.Println("directory") }
View Source
const (
	O_APPEND = os.O_APPEND
	O_CREATE = os.O_CREATE
	O_EXCL   = os.O_EXCL
	O_RDONLY = os.O_RDONLY
	O_RDWR   = os.O_RDWR
	O_SYNC   = os.O_SYNC
	O_TRUNC  = os.O_TRUNC
	O_WRONLY = os.O_WRONLY
)

File open flags exposed at core scope.

r := core.OpenFile("agent.log", core.O_CREATE|core.O_WRONLY, 0o644)
if !r.OK { return r }
View Source
const (
	PathSeparator     = os.PathSeparator
	PathListSeparator = os.PathListSeparator
)

Path separators exposed at core scope.

parts := core.Split("a/b", string(core.PathSeparator))
View Source
const (
	KindInvalid       = reflect.Invalid
	KindBool          = reflect.Bool
	KindInt           = reflect.Int
	KindInt8          = reflect.Int8
	KindInt16         = reflect.Int16
	KindInt32         = reflect.Int32
	KindInt64         = reflect.Int64
	KindUint          = reflect.Uint
	KindUint8         = reflect.Uint8
	KindUint16        = reflect.Uint16
	KindUint32        = reflect.Uint32
	KindUint64        = reflect.Uint64
	KindFloat32       = reflect.Float32
	KindFloat64       = reflect.Float64
	KindComplex64     = reflect.Complex64
	KindComplex128    = reflect.Complex128
	KindArray         = reflect.Array
	KindChan          = reflect.Chan
	KindFunc          = reflect.Func
	KindInterface     = reflect.Interface
	KindMap           = reflect.Map
	KindPointer       = reflect.Pointer
	KindSlice         = reflect.Slice
	KindString        = reflect.String
	KindStruct        = reflect.Struct
	KindUintptr       = reflect.Uintptr
	KindUnsafePointer = reflect.UnsafePointer
)

Common Kind constants — re-exported from reflect so consumers can compare without importing reflect.

switch core.TypeOf(v).Kind() {
case core.KindString:
case core.KindInt, core.KindInt64:
}
View Source
const (
	Nanosecond  = time.Nanosecond
	Microsecond = time.Microsecond
	Millisecond = time.Millisecond
	Second      = time.Second
	Minute      = time.Minute
	Hour        = time.Hour
)

Common Duration units. Multiply by an integer to build a Duration.

timeout := 5 * core.Second
pause   := 250 * core.Millisecond
View Source
const (
	TimeRFC3339     = time.RFC3339
	TimeRFC3339Nano = time.RFC3339Nano
	TimeRFC1123     = time.RFC1123
	TimeRFC822      = time.RFC822
	TimeKitchen     = time.Kitchen  // "3:04PM"
	TimeStamp       = time.Stamp    // "Jan _2 15:04:05"
	TimeDateTime    = time.DateTime // "2006-01-02 15:04:05"
	TimeDateOnly    = time.DateOnly // "2006-01-02"
	TimeTimeOnly    = time.TimeOnly // "15:04:05"
)

Common time format constants. Layouts compatible with time.Format.

stamp := core.TimeFormat(core.Now(), core.TimeRFC3339)
View Source
const (
	RFC3339     = time.RFC3339
	RFC3339Nano = time.RFC3339Nano
	RFC1123     = time.RFC1123
	Kitchen     = time.Kitchen  // "3:04PM"
	DateTime    = time.DateTime // "2006-01-02 15:04:05"
	DateOnly    = time.DateOnly // "2006-01-02"
	TimeOnly    = time.TimeOnly // "15:04:05"
)

Bare-name layout constants matching the stdlib spelling, for callers that mirror time.Format usage directly. Equivalent to the Time*-prefixed set above; both are kept so existing TimeRFC3339 references and new RFC3339 references resolve to the same layout.

s := core.TimeFormat(core.Now(), core.RFC3339)
View Source
const (
	January   = time.January
	February  = time.February
	March     = time.March
	April     = time.April
	May       = time.May
	June      = time.June
	July      = time.July
	August    = time.August
	September = time.September
	October   = time.October
	November  = time.November
	December  = time.December
)

Months of the year, for use with Date and time formatting.

ts := core.Date(2026, core.December, 25, 0, 0, 0, 0, core.UTC)
View Source
const (
	Sunday    = time.Sunday
	Monday    = time.Monday
	Tuesday   = time.Tuesday
	Wednesday = time.Wednesday
	Thursday  = time.Thursday
	Friday    = time.Friday
	Saturday  = time.Saturday
)

Days of the week, for use with Time.Weekday comparisons.

weekend := day == core.Saturday || day == core.Sunday
View Source
const LSPServerName = "core-go-lsp"

LSPServerName identifies this language server in client capability negotiation.

core.Println(core.LSPServerName)  // "core-go-lsp"
View Source
const LSPServerVersion = "0.9.0"

LSPServerVersion follows core/go's release version. Bumped alongside core/go releases so editor capability negotiation stays accurate.

View Source
const O_NOFOLLOW = syscall.O_NOFOLLOW

O_NOFOLLOW makes OpenFile fail with a symlink error if the final path component is a symbolic link — refusing to open a symlink-resolving path. Combine with the other O_* flags. On Windows this constant is 0 (no-op); the symlink-refusal guarantee is unix-only.

// Refuse to create-or-open through a symlinked final component.
r := core.OpenFile(p, core.O_CREATE|core.O_EXCL|core.O_NOFOLLOW|core.O_WRONLY, 0o600)
if !r.OK { return r }

Variables

View Source
var (
	ErrNotExist   = os.ErrNotExist   // file or directory does not exist
	ErrExist      = os.ErrExist      // file already exists
	ErrPermission = os.ErrPermission // permission denied
	ErrInvalid    = os.ErrInvalid    // invalid argument (e.g. nil *File method)
	ErrClosed     = os.ErrClosed     // operation on an already-closed file
)

Sentinel errors for the OS boundary, re-exported so consumers can match against them with core.Is (errors.Is) without importing os. These pair with the IsNotExist / IsExist / IsPermission predicates above — use the predicate when wrapping an errno-bearing OS error, use the sentinel when comparing a value you produced or received directly.

if core.Is(err, core.ErrNotExist) { core.Println("missing") }
View Source
var (
	// PathSkipDir tells PathWalkDir to skip the current directory.
	PathSkipDir = filepath.SkipDir

	// PathSkipAll tells PathWalkDir to stop walking immediately.
	PathSkipAll = filepath.SkipAll
)
View Source
var AnError = NewError("core test sentinel error")

AnError is a sentinel error for tests that need a non-nil error without caring about its content. Mirrors testify's assert.AnError.

core.AssertError(t, somethingThatFails(), core.AnError.Error())
View Source
var AssertVerbose = false

AssertVerbose toggles the failure-message format. When false (default) each Assert*/Require* emits the AX one-line shape; when true each emits a multi-line testify-style block. Flip it in TestMain when a human is reading failures and you want the readable format.

func TestMain(m *testing.M) {
    core.AssertVerbose = true
    m.Run()
}
View Source
var DefaultHTTPClient = http.DefaultClient

DefaultHTTPClient is the package-level default *HTTPClient. Use it for one-off requests that don't justify a dedicated client.

resp, err := core.DefaultHTTPClient.Do(req)
View Source
var EOF = io.EOF

EOF is the canonical end-of-stream sentinel error.

if errors.Is(err, core.EOF) { /* end of stream */ }
View Source
var ErrHTTPServerClosed = http.ErrServerClosed

ErrHTTPServerClosed is the sentinel returned by HTTPServer.ListenAndServe (and friends) after Shutdown is called. Use core.Is to detect graceful shutdown vs unexpected termination.

if err := srv.ListenAndServe(); !core.Is(err, core.ErrHTTPServerClosed) {
    core.Error("server died", "err", err)
}
View Source
var ErrNoRows = sql.ErrNoRows

ErrNoRows is the canonical "no row matched" sentinel returned by QueryRow when the query returns zero rows.

if Is(err, core.ErrNoRows) { /* handle "not found" */ }
View Source
var ErrTxDone = sql.ErrTxDone

ErrTxDone is returned when a transaction operation runs after Commit or Rollback has already been called.

err := core.ErrTxDone
if core.Is(err, core.ErrTxDone) { core.Println("transaction closed") }
View Source
var Local = time.Local

Local is the system's local time zone.

stamp := core.Now().In(core.Local)
View Source
var RotationWriterFactory func(RotationLogOptions) goio.WriteCloser

RotationWriterFactory creates a rotating writer from options. Set this to enable log rotation (provided by core/go-io integration).

core.RotationWriterFactory = func(opts core.RotationLogOptions) core.WriteCloser {
    return nil
}
View Source
var UTC = time.UTC

UTC is the Coordinated Universal Time zone.

stamp := core.Now().In(core.UTC)

Functions

func Abs

func Abs[T signedOrFloat](x T) T

Abs returns the absolute value of x.

distance := core.Abs(-42)
Example

ExampleAbs normalises a signed value through `Abs` for health-check thresholds. Numeric helpers keep thresholds readable without importing math directly.

Println(Abs(-42))
Output:
42

func AddAsset

func AddAsset(group, name, data string)

AddAsset registers a packed asset at runtime (called from generated init()).

core.AddAsset("agent", "persona/developer.md", "H4sIAAAAAAAA/8pIzcnJBwCGphA2BQAAAA==")
Example

ExampleAddAsset adds an embedded asset through `AddAsset` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

AddAsset("example.embed", "hello.txt", "H4sIAAAAAAAC/8pIzcnJBwQAAP//hqYQNgUAAAA=")
r := GetAsset("example.embed", "hello.txt")
Println(r.Value)
Output:
hello

func After added in v0.10.0

func After(d Duration) <-chan Time

After returns a channel that delivers the current time after duration d. Use in select for timeouts:

select {
case msg := <-ch:
    handle(msg)
case <-core.After(2 * core.Second):
    return core.E("timeout", "no message", nil)
}
Example

ExampleAfter shows the channel-returning timer used in select for timeouts. Pair with a body select-case to bound any blocking read.

ch := make(chan string, 1)
ch <- "msg"
select {
case msg := <-ch:
	Println(msg)
case <-After(100 * Millisecond):
	Println("timeout")
}
Output:
msg

func AllocsPerRun added in v0.12.0

func AllocsPerRun(runs int, fn func()) float64

AllocsPerRun returns the mean number of heap allocations per call when fn is invoked runs times (plus one untimed warm-up call to settle steady-state behaviour). Re-exports testing.AllocsPerRun so callers never need their own `import "testing"` — test.go is the SPOR owner for the testing package; assert.go's AssertAllocs calls this rather than reaching into testing directly.

Misuse-panic contract: runs must be positive — testing.AllocsPerRun divides by runs, so zero panics (the RandPick documented-panic idiom).

avg := core.AllocsPerRun(1000, func() { _ = fastPath() })
Example

ExampleAllocsPerRun measures a function's allocation rate — the SPOR seam AssertAllocs gates through.

Println(AllocsPerRun(100, func() {}))
Output:
0

func Arch

func Arch() string

Arch returns the CPU architecture (amd64, arm64, etc.) the binary was compiled for.

if core.Arch() == "arm64" { core.Println("Apple Silicon or arm64 Linux") }
Example

ExampleArch returns the host CPU architecture through `Arch` (e.g. "arm64", "amd64").

Println(Arch())

func ArgBool

func ArgBool(index int, args ...any) bool

ArgBool extracts a bool at the given index.

debug := core.ArgBool(2, args...)
Example

ExampleArgBool reads a boolean argument through `ArgBool` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

Println(ArgBool(2, "deploy", 8080, true))
Output:
true

func ArgInt

func ArgInt(index int, args ...any) int

ArgInt extracts an int at the given index.

port := core.ArgInt(1, args...)
Example

ExampleArgInt reads an integer argument through `ArgInt` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

Println(ArgInt(1, "deploy", 8080))
Output:
8080

func ArgString

func ArgString(index int, args ...any) string

ArgString extracts a string at the given index.

name := core.ArgString(0, args...)
Example

ExampleArgString reads a string argument through `ArgString` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

Println(ArgString(0, "deploy", 8080))
Output:
deploy

func Args

func Args() []string

Args returns the command-line arguments.

args := core.Args()
Example

ExampleArgs returns the command-line arguments through `Args`.

Println(len(Args()) > 0)
Output:
true

func As

func As(err error, target any) bool

As finds the first error in err's tree that matches target. Wrapper around errors.As for convenience.

err := core.E("agent.Run", "failed", nil)
var coreErr *core.Err
if core.As(err, &coreErr) { core.Println(coreErr.Operation) }
Example

ExampleAs extracts a typed error through `As` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := E("worker.Run", "failed", nil)
var target *Err
Println(As(err, &target))
Println(target.Operation)
Output:
true
worker.Run

func AsBytes added in v0.10.0

func AsBytes(s string) []byte

AsBytes returns a read-only []byte view of s without copying. See the package-level safety contract above before using.

digest := sha256.Sum256(core.AsBytes("payload"))
_, _ = w.Write(core.AsBytes(line))
Example
b := AsBytes("homelab")
Println(len(b))
Output:
7

func AsString added in v0.10.0

func AsString(b []byte) string

AsString returns a string view of b without copying. The source b must be freshly built and never referenced again by the caller. See the package-level safety contract above before using.

var buf bytes.Buffer
buf.WriteString("agent ")
buf.WriteString(name)
return core.AsString(buf.Bytes())
Example
s := AsString([]byte("codex"))
Println(s)
Output:
codex

func AssertAllocs added in v0.12.0

func AssertAllocs(t TB, max int, fn func(), msg ...string)

AssertAllocs fails the test if calling fn allocates more than max heap allocations per run, averaged over repeated calls — the house alloc-gate one-liner for locking in a hot path's allocation ceiling.

core.AssertAllocs(t, 0, func() { _ = fastPath() })
core.AssertAllocs(t, 1, func() { r = core.Ok("ready") })
Example

ExampleAssertAllocs gates a hot path's allocation ceiling through `AssertAllocs` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertAllocs(t, 0, func() { _ = Abs(-1) })

func AssertCLI

func AssertCLI(t TB, c *Core, tc CLITest)

AssertCLI executes tc via c.Process() and asserts the outcome. The Core must have a service registering "process.run" — typically dappco.re/go-process — for the dispatch to reach a real exec.

c := core.New(core.WithService(process.Register))
core.AssertCLI(t, c, core.CLITest{
    Cmd: "go", Args: []string{"version"},
    WantOK: true, Contains: "go1.",
})
Example

ExampleAssertCLI demonstrates the canonical CLI test shape: build a Core, register a process.run handler (typically dappco.re/go-process in production code, an in-test fake here), then dispatch a CLITest case that asserts on stdout substring and OK status.

c := New()
c.Action("process.run", func(ctx Context, opts Options) Result {
	return Result{Value: "go version go1.26.0\n", OK: true}
})

tc := CLITest{
	Cmd:      "go",
	Args:     []string{"version"},
	WantOK:   true,
	Contains: "go1.26",
}
r := c.Process().Run(Background(), tc.Cmd, tc.Args...)
Println(r.OK)
Println(Contains(r.Value.(string), tc.Contains))
Output:
true
true
Example (StubProcess)

ExampleAssertCLI_stubProcess dispatches a CLITest case through `AssertCLI` for AX-10 binary validation. Like assert_example_test.go's helpers, this is compiled but not executed (no "Output:" comment): AssertCLI takes a live TB, which an Example function signature can never supply. cli_example_test.go already declares `ExampleAssertCLI` (attached to cli.go, documenting the same dispatch by calling c.Process() directly) — this file's file-aware requirement is for the cli_assert.go symbol itself, so this variant calls the real AssertCLI helper the symbol names instead of redeclaring an identical duplicate under a different file.

var t *T
c := New()
c.Action("process.run", func(ctx Context, opts Options) Result {
	return Result{Value: "go version go1.26.0\n", OK: true}
})

AssertCLI(t, c, CLITest{
	Cmd: "go", Args: []string{"version"},
	WantOK: true, Contains: "go1.26",
})

func AssertCLIs

func AssertCLIs(t *T, c *Core, cases []CLITest)

AssertCLIs runs each CLITest sequentially under a sub-test named after tc.Name (or tc.Cmd if Name is empty). Convenience for table-driven CLI scenarios.

core.AssertCLIs(t, c, []core.CLITest{
    {Name: "version", Cmd: "go", Args: []string{"version"}, WantOK: true, Contains: "go1."},
    {Name: "vet", Cmd: "go", Args: []string{"vet", "./..."}, WantOK: true},
})
Example

ExampleAssertCLIs runs a table of CLI scenarios through `AssertCLIs` for AX-10 binary validation. Compiled but not executed (no "Output:" comment): AssertCLIs takes a live *T, which an Example function signature can never supply.

var t *T
c := New()
c.Action("process.run", func(ctx Context, opts Options) Result {
	return Result{Value: "go version go1.26.0\n", OK: true}
})

AssertCLIs(t, c, []CLITest{
	{Name: "version", Cmd: "go", Args: []string{"version"}, WantOK: true, Contains: "go1."},
	{Name: "vet", Cmd: "go", Args: []string{"vet", "./..."}, WantOK: true},
})

func AssertContains

func AssertContains(t TB, haystack, needle any, msg ...string)

AssertContains fails the test if needle is not present in haystack. Supports strings (substring match), slices/arrays (deep-equal element membership), and maps (key membership).

core.AssertContains(t, "hello world", "world")
core.AssertContains(t, []string{"a", "b"}, "a")
core.AssertContains(t, map[string]int{"x": 1}, "x")
Example

ExampleAssertContains asserts membership through `AssertContains` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertContains(t, []string{"alpha", "bravo"}, "bravo")
Example (Map)

ExampleAssertContains_map asserts key membership through `AssertContains` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertContains(t, map[string]int{"x": 1}, "x")

func AssertElementsMatch

func AssertElementsMatch(t TB, want, got any, msg ...string)

AssertElementsMatch fails the test if want and got are not slices/arrays containing the same elements regardless of order. Uses deep equality per element.

core.AssertElementsMatch(t, []int{1, 2, 3}, []int{3, 1, 2})
Example

ExampleAssertElementsMatch asserts unordered list equality through `AssertElementsMatch` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertElementsMatch(t, []string{"alpha", "bravo"}, []string{"bravo", "alpha"})
Example (Ints)

ExampleAssertElementsMatch_ints asserts unordered int-slice equality through `AssertElementsMatch` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertElementsMatch(t, []int{1, 2, 3}, []int{3, 2, 1})

func AssertEmpty

func AssertEmpty(t TB, v any, msg ...string)

AssertEmpty fails the test if v is not empty. Treats zero-length strings/slices/arrays/maps/channels and nil as empty.

core.AssertEmpty(t, results)
Example

ExampleAssertEmpty asserts emptiness through `AssertEmpty` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertEmpty(t, []string{})
Example (String)

ExampleAssertEmpty_string asserts an empty string through `AssertEmpty` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertEmpty(t, "")

func AssertEqual

func AssertEqual(t TB, want, got any, msg ...string)

AssertEqual fails the test if want and got are not deeply equal.

core.AssertEqual(t, "expected", result.Value)
core.AssertEqual(t, 42, result.Count)
Example

ExampleAssertEqual asserts equal values through `AssertEqual` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertEqual(t, "expected", "expected")
Example (Numeric)

ExampleAssertEqual_numeric asserts equal integers through `AssertEqual` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertEqual(t, 4, len("core"))

func AssertError

func AssertError(t TB, err error, msg ...string)

AssertError fails the test if err is nil. Optional substring matches against err.Error() for tighter assertions.

core.AssertError(t, parseFails())
core.AssertError(t, parseFails(), "invalid syntax")
Example

ExampleAssertError asserts an error through `AssertError` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertError(t, AnError, "sentinel")
Example (Wrapped)

ExampleAssertError_wrapped asserts a wrapped error through `AssertError` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertError(t, Wrap(AnError, "example", "detail"))

func AssertErrorIs

func AssertErrorIs(t TB, err, target error, msg ...string)

AssertErrorIs fails the test if err does not wrap target (Is).

core.AssertErrorIs(t, err, fs.ErrNotExist)
Example

ExampleAssertErrorIs asserts wrapped error identity through `AssertErrorIs` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertErrorIs(t, Wrap(AnError, "example", "wrapped"), AnError)
Example (Sentinel)

ExampleAssertErrorIs_sentinel asserts a wrapped sentinel error through `AssertErrorIs` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertErrorIs(t, Wrap(ErrNotExist, "lookup", "missing"), ErrNotExist)

func AssertFalse

func AssertFalse(t TB, condition bool, msg ...string)

AssertFalse fails the test if condition is true.

core.AssertFalse(t, c.Fs().Exists(deletedPath))
Example

ExampleAssertFalse asserts a false condition through `AssertFalse` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertFalse(t, len("") > 0)
Example (WithMessage)

ExampleAssertFalse_withMessage asserts a false condition with context through `AssertFalse` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
items := []string{}
AssertFalse(t, len(items) > 0, "items must be empty")

func AssertGreater

func AssertGreater(t TB, got, want any, msg ...string)

AssertGreater fails the test if got is not strictly greater than want. Works on numeric kinds (int, uint, float) and strings.

core.AssertGreater(t, count, 0)
Example

ExampleAssertGreater asserts greater-than order through `AssertGreater` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertGreater(t, 3, 2)
Example (String)

ExampleAssertGreater_string asserts string ordering through `AssertGreater` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertGreater(t, "b", "a")

func AssertGreaterOrEqual

func AssertGreaterOrEqual(t TB, got, want any, msg ...string)

AssertGreaterOrEqual fails the test if got is less than want.

core.AssertGreaterOrEqual(t, elapsed, minDuration)
Example

ExampleAssertGreaterOrEqual asserts greater-or-equal order through `AssertGreaterOrEqual` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertGreaterOrEqual(t, 3, 3)
Example (Duration)

ExampleAssertGreaterOrEqual_duration asserts elapsed-time ordering through `AssertGreaterOrEqual` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
elapsed := 5 * Second
minDuration := 2 * Second
AssertGreaterOrEqual(t, elapsed, minDuration)

func AssertInDelta

func AssertInDelta(t TB, want, got, delta float64, msg ...string)

AssertInDelta fails the test if |got - want| > delta. Use for float comparisons where exact equality is not appropriate.

core.AssertInDelta(t, expected, actual, 0.0001)
Example

ExampleAssertInDelta asserts approximate numeric equality through `AssertInDelta` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertInDelta(t, 1.0, 1.01, 0.02)
Example (Exact)

ExampleAssertInDelta_exact asserts exact numeric equality (zero delta) through `AssertInDelta` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertInDelta(t, 2.5, 2.5, 0)

func AssertLen

func AssertLen(t TB, v any, want int, msg ...string)

AssertLen fails the test if the length of v does not equal want. Works on strings, slices, arrays, maps, and channels.

core.AssertLen(t, items, 3)
Example

ExampleAssertLen asserts length through `AssertLen` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertLen(t, []string{"alpha", "bravo"}, 2)
Example (String)

ExampleAssertLen_string asserts string length through `AssertLen` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertLen(t, "agent", 5)

func AssertLess

func AssertLess(t TB, got, want any, msg ...string)

AssertLess fails the test if got is not strictly less than want.

core.AssertLess(t, errorCount, limit)
Example

ExampleAssertLess asserts less-than order through `AssertLess` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertLess(t, 2, 3)
Example (String)

ExampleAssertLess_string asserts string ordering through `AssertLess` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertLess(t, "a", "b")

func AssertLessOrEqual

func AssertLessOrEqual(t TB, got, want any, msg ...string)

AssertLessOrEqual fails the test if got is greater than want.

Example

ExampleAssertLessOrEqual asserts less-or-equal order through `AssertLessOrEqual` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertLessOrEqual(t, 3, 3)
Example (Float)

ExampleAssertLessOrEqual_float asserts float ordering through `AssertLessOrEqual` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertLessOrEqual(t, 1.5, 2.5)

func AssertNil

func AssertNil(t TB, v any, msg ...string)

AssertNil fails the test if v is non-nil. Handles typed-nil interface values (e.g. a (*Foo)(nil) inside an any).

core.AssertNil(t, returnedPointer)
Example

ExampleAssertNil asserts nil through `AssertNil` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNil(t, nil)
Example (TypedNil)

ExampleAssertNil_typedNil asserts a typed-nil interface value through `AssertNil` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
var p *int
var v any = p
AssertNil(t, v)

func AssertNoError

func AssertNoError(t TB, err error, msg ...string)

AssertNoError fails the test if err is non-nil.

core.AssertNoError(t, c.Fs().Write(p, "data").Error())
Example

ExampleAssertNoError asserts no error through `AssertNoError` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNoError(t, nil)
Example (WithMessage)

ExampleAssertNoError_withMessage asserts no error with context through `AssertNoError` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNoError(t, nil, "setup phase")

func AssertNotContains

func AssertNotContains(t TB, haystack, needle any, msg ...string)

AssertNotContains fails the test if needle IS present in haystack.

Example

ExampleAssertNotContains asserts absence through `AssertNotContains` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNotContains(t, []string{"alpha", "bravo"}, "charlie")
Example (String)

ExampleAssertNotContains_string asserts substring absence through `AssertNotContains` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNotContains(t, "agent dispatch", "missing")

func AssertNotEmpty

func AssertNotEmpty(t TB, v any, msg ...string)

AssertNotEmpty fails the test if v is empty (see AssertEmpty).

core.AssertNotEmpty(t, response.Body)
Example

ExampleAssertNotEmpty asserts non-emptiness through `AssertNotEmpty` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNotEmpty(t, []string{"alpha"})
Example (Map)

ExampleAssertNotEmpty_map asserts a non-empty map through `AssertNotEmpty` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNotEmpty(t, map[string]int{"x": 1})

func AssertNotEqual

func AssertNotEqual(t TB, want, got any, msg ...string)

AssertNotEqual fails the test if want and got are deeply equal.

core.AssertNotEqual(t, oldValue, newValue)
Example

ExampleAssertNotEqual asserts different values through `AssertNotEqual` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNotEqual(t, "old", "new")
Example (Numeric)

ExampleAssertNotEqual_numeric asserts different integers through `AssertNotEqual` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNotEqual(t, 1, 2)

func AssertNotNil

func AssertNotNil(t TB, v any, msg ...string)

AssertNotNil fails the test if v is nil.

core.AssertNotNil(t, c.Fs())
Example

ExampleAssertNotNil asserts a non-nil value through `AssertNotNil` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNotNil(t, "value")
Example (Pointer)

ExampleAssertNotNil_pointer asserts a non-nil pointer through `AssertNotNil` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNotNil(t, &struct{}{})

func AssertNotPanics

func AssertNotPanics(t TB, fn func(), msg ...string)

AssertNotPanics fails the test if calling fn panics.

core.AssertNotPanics(t, func() { safeDivide(10, 2) })
Example

ExampleAssertNotPanics asserts non-panicking behaviour through `AssertNotPanics` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNotPanics(t, func() { /* no-op closure demonstrates non-panicking call */ })
Example (Arithmetic)

ExampleAssertNotPanics_arithmetic asserts a non-panicking closure through `AssertNotPanics` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertNotPanics(t, func() { _ = 10 / 2 })

func AssertPanics

func AssertPanics(t TB, fn func(), msg ...string)

AssertPanics fails the test if calling fn does not panic.

core.AssertPanics(t, func() { mustParse("garbage") })
Example

ExampleAssertPanics asserts panic behaviour through `AssertPanics` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertPanics(t, func() { panic("boom") })
Example (Error)

ExampleAssertPanics_error asserts a panic carrying an error value through `AssertPanics` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertPanics(t, func() { panic(AnError) })

func AssertPanicsWithError

func AssertPanicsWithError(t TB, wantSubstr string, fn func(), msg ...string)

AssertPanicsWithError fails the test if fn does not panic, or panics with a value whose error string does not contain wantSubstr. Argument order matches testify's PanicsWithError(t, errString, fn).

core.AssertPanicsWithError(t, "empty input", func() { mustParse("") })
Example

ExampleAssertPanicsWithError asserts panic error text through `AssertPanicsWithError` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertPanicsWithError(t, "sentinel", func() { panic(AnError) })
Example (NonError)

ExampleAssertPanicsWithError_nonError asserts panic text from a non-error value through `AssertPanicsWithError` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertPanicsWithError(t, "boom", func() { panic("boom") })

func AssertSame

func AssertSame(t TB, want, got any, msg ...string)

AssertSame fails the test if want and got are not the same pointer.

core.AssertSame(t, c.Fs(), c.Fs())  // singleton check
Example

ExampleAssertSame asserts pointer identity through `AssertSame` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
a := &struct{}{}
b := a // a second reference to the same pointer
AssertSame(t, a, b)
Example (Core)

ExampleAssertSame_core asserts pointer identity on a Core singleton through `AssertSame` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
c := New()
// Core() returns the receiver itself, so this is genuine identity
// between two independently obtained references, not a self-compare.
AssertSame(t, c, c.Core())

func AssertTrue

func AssertTrue(t TB, condition bool, msg ...string)

AssertTrue fails the test if condition is false.

core.AssertTrue(t, result.OK)
core.AssertTrue(t, len(items) > 0, "items must not be empty")
Example

ExampleAssertTrue asserts a true condition through `AssertTrue` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
AssertTrue(t, len("core") > 0)
Example (WithMessage)

ExampleAssertTrue_withMessage asserts a true condition with context through `AssertTrue` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
items := []string{"agent"}
AssertTrue(t, len(items) > 0, "items must not be empty")

func Base64Encode

func Base64Encode(src []byte) string

Base64Encode returns src encoded as a standard base64 string.

s := core.Base64Encode([]byte("hello"))

Zero-copy return: pre-allocates the encoded buffer and aliases via AsString to skip stdlib's return-side copy. Saves one alloc per call.

Example

ExampleBase64Encode encodes bytes as base64 through `Base64Encode` for token and payload encoding. Byte and string encoders return predictable wrapper values for tokens and payloads.

Println(Base64Encode([]byte("hello")))
Output:
aGVsbG8=

func Base64URLEncode

func Base64URLEncode(src []byte) string

Base64URLEncode returns src encoded as a URL-safe base64 string.

s := core.Base64URLEncode([]byte("hello"))
Example

ExampleBase64URLEncode encodes bytes for URL-safe base64 through `Base64URLEncode` for token and payload encoding. Byte and string encoders return predictable wrapper values for tokens and payloads.

Println(Base64URLEncode([]byte("hello?")))
Output:
aGVsbG8_

func Cast

func Cast[T any](r Result) (T, bool)

Cast extracts a typed value from a Result. Returns (zero, false) when the Result is not OK or Value isn't assignable to T. Single expression replacing the (Result.OK check + type assertion) pair.

cfg, ok := core.Cast[*Config](core.JSONUnmarshal(data, &Config{}))
if !ok { return r }
if user, ok := core.Cast[*User](svc.Get(id)); ok { use(user) }
Example

ExampleCast casts a Result value through `Cast` for Result-based control flow. Success, fallback, casting, and error inspection all use the same Result shape.

r := Result{Value: "hello", OK: true}
s, ok := Cast[string](r)
Println(s, ok)
Output:
hello true

func Ceil

func Ceil(x float64) float64

Ceil returns the least integer value greater than or equal to x.

n := core.Ceil(3.1)
Example

ExampleCeil rounds a value up through `Ceil` for health-check thresholds. Numeric helpers keep thresholds readable without importing math directly.

Println(Ceil(3.1))
Output:
4

func Clamp added in v0.10.0

func Clamp[T Ordered](x, lo, hi T) T

Clamp constrains x to the closed interval [lo, hi]. If lo > hi the result is undefined (caller's responsibility). Used by gradient clipping, normalisation, slider/progress bounds, and tile coords.

pct := core.Clamp(progress, 0.0, 100.0)
idx := core.Clamp(cursor, 0, len(items)-1)
Example

ExampleClamp constrains a value to a range through `Clamp` for health-check thresholds. Numeric helpers keep thresholds readable without importing math directly.

Println(Clamp(15, 0, 10))
Output:
10

func CleanPath

func CleanPath(p, ds string) string

CleanPath removes redundant separators and resolves . and .. elements.

core.CleanPath("/tmp//file", "/")     // "/tmp/file"
core.CleanPath("a/b/../c", "/")       // "a/c"

Fast path: when ds is the OS-native separator (the >99% case), delegate to stdlib filepath.Clean — byte-level scan, 2 allocs vs the Split/Join pipeline's 6.

Example

ExampleCleanPath normalises a path through `CleanPath` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

Println(CleanPath("/tmp//file", "/"))
Println(CleanPath("a/b/../c", "/"))
Println(CleanPath("deploy/to/homelab", "/"))
Output:
/tmp/file
a/c
deploy/to/homelab

func Clone added in v0.10.2

func Clone(s string) string

Clone returns a fresh copy of s, detached from its backing memory. Use this when s aliases a reusable buffer (e.g. via core.AsString over a scratch slice) and the result must outlive the buffer's next reuse — map keys, struct fields, channel sends.

key := core.Clone(core.AsString(scratch))  // map[key] = ... is safe
Example

ExampleClone returns an independent copy of a string through `Clone`.

Println(Clone("agent"))
Output:
agent

func CloseStream

func CloseStream(v any)

CloseStream closes any value that implements Closer.

core.CloseStream(r.Value)
Example

ExampleCloseStream closes a stream through `CloseStream` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

CloseStream(NewReader("not a closer"))
Println("ok")
Output:
ok

func Coalesce added in v0.11.0

func Coalesce[T comparable](vals ...T) T

Coalesce returns the first non-zero value, or the zero value when every argument is zero — the fallback chain (primary, secondary, default) as one call. Replaces the hand-rolled firstNonEmpty/firstNonNil helpers scattered across consumers.

name := core.Coalesce(req.Name, cfg.Name, "anonymous")
timeout := core.Coalesce(flag, env, 30)

func Compare

func Compare[T Ordered](a, b T) int

Compare returns -1 when a is less than b, 0 when equal, and +1 when greater. Wraps cmp.Compare for the canonical ordering.

order := core.Compare("alpha", "beta")  // -1
order := core.Compare(7, 7)             //  0
Example

ExampleCompare orders two values through `Compare` for priority comparison. Ordering decisions use the core comparison wrapper rather than importing cmp directly.

Println(Compare("alpha", "bravo"))
Println(Compare(42, 42))
Println(Compare(9, 3))
Output:
-1
0
1

func Concat

func Concat(parts ...string) string

Concat joins variadic string parts into one string. Hook point for validation, sanitisation, and security checks.

core.Concat("cmd.", "deploy.to.homelab", ".description")
core.Concat("https://", host, "/api/v1")
Example

ExampleConcat concatenates text through `Concat` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(Concat("hello", " ", "world"))
Output:
hello world

func ConfigGet

func ConfigGet[T any](e *Config, key string) T

ConfigGet retrieves a typed configuration value.

cfg := (&core.Config{}).New()
cfg.Set("config.host", "homelab.lthn.sh")
host := core.ConfigGet[string](cfg, "config.host")
core.Println(host)
Example

ExampleConfigGet reads a typed config value through `ConfigGet` for service configuration. Callers write untyped settings and read back typed values or enabled features.

cfg := (&Config{}).New()
cfg.Set("host", "localhost")
Println(ConfigGet[string](cfg, "host"))
Output:
localhost

func Contains

func Contains(s, substr string) bool

Contains returns true if s contains substr.

core.Contains("hello world", "world")  // true
Example

ExampleContains checks text membership through `Contains` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(Contains("hello world", "world"))
Println(Contains("hello world", "mars"))
Output:
true
false

func ContainsAny added in v0.10.4

func ContainsAny(s, chars string) bool

ContainsAny reports whether any Unicode code point in chars is in s.

core.ContainsAny("user@host", "@:")  // true
Example

ExampleContainsAny reports whether any listed rune is present through `ContainsAny`.

Println(ContainsAny("agent", "xyz"))
Println(ContainsAny("agent", "ge"))
Output:
false
true

func ContainsRune added in v0.10.4

func ContainsRune(s string, r rune) bool

ContainsRune reports whether the Unicode code point r is in s.

core.ContainsRune("café", 'é')  // true
Example

ExampleContainsRune reports whether a rune is present through `ContainsRune`.

Println(ContainsRune("agent", 'g'))
Output:
true

func CopyValue added in v0.10.4

func CopyValue(dst, src Value) int

CopyValue copies the contents of src into dst until dst is full or src is exhausted, returning the number of elements copied. Both must be slices (or dst an array) with assignable element types. Named CopyValue (not Copy) because core.Copy is the io stream copier.

n := core.CopyValue(dstVal, srcVal)
Example

ExampleCopyValue copies between slice Values through `CopyValue`.

dst := MakeSlice(TypeFor[[]int](), 3, 3)
Println(CopyValue(dst, dst))
Output:
3

func Count added in v0.10.4

func Count(s, substr string) int

Count returns the number of non-overlapping instances of substr in s. An empty substr returns 1 + the rune count of s (stdlib semantics).

core.Count("a.b.c", ".")  // 2
Example

ExampleCount counts non-overlapping occurrences through `Count`.

Println(Count("banana", "a"))
Output:
3

func Cut added in v0.10.4

func Cut(s, sep string) (before, after string, found bool)

Cut slices s around the first occurrence of sep, returning the text before and after it and whether sep was found. The idiomatic replacement for SplitN(s, sep, 2) when both halves are needed.

key, value, ok := core.Cut("port=8080", "=")  // "port", "8080", true
Example

ExampleCut splits a header line on its first separator, taking both halves and whether the separator was present in one pass.

name, value, found := Cut("Authorization: Bearer abc", ": ")
Println(name)
Println(value)
Println(found)
Output:
Authorization
Bearer abc
true

func CutPrefix added in v0.10.4

func CutPrefix(s, prefix string) (after string, found bool)

CutPrefix returns s without the leading prefix and reports whether the prefix was present. Unlike TrimPrefix it tells the caller whether a cut actually happened.

rest, ok := core.CutPrefix("--verbose", "--")  // "verbose", true
Example

ExampleCutPrefix splits off a leading prefix through `CutPrefix`.

after, found := CutPrefix("agent.go", "agent.")
Println(after, found)
Output:
go true

func CutSuffix added in v0.10.4

func CutSuffix(s, suffix string) (before string, found bool)

CutSuffix returns s without the trailing suffix and reports whether the suffix was present — the trailing-end sibling of CutPrefix.

base, ok := core.CutSuffix("main.go", ".go")  // "main", true
Example

ExampleCutSuffix splits off a trailing suffix through `CutSuffix`.

before, found := CutSuffix("agent.go", ".go")
Println(before, found)
Output:
agent true

func Debug

func Debug(msg string, keyvals ...any)

Debug logs to the default logger.

core.SetLevel(core.LevelDebug)
core.Debug("agent trace", "task", "task-42")
Example

ExampleDebug writes a debug event through `Debug` for operator logging. Loggers support levels, redaction, and default routing for operator output.

old := Default()
defer SetDefault(old)

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelDebug, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
SetDefault(log)
Debug("trace")
Println(Contains(buf.String(), "[DBG] trace"))
Output:
true

func DeepEqual

func DeepEqual(x, y any) bool

DeepEqual reports whether x and y are deeply equal — recursively comparing slices, maps, structs, etc. Differs from == in that it follows pointers and compares unexported fields.

core.DeepEqual([]int{1, 2, 3}, []int{1, 2, 3})  // true
core.DeepEqual(map[string]int{"a": 1}, map[string]int{"a": 1})  // true
Example

ExampleDeepEqual compares nested values through `DeepEqual` for runtime inspection. Reflection stays behind a narrow core surface for rare inspection code.

Println(DeepEqual([]int{1, 2, 3}, []int{1, 2, 3}))
Output:
true

func E

func E(op, msg string, err error) error

E creates a new Err with operation context. The underlying error can be nil for creating errors without a cause.

Example:

return log.E("user.Save", "failed to save user", err)
return log.E("api.Call", "rate limited", nil)  // No underlying cause
Example

ExampleE builds a scoped error through `E` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := E("cache.Get", "key not found", nil)
Println(Operation(err))
Println(ErrorMessage(err))
Output:
cache.Get
key not found

func Env

func Env(key string) string

Env returns a system information value by key. Core keys (OS, DIR_HOME, DS, etc.) are pre-populated at init. Unknown keys fall through to core.Getenv — making Env a universal replacement for core.Getenv.

core.Env("OS")           // "darwin" (pre-populated)
core.Env("DIR_HOME")     // "/Users/snider" (pre-populated)
core.Env("FORGE_TOKEN")  // falls through to core.Getenv
Example

ExampleEnv reads environment access through `Env` for runtime diagnostics. Runtime and environment facts are exposed as stable diagnostic values.

Println(Env("OS"))   // e.g. "darwin"
Println(Env("ARCH")) // e.g. "arm64"

func EnvKeys

func EnvKeys() []string

EnvKeys returns all available environment keys.

keys := core.EnvKeys()
Example

ExampleEnvKeys lists environment keys through `EnvKeys` for runtime diagnostics. Runtime and environment facts are exposed as stable diagnostic values.

keys := EnvKeys()
Println(len(keys) > 0)
Output:
true

func Environ

func Environ() []string

Environ returns a copy of strings representing the environment.

env := core.Environ()
Example

ExampleEnviron returns the environment as KEY=VALUE strings through `Environ`.

Println(len(Environ()) > 0)
Output:
true

func EqualFold added in v0.10.4

func EqualFold(s, t string) bool

EqualFold reports whether s and t are equal under simple Unicode case-folding — the case-insensitive comparison that avoids allocating two Lower copies just to compare them.

core.EqualFold("Bearer", "bearer")  // true
Example

ExampleEqualFold compares two scheme names case-insensitively without allocating Lower copies of either.

Println(EqualFold("Bearer", "bearer"))
Output:
true

func Error

func Error(msg string, keyvals ...any)

Error logs to the default logger.

core.Error("agent failed", "service", "homelab")
Example

ExampleError writes or renders an error through `Error` for operator logging. Loggers support levels, redaction, and default routing for operator output.

old := Default()
defer SetDefault(old)

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelError, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
SetDefault(log)
Error("failed", "op", "deploy")
Println(Contains(buf.String(), `[ERR] failed op="deploy"`))
Output:
true

func ErrorCode

func ErrorCode(err error) string

ErrorCode extracts the error code from an error. Returns empty string if the error is not an *Err or has no code.

err := core.WrapCode(nil, "RATE_LIMITED", "agent.Call", "too many requests")
code := core.ErrorCode(err)
core.Println(code)
Example

ExampleErrorCode reads the code from an error through `ErrorCode` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := NewCode("NOT_FOUND", "missing")
Println(ErrorCode(err))
Output:
NOT_FOUND

func ErrorJoin

func ErrorJoin(errs ...error) error

ErrorJoin combines multiple errors into one.

core.ErrorJoin(err1, err2, err3)
Example

ExampleErrorJoin joins errors through `ErrorJoin` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := ErrorJoin(NewError("first"), NewError("second"))
Println(Contains(err.Error(), "first"))
Println(Contains(err.Error(), "second"))
Output:
true
true

func ErrorMessage

func ErrorMessage(err error) string

Message extracts the message from an error. Returns the error's Error() string if not an *Err.

err := core.E("config.Load", "missing config.host", nil)
msg := core.ErrorMessage(err)
core.Println(msg)
Example

ExampleErrorMessage reads the message from an error through `ErrorMessage` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := E("cache.Get", "missing", nil)
Println(ErrorMessage(err))
Output:
missing

func Errorf

func Errorf(format string, args ...any) error

Errorf returns an error formatted per fmt.Errorf semantics. Use core.E or core.NewCode for structured errors; reach for Errorf only when interoperating with code that expects an %w-style chain.

err := core.Errorf("connect %s: %w", host, cause)
Example
err := Errorf("deploy failed: %s", "timeout")
Println(err.Error())
Output:
deploy failed: timeout

func Exit

func Exit(code int)

Exit terminates the current process with code.

core.Exit(1)
Example

ExampleExit documents the package-level exit helper for call sites without a Core value. Production exit paths are documented without terminating the example test process.

// core.Exit(1) terminates the process in production
Println("package-level")
Output:
package-level
Example (PackageLevel)

ExampleExit_packageLevel documents the package-level exit helper for call sites with no *Core in scope. Exit terminates the process for real in production, and the osExit test-hook that would let it be overridden safely is unexported (package core only) — unreachable from this external test package — so the call is shown only in comment form rather than invoked.

// core.Exit(1) terminates the process immediately; not invoked here.
Println("package-level exit path documented")
Output:
package-level exit path documented

func Fields added in v0.10.4

func Fields(s string) []string

Fields splits s around runs of whitespace, returning the non-empty substrings. The whitespace-delimited tokeniser — Split needs an explicit separator and keeps empties, Fields collapses any run.

core.Fields("  go   test ./... ")  // ["go", "test", "./..."]
Example

ExampleFields tokenises a command line on whitespace, collapsing any run of spaces — unlike Split which needs an explicit separator and keeps empties.

Println(Join(",", Fields("  go   test ./... ")...))
Output:
go,test,./...

func FilterArgs

func FilterArgs(args []string) []string

FilterArgs removes empty strings and Go test runner flags from an argument list.

clean := core.FilterArgs(os.Args[1:])
Example

ExampleFilterArgs filters arguments through `FilterArgs` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

Println(FilterArgs([]string{"deploy", "-test.v", "", "--target=homelab"}))
Output:
[deploy --target=homelab]

func FirstNonBlank added in v0.11.0

func FirstNonBlank(vals ...string) string

FirstNonBlank returns the first value whose trimmed form is non-empty — a whitespace-only string (" ") counts as blank and falls through — returning the ORIGINAL untrimmed value, or "" when every value is blank. The whitespace-aware sibling of Coalesce for the "first meaningful string" pattern, where a blank field should defer to the next fallback.

title := core.FirstNonBlank(userTitle, cfg.Title, "untitled")

func FirstPositive added in v0.11.0

func FirstPositive[T Ordered](vals ...T) T

FirstPositive returns the first value strictly greater than the zero value, or the zero value when none is — the numeric fallback chain (a value of 0 means "unset, try the next"). For numbers this reads as "first positive"; the Ordered constraint also admits strings, where it degenerates to Coalesce.

patchSize := core.FirstPositive(cfg.PatchSize, defaultPatchSize)
softTokens := core.FirstPositive(override, computed, 256)

func Floor

func Floor(x float64) float64

Floor returns the greatest integer value less than or equal to x.

n := core.Floor(3.7)
Example

ExampleFloor rounds a value down through `Floor` for health-check thresholds. Numeric helpers keep thresholds readable without importing math directly.

Println(Floor(3.7))
Output:
3

func FormatInt

func FormatInt(i int64, base int) string

FormatInt converts an int64 to a string in the given base.

s := core.FormatInt(255, 16) // "ff"
Example

ExampleFormatInt formats an integer with a base through `FormatInt` for CLI argument conversion. Numeric parsing and formatting use core helpers for CLI-friendly values.

Println(FormatInt(255, 16))
Output:
ff

func FormatStackTrace

func FormatStackTrace(err error) string

FormatStackTrace returns a pretty-printed logical stack trace.

err := core.Wrap(core.E("net.Dial", "refused", nil), "agent.Ping", "homelab unreachable")
trace := core.FormatStackTrace(err)
core.Println(trace)
Example

ExampleFormatStackTrace formats a stack trace through `FormatStackTrace` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := Wrap(Wrap(NewError("root"), "db.Query", "failed"), "api.Get", "failed")
Println(FormatStackTrace(err))
Output:
api.Get -> db.Query

func FormatUint

func FormatUint(i uint64, base int) string

FormatUint converts a uint64 to a string in the given base.

s := core.FormatUint(255, 16) // "ff"
Example

ExampleFormatUint formats an unsigned integer in a given base through `FormatUint`.

Println(FormatUint(255, 16))
Output:
ff

func Getenv

func Getenv(key string) string

Getenv retrieves the value of the environment variable named by key.

token := core.Getenv("FORGE_TOKEN")
Example

ExampleGetenv reads an environment variable through `Getenv`.

Setenv("CORE_EXAMPLE", "homelab")
Println(Getenv("CORE_EXAMPLE"))
Unsetenv("CORE_EXAMPLE")
Output:
homelab

func Getpid

func Getpid() int

Getpid returns the process id of the caller.

pid := core.Getpid()
Example

ExampleGetpid returns the current process ID through `Getpid`.

Println(Getpid() > 0)
Output:
true

func Getppid

func Getppid() int

Getppid returns the parent process id of the caller.

ppid := core.Getppid()
Example

ExampleGetppid returns the parent process ID through `Getppid`.

Println(Getppid() > 0)
Output:
true

func GoVersion

func GoVersion() string

GoVersion returns the Go runtime version string (e.g. "go1.26.0") the binary was compiled with.

core.Println(core.GoVersion())  // "go1.26.0"
Example

ExampleGoVersion returns the Go runtime version through `GoVersion`.

Println(GoVersion())

func HTMLEscape

func HTMLEscape(s string) string

HTMLEscape returns s with special HTML characters escaped.

escaped := core.HTMLEscape(`<a href="/search?q=go&lang=en">Go</a>`)
Example

ExampleHTMLEscape escapes dashboard text through `HTMLEscape` for dashboard HTML text. UI-bound strings are escaped and unescaped without importing html directly.

Println(HTMLEscape(`<span data-x="1">Core & Go</span>`))
Output:
&lt;span data-x=&#34;1&#34;&gt;Core &amp; Go&lt;/span&gt;

func HTMLUnescape

func HTMLUnescape(s string) string

HTMLUnescape returns s with HTML character references unescaped.

unescaped := core.HTMLUnescape("&lt;strong&gt;Go&lt;/strong&gt;")
Example

ExampleHTMLUnescape unescapes dashboard text through `HTMLUnescape` for dashboard HTML text. UI-bound strings are escaped and unescaped without importing html directly.

Println(HTMLUnescape("&lt;strong&gt;Core&lt;/strong&gt;"))
Output:
<strong>Core</strong>

func HTTPError added in v0.10.0

func HTTPError(w ResponseWriter, error string, code int)

HTTPError replies to the request with the given status code and a plain-text error message body.

if !valid {
    core.HTTPError(w, "missing field", core.StatusBadRequest)
    return
}
Example
rec := NewHTTPTestRecorder()
HTTPError(rec, "missing field", StatusBadRequest)
Println(rec.Code)
Println(rec.Body.String())
Output:
400
missing field

func HTTPStatusText

func HTTPStatusText(code int) string

HTTPStatusText returns the canonical text for an HTTP status code, e.g. 200 → "OK".

status := core.HTTPStatusText(202)
core.Println(status)
Example

ExampleHTTPStatusText reads status reason text through `HTTPStatusText` for a Lethean drive integration. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

Println(HTTPStatusText(201))
Output:
Created

func HasPrefix

func HasPrefix(s, prefix string) bool

HasPrefix returns true if s starts with prefix.

core.HasPrefix("--verbose", "--")  // true
Example

ExampleHasPrefix checks a text prefix through `HasPrefix` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(HasPrefix("--verbose", "--"))
Output:
true

func HasSuffix

func HasSuffix(s, suffix string) bool

HasSuffix returns true if s ends with suffix.

core.HasSuffix("test.go", ".go")  // true
Example

ExampleHasSuffix checks a text suffix through `HasSuffix` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(HasSuffix("report.pdf", ".pdf"))
Output:
true

func HexEncode

func HexEncode(src []byte) string

HexEncode returns src encoded as a lowercase hexadecimal string.

s := core.HexEncode([]byte("hello"))

Zero-copy: skips the stdlib EncodeToString return-side copy by aliasing the freshly-allocated dst buffer via AsString. Saves one alloc per call — load-bearing on SHA256HexString and friends.

Example

ExampleHexEncode encodes bytes as hex through `HexEncode` for token and payload encoding. Byte and string encoders return predictable wrapper values for tokens and payloads.

Println(HexEncode([]byte("hello")))
Output:
68656c6c6f

func ID

func ID() string

ID returns a unique identifier. Format: "id-{counter}-{random}". Counter is process-wide atomic. Random suffix prevents collision across restarts.

id := core.ID()  // "id-1-a3f2b1"
id2 := core.ID() // "id-2-c7e4d9"

Implementation: builds into a single pre-sized []byte then handed to AsString — one heap allocation total even when the prefix + counter + hex suffix would otherwise each cost a string. Previously cost 5 allocs through Concat / FormatUint / RandomBytes / HexEncode / final.

Example
id := ID()
Println(HasPrefix(id, "id-"))
Output:
true
Example (Format)

ExampleID_format formats an identifier through `ID` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

id := ID()
Println(HasPrefix(id, "id-"))
Output:
true

func Index added in v0.10.0

func Index(s, sep string) int

Index returns the byte position of the first occurrence of sep in s, or -1 when sep is absent.

core.Index("key=value", "=")         // 3
core.Index("nothing here", "?")      // -1
Example

ExampleIndex finds a substring position through `Index` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(Index("key=value", "="))
Output:
3

func IndexAny added in v0.10.4

func IndexAny(s, chars string) int

IndexAny returns the byte position of the first occurrence in s of any Unicode code point in chars, or -1 when none are present. The character-class form of Index.

core.IndexAny("a/b\\c", "/\\")  // 1
Example

ExampleIndexAny returns the first index of any listed rune through `IndexAny`.

Println(IndexAny("agent", "ge"))
Output:
1

func Info

func Info(msg string, keyvals ...any)

Info logs to the default logger.

core.Info("agent started", "service", "homelab")
Example

ExampleInfo writes an info event through `Info` for operator logging. Loggers support levels, redaction, and default routing for operator output.

old := Default()
defer SetDefault(old)

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelInfo, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
SetDefault(log)
Info("server started", "port", 8080)
Println(Contains(buf.String(), "[INF] server started port=8080"))
Output:
true

func Is

func Is(err, target error) bool

Is reports whether any error in err's tree matches target. Wrapper around errors.Is for convenience.

err := core.Wrap(core.EOF, "stream.Read", "agent stream closed")
if core.Is(err, core.EOF) { core.Println("done") }
Example

ExampleIs matches an error through `Is` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

cause := NewError("root")
err := Wrap(cause, "worker.Run", "failed")
Println(Is(err, cause))
Output:
true

func IsDigit

func IsDigit(r rune) bool

IsDigit reports whether r is a decimal digit.

core.IsDigit('9')  // true
Example

ExampleIsDigit checks a digit through `IsDigit` for input normalisation. Character checks and case conversion stay behind core unicode helpers.

Println(IsDigit('7'))
Output:
true

func IsExist

func IsExist(err error) bool

IsExist reports whether err indicates an existing path.

if core.IsExist(err) { core.Println("exists") }
Example

ExampleIsExist reports whether an error means "already exists" through `IsExist`.

r := Mkdir(TempDir(), 0o755) // TempDir already exists
if !r.OK {
	_ = IsExist(r.Value.(error))
}

func IsFlag

func IsFlag(arg string) bool

IsFlag returns true if the argument starts with a dash.

core.IsFlag("--verbose")  // true
core.IsFlag("-v")         // true
core.IsFlag("deploy")    // false
Example

ExampleIsFlag checks flag syntax through `IsFlag` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

Println(IsFlag("--verbose"))
Println(IsFlag("deploy"))
Output:
true
false

func IsLetter

func IsLetter(r rune) bool

IsLetter reports whether r is a letter.

core.IsLetter('A')  // true
Example

ExampleIsLetter checks a letter through `IsLetter` for input normalisation. Character checks and case conversion stay behind core unicode helpers.

Println(IsLetter('A'))
Println(IsLetter('7'))
Output:
true
false

func IsLower

func IsLower(r rune) bool

IsLower reports whether r is a lowercase letter.

core.IsLower('a')  // true
Example

ExampleIsLower checks lowercase text through `IsLower` for input normalisation. Character checks and case conversion stay behind core unicode helpers.

Println(IsLower('a'))
Output:
true

func IsNaN

func IsNaN(x float64) bool

IsNaN reports whether x is a floating-point NaN.

if core.IsNaN(value) { return core.E("math", "not a number", nil) }
Example

ExampleIsNaN tests for not-a-number through `IsNaN` for float validation. Numeric helpers keep thresholds readable without importing math directly.

Println(IsNaN(NaN()))
Println(IsNaN(1.0))
Output:
true
false

func IsNotExist

func IsNotExist(err error) bool

IsNotExist reports whether err indicates a missing path.

if core.IsNotExist(err) { core.Println("missing") }
Example

ExampleIsNotExist reports whether an error means "not found" through `IsNotExist`.

Println(IsNotExist(ErrNotExist))
Output:
true

func IsPermission

func IsPermission(err error) bool

IsPermission reports whether err indicates a permission failure.

if core.IsPermission(err) { core.Println("denied") }
Example

ExampleIsPermission reports whether an error means "permission denied" through `IsPermission`.

r := Open("/root/secret-core-example")
if !r.OK {
	_ = IsPermission(r.Value.(error))
}

func IsSpace

func IsSpace(r rune) bool

IsSpace reports whether r is a space character.

core.IsSpace('\n')  // true
Example

ExampleIsSpace checks whitespace through `IsSpace` for input normalisation. Character checks and case conversion stay behind core unicode helpers.

Println(IsSpace('\n'))
Output:
true

func IsUpper

func IsUpper(r rune) bool

IsUpper reports whether r is an uppercase letter.

core.IsUpper('A')  // true
Example

ExampleIsUpper checks uppercase text through `IsUpper` for input normalisation. Character checks and case conversion stay behind core unicode helpers.

Println(IsUpper('A'))
Output:
true

func Itoa

func Itoa(i int) string

Itoa converts an int to a decimal string.

s := core.Itoa(42)
Example

ExampleItoa formats an integer through `Itoa` for CLI argument conversion. Numeric parsing and formatting use core helpers for CLI-friendly values.

Println(Itoa(42))
Output:
42

func JSONMarshalString

func JSONMarshalString(v any) string

JSONMarshalString serialises a value to a JSON string.

s := core.JSONMarshalString(myStruct)
Example

ExampleJSONMarshalString serialises a value to JSON text through `JSONMarshalString` for configuration serialisation. Serialisation and parsing return core Results for configuration payloads.

type appConfig struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}
Println(JSONMarshalString(appConfig{Host: "localhost", Port: 8080}))
Output:
{"host":"localhost","port":8080}

func JSONValid added in v0.10.4

func JSONValid(data []byte) bool

JSONValid reports whether data is a well-formed JSON encoding. Use it to gate a payload before storing or forwarding it without paying a full Unmarshal into a throwaway target.

if !core.JSONValid(body) { return core.NewError("malformed JSON body") }
Example

ExampleJSONValid gates a payload without decoding it.

Println(JSONValid([]byte(`{"ok":true}`)))
Println(JSONValid([]byte(`{"ok":`)))
Output:
true
false

func Join

func Join(sep string, parts ...string) string

Join joins parts with a separator into a single string.

core.Join("/", "deploy", "to", "homelab")      // "deploy/to/homelab"
core.Join(".", "cmd", "deploy", "description")  // "cmd.deploy.description"
Example

ExampleJoin joins text fields through `Join` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(Join("/", "deploy", "to", "homelab"))
Output:
deploy/to/homelab

func JoinPath

func JoinPath(segments ...string) string

JoinPath joins string segments into a path with "/" separator.

core.JoinPath("deploy", "to", "homelab")  // → "deploy/to/homelab"
Example

ExampleJoinPath joins path segments through `JoinPath` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

Println(JoinPath("deploy", "to", "homelab"))
Output:
deploy/to/homelab
Example (Utils)

ExampleJoinPath_utils joins path segments through `JoinPath` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

Println(JoinPath("deploy", "to", "homelab"))
Output:
deploy/to/homelab

func Keccak256

func Keccak256(data []byte) [32]byte

Keccak256 returns the legacy pre-NIST Keccak-256 digest of data.

Keccak-256 uses legacy Keccak padding/domain separator (0x01). It differs from FIPS-202 SHA3-256, which uses standardized SHA-3 padding (0x06).

sum := core.Keccak256([]byte("hello"))
Example

ExampleKeccak256 hashes bytes with Keccak through `Keccak256` for Ethereum-compatible digest work. SHA3 and Keccak helpers cover Ethereum-compatible digest inputs without direct crypto imports.

sum := Keccak256([]byte("hello"))
Println(HexEncode(sum[:])[:16])
Output:
1c8aff950685c2ed

func Keccak256Hex

func Keccak256Hex(data []byte) string

Keccak256Hex returns the legacy pre-NIST Keccak-256 digest as lowercase hexadecimal.

sum := core.Keccak256Hex([]byte("hello"))
Example

ExampleKeccak256Hex hashes bytes with Keccak and hex output through `Keccak256Hex` for Ethereum-compatible digest work. SHA3 and Keccak helpers cover Ethereum-compatible digest inputs without direct crypto imports.

Println(Keccak256Hex([]byte("hello"))[:16])
Output:
1c8aff950685c2ed

func LSPDiagnosticSources

func LSPDiagnosticSources() []string

LSPDiagnosticSources returns the registered source names sorted alphabetically — useful for capability negotiation and debug pages.

for _, name := range core.LSPDiagnosticSources() {
    core.Println("LSP source:", name)
}
Example

ExampleLSPDiagnosticSources lists registered diagnostic sources through `LSPDiagnosticSources`.

_ = LSPDiagnosticSources() // the names of every registered diagnostic source

func LSPRegisterDiagnostic

func LSPRegisterDiagnostic(name string, fn LSPDiagnosticSource)

LSPRegisterDiagnostic adds a named diagnostic source. The source runs on every textDocument/didOpen and didSave event. Replacing a source with the same name overwrites the previous registration.

core.LSPRegisterDiagnostic("test-imports", testImportsDiagnostic)
core.LSPRegisterDiagnostic("spor", sporDiagnostic)
Example

ExampleLSPRegisterDiagnostic registers a diagnostic source through `LSPRegisterDiagnostic`.

LSPRegisterDiagnostic("example-linter", func(uri string, content []byte) []LSPDiagnostic {
	return nil
})
// Registered sources are global process state; no deterministic output.

func LastIndex added in v0.10.0

func LastIndex(s, substr string) int

LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present. Mirrors strings.LastIndex; pair with Index when consumer code needs both ends of a delimiter.

colon := core.LastIndex("host.example.com:8080", ":")  // 16
Example

ExampleLastIndex finds the last instance of a substring through `LastIndex` for command text handling. Pair with Index when consumer code needs both ends of a delimiter.

Println(LastIndex("host.example.com:8080", ":"))
Println(LastIndex("no-colon", ":"))
Output:
16
-1

func LookupEnv

func LookupEnv(key string) (string, bool)

LookupEnv retrieves the value of the environment variable named by key.

value, ok := core.LookupEnv("FORGE_TOKEN")
Example

ExampleLookupEnv reports whether an environment variable is set through `LookupEnv`.

Setenv("CORE_EXAMPLE", "x")
_, ok := LookupEnv("CORE_EXAMPLE")
Println(ok)
Unsetenv("CORE_EXAMPLE")
Output:
true

func Lower

func Lower(s string) string

Lower returns s in lowercase.

core.Lower("HELLO")  // "hello"
Example

ExampleLower normalises text to lower case through `Lower` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(Lower("HELLO"))
Output:
hello

func MapClone

func MapClone[K comparable, V any](m map[K]V) map[K]V

MapClone returns a shallow clone of m. A nil map remains nil.

copy := core.MapClone(map[string]int{"a": 1})
Example

ExampleMapClone clones a map through `MapClone` for metadata maps. Map helpers cover selection, cloning, filtering, and merging with typed values.

original := map[string]int{"api": 8080}
clone := MapClone(original)
clone["api"] = 8181

Println(original["api"])
Println(clone["api"])
Output:
8080
8181

func MapFilter

func MapFilter[K comparable, V any](m map[K]V, pred func(K, V) bool) map[K]V

MapFilter returns a new map containing only entries for which pred returns true. A nil result is returned for an empty input.

enabled := core.MapFilter(features, func(name string, on bool) bool { return on })
Example

ExampleMapFilter filters a map through `MapFilter` for metadata maps. Map helpers cover selection, cloning, filtering, and merging with typed values.

features := map[string]bool{"stable": true, "experimental": false}
enabled := MapFilter(features, func(_ string, on bool) bool { return on })
Println(MapHasKey(enabled, "stable"))
Println(MapHasKey(enabled, "experimental"))
Output:
true
false

func MapHasKey

func MapHasKey[K comparable, V any](m map[K]V, k K) bool

MapHasKey reports whether k is present in m.

if core.MapHasKey(config, "debug") { ... }
Example

ExampleMapHasKey checks a map key through `MapHasKey` for metadata maps. Map helpers cover selection, cloning, filtering, and merging with typed values.

Println(MapHasKey(map[string]int{"port": 8080}, "port"))
Output:
true

func MapKeys

func MapKeys[K comparable, V any](m map[K]V) []K

MapKeys returns the keys from m. Map iteration order is not stable; sort the result when order matters.

keys := core.MapKeys(map[string]int{"a": 1, "b": 2})
Example

ExampleMapKeys lists map keys through `MapKeys` for metadata maps. Map helpers cover selection, cloning, filtering, and merging with typed values.

ports := map[string]int{"api": 8080, "admin": 9090}
keys := MapKeys(ports)
SliceSort(keys)
Println(keys)
Output:
[admin api]

func MapMerge

func MapMerge[K comparable, V any](a, b map[K]V) map[K]V

MapMerge returns a new map containing all entries from a and b. When a key appears in both, b's value wins.

combined := core.MapMerge(defaults, overrides)
Example

ExampleMapMerge merges maps through `MapMerge` for metadata maps. Map helpers cover selection, cloning, filtering, and merging with typed values.

defaults := map[string]int{"port": 8080, "workers": 2}
overrides := map[string]int{"workers": 4}
merged := MapMerge(defaults, overrides)

Println(merged["port"])
Println(merged["workers"])
Output:
8080
4

func MapString added in v0.11.0

func MapString[K comparable](m map[K]any, key K) string

MapString returns the string at key, or "" when the key is absent or its value is not a string — the safe typed accessor for a decoded map[K]any (a JSON object, a metadata blob), replacing the hand-rolled strVal helpers across consumers.

name := core.MapString(row, "name")

func MapValues

func MapValues[K comparable, V any](m map[K]V) []V

MapValues returns the values from m. Map iteration order is not stable; sort the result when order matters.

values := core.MapValues(map[string]int{"a": 1, "b": 2})
Example

ExampleMapValues lists map values through `MapValues` for metadata maps. Map helpers cover selection, cloning, filtering, and merging with typed values.

ports := map[string]int{"api": 8080, "admin": 9090}
values := MapValues(ports)
SliceSort(values)
Println(values)
Output:
[8080 9090]

func Max

func Max[T Ordered](a, b T) T

Max returns the larger of a and b.

high := core.Max(3, 7)
Example

ExampleMax selects the higher value through `Max` for health-check thresholds. Numeric helpers keep thresholds readable without importing math directly.

Println(Max(3, 7))
Output:
7

func Min

func Min[T Ordered](a, b T) T

Min returns the smaller of a and b.

low := core.Min(3, 7)
Example

ExampleMin selects the lower value through `Min` for health-check thresholds. Numeric helpers keep thresholds readable without importing math directly.

Println(Min(3, 7))
Output:
3

func MustCast

func MustCast[T any](r Result) T

MustCast extracts a typed value from a Result. Panics with the underlying error when the Result is not OK or when Value isn't assignable to T. Use for fast-fail paths — init, test setup, must-have config — where the type-assertion is part of the contract.

cfg := core.MustCast[*Config](core.JSONUnmarshal(data, &Config{}))
dir := core.MustCast[string](core.PathAbs("."))
Example

ExampleMustCast unwraps and type-asserts a Result through `MustCast` for Result-based control flow. Success, fallback, casting, and error inspection all use the same Result shape.

n := MustCast[int](Ok(42))
Println(n)
Output:
42

func MustServiceFor

func MustServiceFor[T any](c *Core, name string) T

MustServiceFor retrieves a registered service by name and asserts its type. Panics if the service is not found or the type assertion fails.

cli := core.MustServiceFor[*Cli](c, "cli")
Example

ExampleMustServiceFor retrieves a required typed service through `MustServiceFor` for service registration. Services register by name and can be recovered with typed helpers.

c := New()
c.RegisterService("worker", &exampleRegisteredService{name: "worker"})
svc := MustServiceFor[*exampleRegisteredService](c, "worker")
Println(svc.name)
Output:
worker

func NaN

func NaN() float64

NaN returns an IEEE 754 not-a-number value.

if core.IsNaN(x) { x = 0 }
Example

ExampleNaN produces an IEEE-754 not-a-number through `NaN` for float sentinels. Numeric helpers keep thresholds readable without importing math directly.

Println(IsNaN(NaN()))
Output:
true

func NetPipe

func NetPipe() (Conn, Conn)

NetPipe returns a connected, in-memory, full-duplex Conn pair. Useful for testing protocols against a real Conn without a real socket.

a, b := core.NetPipe()
defer a.Close(); defer b.Close()
Example

ExampleNetPipe creates an in-memory connection pair through `NetPipe` for network health checks. Network primitives are reached through core wrappers and Result-shaped calls.

left, right := NetPipe()
defer right.Close()

go func() {
	WriteString(left, "ping")
	left.Close()
}()

data := ReadAll(right)
Println(data.Value)
Output:
ping

func NewBuffer

func NewBuffer(b ...[]byte) *bytes.Buffer

NewBuffer returns a bytes.Buffer initialised with b. With no input, it returns an empty bytes.Buffer.

buf := core.NewBuffer([]byte("hello"))
empty := core.NewBuffer()
Example

ExampleNewBuffer creates an empty buffer through `NewBuffer` for in-memory payload assembly. Buffer creation stays on the core wrapper surface for later stream or encoding work.

buf := NewBuffer([]byte("hello"))
Println(buf.String())

empty := NewBuffer()
Println(empty.Len())
Output:
hello
0

func NewBufferReader added in v0.10.0

func NewBufferReader(b []byte) *bytes.Reader

NewBufferReader returns a bytes.Reader over b — the bytes flavour of NewReader, which works on strings. Use for HTTP body construction and other Reader-shaped consumers.

body := core.NewBufferReader([]byte(`{"port":8080}`))
req, _ := core.HTTPNewRequest("POST", url, body)
Example

ExampleNewBufferReader creates a bytes.Reader over a byte slice through `NewBufferReader` for HTTP body construction. Buffer creation stays on the core wrapper surface for later stream or encoding work.

rd := NewBufferReader([]byte("hello"))
out := make([]byte, 5)
rd.Read(out)
Println(string(out))
Output:
hello

func NewBufferString

func NewBufferString(s string) *bytes.Buffer

NewBufferString returns a bytes.Buffer initialised with s.

buf := core.NewBufferString("hello")
Example

ExampleNewBufferString creates a buffer from existing text through `NewBufferString` for in-memory payload assembly. Buffer creation stays on the core wrapper surface for later stream or encoding work.

buf := NewBufferString("hello world")
Println(buf.String())
Println(buf.Len())
Output:
hello world
11

func NewBuilder

func NewBuilder() *strings.Builder

NewBuilder returns a new strings.Builder.

b := core.NewBuilder()
b.WriteString("hello")
b.String() // "hello"
Example

ExampleNewBuilder builds text incrementally through `NewBuilder` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

b := NewBuilder()
b.WriteString("hello")
b.WriteString(" world")
Println(b.String())
Output:
hello world

func NewCode

func NewCode(code, msg string) error

NewCode creates an error with just code and message (no underlying error). Useful for creating sentinel errors with codes.

Example:

var ErrNotFound = log.NewCode("NOT_FOUND", "resource not found")
Example

ExampleNewCode creates a coded error through `NewCode` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := NewCode("NOT_FOUND", "resource missing")
Println(ErrorCode(err))
Println(ErrorMessage(err))
Output:
NOT_FOUND
resource missing

func NewError

func NewError(text string) error

NewError creates a simple core.*Err carrying the given text. Returns *Err so introspection helpers (Operation/ErrorCode/ ErrorMessage) work uniformly across NewError, NewCode, and E.

err := core.NewError("config.host missing")
core.Println(err.Error())
Example

ExampleNewError creates a simple error through `NewError` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := NewError("plain error")
Println(err.Error())
Output:
plain error

func NewLineScanner

func NewLineScanner(r Reader) *bufio.Scanner

NewLineScanner returns a bufio.Scanner configured for line-oriented reads.

scanner := core.NewLineScanner(r)
Example

ExampleNewLineScanner scans lines through `NewLineScanner` for line-oriented logs. Line scanning stays on the core wrapper surface, including larger buffer cases.

scanner := NewLineScanner(NewReader("alpha\nbravo\n"))
for scanner.Scan() {
	Println(scanner.Text())
}
Output:
alpha
bravo

func NewLineScannerWithSize

func NewLineScannerWithSize(r Reader, max int) *bufio.Scanner

NewLineScannerWithSize returns a bufio.Scanner configured for line-oriented reads with a custom maximum line size.

scanner := core.NewLineScannerWithSize(r, 2*1024*1024)
Example

ExampleNewLineScannerWithSize scans long lines through `NewLineScannerWithSize` for line-oriented logs. Line scanning stays on the core wrapper surface, including larger buffer cases.

scanner := NewLineScannerWithSize(NewReader("alpha\n"), 1024)
Println(scanner.Scan())
Println(scanner.Text())
Output:
true
alpha

func NewReader

func NewReader(s string) *strings.Reader

NewReader returns a strings.NewReader for the given string.

r := core.NewReader("hello world")
Example

ExampleNewReader creates a text reader through `NewReader` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

r := ReadAll(NewReader("hello"))
Println(r.Value)
Output:
hello

func Now

func Now() time.Time

Now returns the current local time.

started := core.Now()
Example

ExampleNow reads the current time through `Now` for health-check timing. Durations, parsing, and timestamps use core time wrappers for service code.

Println(!Now().IsZero())
Output:
true

func NumCPU

func NumCPU() int

NumCPU returns the number of logical CPUs available to the running process.

workers := core.NumCPU()
core.Println(workers)
Example

ExampleNumCPU returns the number of logical CPUs through `NumCPU`.

Println(NumCPU() > 0)
Output:
true

func OS

func OS() string

OS returns the operating system name (darwin, linux, windows, etc.) the binary is running on.

if core.OS() == "darwin" { core.Println("on a Mac") }
Example

ExampleOS returns the host operating system through `OS` (e.g. "darwin", "linux").

Println(OS())

func On added in v0.12.0

func On[T Message](c *Core, fn func(T) Result)

On registers a type-filtered broadcast subscriber — typed sugar over RegisterAction that removes the hand-written message type switch. Non-matching messages pass with OK (broadcast semantics: not mine). The bus itself stays untyped (the three-line law); typing happens at the subscription boundary.

core.On(c, func(ev core.ActionTaskCompleted) core.Result {
    core.Info("task done", "id", ev.TaskIdentifier)
    return core.Ok(nil)
})
Example

ExampleOn subscribes with a typed handler — no hand-written switch.

c := New()
On(c, func(ev ActionTaskProgress) Result {
	Println(ev.Message)
	return Ok(nil)
})
c.ACTION(ActionTaskProgress{Message: "halfway"})
Output:
halfway

func Operation

func Operation(err error) string

Operation extracts the operation name from an error. Returns empty string if the error is not an *Err.

err := core.E("agent.Run", "failed", nil)
op := core.Operation(err)
core.Println(op)
Example

ExampleOperation reads the operation from an error through `Operation` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := E("cache.Get", "missing", nil)
Println(Operation(err))
Output:
cache.Get

func ParseFlag

func ParseFlag(arg string) (key, value string, valid bool)

ParseFlag parses a single flag argument into key, value, and validity. Single dash (-) requires exactly 1 character (letter, emoji, unicode). Double dash (--) requires 2+ characters.

"-v"           → "v", "", true
"-🔥"          → "🔥", "", true
"--verbose"    → "verbose", "", true
"--port=8080"  → "port", "8080", true
"-verbose"     → "", "", false  (single dash, 2+ chars)
"--v"          → "", "", false  (double dash, 1 char)
"hello"        → "", "", false  (not a flag)
Example

ExampleParseFlag parses a flag through `ParseFlag` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

key, value, ok := ParseFlag("--target=homelab")
Println(key)
Println(value)
Println(ok)
Output:
target
homelab
true

func Path

func Path(segments ...string) string

Path builds a clean, absolute filesystem path from segments. Uses Env("DS") for the OS directory separator. Relative paths are anchored to DIR_HOME. Absolute paths pass through.

core.Path("Code", ".core")      // "/Users/snider/Code/.core"
core.Path("/tmp", "workspace")  // "/tmp/workspace"
core.Path()                     // "/Users/snider"
Example

ExamplePath constructs a clean path through `Path` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

Println(PathBase(Path("Code", "core")))
Println(PathBase(Path("/tmp", "workspace")))
Output:
core
workspace

func PathBase

func PathBase(p string) string

PathBase returns the last element of a path.

core.PathBase("/Users/snider/Code/core")  // "core"
core.PathBase("deploy/to/homelab")        // "homelab"
Example

ExamplePathBase reads a base name through `PathBase` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

Println(PathBase("/srv/workspaces/alpha"))
Output:
alpha

func PathChangeExt

func PathChangeExt(p, newExt string) string

PathChangeExt returns p with its file extension replaced by newExt. newExt may include a leading dot or omit it — both forms are accepted. If p has no extension, newExt is appended.

core.PathChangeExt("data.json", ".yaml")  // "data.yaml"
core.PathChangeExt("data.json", "yaml")   // "data.yaml"
core.PathChangeExt("README", ".md")       // "README.md"
Example

ExamplePathChangeExt rewrites a file extension through `PathChangeExt` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

Println(PathChangeExt("config.json", "yaml"))
Println(PathChangeExt("README", ".md"))
Output:
config.yaml
README.md

func PathDir

func PathDir(p string) string

PathDir returns all but the last element of a path.

core.PathDir("/Users/snider/Code/core")  // "/Users/snider/Code"
Example

ExamplePathDir reads a directory name through `PathDir` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

Println(PathDir("/srv/workspaces/alpha"))
Output:
/srv/workspaces

func PathExt

func PathExt(p string) string

PathExt returns the file extension including the dot.

core.PathExt("main.go")   // ".go"
core.PathExt("Makefile")  // ""
Example

ExamplePathExt reads an extension through `PathExt` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

Println(PathExt("report.pdf"))
Output:
.pdf

func PathGlob

func PathGlob(pattern string) []string

PathGlob returns file paths matching a pattern.

core.PathGlob("/tmp/agent-*.log")
Example

ExamplePathGlob expands a glob through `PathGlob` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-path-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "a.txt"), "a")
fs.Write(Path(dir, "b.txt"), "b")

matches := PathGlob(Path(dir, "*.txt"))
for i, match := range matches {
	matches[i] = PathBase(match)
}
SliceSort(matches)
Println(matches)
Output:
[a.txt b.txt]

func PathIsAbs

func PathIsAbs(p string) bool

PathIsAbs returns true if the path is absolute. Handles Unix (starts with /) and Windows (drive letter like C:).

core.PathIsAbs("/tmp")     // true
core.PathIsAbs("C:\\tmp")  // true
core.PathIsAbs("relative") // false
Example

ExamplePathIsAbs checks whether a path is absolute through `PathIsAbs` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

Println(PathIsAbs("/tmp/workspace"))
Println(PathIsAbs("workspace"))
Output:
true
false

func PathJoin

func PathJoin(segments ...string) string

PathJoin joins path segments using OS-native filepath semantics. Unlike Path, it preserves relative paths.

core.PathJoin("deploy", "to", "homelab") // "deploy/to/homelab"
Example

ExamplePathJoin joins elements with the OS separator through `PathJoin`.

Println(PathJoin("workspace", "agent", "readme.md"))
Output:
workspace/agent/readme.md

func PathToSlash

func PathToSlash(p string) string

PathToSlash converts OS-native separators in p to slash separators.

p := core.PathToSlash(core.PathJoin("templates", "agent"))
Example

ExamplePathToSlash converts OS separators to forward slashes through `PathToSlash`.

Println(PathToSlash(PathJoin("a", "b")))
Output:
a/b

func PinSlice added in v0.10.3

func PinSlice[T any](slice []T, view *PinnedView)

PinSlice pins slice's backing array and populates view in place. view must point to a stack or heap PinnedView (typically a local variable). The function is safe to call with an empty slice; in that case view is left zero-valued and Release is a no-op.

var view core.PinnedView
core.PinSlice(indices, &view)
defer view.Release()
C.fn(view.Ptr(), C.size_t(view.Len()))
Example

ExamplePinSlice pins a slice's backing array for the cgo boundary through `PinSlice`.

var view PinnedView
PinSlice([]int32{1, 2, 3, 4}, &view)
defer view.Release()
Println(view.Len())
Output:
4

func Pow

func Pow(x, y float64) float64

Pow returns x raised to the power y.

squared := core.Pow(4, 2)
Example

ExamplePow raises a value to a power through `Pow` for health-check thresholds. Numeric helpers keep thresholds readable without importing math directly.

Println(Pow(2, 3))
Output:
8

func Print

func Print(w Writer, format string, args ...any)

Print writes a formatted line to a writer (defaulting to stdout when w is nil), appending a newline. The canonical formatted-output helper.

core.Print(nil, "hello %s", "world")    // → stdout
core.Print(buf, "port: %d", 8080)       // → buf
Example

ExamplePrint writes formatted output to a writer through `Print`.

buf := NewBuffer()
Print(buf, "%s ready", "agent")
Println(buf.String())
Output:
agent ready

func Println

func Println(args ...any)

Println prints values to stdout separated by spaces with a trailing newline. The canonical replacement for fmt.Println.

core.Println("hello", 42, true)
Example

ExamplePrintln writes a line to stdout through `Println`.

Println("agent ready")
Output:
agent ready

func Pull

func Pull[V any](seq Seq[V]) (next func() (V, bool), stop func())

Pull converts a push-style Seq into a pull-style (next, stop) pair. next() returns (value, ok); stop() releases iterator resources.

next, stop := core.Pull(seq)
defer stop()
for {
    v, ok := next()
    if !ok { break }
    core.Println(v)
}
Example
var seq Seq[int] = func(yield func(int) bool) {
	for i := 1; i <= 3; i++ {
		if !yield(i) {
			return
		}
	}
}

next, stop := Pull(seq)
defer stop()
for {
	v, ok := next()
	if !ok {
		break
	}
	Println(v)
}
Output:
1
2
3

func Pull2

func Pull2[K, V any](seq Seq2[K, V]) (next func() (K, V, bool), stop func())

Pull2 converts a push-style Seq2 into a pull-style (next, stop) pair. next() returns (key, value, ok); stop() releases iterator resources.

next, stop := core.Pull2(entries)
defer stop()
for {
    k, v, ok := next()
    if !ok { break }
    core.Println(k, v)
}
Example
var seq Seq2[string, int] = func(yield func(string, int) bool) {
	_ = yield("a", 1) && yield("b", 2)
}

next, stop := Pull2(seq)
defer stop()
for {
	k, v, ok := next()
	if !ok {
		break
	}
	Println(k, v)
}
Output:
a 1
b 2

func RandIntn

func RandIntn(n int) int

RandIntn returns a pseudo-random integer in [0, n). It panics when n is less than or equal to zero; use it for fast non-crypto values.

index := core.RandIntn(len(items))
Example

ExampleRandIntn generates a bounded pseudo-random integer through `RandIntn` for session nonce generation. Nonces, strings, and bounded integers return Results suitable for session work.

n := RandIntn(5)
Println(n >= 0 && n < 5)
Output:
true

func RandPick

func RandPick[T any](items []T) T

RandPick returns a pseudo-random item from items. It panics when items is empty; use it for fast non-crypto selection only.

choice := core.RandPick([]string{"red", "green", "blue"})
Example

ExampleRandPick picks a random element through `RandPick` for session nonce generation. Nonces, strings, and bounded integers return Results suitable for session work.

choices := []string{"alpha", "bravo", "charlie"}
Println(SliceContains(choices, RandPick(choices)))
Output:
true

func Repeat added in v0.10.4

func Repeat(s string, count int) string

Repeat returns a new string consisting of count copies of s. It panics when count is negative or the result overflows (stdlib contract); callers control both inputs so this stays infallible.

core.Repeat("=", 8)  // "========"
Example

ExampleRepeat builds a fixed-width rule through `Repeat`.

Println(Repeat("=", 8))
Output:
========

func Replace

func Replace(s, old, new string) string

Replace replaces all occurrences of old with new in s.

core.Replace("deploy/to/homelab", "/", ".")  // "deploy.to.homelab"
Example

ExampleReplace replaces text through `Replace` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(Replace("deploy/to/homelab", "/", "."))
Output:
deploy.to.homelab

func RequireNoError

func RequireNoError(t TB, err error, msg ...string)

RequireNoError fails the test AND stops it if err is non-nil. Use when the rest of the test depends on the operation succeeding.

core.RequireNoError(t, c.Fs().Write(p, "data").Error())
Example

ExampleRequireNoError requires no error through `RequireNoError` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
RequireNoError(t, nil)
Example (WithMessage)

ExampleRequireNoError_withMessage requires no error with context through `RequireNoError` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
RequireNoError(t, nil, "fixture setup")

func RequireNotEmpty

func RequireNotEmpty(t TB, v any, msg ...string)

RequireNotEmpty fails the test AND stops it if v is empty. Use to guard test invariants where downstream assertions presume non-empty fixture data.

core.RequireNotEmpty(t, fixturePath)
Example

ExampleRequireNotEmpty requires non-empty input through `RequireNotEmpty` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
RequireNotEmpty(t, []string{"alpha"})
Example (String)

ExampleRequireNotEmpty_string requires a non-empty string through `RequireNotEmpty` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
RequireNotEmpty(t, "fixturePath")

func RequireTrue

func RequireTrue(t TB, condition bool, msg ...string)

RequireTrue fails the test AND stops it if condition is false. Use to guard test invariants where continuing past a false condition is meaningless.

core.RequireTrue(t, scanner.Scan(), "scan precondition")
Example

ExampleRequireTrue requires a true condition through `RequireTrue` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
RequireTrue(t, true)
Example (WithMessage)

ExampleRequireTrue_withMessage requires a true condition with context through `RequireTrue` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
RequireTrue(t, true, "scan precondition")

func Root

func Root(err error) error

Root returns the root cause of an error chain. Unwraps until no more wrapped errors are found.

cause := core.NewError("connection refused")
err := core.Wrap(cause, "agent.Ping", "homelab unreachable")
root := core.Root(err)
core.Println(root)
Example

ExampleRoot reports the root value through `Root` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

cause := NewError("original")
wrapped := Wrap(cause, "op1", "first wrap")
double := Wrap(wrapped, "op2", "second wrap")
Println(Root(double))
Output:
original

func Round

func Round(x float64) float64

Round returns the nearest integer, rounding half away from zero.

n := core.Round(3.5)
Example

ExampleRound rounds a value to the nearest integer through `Round` for health-check thresholds. Numeric helpers keep thresholds readable without importing math directly.

Println(Round(3.5))
Output:
4

func RuneCount

func RuneCount(s string) int

RuneCount returns the number of runes (unicode characters) in s.

core.RuneCount("hello")  // 5
core.RuneCount("🔥")     // 1
Example

ExampleRuneCount counts runes through `RuneCount` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(RuneCount("hello"))
Println(RuneCount("é"))
Output:
5
1

func SHA3Shake128

func SHA3Shake128(data []byte, outLen int) []byte

SHA3Shake128 returns outLen bytes from SHAKE128 applied to data.

sum := core.SHA3Shake128([]byte("hello"), 32)
Example

ExampleSHA3Shake128 generates SHAKE128 output through `SHA3Shake128` for Ethereum-compatible digest work. SHA3 and Keccak helpers cover Ethereum-compatible digest inputs without direct crypto imports.

sum := SHA3Shake128([]byte("hello"), 8)
Println(len(sum))
Println(HexEncode(sum))
Output:
8
8eb4b6a932f28033

func SHA3Shake256

func SHA3Shake256(data []byte, outLen int) []byte

SHA3Shake256 returns outLen bytes from SHAKE256 applied to data.

sum := core.SHA3Shake256([]byte("hello"), 64)
Example

ExampleSHA3Shake256 generates SHAKE256 output through `SHA3Shake256` for Ethereum-compatible digest work. SHA3 and Keccak helpers cover Ethereum-compatible digest inputs without direct crypto imports.

sum := SHA3Shake256([]byte("hello"), 8)
Println(len(sum))
Println(HexEncode(sum))
Output:
8
1234075ae4a1e773

func SHA3_256

func SHA3_256(data []byte) [32]byte

SHA3_256 returns the FIPS-202 SHA3-256 digest of data.

SHA3-256 uses the standardized SHA-3 padding/domain separator (0x06). It is not pre-NIST Keccak-256, which uses legacy Keccak padding (0x01). Use Keccak256 for Ethereum, EVM chains, ENS, RLP signing, and other Web3 consensus hashes.

sum := core.SHA3_256([]byte("hello"))

func SHA3_256Hex

func SHA3_256Hex(data []byte) string

SHA3_256Hex returns the FIPS-202 SHA3-256 digest as lowercase hexadecimal.

sum := core.SHA3_256Hex([]byte("hello"))

func SHA256

func SHA256(data []byte) [32]byte

SHA256 returns the SHA-256 digest of data.

sum := core.SHA256([]byte("hello"))
Example

ExampleSHA256 hashes a byte payload through `SHA256` for session-token cryptography. Callers stay on the core wrapper surface while receiving fixed-size digests or Result values.

sum := SHA256([]byte("hello"))
Println(HexEncode(sum[:]))
Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

func SHA256Hex

func SHA256Hex(data []byte) string

SHA256Hex returns the SHA-256 digest of data as lowercase hexadecimal.

sum := core.SHA256Hex([]byte("hello"))
Example

ExampleSHA256Hex hashes bytes and formats hex through `SHA256Hex` for session-token cryptography. Callers stay on the core wrapper surface while receiving fixed-size digests or Result values.

Println(SHA256Hex([]byte("hello")))
Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

func SHA256HexString

func SHA256HexString(s string) string

SHA256HexString returns the SHA-256 digest of s as lowercase hexadecimal.

sum := core.SHA256HexString("hello")
Example

ExampleSHA256HexString hashes a string and formats hex through `SHA256HexString` for session-token cryptography. Callers stay on the core wrapper surface while receiving fixed-size digests or Result values.

Println(SHA256HexString("hello"))
Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

func SHA256String

func SHA256String(s string) [32]byte

SHA256String returns the SHA-256 digest of s.

sum := core.SHA256String("hello")
Example

ExampleSHA256String hashes a string payload through `SHA256String` for session-token cryptography. Callers stay on the core wrapper surface while receiving fixed-size digests or Result values.

sum := SHA256String("hello")
Println(HexEncode(sum[:]))
Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

func SQLDrivers

func SQLDrivers() []string

SQLDrivers returns a sorted list of registered driver names. Useful for diagnostics ("which drivers were imported?").

drivers := core.SQLDrivers()
core.Println(core.Join(", ", drivers...))
Example

ExampleSQLDrivers lists SQL drivers through `SQLDrivers` for database adapter setup. Database opening and sentinel checks use aliases without importing database/sql directly.

drivers := SQLDrivers()
Println(len(drivers) >= 0)
Output:
true

func SQLIsNoRows

func SQLIsNoRows(err error) bool

SQLIsNoRows is a convenience for the most common error check.

if core.SQLIsNoRows(err) { /* not found */ }
Example

ExampleSQLIsNoRows checks the no-rows sentinel through `SQLIsNoRows` for database adapter setup. Database opening and sentinel checks use aliases without importing database/sql directly.

Println(SQLIsNoRows(ErrNoRows))
Println(ErrTxDone != nil)
Output:
true
true

func SanitisePath

func SanitisePath(path string) string

SanitisePath extracts the base filename and rejects traversal attempts. Returns "invalid" for dangerous inputs.

core.SanitisePath("../../etc/passwd")  // "passwd"
core.SanitisePath("")                  // "invalid"
core.SanitisePath("..")                // "invalid"
Example
Println(SanitisePath("../../etc/passwd"))
Println(SanitisePath(""))
Println(SanitisePath("/some/path/file.txt"))
Output:
passwd
invalid
file.txt
Example (Base)

ExampleSanitisePath_base sanitises a base path through `SanitisePath` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

Println(SanitisePath("../../etc/passwd"))
Println(SanitisePath(""))
Output:
passwd
invalid

func Security

func Security(msg string, keyvals ...any)

Security logs to the default logger.

core.Security("entitlement.denied", "action", "process.run")
Example

ExampleSecurity writes a security event through `Security` for operator logging. Loggers support levels, redaction, and default routing for operator output.

old := Default()
defer SetDefault(old)

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelError, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
SetDefault(log)
Security("access denied", "user", "unknown", "action", "admin.nuke")
Println(Contains(buf.String(), `[SEC] access denied user="unknown" action="admin.nuke"`))
Output:
true

func ServiceFor

func ServiceFor[T any](c *Core, name string) (T, bool)

ServiceFor retrieves a registered service by name and asserts its type.

prep, ok := core.ServiceFor[*agentic.PrepSubsystem](c, "agentic")
Example

ExampleServiceFor retrieves a typed service through `ServiceFor` for service registration. Services register by name and can be recovered with typed helpers.

c := New(
	WithService(func(c *Core) Result {
		return c.Service("cache", Service{
			OnStart: func() Result { return Result{OK: true} },
		})
	}),
)

svc := c.Service("cache")
Println(svc.OK)
Output:
true

func SetDefault

func SetDefault(l *Log)

SetDefault sets the default logger.

log := core.NewLog(core.LogOptions{Level: core.LevelInfo, Output: core.Stdout()})
core.SetDefault(log)
Example

ExampleSetDefault replaces the default logger through `SetDefault` for operator logging. Loggers support levels, redaction, and default routing for operator output.

old := Default()
defer SetDefault(old)

log := NewLog(LogOptions{Level: LevelQuiet, Output: NewBuffer()})
SetDefault(log)
Println(Default() == log)
Output:
true

func SetLevel

func SetLevel(level Level)

SetLevel sets the default logger's level.

core.SetLevel(core.LevelWarn)
Example

ExampleSetLevel changes log level through `SetLevel` for operator logging. Loggers support levels, redaction, and default routing for operator output.

old := Default()
defer SetDefault(old)

SetDefault(NewLog(LogOptions{Level: LevelQuiet, Output: NewBuffer()}))
SetLevel(LevelDebug)
Println(Default().Level())
Output:
debug

func SetRedactKeys

func SetRedactKeys(keys ...string)

SetRedactKeys sets the default logger's redaction keys.

core.SetRedactKeys("token", "authorization")
Example

ExampleSetRedactKeys configures redaction keys through `SetRedactKeys` for operator logging. Loggers support levels, redaction, and default routing for operator output.

old := Default()
defer SetDefault(old)

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelInfo, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
SetDefault(log)
SetRedactKeys("token")
Info("auth", "token", "secret")
Println(Contains(buf.String(), `token="[REDACTED]"`))
Output:
true

func Sign added in v0.10.0

func Sign[T signedOrFloat](x T) T

Sign returns -1 when x is negative, 0 when zero, and +1 when positive. NaN inputs return 0.

dir := core.Sign(delta)
Example

ExampleSign reports the sign of a value through `Sign` for health-check thresholds. Numeric helpers keep thresholds readable without importing math directly.

Println(Sign(-3))
Output:
-1

func Since

func Since(t time.Time) time.Duration

Since returns the time elapsed since t.

elapsed := core.Since(started)
Example

ExampleSince measures elapsed time through `Since` for health-check timing. Durations, parsing, and timestamps use core time wrappers for service code.

Println(Since(UnixTime(0)) > 0)
Output:
true

func Sleep

func Sleep(d time.Duration)

Sleep pauses the current goroutine for at least d.

core.Sleep(50 * time.Millisecond)
Example

ExampleSleep pauses execution through `Sleep` for health-check timing. Durations, parsing, and timestamps use core time wrappers for service code.

Sleep(0)
Println("awake")
Output:
awake

func SliceAll

func SliceAll[T any](s []T, pred func(T) bool) bool

SliceAll reports whether every element of s satisfies pred. Vacuously true for empty slices.

allPositive := core.SliceAll(nums, func(n int) bool { return n > 0 })
Example

ExampleSliceAll checks whether every list item matches through `SliceAll` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

Println(SliceAll([]int{1, 2, 3}, func(n int) bool { return n > 0 }))
Output:
true

func SliceAny

func SliceAny[T any](s []T, pred func(T) bool) bool

SliceAny reports whether at least one element of s satisfies pred.

hasNeg := core.SliceAny(nums, func(n int) bool { return n < 0 })
Example

ExampleSliceAny checks whether any list item matches through `SliceAny` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

Println(SliceAny([]int{1, 2, 3}, func(n int) bool { return n > 2 }))
Output:
true

func SliceClone

func SliceClone[T any](s []T) []T

SliceClone returns a shallow copy of s.

copy := core.SliceClone([]string{"a", "b"})
Example

ExampleSliceSortFunc sorts a list with a comparator through `SliceSortFunc` for agent lists. Use SliceSort when natural ordering applies; SliceSortFunc covers the comparator-required cases (struct fields, mixed-criteria orderings). ExampleSliceClone returns an independent copy of a slice through `SliceClone`.

Println(SliceClone([]int{1, 2, 3}))
Output:
[1 2 3]

func SliceContains

func SliceContains[T comparable](s []T, v T) bool

SliceContains reports whether s contains v.

ok := core.SliceContains([]string{"a", "b"}, "b")
Example

ExampleSliceContains checks list membership through `SliceContains` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

Println(SliceContains([]string{"alpha", "bravo"}, "bravo"))
Output:
true

func SliceDrop

func SliceDrop[T any](s []T, n int) []T

SliceDrop returns s with the first n elements removed. If n >= len(s), returns nil. If n <= 0, returns the whole slice.

rest := core.SliceDrop(items, 1)  // tail
Example

ExampleSliceDrop drops a list prefix through `SliceDrop` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

Println(SliceDrop([]string{"alpha", "bravo", "charlie"}, 1))
Output:
[bravo charlie]

func SliceEqual added in v0.11.0

func SliceEqual[T comparable](a, b []T) bool

SliceEqual reports whether a and b have the same length and equal elements in the same order — the core surface for the common "are these two slices the same" check, replacing the hand-rolled sameIntSlice/bytesEqual/int32SlicesEqual helpers across consumers.

core.SliceEqual([]int{1, 2}, []int{1, 2}) // true
core.SliceEqual([]byte("ab"), []byte("ac")) // false

func SliceFilter

func SliceFilter[T any](s []T, pred func(T) bool) []T

SliceFilter returns a new slice containing only elements for which pred returns true. Order is preserved.

even := core.SliceFilter([]int{1, 2, 3, 4}, func(n int) bool { return n%2 == 0 })
Example

ExampleSliceFilter filters a list through `SliceFilter` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

evens := SliceFilter([]int{1, 2, 3, 4}, func(n int) bool { return n%2 == 0 })
Println(evens)
Output:
[2 4]

func SliceFlatMap

func SliceFlatMap[T any, U any](s []T, fn func(T) []U) []U

SliceFlatMap applies fn to each element of s and concatenates the resulting slices into one. Useful for "expand each input into 0-N outputs" patterns.

tokens := core.SliceFlatMap(lines, func(l string) []string {
    return core.Split(l, " ")
})
Example

ExampleSliceFlatMap expands list values through `SliceFlatMap` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

parts := SliceFlatMap([]string{"alpha bravo", "charlie"}, func(s string) []string {
	return Split(s, " ")
})
Println(parts)
Output:
[alpha bravo charlie]

func SliceIndex

func SliceIndex[T comparable](s []T, v T) int

SliceIndex returns the first index of v in s, or -1 if absent.

i := core.SliceIndex([]string{"a", "b"}, "b")
Example

ExampleSliceIndex finds a list index through `SliceIndex` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

Println(SliceIndex([]string{"alpha", "bravo"}, "bravo"))
Output:
1

func SliceMap

func SliceMap[T any, U any](s []T, fn func(T) U) []U

SliceMap returns a new slice where each element of s has been transformed by fn. Note: the name is "SliceMap" (transform a slice), not "Map" — core.Map* funcs operate on key-value maps.

upper := core.SliceMap([]string{"a", "b"}, strings.ToUpper)
lengths := core.SliceMap(words, func(w string) int { return len(w) })
Example

ExampleSliceMap maps list values through `SliceMap` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

labels := SliceMap([]int{1, 2, 3}, func(n int) string { return Sprintf("node-%d", n) })
Println(labels)
Output:
[node-1 node-2 node-3]

func SliceReduce

func SliceReduce[T any, U any](s []T, init U, fn func(U, T) U) U

SliceReduce folds s into a single accumulated value, starting from init and applying fn to each element.

sum := core.SliceReduce([]int{1, 2, 3}, 0, func(acc, n int) int { return acc + n })
concat := core.SliceReduce([]string{"a","b"}, "", func(acc, s string) string { return acc + s })
Example

ExampleSliceReduce reduces list values through `SliceReduce` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

sum := SliceReduce([]int{1, 2, 3}, 0, func(acc, n int) int { return acc + n })
Println(sum)
Output:
6

func SliceReverse

func SliceReverse[T any](s []T)

SliceReverse reverses s in place.

core.SliceReverse(items)
Example

ExampleSliceReverse reverses a list through `SliceReverse` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

names := []string{"alpha", "bravo", "charlie"}
SliceReverse(names)
Println(names)
Output:
[charlie bravo alpha]

func SliceSort

func SliceSort[T Ordered](s []T)

SliceSort sorts s in place in ascending order.

core.SliceSort(scores)
Example

ExampleSliceSort sorts a list through `SliceSort` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

names := []string{"charlie", "alpha", "bravo"}
SliceSort(names)
Println(names)
Output:
[alpha bravo charlie]

func SliceSortFunc added in v0.10.0

func SliceSortFunc[T any](s []T, less func(a, b T) bool)

SliceSortFunc sorts s in place using less to compare elements. The sort is not guaranteed to be stable. Use SliceSort when natural ordering applies; SliceSortFunc covers the comparator-required cases (sorting structs by a field, mixed-criteria order, etc.).

core.SliceSortFunc(items, func(a, b Item) bool { return a.Path < b.Path })
Example
type item struct {
	Path string
}
items := []item{{Path: "/c"}, {Path: "/a"}, {Path: "/b"}}
SliceSortFunc(items, func(a, b item) bool { return a.Path < b.Path })
for _, it := range items {
	Println(it.Path)
}
Output:
/a
/b
/c

func SliceSorted

func SliceSorted[T Ordered](seq Seq[T]) []T

SliceSorted collects seq into a sorted slice.

names := core.SliceSorted(seq)
Example

ExampleSliceSorted collects an iterator into a sorted slice through `SliceSorted`.

seq := func(yield func(int) bool) {
	for _, v := range []int{3, 1, 2} {
		if !yield(v) {
			return
		}
	}
}
Println(SliceSorted(seq))
Output:
[1 2 3]

func SliceTake

func SliceTake[T any](s []T, n int) []T

SliceTake returns at most the first n elements of s. If n >= len(s), returns the whole slice. If n <= 0, returns nil.

first3 := core.SliceTake(items, 3)
Example

ExampleSliceTake takes a list prefix through `SliceTake` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

Println(SliceTake([]string{"alpha", "bravo", "charlie"}, 2))
Output:
[alpha bravo]

func SliceUniq

func SliceUniq[T comparable](s []T) []T

SliceUniq returns a new slice with duplicate values removed, preserving order.

names := core.SliceUniq([]string{"a", "b", "a"})
Example

ExampleSliceUniq deduplicates a list through `SliceUniq` for agent lists. List transforms, predicates, and reducers remain typed core helpers.

Println(SliceUniq([]string{"alpha", "alpha", "bravo"}))
Output:
[alpha bravo]

func Split

func Split(s, sep string) []string

Split splits s by separator.

core.Split("a/b/c", "/")  // ["a", "b", "c"]
Example

ExampleSplit splits text through `Split` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

parts := Split("deploy/to/homelab", "/")
Println(parts)
Output:
[deploy to homelab]

func SplitN

func SplitN(s, sep string, n int) []string

SplitN splits s by separator into at most n parts.

core.SplitN("key=value=extra", "=", 2)  // ["key", "value=extra"]
Example

ExampleSplitN splits text with a limit through `SplitN` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(SplitN("key=value=extra", "=", 2))
Output:
[key value=extra]

func Sprint

func Sprint(args ...any) string

Sprint converts variadic values to their default string representation. Identical to fmt.Sprint.

core.Sprint(42)       // "42"
core.Sprint(err)      // "connection refused"
Example

ExampleSprint concatenates operands into a string through `Sprint`.

Println(Sprint("count=", 42))
Output:
count=42

func Sprintf

func Sprintf(format string, args ...any) string

Sprintf formats according to format and returns the resulting string. Identical to fmt.Sprintf.

core.Sprintf("%v=%q", "key", "value")  // `key="value"`
core.Sprintf("[%s] %d agents online", region, count)
Example

ExampleSprintf formats a string through `Sprintf`.

Println(Sprintf("%s=%d", "agents", 5))
Output:
agents=5

func Sprintln

func Sprintln(args ...any) string

Sprintln formats values with default formatting plus a trailing newline.

line := core.Sprintln("agent", "ready")
Example
Print(Stdout(), Sprintln("deploy", "done"))
Output:
deploy done

func StackBuf

func StackBuf() []byte

StackBuf returns the Go runtime stack trace of the current goroutine as a byte slice. Used for crash reports and panic recovery.

report := core.StackBuf()
core.Println(string(report))
Example

ExampleStackBuf captures the current goroutine stack through `StackBuf`.

Println(len(StackBuf()) > 0)
Output:
true

func StackTrace

func StackTrace(err error) []string

StackTrace returns the logical stack trace (chain of operations) from an error. It returns an empty slice if no operational context is found.

err := core.Wrap(core.E("net.Dial", "refused", nil), "agent.Ping", "homelab unreachable")
stack := core.StackTrace(err)
core.Println(core.Join(" -> ", stack...))
Example

ExampleStackTrace captures a stack trace through `StackTrace` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := Wrap(Wrap(NewError("root"), "db.Query", "failed"), "api.Get", "failed")
Println(StackTrace(err))
Output:
[api.Get db.Query]

func TempDir

func TempDir() string

TempDir returns the default directory for temporary files.

dir := core.TempDir()
Example

ExampleErrNotExist matches a failed Open against the re-exported sentinel without importing os. ExampleTempDir returns the system temporary directory through `TempDir`.

Println(TempDir() != "")
Output:
true

func Tick added in v0.10.4

func Tick(d Duration) <-chan Time

Tick is a convenience wrapper for NewTicker that returns only the channel. The underlying Ticker is never recovered, so Tick leaks and is only safe for tickers that live for the lifetime of the program. Prefer NewTicker + Stop for anything shorter-lived.

for range core.Tick(time.Minute) { poll() }
Example

ExampleTick delivers periodic ticks on a channel through `Tick`.

ch := Tick(Hour)
_ = ch // a long interval; the channel fires once per period

func TimeFormat

func TimeFormat(t time.Time, layout string) string

TimeFormat formats t as a string using the given layout. Layout constants are exported as TimeRFC3339, TimeDateTime, etc.

s := core.TimeFormat(core.Now(), core.TimeRFC3339)
Example

ExampleTimeFormat formats a timestamp through `TimeFormat` for health-check timing. Durations, parsing, and timestamps use core time wrappers for service code.

t := UnixTime(1714262400)
Println(TimeFormat(t, TimeDateOnly))
Output:
2024-04-28

func ToLower

func ToLower(r rune) rune

ToLower maps r to lowercase.

core.ToLower('A')  // 'a'
Example

ExampleToLower converts text to lower case through `ToLower` for input normalisation. Character checks and case conversion stay behind core unicode helpers.

Println(string(ToLower('A')))
Output:
a

func ToUpper

func ToUpper(r rune) rune

ToUpper maps r to uppercase.

core.ToUpper('a')  // 'A'
Example

ExampleToUpper converts text to upper case through `ToUpper` for input normalisation. Character checks and case conversion stay behind core unicode helpers.

Println(string(ToUpper('a')))
Output:
A

func Trim

func Trim(s string) string

Trim removes leading and trailing whitespace.

core.Trim("  hello  ")  // "hello"
Example

ExampleTrim trims surrounding text through `Trim` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(Trim("  spaced  "))
Output:
spaced

func TrimCutset added in v0.10.0

func TrimCutset(s, cutset string) string

TrimCutset removes any leading and trailing characters in cutset from s. The character-class form of Trim — TrimSpace handles only whitespace, TrimCutset handles arbitrary character sets.

core.TrimCutset("//path//", "/")     // "path"
core.TrimCutset("[name]", "[]")      // "name"
Example

ExampleTrimCutset trims any character class from both ends of a string through `TrimCutset` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(TrimCutset("//path//", "/"))
Output:
path

func TrimLeft added in v0.10.0

func TrimLeft(s, cutset string) string

TrimLeft removes any leading characters in cutset from s.

core.TrimLeft("///path", "/")        // "path"
core.TrimLeft("---verbose", "-")     // "verbose"
Example

ExampleTrimLeft trims any leading character class through `TrimLeft` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(TrimLeft("---verbose", "-"))
Output:
verbose

func TrimPrefix

func TrimPrefix(s, prefix string) string

TrimPrefix removes prefix from s.

core.TrimPrefix("--verbose", "--")  // "verbose"
Example

ExampleTrimPrefix removes a text prefix through `TrimPrefix` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(TrimPrefix("--verbose", "--"))
Output:
verbose

func TrimRight added in v0.10.0

func TrimRight(s, cutset string) string

TrimRight removes any trailing characters in cutset from s.

core.TrimRight("path///", "/")       // "path"
core.TrimRight("hello!!!", "!")      // "hello"
Example

ExampleTrimRight trims any trailing character class through `TrimRight` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(TrimRight("hello!!!", "!"))
Output:
hello

func TrimSuffix

func TrimSuffix(s, suffix string) string

TrimSuffix removes suffix from s.

core.TrimSuffix("test.go", ".go")  // "test"
Example

ExampleTrimSuffix removes a text suffix through `TrimSuffix` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(TrimSuffix("report.pdf", ".pdf"))
Output:
report

func URLEncode

func URLEncode(s string) string

URLEncode escapes a string for use in URL query components.

s := core.URLEncode("hello world")
Example

ExampleURLEncode encodes query text through `URLEncode` for remote endpoint handling. Endpoint parsing, escaping, and normalisation use core URL wrappers.

Println(URLEncode("hello world"))
Output:
hello+world

func URLNormalize

func URLNormalize(rawURL string) string

URLNormalize parses and re-encodes a URL into net/url's canonical string form.

s := core.URLNormalize("https://example.com/a b")
Example

ExampleURLNormalize normalises an endpoint through `URLNormalize` for remote endpoint handling. Endpoint parsing, escaping, and normalisation use core URL wrappers.

Println(URLNormalize("https://example.com/a b?q=hello world"))
Output:
https://example.com/a%20b?q=hello world

func URLPathEscape

func URLPathEscape(s string) string

URLPathEscape escapes a string for use in URL path components.

s := core.URLPathEscape("a/b")
Example

ExampleURLPathEscape escapes a path segment through `URLPathEscape` for remote endpoint handling. Endpoint parsing, escaping, and normalisation use core URL wrappers.

Println(URLPathEscape("deploy/to homelab"))
Output:
deploy%2Fto%20homelab

func UnixNow

func UnixNow() int64

UnixNow returns the current Unix timestamp in seconds.

ts := core.UnixNow()
Example

ExampleUnixNow reads the current Unix timestamp through `UnixNow` for health-check timing. Durations, parsing, and timestamps use core time wrappers for service code.

Println(UnixNow() > 0)
Output:
true

func UnixTime

func UnixTime(sec int64) time.Time

UnixTime returns the time corresponding to the given Unix timestamp (seconds since 1970-01-01 UTC).

ts := core.UnixTime(1714291200)
Example

ExampleUnixTime builds a timestamp from seconds through `UnixTime` for health-check timing. Durations, parsing, and timestamps use core time wrappers for service code.

Println(Contains(Sprint(UnixTime(0)), "1970-01-01"))
Output:
true

func Until

func Until(t time.Time) time.Duration

Until returns the duration until t.

wait := core.Until(deadline)
Example

ExampleUntil measures time until a deadline through `Until` for health-check timing. Durations, parsing, and timestamps use core time wrappers for service code.

Println(Until(UnixTime(32503680000)) > 0)
Output:
true

func Upper

func Upper(s string) string

Upper returns s in uppercase.

core.Upper("hello")  // "HELLO"
Example

ExampleUpper normalises text to upper case through `Upper` for command text handling. Text predicates and transforms stay on the core string wrapper surface.

Println(Upper("hello"))
Output:
HELLO

func Username

func Username() string

Username returns the current system username, falling back to USER / USERNAME env vars when user lookup fails (e.g. distroless containers without a /etc/passwd entry).

user := core.Username()
core.Println(user)
Example

ExampleUsername reads the current username through `Username` for operator logging. Loggers support levels, redaction, and default routing for operator output.

Println(Username() != "")
Output:
true

func Warn

func Warn(msg string, keyvals ...any)

Warn logs to the default logger.

core.Warn("agent degraded", "service", "homelab")
Example

ExampleWarn writes a warning event through `Warn` for operator logging. Loggers support levels, redaction, and default routing for operator output.

old := Default()
defer SetDefault(old)

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelWarn, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
SetDefault(log)
Warn("deprecated", "feature", "old-api")
Println(Contains(buf.String(), `[WRN] deprecated feature="old-api"`))
Output:
true

func WithCancel

func WithCancel(parent Context) (Context, CancelFunc)

WithCancel returns a copy of parent with a new cancellation channel. Calling cancel cancels the returned Context but not the parent.

ctx, cancel := core.WithCancel(core.Background())
defer cancel()
go worker(ctx)
Example

ExampleWithCancel creates a cancellable context through `WithCancel` for request lifetime control. Cancellation and timeout lifetimes are created through the core context surface.

ctx, cancel := WithCancel(Background())
cancel()
Println(ctx.Err() != nil)
Output:
true

func WithDeadline

func WithDeadline(parent Context, deadline Time) (Context, CancelFunc)

WithDeadline returns a copy of parent that cancels at deadline or when cancel is called, whichever comes first.

deadline := core.Now().Add(2 * core.Minute)
ctx, cancel := core.WithDeadline(core.Background(), deadline)
defer cancel()
Example

ExampleWithDeadline derives a context that cancels at a deadline through `WithDeadline`.

ctx, cancel := WithDeadline(Background(), Now().Add(Hour))
defer cancel()
_ = ctx // cancels automatically once the deadline passes

func WithTimeout

func WithTimeout(parent Context, d Duration) (Context, CancelFunc)

WithTimeout returns a copy of parent that cancels after d elapses or cancel is called, whichever comes first.

ctx, cancel := core.WithTimeout(core.Background(), 5*core.Second)
defer cancel()
r := core.HTTPGet("https://lthn.sh/health").WithContext(ctx)
Example

ExampleWithTimeout creates a timeout context through `WithTimeout` for request lifetime control. Cancellation and timeout lifetimes are created through the core context surface.

ctx, cancel := WithTimeout(Background(), 50*Millisecond)
defer cancel()
Println(ctx.Err() == nil)
Output:
true

func Wrap

func Wrap(err error, op, msg string) error

Wrap wraps an error with operation context. Returns nil if err is nil, to support conditional wrapping. Preserves error Code if the wrapped error is an *Err.

Example:

return log.Wrap(err, "db.Query", "database query failed")
Example

ExampleWrap wraps an error through `Wrap` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

cause := NewError("connection refused")
err := Wrap(cause, "database.Connect", "failed to reach host")
Println(Operation(err))
Println(Is(err, cause))
Output:
database.Connect
true

func WrapCode

func WrapCode(err error, code, op, msg string) error

WrapCode wraps an error with operation context and error code. Returns nil only if both err is nil AND code is empty. Useful for API errors that need machine-readable codes.

Example:

return log.WrapCode(err, "VALIDATION_ERROR", "user.Validate", "invalid email")
Example

ExampleWrapCode wraps an error with a code through `WrapCode` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := WrapCode(NewError("bad input"), "VALIDATION", "user.Save", "invalid user")
Println(ErrorCode(err))
Println(Operation(err))
Output:
VALIDATION
user.Save

Types

type API

type API struct {
	// contains filtered or unexported fields
}

API manages remote streams and protocol handlers.

c := core.New()
api := c.API()
_ = api.Protocols()

func (*API) Call

func (a *API) Call(endpoint string, action string, opts Options) Result

Call invokes a named Action on a remote endpoint. This is the remote equivalent of c.Action("name").Run(ctx, opts).

r := c.API().Call("charon", "agentic.status", opts)
Example

ExampleAPI_Call calls a remote method through `API.Call` for a Lethean drive integration. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

c := New()
c.API().RegisterProtocol("http", func(_ *DriveHandle) (Stream, error) {
	return &exampleStream{response: []byte(`{"ok":true}`)}, nil
})
c.Drive().New(NewOptions(
	Option{Key: "name", Value: "charon"},
	Option{Key: "transport", Value: "http://10.69.69.165:9101"},
))

r := c.API().Call("charon", "agent.status", NewOptions())
Println(r.Value)
Output:
{"ok":true}

func (*API) Discover added in v0.12.0

func (a *API) Discover() Result

Discover queries the bound endpoint's capability map — sugar over Invoke("core.actions", ...). Every Core answers it, so a mesh of Core apps is walkable.

r := c.API("codex").Discover()
Example

ExampleAPI_Discover queries a peer's capability map — every Core answers core.actions, so a mesh is walkable.

c := New()
r := c.API().Discover() // unbound view: coded failure, never a panic
Println(r.OK)
Output:
false

func (*API) Exists added in v0.12.0

func (a *API) Exists() bool

Exists reports whether the bound endpoint has a Drive handle — the capability check for named remotes.

if c.API("codex").Exists() { ... }
Example

ExampleAPI_Exists is the capability check for named remotes.

c := New()
c.Drive().New(NewOptions(
	Option{Key: "name", Value: "codex"},
	Option{Key: "transport", Value: "mcp://mcp.lthn.sh"},
))
Println(c.API("codex").Exists())
Output:
true

func (*API) Invoke added in v0.12.0

func (a *API) Invoke(action string, opts Options) Result

Invoke calls a named Action on the bound endpoint — the verb for c.API(name). Fails with operation "api.Invoke" when the view has no binding.

r := c.API("codex").Invoke("agentic.status", opts)
Example

ExampleAPI_Invoke fails with a coded Result when nothing is bound.

c := New()
r := c.API().Invoke("engine.status", NewOptions())
Println(r.OK)
Output:
false

func (*API) On added in v0.12.0

func (a *API) On(name string) *API

On returns a view of the API bound to a named Drive endpoint. The view shares the protocol registry with the parent; only the binding is new. Sugar reached via c.API(name).

lem := c.API().On("lem-local")
r := lem.Invoke("engine.status", opts)
Example

ExampleAPI_On binds without connecting — the view is queryable.

c := New()
lem := c.API().On("lem-local")
Println(lem.Exists())
Output:
false

func (*API) Protocols

func (a *API) Protocols() []string

Protocols returns all registered protocol scheme names.

c := core.New()
schemes := c.API().Protocols()
core.Println(core.Join(", ", schemes...))
Example

ExampleAPI_Protocols lists transport protocols through `API.Protocols` for a Lethean drive integration. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

c := New()
c.API().RegisterProtocol("http", func(_ *DriveHandle) (Stream, error) {
	return &exampleStream{}, nil
})
Println(c.API().Protocols())
Output:
[http]

func (*API) RegisterProtocol

func (a *API) RegisterProtocol(scheme string, factory StreamFactory)

RegisterProtocol registers a stream factory for a URL scheme. Consumer packages call this during OnStartup.

c.API().RegisterProtocol("http", httpStreamFactory)
c.API().RegisterProtocol("https", httpStreamFactory)
c.API().RegisterProtocol("mcp", mcpStreamFactory)
Example

ExampleAPI_RegisterProtocol registers a transport protocol through `API.RegisterProtocol` for a Lethean drive integration. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

c := New()
c.API().RegisterProtocol("http", func(h *DriveHandle) (Stream, error) {
	return &exampleStream{response: []byte("pong")}, nil
})
Println(c.API().Protocols())
Output:
[http]

func (*API) Stream

func (a *API) Stream(name ...string) Result

Stream opens a connection to a named endpoint. Looks up the endpoint in Drive, extracts the protocol from the transport URL, and delegates to the registered protocol handler. On a bound view the name may be omitted — the binding is used.

r := c.API().Stream("charon")
r = c.API("charon").Stream()
if r.OK { stream := r.Value.(Stream) }
Example

ExampleAPI_Stream opens a stream through `API.Stream` for a Lethean drive integration. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

c := New()
c.API().RegisterProtocol("http", func(h *DriveHandle) (Stream, error) {
	return &exampleStream{response: []byte(Concat("connected to ", h.Name))}, nil
})
c.Drive().New(NewOptions(
	Option{Key: "name", Value: "charon"},
	Option{Key: "transport", Value: "http://10.69.69.165:9101"},
))

r := c.API().Stream("charon")
if r.OK {
	stream := r.Value.(Stream)
	resp, _ := stream.Receive()
	Println(string(resp))
	stream.Close()
}
Output:
connected to charon

type Action

type Action struct {
	Name        string
	Handler     ActionHandler
	Description string
	Schema      Options // declares expected input keys (optional)
	// contains filtered or unexported fields
}

Action is a registered named action.

action := c.Action("process.run")
action.Description  // "Execute a command"
action.Schema       // expected input keys
Example

ExampleAction declares action metadata for an agent dispatch workflow. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

a := &Action{Name: "deploy", Description: "Deploy service"}
Println(a.Name)
Println(a.Description)
Output:
deploy
Deploy service

func (*Action) Disable

func (a *Action) Disable()

Disable marks the action as soft-disabled. Run() returns Result{OK: false} with Code "action.disabled" until Enable is called. The handler stays registered so the capability is queryable but cannot fire.

c.Action("dangerous.purge").Disable()  // re-enable later via .Enable()
Example

ExampleAction_Disable soft-disables an action through `Action.Disable`.

c := New()
a := c.Action("agent.deploy", func(_ Context, _ Options) Result { return Result{OK: true} })
a.Disable()
Println(a.Enabled())
Output:
false

func (*Action) Enable

func (a *Action) Enable()

Enable marks the action as runnable. Actions are enabled at registration time; use this to re-enable an action that was previously disabled. No-op when the action has no handler.

c.Action("process.run").Enable()
Example

ExampleCore_Progress reports task progress through `Core.Progress` for background task progress. Asynchronous work reports progress through Core task helpers. ExampleAction_Enable re-enables a disabled action through `Action.Enable`.

c := New()
a := c.Action("agent.deploy", func(_ Context, _ Options) Result { return Result{OK: true} })
a.Disable()
a.Enable()
Println(a.Enabled())
Output:
true

func (*Action) Enabled

func (a *Action) Enabled() bool

Enabled reports whether the action will run when invoked.

if c.Action("process.run").Enabled() { ... }
Example

ExampleAction_Enabled reports whether an action is active through `Action.Enabled`.

c := New()
a := c.Action("agent.deploy", func(_ Context, _ Options) Result { return Result{OK: true} })
Println(a.Enabled())
Output:
true

func (*Action) Exists

func (a *Action) Exists() bool

Exists returns true if this action has a registered handler.

if c.Action("process.run").Exists() { ... }
Example

ExampleAction_Exists checks action availability before and after registering a handler. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

c := New()
Println(c.Action("agent.missing").Exists())

c.Action("agent.present", func(_ Context, _ Options) Result { return Result{OK: true} })
Println(c.Action("agent.present").Exists())
Output:
false
true

func (*Action) Run

func (a *Action) Run(ctx Context, opts Options) (result Result)

Run executes the action with panic recovery. Returns Result{OK: false} if the action has no handler (not registered).

r := c.Action("process.run").Run(ctx, opts)
Example

ExampleAction_Run runs `Action.Run` with representative caller inputs for an agent dispatch workflow. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

c := New()
c.Action("math.double", func(_ Context, opts Options) Result {
	return Result{Value: opts.Int("n") * 2, OK: true}
})

r := c.Action("math.double").Run(Background(), NewOptions(
	Option{Key: "n", Value: 21},
))
Println(r.Value)
Output:
42
Example (EntitlementDenied)

ExampleAction_Run_entitlementDenied rejects a gated action through `Action.Run` when entitlement denies access for an agent dispatch workflow. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

c := New()
c.Action("agent.premium", func(_ Context, _ Options) Result {
	return Result{Value: "secret", OK: true}
})
c.SetEntitlementChecker(func(action string, _ int, _ Context) Entitlement {
	if action == "agent.premium" {
		return Entitlement{Allowed: false, Reason: "upgrade"}
	}
	return Entitlement{Allowed: true, Unlimited: true}
})

r := c.Action("agent.premium").Run(Background(), NewOptions())
Println(r.OK)
Output:
false
Example (PanicRecovery)

ExampleAction_Run_panicRecovery recovers a panicking handler through `Action.Run` for an agent dispatch workflow. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

c := New()
c.Action("agent.boom", func(_ Context, _ Options) Result {
	panic("explosion")
})

r := c.Action("agent.boom").Run(Background(), NewOptions())
Println(r.OK)
Output:
false

type ActionHandler

type ActionHandler func(Context, Options) Result

ActionHandler is the function signature for all named actions.

func(ctx Context, opts core.Options) core.Result
Example

ExampleActionHandler declares an action handler through `ActionHandler` for an agent dispatch workflow. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

var handler ActionHandler = func(_ Context, opts Options) Result {
	return Result{Value: opts.String("name"), OK: true}
}
Println(handler(Background(), NewOptions(Option{Key: "name", Value: "deploy"})).Value)
Output:
deploy

type ActionServiceReload added in v0.12.0

type ActionServiceReload struct{}

ActionServiceReload is broadcast when ServiceReload completes.

c.RegisterAction(func(_ *core.Core, msg core.Message) core.Result {
    if _, ok := msg.(core.ActionServiceReload); ok {
        core.Info("configuration reloaded")
    }
    return core.Result{OK: true}
})

type ActionServiceShutdown

type ActionServiceShutdown struct{}

ActionServiceShutdown is broadcast when Core begins service shutdown.

c := core.New()
c.Action("service.shutdown", func(ctx Context, opts core.Options) core.Result {
    name := opts.String("name")
    core.Println(core.Sprintf("service %s stopped", name))
    return core.Result{OK: true}
})
Example

ExampleActionServiceShutdown emits the service-shutdown action contract through `ActionServiceShutdown` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

Println(Sprint(ActionServiceShutdown{}))
Output:
{}

type ActionServiceStartup

type ActionServiceStartup struct{}

ActionServiceStartup is broadcast when a Core service finishes startup.

c := core.New()
c.Action("service.startup", func(ctx Context, opts core.Options) core.Result {
    name := opts.String("name")
    core.Println(core.Sprintf("service %s started", name))
    return core.Result{OK: true}
})
Example

ExampleActionServiceStartup emits the service-startup action contract through `ActionServiceStartup` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

Println(Sprint(ActionServiceStartup{}))
Output:
{}

type ActionTaskCompleted

type ActionTaskCompleted struct {
	TaskIdentifier string
	Action         string
	Result         Result
}

ActionTaskCompleted is broadcast when an asynchronous task finishes.

event := core.ActionTaskCompleted{TaskIdentifier: "task-42", Action: "agent.run", Result: core.Result{Value: "done", OK: true}}
core.New().ACTION(event)
Example

ExampleActionTaskCompleted creates a task-completed action event through `ActionTaskCompleted` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

ev := ActionTaskCompleted{TaskIdentifier: "task-1", Action: "deploy", Result: Result{Value: "done", OK: true}}
Println(ev.Action)
Println(ev.Result.Value)
Output:
deploy
done

type ActionTaskProgress

type ActionTaskProgress struct {
	TaskIdentifier string
	Action         string
	Progress       float64
	Message        string
}

ActionTaskProgress is broadcast when an asynchronous task reports progress.

event := core.ActionTaskProgress{TaskIdentifier: "task-42", Action: "agent.run", Progress: 0.75, Message: "indexing repo"}
core.New().ACTION(event)
Example

ExampleActionTaskProgress creates a task-progress action event through `ActionTaskProgress` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

ev := ActionTaskProgress{TaskIdentifier: "task-1", Action: "deploy", Progress: 0.5, Message: "halfway"}
Println(ev.TaskIdentifier)
Println(ev.Progress)
Println(ev.Message)
Output:
task-1
0.5
halfway

type ActionTaskStarted

type ActionTaskStarted struct {
	TaskIdentifier string
	Action         string
	Options        Options
}

ActionTaskStarted is broadcast when an asynchronous task begins.

event := core.ActionTaskStarted{TaskIdentifier: "task-42", Action: "agent.run"}
core.New().ACTION(event)
Example

ExampleActionTaskStarted creates a task-started action event through `ActionTaskStarted` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

ev := ActionTaskStarted{TaskIdentifier: "task-1", Action: "deploy"}
Println(ev.TaskIdentifier)
Println(ev.Action)
Output:
task-1
deploy

type Addr

type Addr = net.Addr

Addr is a network endpoint address.

r := core.NetListen("tcp", "127.0.0.1:0")
if !r.OK { return r }
ln := r.Value.(core.Listener)
defer ln.Close()
addr := ln.Addr()
core.Println(addr.String())

type App

type App struct {
	Name        string
	Version     string
	Description string
	Filename    string
	Path        string
	Runtime     any // GUI runtime (e.g., Wails App). Nil for CLI-only.
}

App holds the application identity and optional GUI runtime.

app := core.App{}.New(core.NewOptions(
    core.Option{Key: "name", Value: "Core CLI"},
    core.Option{Key: "version", Value: "1.0.0"},
))

func (App) Find

func (a App) Find(filename, name string) Result

Find locates a program on PATH and returns a Result containing the App. Uses core.Stat to search PATH directories — no os/exec dependency.

r := core.App{}.Find("node", "Node.js")
if r.OK { app := r.Value.(*App) }
Example

ExampleApp_Find resolves application metadata from an executable path and display name. Application metadata is registered once and found later by stable names.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-app-example"))
defer fs.DeleteAll(dir)

bin := Path(dir, "forge")
fs.WriteMode(bin, "#!/bin/sh\n", 0755)

r := App{}.Find(bin, "Forge")
app := r.Value.(*App)
Println(r.OK)
Println(app.Name)
Println(PathBase(app.Filename))
Println(PathBase(app.Path))
Output:
true
Forge
forge
forge

func (App) New

func (a App) New(opts Options) App

New creates an App from Options.

app := core.App{}.New(core.NewOptions(
    core.Option{Key: "name", Value: "myapp"},
    core.Option{Key: "version", Value: "1.0.0"},
))
Example

ExampleApp_New builds application metadata from name, version, description, and binary filename options. Application metadata is registered once and found later by stable names.

app := App{}.New(NewOptions(
	Option{Key: "name", Value: "forge"},
	Option{Key: "version", Value: "1.2.3"},
	Option{Key: "description", Value: "deployment tool"},
	Option{Key: "filename", Value: "forge"},
))

Println(app.Name)
Println(app.Version)
Println(app.Description)
Println(app.Filename)
Output:
forge
1.2.3
deployment tool
forge

type Array

type Array[T comparable] struct {
	// contains filtered or unexported fields
}

Array is a typed slice with common operations.

agents := core.NewArray("codex", "hades")
agents.AddUnique("homelab")

func NewArray

func NewArray[T comparable](items ...T) *Array[T]

NewArray creates an empty Array.

agents := core.NewArray("codex", "hades")
core.Println(agents.Len())
Example

ExampleNewArray creates a typed array through `NewArray` for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray[string]()
a.Add("alpha")
a.Add("bravo")
a.Add("charlie")

Println(a.Len())
Println(a.Contains("bravo"))
Output:
3
true

func (*Array[T]) Add

func (s *Array[T]) Add(values ...T)

Add appends values.

agents := core.NewArray("codex")
agents.Add("hades", "homelab")
Example

ExampleArray_Add adds a value through `Array.Add` for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray[string]()
a.Add("alpha", "bravo")
Println(a.AsSlice())
Output:
[alpha bravo]

func (*Array[T]) AddUnique

func (s *Array[T]) AddUnique(values ...T)

AddUnique appends values only if not already present.

agents := core.NewArray("codex")
agents.AddUnique("codex", "hades")
Example

ExampleArray_AddUnique adds a value through `Array.AddUnique` only when it is absent for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray[string]()
a.AddUnique("alpha")
a.AddUnique("alpha") // no duplicate
a.AddUnique("bravo")

Println(a.Len())
Output:
2

func (*Array[T]) AsSlice

func (s *Array[T]) AsSlice() []T

AsSlice returns a copy of the underlying slice.

agents := core.NewArray("codex", "hades")
names := agents.AsSlice()
core.Println(core.Join(", ", names...))
Example

ExampleArray_AsSlice exports values through `Array.AsSlice` as a slice for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray("alpha", "bravo")
Println(a.AsSlice())
Output:
[alpha bravo]

func (*Array[T]) Clear

func (s *Array[T]) Clear()

Clear removes all elements.

agents := core.NewArray("codex", "hades")
agents.Clear()
Example

ExampleArray_Clear clears entries through `Array.Clear` for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray("alpha", "bravo")
a.Clear()
Println(a.Len())
Output:
0

func (*Array[T]) Contains

func (s *Array[T]) Contains(val T) bool

Contains returns true if the value is in the slice.

agents := core.NewArray("codex", "hades")
if agents.Contains("hades") {
    core.Println("agent present")
}
Example

ExampleArray_Contains checks text membership through `Array.Contains` for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray("alpha", "bravo")
Println(a.Contains("bravo"))
Println(a.Contains("charlie"))
Output:
true
false

func (*Array[T]) Deduplicate

func (s *Array[T]) Deduplicate()

Deduplicate removes duplicate values, preserving order.

agents := core.NewArray("codex", "codex", "hades")
agents.Deduplicate()
Example

ExampleArray_Deduplicate deduplicates values through `Array.Deduplicate` for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray("alpha", "alpha", "bravo")
a.Deduplicate()
Println(a.AsSlice())
Output:
[alpha bravo]

func (*Array[T]) Each

func (s *Array[T]) Each(fn func(T))

Each runs a function on every element.

agents := core.NewArray("codex", "hades")
agents.Each(func(name string) { core.Println(name) })
Example

ExampleArray_Each iterates entries through `Array.Each` for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray("alpha", "bravo", "charlie")
var labels []string
a.Each(func(item string) {
	labels = append(labels, Upper(item[:1]))
})
Println(labels)
Output:
[A B C]

func (*Array[T]) Filter

func (s *Array[T]) Filter(fn func(T) bool) Result

Filter returns a new Array with elements matching the predicate.

agents := core.NewArray("codex", "hades", "homelab")
r := agents.Filter(func(name string) bool { return core.HasPrefix(name, "h") })
if !r.OK {
    return r
}
filtered := r.Value.(*core.Array[string])
core.Println(filtered.Len())
Example

ExampleArray_Filter filters values through `Array.Filter` for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray[int]()
a.Add(1)
a.Add(2)
a.Add(3)
a.Add(4)

r := a.Filter(func(n int) bool { return n%2 == 0 })
Println(r.OK)
Output:
true

func (*Array[T]) IndexOf added in v0.10.0

func (s *Array[T]) IndexOf(val T) int

IndexOf returns the index of the first occurrence of val, or -1 when absent. Companion to Contains for callers that need the position.

if i := agents.IndexOf("hades"); i >= 0 {
    core.Println("at", i)
}
Example

ExampleArray_IndexOf returns the index of a value through `Array.IndexOf`.

a := NewArray("codex", "hades", "homelab")
Println(a.IndexOf("hades"))
Output:
1

func (*Array[T]) Len

func (s *Array[T]) Len() int

Len returns the number of elements.

agents := core.NewArray("codex", "hades")
count := agents.Len()
core.Println(count)
Example

ExampleArray_Len counts entries through `Array.Len` for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray("alpha", "bravo")
Println(a.Len())
Output:
2

func (*Array[T]) Remove

func (s *Array[T]) Remove(val T)

Remove removes the first occurrence of a value.

agents := core.NewArray("codex", "hades", "homelab")
agents.Remove("hades")
Example

ExampleArray_Remove removes a value through `Array.Remove` for an in-memory agent queue. Typed collection helpers cover queue operations without exposing slices directly.

a := NewArray("alpha", "bravo", "charlie")
a.Remove("bravo")
Println(a.AsSlice())
Output:
[alpha charlie]

type AssetGroup

type AssetGroup struct {
	// contains filtered or unexported fields
}

AssetGroup holds a named collection of packed assets.

core.AddAsset("agent", "persona/developer.md", "H4sIAAAAAAAA/8pIzcnJBwCGphA2BQAAAA==")
r := core.GetAsset("agent", "persona/developer.md")
_ = r

type AssetRef

type AssetRef struct {
	Name     string
	Path     string
	Group    string
	FullPath string
}

AssetRef is a reference to an asset found in source code.

ref := core.AssetRef{Name: "developer.md", Group: "persona", Path: "persona/developer.md"}
core.Println(ref.Path)

type AtomicBool

type AtomicBool struct {
	// contains filtered or unexported fields
}

AtomicBool is a race-free atomic boolean. Zero value is false.

var ready core.AtomicBool
ready.Store(true)
if ready.Load() { core.Println("agent ready") }
Example

ExampleAtomicBool updates a boolean atomically through `AtomicBool` for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var ready AtomicBool
if !ready.Load() {
	Println("not ready")
}
ready.Store(true)
if ready.Load() {
	Println("ready")
}
Output:
not ready
ready

func (*AtomicBool) CompareAndSwap

func (a *AtomicBool) CompareAndSwap(old, new bool) bool

CompareAndSwap stores new only if the current value equals old.

if a.CompareAndSwap(false, true) { /* claimed */ }
Example

ExampleAtomicBool_CompareAndSwap updates `AtomicBool.CompareAndSwap` only when the previous value matches for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var ready AtomicBool
Println(ready.CompareAndSwap(false, true))
Println(ready.Load())
Output:
true
true

func (*AtomicBool) Load

func (a *AtomicBool) Load() bool

Load returns the current value.

var ready core.AtomicBool
ready.Store(true)
current := ready.Load()
core.Println(current)
Example

ExampleAtomicPointer_CompareAndSwap updates `AtomicPointer.CompareAndSwap` only when the previous value matches for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes. ExampleAtomicBool_Load reads a boolean atomically through `AtomicBool.Load`.

var b AtomicBool
b.Store(true)
Println(b.Load())
Output:
true

func (*AtomicBool) Store

func (a *AtomicBool) Store(val bool)

Store sets the value.

var ready core.AtomicBool
ready.Store(true)
Example

ExampleAtomicBool_Store writes a boolean atomically through `AtomicBool.Store`.

var b AtomicBool
b.Store(true)
Println(b.Load())
Output:
true

func (*AtomicBool) Swap

func (a *AtomicBool) Swap(new bool) bool

Swap stores new and returns the previous value.

var ready core.AtomicBool
previous := ready.Swap(true)
core.Println(previous)
Example

ExampleAtomicBool_Swap swaps a value through `AtomicBool.Swap` and returns the previous value for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var ready AtomicBool
ready.Store(true)
Println(ready.Swap(false))
Println(ready.Load())
Output:
true
false

type AtomicInt32

type AtomicInt32 struct {
	// contains filtered or unexported fields
}

AtomicInt32 is a race-free atomic int32. Zero value is 0.

var queueDepth core.AtomicInt32
queueDepth.Store(3)
core.Println(queueDepth.Load())
Example

ExampleAtomicInt32 updates a 32-bit integer atomically through `AtomicInt32` for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var counter AtomicInt32
counter.Store(10)
Println(counter.Add(5))
Println(counter.Swap(1))
Println(counter.Load())
Output:
15
15
1

func (*AtomicInt32) Add

func (a *AtomicInt32) Add(delta int32) int32

Add atomically adds delta and returns the new value.

new := a.Add(1)
Example

ExampleAtomicInt32_Add atomically adds and returns the new value through `AtomicInt32.Add`.

var n AtomicInt32
n.Store(5)
Println(n.Add(3))
Output:
8

func (*AtomicInt32) CompareAndSwap

func (a *AtomicInt32) CompareAndSwap(old, new int32) bool

CompareAndSwap stores new only if the current value equals old.

var queueDepth core.AtomicInt32
if queueDepth.CompareAndSwap(0, 1) {
    core.Println("worker claimed queue")
}
Example

ExampleAtomicInt32_CompareAndSwap updates `AtomicInt32.CompareAndSwap` only when the previous value matches for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var state AtomicInt32
if state.CompareAndSwap(0, 1) {
	Println("claimed")
}
if !state.CompareAndSwap(0, 2) {
	Println("already claimed")
}
Output:
claimed
already claimed

func (*AtomicInt32) Load

func (a *AtomicInt32) Load() int32

Load returns the current value.

var queueDepth core.AtomicInt32
queueDepth.Store(3)
depth := queueDepth.Load()
core.Println(depth)
Example

ExampleAtomicInt32_Load reads an int32 atomically through `AtomicInt32.Load`.

var n AtomicInt32
n.Store(5)
Println(n.Load())
Output:
5

func (*AtomicInt32) Store

func (a *AtomicInt32) Store(val int32)

Store sets the value.

var queueDepth core.AtomicInt32
queueDepth.Store(3)
Example

ExampleAtomicInt32_Store writes an int32 atomically through `AtomicInt32.Store`.

var n AtomicInt32
n.Store(42)
Println(n.Load())
Output:
42

func (*AtomicInt32) Swap

func (a *AtomicInt32) Swap(new int32) int32

Swap stores new and returns the previous value.

var queueDepth core.AtomicInt32
previous := queueDepth.Swap(5)
core.Println(previous)
Example

ExampleAtomicInt32_Swap stores and returns the previous value through `AtomicInt32.Swap`.

var n AtomicInt32
n.Store(5)
Println(n.Swap(9))
Output:
5

type AtomicInt64

type AtomicInt64 struct {
	// contains filtered or unexported fields
}

AtomicInt64 is a race-free atomic int64. Zero value is 0.

var taskID core.AtomicInt64
next := taskID.Add(1)
core.Println(next)
Example

ExampleAtomicInt64 updates a 64-bit integer atomically through `AtomicInt64` for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var counter AtomicInt64
counter.Add(1)
counter.Add(1)
counter.Add(1)
Println(counter.Load())
Output:
3

func (*AtomicInt64) Add

func (a *AtomicInt64) Add(delta int64) int64

Add atomically adds delta and returns the new value.

var taskID core.AtomicInt64
next := taskID.Add(1)
core.Println(next)
Example

ExampleAtomicInt64_Add atomically adds and returns the new value through `AtomicInt64.Add`.

var n AtomicInt64
n.Store(5)
Println(n.Add(3))
Output:
8

func (*AtomicInt64) CompareAndSwap

func (a *AtomicInt64) CompareAndSwap(old, new int64) bool

CompareAndSwap stores new only if the current value equals old.

var taskID core.AtomicInt64
if taskID.CompareAndSwap(0, 1) {
    core.Println("first task")
}
Example

ExampleAtomicInt64_CompareAndSwap updates `AtomicInt64.CompareAndSwap` only when the previous value matches for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var counter AtomicInt64
counter.Store(7)
Println(counter.CompareAndSwap(7, 9))
Println(counter.Load())
Output:
true
9

func (*AtomicInt64) Load

func (a *AtomicInt64) Load() int64

Load returns the current value.

var taskID core.AtomicInt64
taskID.Store(42)
current := taskID.Load()
core.Println(current)
Example

ExampleAtomicInt64_Load reads an int64 atomically through `AtomicInt64.Load`.

var n AtomicInt64
n.Store(5)
Println(n.Load())
Output:
5

func (*AtomicInt64) Store

func (a *AtomicInt64) Store(val int64)

Store sets the value.

var taskID core.AtomicInt64
taskID.Store(42)
Example

ExampleAtomicInt64_Store writes an int64 atomically through `AtomicInt64.Store`.

var n AtomicInt64
n.Store(42)
Println(n.Load())
Output:
42

func (*AtomicInt64) Swap

func (a *AtomicInt64) Swap(new int64) int64

Swap stores new and returns the previous value.

var taskID core.AtomicInt64
previous := taskID.Swap(100)
core.Println(previous)
Example

ExampleAtomicInt64_Swap swaps a value through `AtomicInt64.Swap` and returns the previous value for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var counter AtomicInt64
counter.Store(7)
Println(counter.Swap(9))
Println(counter.Load())
Output:
7
9

type AtomicPointer

type AtomicPointer[T any] struct {
	// contains filtered or unexported fields
}

AtomicPointer is a race-free atomic *T. Zero value is nil.

var current core.AtomicPointer[Config]
current.Store(&Config{...})
cfg := current.Load()
Example

ExampleAtomicPointer updates a typed pointer atomically through `AtomicPointer` for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var current AtomicPointer[config]
current.Store(&config{name: "v1"})
cfg := current.Load()
Println(cfg.name)
current.Store(&config{name: "v2"})
Println(current.Load().name)
Output:
v1
v2

func (*AtomicPointer[T]) CompareAndSwap

func (a *AtomicPointer[T]) CompareAndSwap(old, new *T) bool

CompareAndSwap stores new only if the current pointer equals old.

var current core.AtomicPointer[core.ConfigOptions]
old := core.ConfigOptions{}
next := core.ConfigOptions{Settings: map[string]any{"config.host": "homelab.lthn.sh"}}
current.Store(&old)
_ = current.CompareAndSwap(&old, &next)
Example
var current AtomicPointer[config]
first := &config{name: "v1"}
second := &config{name: "v2"}
current.Store(first)

Println(current.CompareAndSwap(first, second))
Println(current.Load().name)
Output:
true
v2

func (*AtomicPointer[T]) Load

func (a *AtomicPointer[T]) Load() *T

Load returns the current pointer.

var current core.AtomicPointer[core.ConfigOptions]
cfg := core.ConfigOptions{Settings: map[string]any{"config.host": "homelab.lthn.sh"}}
current.Store(&cfg)
loaded := current.Load()
_ = loaded
Example

ExampleAtomicPointer_Load reads a pointer atomically through `AtomicPointer.Load`.

var p AtomicPointer[int]
v := 42
p.Store(&v)
Println(*p.Load())
Output:
42

func (*AtomicPointer[T]) Store

func (a *AtomicPointer[T]) Store(val *T)

Store sets the pointer.

var current core.AtomicPointer[core.ConfigOptions]
cfg := core.ConfigOptions{Settings: map[string]any{"config.host": "homelab.lthn.sh"}}
current.Store(&cfg)
Example

ExampleAtomicPointer_Store writes a pointer atomically through `AtomicPointer.Store`.

var p AtomicPointer[string]
s := "agent"
p.Store(&s)
Println(*p.Load())
Output:
agent

func (*AtomicPointer[T]) Swap

func (a *AtomicPointer[T]) Swap(new *T) *T

Swap stores new and returns the previous pointer.

var current core.AtomicPointer[core.ConfigOptions]
next := core.ConfigOptions{Settings: map[string]any{"config.host": "homelab.lthn.sh"}}
previous := current.Swap(&next)
_ = previous
Example

ExampleAtomicPointer_Swap swaps a value through `AtomicPointer.Swap` and returns the previous value for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var current AtomicPointer[config]
first := &config{name: "v1"}
second := &config{name: "v2"}
current.Store(first)

Println(current.Swap(second).name)
Println(current.Load().name)
Output:
v1
v2

type AtomicUint32

type AtomicUint32 struct {
	// contains filtered or unexported fields
}

AtomicUint32 is a race-free atomic uint32. Zero value is 0.

var workers core.AtomicUint32
workers.Add(1)
core.Println(workers.Load())
Example

ExampleAtomicUint32 updates an unsigned 32-bit integer atomically through `AtomicUint32` for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var counter AtomicUint32
counter.Store(10)
Println(counter.Add(5))
Println(counter.Swap(1))
Println(counter.Load())
Output:
15
15
1

func (*AtomicUint32) Add

func (a *AtomicUint32) Add(delta uint32) uint32

Add atomically adds delta and returns the new value.

var workers core.AtomicUint32
workers.Add(1)
Example

ExampleAtomicUint32_Add atomically adds and returns the new value through `AtomicUint32.Add`.

var n AtomicUint32
n.Store(5)
Println(n.Add(3))
Output:
8

func (*AtomicUint32) CompareAndSwap

func (a *AtomicUint32) CompareAndSwap(old, new uint32) bool

CompareAndSwap stores new only if the current value equals old.

var workers core.AtomicUint32
if workers.CompareAndSwap(0, 4) {
    core.Println("pool opened")
}
Example

ExampleAtomicUint32_CompareAndSwap updates `AtomicUint32.CompareAndSwap` only when the previous value matches for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var counter AtomicUint32
counter.Store(10)
Println(counter.CompareAndSwap(10, 11))
Println(counter.Load())
Output:
true
11

func (*AtomicUint32) Load

func (a *AtomicUint32) Load() uint32

Load returns the current value.

var workers core.AtomicUint32
workers.Store(4)
core.Println(workers.Load())
Example

ExampleAtomicUint32_Load reads a uint32 atomically through `AtomicUint32.Load`.

var n AtomicUint32
n.Store(5)
Println(n.Load())
Output:
5

func (*AtomicUint32) Store

func (a *AtomicUint32) Store(val uint32)

Store sets the value.

var workers core.AtomicUint32
workers.Store(4)
Example

ExampleAtomicUint32_Store writes a uint32 atomically through `AtomicUint32.Store`.

var n AtomicUint32
n.Store(42)
Println(n.Load())
Output:
42

func (*AtomicUint32) Swap

func (a *AtomicUint32) Swap(new uint32) uint32

Swap stores new and returns the previous value.

var workers core.AtomicUint32
previous := workers.Swap(8)
core.Println(previous)
Example

ExampleAtomicUint32_Swap stores and returns the previous value through `AtomicUint32.Swap`.

var n AtomicUint32
n.Store(5)
Println(n.Swap(9))
Output:
5

type AtomicUint64

type AtomicUint64 struct {
	// contains filtered or unexported fields
}

AtomicUint64 is a race-free atomic uint64. Zero value is 0.

var bytesSeen core.AtomicUint64
bytesSeen.Add(4096)
core.Println(bytesSeen.Load())
Example

ExampleAtomicUint64 updates an unsigned 64-bit integer atomically through `AtomicUint64` for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var counter AtomicUint64
counter.Store(10)
Println(counter.Add(5))
Println(counter.Swap(1))
Println(counter.Load())
Output:
15
15
1

func (*AtomicUint64) Add

func (a *AtomicUint64) Add(delta uint64) uint64

Add atomically adds delta and returns the new value.

var bytesSeen core.AtomicUint64
bytesSeen.Add(4096)
Example

ExampleAtomicUint64_Add atomically adds and returns the new value through `AtomicUint64.Add`.

var n AtomicUint64
n.Store(5)
Println(n.Add(3))
Output:
8

func (*AtomicUint64) CompareAndSwap

func (a *AtomicUint64) CompareAndSwap(old, new uint64) bool

CompareAndSwap stores new only if the current value equals old.

var bytesSeen core.AtomicUint64
if bytesSeen.CompareAndSwap(0, 4096) {
    core.Println("first payload")
}
Example

ExampleAtomicUint64_CompareAndSwap updates `AtomicUint64.CompareAndSwap` only when the previous value matches for shared runtime state. Concurrent state changes use explicit load, store, swap, and compare-and-swap shapes.

var counter AtomicUint64
counter.Store(10)
Println(counter.CompareAndSwap(10, 11))
Println(counter.Load())
Output:
true
11

func (*AtomicUint64) Load

func (a *AtomicUint64) Load() uint64

Load returns the current value.

var bytesSeen core.AtomicUint64
bytesSeen.Store(4096)
core.Println(bytesSeen.Load())
Example

ExampleAtomicUint64_Load reads a uint64 atomically through `AtomicUint64.Load`.

var n AtomicUint64
n.Store(5)
Println(n.Load())
Output:
5

func (*AtomicUint64) Store

func (a *AtomicUint64) Store(val uint64)

Store sets the value.

var bytesSeen core.AtomicUint64
bytesSeen.Store(4096)
Example

ExampleAtomicUint64_Store writes a uint64 atomically through `AtomicUint64.Store`.

var n AtomicUint64
n.Store(42)
Println(n.Load())
Output:
42

func (*AtomicUint64) Swap

func (a *AtomicUint64) Swap(new uint64) uint64

Swap stores new and returns the previous value.

var bytesSeen core.AtomicUint64
previous := bytesSeen.Swap(8192)
core.Println(previous)
Example

ExampleAtomicUint64_Swap stores and returns the previous value through `AtomicUint64.Swap`.

var n AtomicUint64
n.Store(5)
Println(n.Swap(9))
Output:
5

type B

type B = testing.B

B is the canonical Go benchmark handle, exported as core.B.

func BenchmarkSomething(b *core.B) { ... }
Example

ExampleB documents the benchmark alias through `B` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var b *B
_ = b

type BufReader

type BufReader = bufio.Reader

BufReader is the Core alias for bufio.Reader — buffered byte-stream reads with delimiter support (ReadString, ReadBytes, ReadLine).

r := core.NewBufReader(core.Stdin())
line, err := r.ReadString('\n')

func NewBufReader

func NewBufReader(r Reader) *BufReader

NewBufReader wraps r in a Core BufReader for delimiter-based reads.

r := core.NewBufReader(core.Stdin())
line, err := r.ReadString('\n')
Example

ExampleNewBufReader wraps a reader for buffered, line-oriented reads through `NewBufReader`.

br := NewBufReader(NewReader("agent ready\n"))
line, _ := br.ReadString('\n')
Println(Trim(line))
Output:
agent ready

type Buffer added in v0.10.0

type Buffer = bytes.Buffer

Buffer is an alias for bytes.Buffer — an in-memory byte sequence with io.Reader/io.Writer methods. Lets consumers declare buffer-typed fields and locals without importing bytes.

type Sink struct {
    out core.Buffer
}

var buf core.Buffer
buf.WriteString("ready")
Example

ExampleBuffer declares a Buffer-typed local through the `Buffer` alias for in-memory payload assembly. Buffer creation stays on the core wrapper surface for later stream or encoding work.

var b Buffer
b.WriteString("ready")
Println(b.String())
Output:
ready

type Builder added in v0.10.0

type Builder = strings.Builder

Builder is an alias for strings.Builder — the byte-by-byte string assembly type. Lets consumers declare builder-typed fields and locals without importing strings.

type Sink struct {
    out core.Builder
}

var b core.Builder
b.WriteString("ready")
Example

ExampleBuilder declares a Builder-typed local through the `Builder` alias for command text handling. Text predicates and transforms stay on the core string wrapper surface.

var b Builder
b.WriteString("hello")
b.WriteString(" world")
Println(b.String())
Output:
hello world

type CLITest

type CLITest struct {
	Name     string   // optional scenario name for failure messages
	Cmd      string   // binary to invoke (PATH-resolvable or absolute)
	Args     []string // command-line arguments
	Dir      string   // working directory; "" means current
	Stdin    string   // stdin content; "" means none
	Env      []string // additional env vars (e.g. "GOWORK=off")
	WantOK   bool     // expected Result.OK
	Output   string   // exact stdout match (skipped when "")
	Contains string   // substring stdout match (skipped when "")
}

CLITest is a single CLI scenario. The runner executes Cmd with Args in Dir (current working directory if empty), feeds Stdin, and asserts the resulting Result matches Want* expectations. Use Output for an exact-match check or Contains for a substring assertion.

tc := core.CLITest{
    Cmd: "git", Args: []string{"--version"},
    WantOK: true, Contains: "git version",
}

type CancelFunc

type CancelFunc = context.CancelFunc

CancelFunc cancels a Context derived via WithCancel/WithTimeout/WithDeadline. Calling it releases resources associated with the Context.

ctx, cancel := core.WithCancel(core.Background())
defer cancel()

type Cli

type Cli struct {
	*ServiceRuntime[CliOptions]
	// contains filtered or unexported fields
}

Cli is the CLI surface for the Core command tree.

c := core.New(core.WithOption("name", "homelab"))
cli := c.Cli()
cli.Print("%s ready", c.App().Name)

func (*Cli) Banner

func (cl *Cli) Banner() string

Banner returns the banner string.

c := core.New(core.WithOption("name", "homelab"))
banner := c.Cli().Banner()
core.Println(banner)
Example

ExampleCli_Banner returns the rendered CLI banner through `Cli.Banner`.

cli := New(WithCli()).Cli()
cli.SetBanner(func(*Cli) string { return "Lethean" })
Println(cli.Banner())
Output:
Lethean

func (*Cli) Print

func (cl *Cli) Print(format string, args ...any)

Print writes to the CLI output (defaults to core.Stdout()).

c.Cli().Print("hello %s", "world")
Example

ExampleCli_Print writes formatted text to the CLI output through `Cli.Print`.

cli := New(WithCli()).Cli()
buf := NewBuffer()
cli.SetOutput(buf)
cli.Print("port=%d", 8080)
Println(buf.String())
Output:
port=8080

func (*Cli) PrintHelp

func (cl *Cli) PrintHelp()

PrintHelp prints available commands.

c.Cli().PrintHelp()
Example

ExampleCli_PrintHelp writes usage text to the CLI output through `Cli.PrintHelp`.

cli := New(WithCli()).Cli()
cli.SetOutput(NewBuffer())
cli.PrintHelp()

func (*Cli) Run

func (cl *Cli) Run(args ...string) Result

Run resolves core.Args() to a command path and executes it.

c.Cli().Run()
c.Cli().Run("deploy", "to", "homelab")
Example

ExampleCli_Run dispatches CLI arguments to registered commands through `Cli.Run`.

cli := New(WithCli()).Cli()
cli.SetOutput(NewBuffer())
if false {
	cli.Run("version") // dispatches the named command
}

func (*Cli) SetBanner

func (cl *Cli) SetBanner(fn func(*Cli) string)

SetBanner sets the banner function.

c.Cli().SetBanner(func(_ *core.Cli) string { return "My App v1.0" })
Example

ExampleCli_SetBanner sets the CLI banner renderer through `Cli.SetBanner`.

cli := New(WithCli()).Cli()
cli.SetBanner(func(*Cli) string { return "Core v1" })
Println(cli.Banner())
Output:
Core v1

func (*Cli) SetOutput

func (cl *Cli) SetOutput(w Writer)

SetOutput sets the CLI output writer.

c.Cli().SetOutput(core.Stderr())
Example

ExampleCli_SetOutput redirects CLI output to a writer through `Cli.SetOutput`.

cli := New(WithCli()).Cli()
buf := NewBuffer()
cli.SetOutput(buf)
cli.Print("ready")
Println(buf.String())
Output:
ready

type CliOptions

type CliOptions struct{}

CliOptions holds configuration for the Cli service.

c := core.New()
runtime := core.NewServiceRuntime(c, core.CliOptions{})
_ = runtime.Options()

type Closer

type Closer = io.Closer

Closer is the canonical io.Closer interface.

r := core.HTTPGet("https://api.lethean.example/health")
if !r.OK { return r }
var closer core.Closer = r.Value.(*core.Response).Body
defer closer.Close()

type Cmd

type Cmd = exec.Cmd

Cmd is os/exec.Cmd for adapters that need command handles.

var cmd *core.Cmd
_ = cmd

type Command

type Command struct {
	Name        string
	Description string        // i18n key — derived from path if empty
	Path        string        // "deploy/to/homelab"
	Action      CommandAction // business logic
	Managed     string        // "" = one-shot, "process.daemon" = managed lifecycle
	Flags       Options       // declared flags
	Hidden      bool
}

Command is the DTO for an executable operation. Commands are declarative — they carry enough information for multiple consumers:

  • core.Cli() runs the Action

  • core/cli adds rich help, completion, man pages

  • go-process wraps Managed commands with lifecycle (PID, health, signals)

    c.Command("serve", core.Command{ Action: handler, Managed: "process.daemon", // go-process provides start/stop/restart })

Usage:

cmd := core.Command{Action: func(opts core.Options) core.Result {
    return core.Result{Value: core.Sprintf("deploy %s", opts.String("target")), OK: true}
}}
r := cmd.Run(core.NewOptions(core.Option{Key: "target", Value: "homelab"}))
if !r.OK { return r }

func (*Command) I18nKey

func (cmd *Command) I18nKey() string

I18nKey returns the i18n key for this command's description.

cmd with path "deploy/to/homelab" → "cmd.deploy.to.homelab.description"
Example

ExampleCommand_I18nKey builds an i18n key through `Command.I18nKey` for managed CLI command dispatch. Command registration and lookup use managed metadata before execution.

cmd := &Command{Path: "deploy/to/homelab"}
Println(cmd.I18nKey())
Output:
cmd.deploy.to.homelab.description

func (*Command) IsManaged

func (cmd *Command) IsManaged() bool

IsManaged returns true if this command has a managed lifecycle.

if cmd.IsManaged() { /* go-process handles start/stop */ }
Example

ExampleCommand_IsManaged checks managed command state through `Command.IsManaged` for managed CLI command dispatch. Command registration and lookup use managed metadata before execution.

cmd := &Command{Managed: "process.daemon"}
Println(cmd.IsManaged())
Output:
true

func (*Command) Run

func (cmd *Command) Run(opts Options) Result

Run executes the command's action with the given options.

result := cmd.Run(core.NewOptions(core.Option{Key: "target", Value: "homelab"}))
Example

ExampleCommand_Run runs `Command.Run` with representative caller inputs for managed CLI command dispatch. Command registration and lookup use managed metadata before execution.

cmd := &Command{
	Action: func(opts Options) Result {
		return Result{Value: opts.String("target"), OK: true}
	},
}
r := cmd.Run(NewOptions(Option{Key: "target", Value: "homelab"}))
Println(r.Value)
Output:
homelab

type CommandAction

type CommandAction func(Options) Result

CommandAction is the function signature for command handlers.

func(opts core.Options) core.Result

type CommandRegistry

type CommandRegistry struct {
	*Registry[*Command]
}

CommandRegistry holds the command tree. Embeds Registry[*Command] for thread-safe named storage with insertion order.

registry := &core.CommandRegistry{Registry: core.NewRegistry[*core.Command]()}
registry.Set("deploy/to/homelab", &core.Command{Name: "homelab"})

type Config

type Config struct {
	*ConfigOptions
	// contains filtered or unexported fields
}

Config holds configuration settings and feature flags.

cfg := (&core.Config{}).New()
cfg.Set("config.host", "homelab.lthn.sh")
core.Println(cfg.String("config.host"))
Example
c := New()
c.Config().Set("database.host", "localhost")
c.Config().Set("database.port", 5432)
c.Config().Enable("dark-mode")

Println(c.Config().String("database.host"))
Println(c.Config().Int("database.port"))
Println(c.Config().Enabled("dark-mode"))
Output:
localhost
5432
true

func (*Config) Bool

func (e *Config) Bool(key string) bool

Bool retrieves a bool config value (false if missing).

debug := c.Config().Bool("debug")
Example

ExampleConfig_Bool reads a boolean through `Config.Bool` for service configuration. Callers write untyped settings and read back typed values or enabled features.

cfg := (&Config{}).New()
cfg.Set("debug", true)
Println(cfg.Bool("debug"))
Output:
true

func (*Config) Disable

func (e *Config) Disable(feature string)

Disable deactivates a feature flag.

c.Config().Disable("dark-mode")
Example

ExampleConfig_Disable turns off a previously enabled feature flag for service configuration. Callers write untyped settings and read back typed values or enabled features.

c := New()
c.Config().Enable("debug")
c.Config().Disable("debug")
Println(c.Config().Enabled("debug"))
Output:
false

func (*Config) Enable

func (e *Config) Enable(feature string)

Enable activates a feature flag.

c.Config().Enable("dark-mode")
Example

ExampleConfig_Enable turns on named feature flags for service configuration. Callers write untyped settings and read back typed values or enabled features.

c := New()
c.Config().Enable("dark-mode")
c.Config().Enable("beta-features")

Println(c.Config().Enabled("dark-mode"))
features := c.Config().EnabledFeatures()
SliceSort(features)
Println(features)
Output:
true
[beta-features dark-mode]

func (*Config) Enabled

func (e *Config) Enabled(feature string) bool

Enabled returns true if a feature flag is active.

if c.Config().Enabled("dark-mode") { ... }
Example

ExampleConfig_Enabled checks whether a feature is enabled through `Config.Enabled` for service configuration. Callers write untyped settings and read back typed values or enabled features.

c := New()
c.Config().Enable("debug")
Println(c.Config().Enabled("debug"))
Output:
true

func (*Config) EnabledFeatures

func (e *Config) EnabledFeatures() []string

EnabledFeatures returns all active feature flag names.

features := c.Config().EnabledFeatures()
Example

ExampleConfig_EnabledFeatures lists enabled feature flags through `Config.EnabledFeatures` for service configuration. Callers write untyped settings and read back typed values or enabled features.

c := New()
c.Config().Enable("beta")
c.Config().Enable("debug")
features := c.Config().EnabledFeatures()
SliceSort(features)
Println(features)
Output:
[beta debug]

func (*Config) FromEnv added in v0.12.0

func (e *Config) FromEnv(prefix string) Result

FromEnv imports environment variables carrying the prefix into the store: MYAPP_DATABASE_HOST → "database.host" (prefix stripped, lowercased, underscores become dots). Returns the import count.

r := c.Config().FromEnv("MYAPP_")
core.Println(r.Int(), "keys imported")
Example

ExampleConfig_FromEnv imports prefixed environment variables: MYAPP_DATABASE_HOST becomes "database.host".

c := New()
r := c.Config().FromEnv("NO_SUCH_PREFIX_XYZ_")
Println(r.Int())
Output:
0

func (*Config) Get

func (e *Config) Get(key string) Result

Get retrieves a configuration value by key.

cfg := (&core.Config{}).New()
cfg.Set("config.host", "homelab.lthn.sh")
r := cfg.Get("config.host")
if r.OK { core.Println(r.Value.(string)) }
Example

ExampleConfig_Get retrieves a value through `Config.Get` for service configuration. Callers write untyped settings and read back typed values or enabled features.

cfg := (&Config{}).New()
cfg.Set("host", "localhost")
Println(cfg.Get("host").Value)
Println(cfg.Get("missing").OK)
Output:
localhost
false

func (*Config) Group added in v0.11.0

func (e *Config) Group(name string) *Config

Group returns a Config view scoped under name: Set/Get/String/Int/Bool and the feature methods operate on "<name>.<key>" in the shared underlying store. Nested groups compose; the root Config's ungrouped keys are unaffected.

db := c.Config("database")
db.Set("host", "localhost")          // stores "database.host"
c.Config().String("database.host")   // "localhost"
Example

ExampleConfig_Group scopes config keys under a group prefix through `Config.Group` — the view reads and writes "<group>.<key>" in the shared store.

c := New()
db := c.Config("database")
db.Set("host", "localhost")

Println(c.Config().String("database.host"))
Println(db.String("host"))
Output:
localhost
localhost

func (*Config) Int

func (e *Config) Int(key string) int

Int retrieves an int config value (0 if missing).

port := c.Config().Int("database.port")
Example

ExampleConfig_Int reads an integer through `Config.Int` for service configuration. Callers write untyped settings and read back typed values or enabled features.

cfg := (&Config{}).New()
cfg.Set("port", 8080)
Println(cfg.Int("port"))
Output:
8080

func (*Config) Load added in v0.12.0

func (e *Config) Load(path string) Result

Load merges a JSON object file into the store. Top-level values land under their keys; nested objects flatten with dotted keys ({"database":{"host":"x"}} → "database.host"). File values overwrite existing keys — call order is precedence order.

r := c.Config().Load("/etc/myapp/config.json")
if !r.OK { return r }
Example

ExampleConfig_Load merges a JSON file into the store with dotted keys.

c := New()
r := c.Config().Load("/nonexistent/config.json")
Println(r.OK)
Output:
false

func (*Config) New

func (e *Config) New() *Config

New initialises a Config with empty settings and features.

cfg := (&core.Config{}).New()
Example

ExampleConfig_New creates an empty configuration with no enabled feature flags. Callers write untyped settings and read back typed values or enabled features.

cfg := (&Config{}).New()
Println(cfg.EnabledFeatures())
Output:
[]

func (*Config) Set

func (e *Config) Set(key string, val any)

Set stores a configuration value by key.

cfg := (&core.Config{}).New()
cfg.Set("config.host", "homelab.lthn.sh")
Example

ExampleConfig_Set sets a value through `Config.Set` for service configuration. Callers write untyped settings and read back typed values or enabled features.

c := New()
c.Config().Set("database.host", "localhost")
c.Config().Set("database.port", 5432)

Println(c.Config().String("database.host"))
Println(c.Config().Int("database.port"))
Output:
localhost
5432

func (*Config) String

func (e *Config) String(key string) string

String retrieves a string config value (empty string if missing).

host := c.Config().String("database.host")
Example

ExampleConfig_String renders `Config.String` as a stable string for service configuration. Callers write untyped settings and read back typed values or enabled features.

cfg := (&Config{}).New()
cfg.Set("host", "localhost")
Println(cfg.String("host"))
Output:
localhost

type ConfigOptions

type ConfigOptions struct {
	Settings map[string]any
	Features map[string]bool
}

ConfigOptions holds configuration data.

opts := core.ConfigOptions{
    Settings: map[string]any{"config.host": "homelab.lthn.sh"},
    Features: map[string]bool{"agentic": true},
}
_ = opts
Example

ExampleConfigOptions groups settings and feature flags through `ConfigOptions` for service configuration. Callers write untyped settings and read back typed values or enabled features.

opts := ConfigOptions{
	Settings: map[string]any{"host": "localhost"},
	Features: map[string]bool{"debug": true},
}
Println(opts.Settings["host"])
Println(opts.Features["debug"])
Output:
localhost
true

type ConfigVar

type ConfigVar[T any] struct {
	// contains filtered or unexported fields
}

ConfigVar is a variable that can be set, unset, and queried for its state.

host := core.NewConfigVar("homelab.lthn.sh")
if host.IsSet() { core.Println(host.Get()) }
Example

ExampleConfigVar toggles a standalone config variable through `ConfigVar` for service configuration. Callers write untyped settings and read back typed values or enabled features.

v := NewConfigVar(42)
Println(v.Get(), v.IsSet())

v.Unset()
Println(v.Get(), v.IsSet())
Output:
42 true
0 false

func NewConfigVar

func NewConfigVar[T any](val T) ConfigVar[T]

NewConfigVar creates a ConfigVar with an initial value marked as set.

debug := core.NewConfigVar(true)
Example (Config)

ExampleNewConfigVar_config initialises configuration values through `NewConfigVar` for service configuration. Callers write untyped settings and read back typed values or enabled features.

v := NewConfigVar("enabled")
Println(v.Get())
Println(v.IsSet())
Output:
enabled
true

func (*ConfigVar[T]) Get

func (v *ConfigVar[T]) Get() T

Get returns the current value.

val := v.Get()
Example

ExampleConfigVar_Get reads a typed config var through `ConfigVar.Get`.

v := NewConfigVar("https://api.lthn.ai")
Println(v.Get())
Output:
https://api.lthn.ai

func (*ConfigVar[T]) IsSet

func (v *ConfigVar[T]) IsSet() bool

IsSet returns true if the value was explicitly set (distinguishes "set to false" from "never set").

if v.IsSet() { /* explicitly configured */ }
Example

ExampleConfigVar_IsSet reports whether a config var holds a value through `ConfigVar.IsSet`.

v := NewConfigVar("ready")
Println(v.IsSet())
Output:
true

func (*ConfigVar[T]) Set

func (v *ConfigVar[T]) Set(val T)

Set sets the value and marks it as explicitly set.

v.Set(true)
Example

ExampleConfigVar_Set sets a value through `ConfigVar.Set` for service configuration. Callers write untyped settings and read back typed values or enabled features.

var v ConfigVar[string]
v.Set("enabled")
Println(v.Get())
Println(v.IsSet())
Output:
enabled
true

func (*ConfigVar[T]) Unset

func (v *ConfigVar[T]) Unset()

Unset resets to zero value and marks as not set.

v.Unset()
v.IsSet()  // false
Example

ExampleConfigVar_Unset clears a value through `ConfigVar.Unset` for service configuration. Callers write untyped settings and read back typed values or enabled features.

v := NewConfigVar("enabled")
v.Unset()
Println(v.Get())
Println(v.IsSet())
Output:

false

type Conn

type Conn = net.Conn

Conn is the canonical network connection interface.

a, b := core.NetPipe()
defer a.Close(); defer b.Close()
var conn core.Conn = a
_ = conn

type Context

type Context = context.Context

Context is the cancellation/deadline carrier passed to Action handlers, Service lifecycle methods, and any I/O-bound Core call. Alias of context.Context — interchangeable at call sites.

ctx := core.Background()
r := c.Action("service.startup").Run(ctx, opts)

func Background

func Background() Context

Background returns the root Context — never cancelled, no deadline, no values. Use as the top-level Context for the application.

ctx := core.Background()
r := c.Action("agent.dispatch").Run(ctx, opts)
Example

ExampleBackground creates a background context through `Background` for request lifetime control. Cancellation and timeout lifetimes are created through the core context surface.

ctx := Background()
Println(ctx.Err() == nil)
Output:
true

func TODO

func TODO() Context

TODO returns a Context for code paths where the proper Context is not yet known — placeholder during refactors. Replace with a real Context before production.

ctx := core.TODO()
// TODO: wire a real Context once the caller is plumbed.
Example

ExampleTODO returns a non-nil placeholder context through `TODO`.

Println(TODO() != nil)
Output:
true

func WithValue

func WithValue(parent Context, key, val any) Context

WithValue returns a copy of parent carrying key=val. Use sparingly — prefer explicit parameters over Context-carried values for everything except request-scoped data (request IDs, auth tokens).

type requestIDKey struct{}
ctx := core.WithValue(core.Background(), requestIDKey{}, "req-12345")
id := ctx.Value(requestIDKey{}).(string)
Example

ExampleWithValue carries a request-scoped value through `WithValue`.

ctx := WithValue(Background(), "agent", "codex")
Println(ctx.Value("agent"))
Output:
codex
type Cookie = http.Cookie

Cookie is the canonical HTTP cookie value type.

cookie := &core.Cookie{Name: "session", Value: "agent-session", Path: "/"}
_ = cookie.String()

type Core

type Core struct {
	// contains filtered or unexported fields
}

Core is the central application object that manages services, assets, and communication.

c := core.New(core.WithOption("name", "homelab"))
ctx := c.Context()
_ = ctx
Example (Accessors)

ExampleCore_accessors reads the grouped accessor methods through `Core` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New(WithCli(), WithOption("name", "ops"))

Println(c.Options().String("name"))
Println(c.App().Name)
Println(c.Data() != nil)
Println(c.Drive() != nil)
Println(c.Fs() != nil)
Println(c.Config() != nil)
Println(c.Error() != nil)
Println(c.Log() != nil)
Println(c.Cli() != nil)
Println(c.IPC() != nil)
Println(c.I18n() != nil)
Output:
ops
ops
true
true
true
true
true
true
true
true
true

func MustNew added in v0.12.0

func MustNew(opts ...CoreOption) *Core

MustNew is New for package-var bundles: the first failed option panics, so a broken bundle fails at import time instead of half-constructing silently (New logs and continues — fine in main(), fatal in a package var nobody inspects).

var Widgets = core.MustNew(
    core.WithService(widgets.Register),
    core.WithServiceLock(),
)
Example

ExampleMustNew builds a package-var bundle that fails at import time instead of half-constructing — the sealed-toolkit constructor.

bundle := MustNew(
	WithOption("name", "widgets"),
	WithServiceLock(),
)
Println(bundle.App().Name)
Output:
widgets

func New

func New(opts ...CoreOption) *Core

New initialises a Core instance by applying options in order. Services registered here form the application conclave — they share IPC access and participate in the lifecycle (ServiceStartup/ServiceShutdown).

c := core.New(
    core.WithOption("name", "myapp"),
    core.WithService(auth.Register),
    core.WithServiceLock(),
)
c.Run()
Example
c := New(
	WithOption("name", "my-app"),
	WithServiceLock(),
)
Println(c.App().Name)
Output:
my-app
Example (WithOptions)

ExampleNew_withOptions passes construction options through `New` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

c := New(WithOptions(NewOptions(Option{Key: "name", Value: "ops"})))
Println(c.App().Name)
Output:
ops
Example (WithService)
c := New(
	WithOption("name", "example"),
	WithService(func(c *Core) Result {
		return c.Service("greeter", Service{
			OnStart: func() Result {
				Info("greeter started", "app", c.App().Name)
				return Result{OK: true}
			},
		})
	}),
)
c.ServiceStartup(Background(), nil)
Println(c.Services())
c.ServiceShutdown(Background())
// Output is non-deterministic (map order), so no Output comment

func (*Core) ACTION

func (c *Core) ACTION(msg Message) Result

ACTION broadcasts a message to all registered handlers (fire-and-forget). Each handler is wrapped in panic recovery. All handlers fire regardless.

c.ACTION(messages.AgentCompleted{Agent: "codex", Status: "completed"})
Example

ExampleCore_ACTION calls the uppercase action helper through `Core.ACTION` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New()
seen := ""
c.RegisterAction(func(_ *Core, msg Message) Result {
	seen = msg.(string)
	return Result{OK: true}
})

c.ACTION("started")
Println(seen)
Output:
started

func (*Core) API

func (c *Core) API(name ...string) *API

API returns the remote communication primitive. With a name it returns a view bound to that Drive endpoint — the named-resource accessor for remotes (see c.Lock, c.Feature, c.Config for the same mechanic on other subsystems).

c.API().Stream("charon")                      // subsystem, as ever
c.API("codex").Invoke("agentic.status", opts) // bound endpoint
c.API("lem-local").Stream()
Example

ExampleHTTPError writes a plain-text error body with the given status code. The handler exits after this call; the Recorder captures the response for assertion in tests. ExampleCore_API returns the HTTP API subsystem through `Core.API`.

Println(New().API() != nil)
Output:
true
Example (Named)

ExampleCore_API_named binds a Drive endpoint by name — the named-resource accessor for remotes.

c := New()
c.API().RegisterProtocol("http", mockFactory("ready"))
c.Drive().New(NewOptions(
	Option{Key: "name", Value: "lem-local"},
	Option{Key: "transport", Value: "http://127.0.0.1:9101"},
))
r := c.API("lem-local").Invoke("engine.status", NewOptions())
Println(r.String())
Output:
ready

func (*Core) Action

func (c *Core) Action(name string, handler ...ActionHandler) *Action

Action gets or registers a named action. With a handler argument: registers the action. Without: returns the action for invocation.

c.Action("process.run", handler)           // register
c.Action("process.run").Run(ctx, opts)     // invoke
c.Action("process.run").Exists()           // check
Example

ExampleCore_Action registers or retrieves an action through `Core.Action` for an agent dispatch workflow. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

c := New()
c.Action("agent.deploy", func(_ Context, _ Options) Result { return Result{OK: true} })
Println(c.Action("agent.deploy").Exists())
Output:
true
Example (Invoke)
c := New()
c.Action("math.add", func(_ Context, opts Options) Result {
	a := opts.Int("a")
	b := opts.Int("b")
	return Result{Value: a + b, OK: true}
})

r := c.Action("math.add").Run(Background(), NewOptions(
	Option{Key: "a", Value: 3},
	Option{Key: "b", Value: 4},
))
Println(r.Value)
Output:
7
Example (Register)
c := New()
c.Action("agent.greet", func(_ Context, opts Options) Result {
	name := opts.String("name")
	return Result{Value: Concat("hello ", name), OK: true}
})
Println(c.Action("agent.greet").Exists())
Output:
true
Example (Remote)

ExampleCore_Action_remote dispatches "host:action" through the named endpoint's transport — the colon law. Local registrations always win.

c := New()
c.API().RegisterProtocol("http", mockFactory("pong"))
c.Drive().New(NewOptions(
	Option{Key: "name", Value: "charon"},
	Option{Key: "transport", Value: "http://10.69.69.165:9101/mcp"},
))
r := c.Action("charon:agentic.status").Run(Background(), NewOptions())
Println(r.String())
Output:
pong

func (*Core) Actions

func (c *Core) Actions() []string

Actions returns all registered named action names in registration order.

names := c.Actions()  // ["process.run", "agentic.dispatch"]
Example
c := New()
c.Action("process.run", func(_ Context, _ Options) Result { return Result{OK: true} })
c.Action("brain.recall", func(_ Context, _ Options) Result { return Result{OK: true} })

// The discovery built-ins lead every listing (W4-1).
Println(c.Actions())
Output:
[core.actions core.info core.health process.run brain.recall]
Example (Action)

ExampleCore_Actions_action registers the action-oriented path through `Core.Actions` for an agent dispatch workflow. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

c := New()
c.Action("agent.deploy", func(_ Context, _ Options) Result { return Result{OK: true} })
c.Action("agent.test", func(_ Context, _ Options) Result { return Result{OK: true} })
Println(c.Actions())
Output:
[core.actions core.info core.health agent.deploy agent.test]

func (*Core) App

func (c *Core) App() *App

App returns application identity metadata.

c.App().Name     // "my-app"
c.App().Version  // "1.0.0"
Example

ExampleCore_App returns application metadata through `Core.App`.

Println(New().App() != nil)
Output:
true

func (*Core) Cli

func (c *Core) Cli() *Cli

Cli returns the CLI command framework (registered as service "cli").

c.Cli().Run("deploy", "to", "homelab")
Example

ExampleCore_Cli returns the CLI subsystem through `Core.Cli`.

Println(New(WithCli()).Cli() != nil)
Output:
true

func (*Core) Command

func (c *Core) Command(path string, command ...Command) Result

Command gets or registers a command by path.

c.Command("deploy", Command{Action: handler})
r := c.Command("deploy")
Example
c := New(WithCli())
c.Command("deploy/to/homelab", Command{
	Action: func(opts Options) Result {
		return Result{Value: Concat("deployed to ", opts.String("_arg")), OK: true}
	},
})

r := c.Cli().Run("deploy", "to", "homelab")
Println(r.OK)
Output:
true
Example (Get)

ExampleCore_Command_get retrieves a value through `Core.Command` for managed CLI command dispatch. Command registration and lookup use managed metadata before execution.

c := New()
c.Command("deploy", Command{Action: func(_ Options) Result { return Result{OK: true} }})
r := c.Command("deploy")
cmd := r.Value.(*Command)
Println(cmd.Name)
Println(cmd.Path)
Output:
deploy
deploy
Example (Managed)

ExampleCore_Command_managed registers managed command metadata through `Core.Command` for managed CLI command dispatch. Command registration and lookup use managed metadata before execution.

c := New()
c.Command("serve", Command{
	Action:  func(_ Options) Result { return Result{OK: true} },
	Managed: "process.daemon",
})

cmd := c.Command("serve").Value.(*Command)
Println(cmd.IsManaged())
Output:
true
Example (Register)

ExampleCore_Command_register registers a value through `Core.Command` for managed CLI command dispatch. Command registration and lookup use managed metadata before execution.

c := New()
c.Command("deploy/to/homelab", Command{
	Description: "Deploy to homelab",
	Action: func(opts Options) Result {
		return Result{Value: "deployed", OK: true}
	},
})

Println(c.Command("deploy/to/homelab").OK)
Output:
true

func (*Core) Commands

func (c *Core) Commands() []string

Commands returns all registered command paths in registration order.

paths := c.Commands()
Example

ExampleCore_Commands lists command names through `Core.Commands` for managed CLI command dispatch. Command registration and lookup use managed metadata before execution.

c := New()
c.Command("deploy", Command{Action: func(_ Options) Result { return Result{OK: true} }})
c.Command("test", Command{Action: func(_ Options) Result { return Result{OK: true} }})

Println(c.Commands())
Output:
[deploy test]

func (*Core) Config

func (c *Core) Config(group ...string) *Config

Config returns runtime settings and feature flags. With a group argument it returns a Config view scoped under that key prefix (see Config.Group).

host := c.Config().String("database.host")
c.Config().Enable("dark-mode")
c.Config("database").Set("host", "localhost") // stores "database.host"
Example

ExampleCore_Config returns the configuration subsystem through `Core.Config`.

Println(New().Config() != nil)
Output:
true

func (*Core) Context

func (c *Core) Context() Context

Context returns Core's lifecycle context (cancelled on shutdown).

ctx := c.Context()
Example

ExampleCore_Context reads the active context through `Core.Context` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New()
Println(c.Context() != nil)
Output:
true

func (*Core) Core

func (c *Core) Core() *Core

Core returns self — satisfies the ServiceRuntime interface.

c := s.Core()
Example

ExampleCore_Core returns the Core instance through `Core.Core` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New()
Println(c.Core() == c)
Output:
true

func (*Core) Data

func (c *Core) Data(name ...string) *Data

Data returns the embedded asset registry (Registry[*Embed]). With a name it returns a view bound to that mount — paths become relative to it (the named-resource accessor, as c.Lock / c.API / c.Config).

r := c.Data().ReadString("brain/coding.md")
r = c.Data("brain").ReadString("coding.md")   // same file
Example

ExampleCore_Data returns the embedded-asset registry through `Core.Data`.

Println(New().Data() != nil)
Output:
true

func (*Core) Drive

func (c *Core) Drive(name ...string) *Drive

Drive returns the transport handle registry (Registry[*DriveHandle]). With a name it returns a view bound to that handle.

r := c.Drive().Get("forge")
if c.Drive("forge").Exists() { url := c.Drive("forge").Transport() }
Example

ExampleCore_Drive returns the remote-endpoint registry through `Core.Drive`.

Println(New().Drive() != nil)
Output:
true

func (*Core) Entitled

func (c *Core) Entitled(action string, quantity ...int) Entitlement

Entitled checks if an action is permitted in the current context. Default: always returns Allowed=true, Unlimited=true. Denials are logged via core.Security().

e := c.Entitled("process.run")
e := c.Entitled("social.accounts", 3)
Example

ExampleCore_Entitled checks an entitlement through `Core.Entitled` for usage-gated agent features. Usage checks separate policy decisions from the action body.

c := New()
e := c.Entitled("deploy")
Println(e.Allowed)
Println(e.Unlimited)
Output:
true
true
Example (Custom)
c := New()
c.SetEntitlementChecker(func(action string, qty int, _ Context) Entitlement {
	if action == "premium" {
		return Entitlement{Allowed: false, Reason: "upgrade required"}
	}
	return Entitlement{Allowed: true, Unlimited: true}
})

Println(c.Entitled("basic").Allowed)
Println(c.Entitled("premium").Allowed)
Println(c.Entitled("premium").Reason)
Output:
true
false
upgrade required
Example (Default)
c := New()
e := c.Entitled("anything")
Println(e.Allowed)
Println(e.Unlimited)
Output:
true
true

func (*Core) Env

func (c *Core) Env(key string) string

Env returns an environment variable by key (cached at init, falls back to os.Getenv).

home := c.Env("DIR_HOME")
token := c.Env("FORGE_TOKEN")
Example

ExampleCore_Env reads environment access through `Core.Env` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New()
Println(c.Env("OS") != "")
Output:
true

func (*Core) Error

func (c *Core) Error() *ErrorPanic

Error returns the panic recovery subsystem.

c.Error().Recover()
Example

ExampleCore_Error returns the panic-recovery subsystem through `Core.Error`.

Println(New().Error() != nil)
Output:
true

func (*Core) Exit

func (c *Core) Exit(code int)

Exit terminates the process with the given code, after running shutdown hooks.

Default 30s timeout — long enough for graceful database shutdown / file flushes, short enough that ops can SIGKILL after waiting (matches systemd TimeoutStopSec).

// fatal error in a signal handler
c.Action("signal.received", func(ctx Context, opts core.Options) core.Result {
    if opts.String("name") == "SIGINT" { c.Exit(0) }
    return core.Result{OK: true}
})
Example

ExampleCore_Exit documents the normal Core exit call without terminating the example process. Production exit paths are documented without terminating the example test process.

c := New()
_ = c // c.Exit(0) terminates the process in production
Println("ready to exit")
Output:
ready to exit

func (*Core) ExitNow

func (c *Core) ExitNow(code int)

ExitNow terminates immediately without running shutdown hooks. Use only when shutdown is hung or unsafe (e.g. inside a panic the shutdown chain may have caused).

defer func() {
    if r := recover(); r != nil { c.ExitNow(2) }
}()
Example

ExampleCore_ExitNow documents immediate termination without running it during the example process. Production exit paths are documented without terminating the example test process.

c := New()
_ = c // c.ExitNow(2) terminates without running ServiceShutdown
Println("emergency")
Output:
emergency

func (*Core) ExitWith

func (c *Core) ExitWith(opts ExitOptions)

ExitWith runs ServiceShutdown with the given timeout, then exits. If shutdown does not complete within Timeout, the process exits anyway and a warning is logged.

// daemon with a tighter shutdown budget
c.ExitWith(core.ExitOptions{Code: 0, Timeout: 5 * core.Second})
Example

ExampleCore_ExitWith configures exit code and shutdown timing without terminating the example process. Production exit paths are documented without terminating the example test process.

c := New()
_ = c // c.ExitWith(core.ExitOptions{Code: 0})
_ = ExitOptions{Code: 0}
Println("configured")
Output:
configured

func (*Core) Feature added in v0.11.0

func (c *Core) Feature(name string) Feature

Feature returns a keyed handle to a single feature flag (name required).

c.Feature("dark-mode").Enable()
if c.Feature("dark-mode").Enabled() { core.Println("on") }
Example

ExampleCore_Feature returns a feature-flag handle through `Core.Feature`.

c := New()
c.Feature("dark-mode").Enable()
Println(c.Feature("dark-mode").Enabled())
Output:
true

func (*Core) Fs

func (c *Core) Fs() *Fs

Fs returns the sandboxed filesystem.

r := c.Fs().Read("/path/to/file")
c.Fs().WriteAtomic("/status.json", data)
Example

ExampleCore_Fs returns the sandboxed filesystem through `Core.Fs`.

Println(New().Fs() != nil)
Output:
true

func (*Core) Go added in v0.10.0

func (c *Core) Go(fn func())

Go spawns a goroutine tracked by Core's waitGroup. ServiceShutdown waits for every tracked goroutine to exit before stopping services, so long-running workers + watchers + reconnect loops don't get orphaned across a clean shutdown. Long-running goroutines should also poll IsShutdown between work units to exit cooperatively.

c.Go(func() {
    for !c.IsShutdown() {
        pollOnce()
        core.Sleep(30 * core.Second)
    }
})
Example

ExampleCore_Go spawns a tracked goroutine through `Core.Go` so ServiceShutdown waits for it to exit before stopping services. Long-running workers and watchers spawn this way to avoid being orphaned across a clean shutdown.

c := New()
done := make(chan struct{})
c.Go(func() {
	Println("worker ran")
	close(done)
})
<-done
c.ServiceShutdown(Background())
Output:
worker ran

func (*Core) I18n

func (c *Core) I18n() *I18n

I18n returns the internationalisation subsystem.

tr := c.I18n().Translate("cmd.deploy.description")
Example

ExampleCore_I18n returns the translation subsystem through `Core.I18n`.

Println(New().I18n() != nil)
Output:
true

func (*Core) IPC

func (c *Core) IPC() *Ipc

IPC returns the message bus internals.

c.IPC()
Example

ExampleCore_IPC returns the IPC action/task subsystem through `Core.IPC`.

Println(New().IPC() != nil)
Output:
true

func (*Core) IsShutdown added in v0.10.0

func (c *Core) IsShutdown() bool

IsShutdown reports whether ServiceShutdown has been initiated. Long-running goroutines spawned via c.Go check this between work units to exit cooperatively before the waitGroup drain blocks.

for !c.IsShutdown() {
    processBatch()
}
Example

ExampleCore_IsShutdown reports whether ServiceShutdown has been initiated. Long-running goroutines poll this between work units to exit cooperatively before the waitGroup drain blocks.

c := New()
Println(c.IsShutdown())
c.ServiceShutdown(Background())
Println(c.IsShutdown())
Output:
false
true

func (*Core) Lock

func (c *Core) Lock(name string) *Lock

Lock returns a named Lock, creating the mutex if needed. Locks are per-Core — separate Core instances do not share mutexes. The returned *Lock wrapper is cached in Core's locks Registry, so subsequent calls for the same name reuse the same pointer (race-safe via Registry.GetOrSet — two goroutines racing the first lookup converge on a single shared *RWMutex).

l := c.Lock("drain")
l.Lock(); defer l.Unlock()
Example

ExampleCore_Lock acquires a lock through `Core.Lock` for lifecycle locking. Lifecycle locks coordinate startup and shutdown without exposing sync primitives directly.

c := New()
lock := c.Lock("drain")
lock.Lock()
Println("locked")
lock.Unlock()
Println("unlocked")
Output:
locked
unlocked

func (*Core) LockApply

func (c *Core) LockApply()

LockApply activates the service-global lock if it was enabled via LockEnable (or WithServiceLock). A no-op when the lock was never enabled.

c := core.New(core.WithServiceLock())
c.LockApply()
Example

ExampleCore_LockApply applies lifecycle locking through `Core.LockApply` for lifecycle locking. Lifecycle locks coordinate startup and shutdown without exposing sync primitives directly.

c := New()
c.LockEnable()
c.LockApply()
Println(c.Service("late", Service{}).OK)
Output:
false

func (*Core) LockEnable

func (c *Core) LockEnable()

LockEnable marks that the service lock should be applied after initialisation. The lock is service-global — it freezes the whole services registry against further registration; there is no per-service lock (a service is a registry entry, not a lockable registry). Pair with LockApply.

c := core.New()
c.LockEnable()
c.LockApply()
Example

ExampleCore_LockEnable enables lifecycle locking through `Core.LockEnable` for lifecycle locking. Lifecycle locks coordinate startup and shutdown without exposing sync primitives directly.

c := New()
c.LockEnable()
c.LockApply()
Println(c.Service("late", Service{}).OK)
Output:
false

func (*Core) Log

func (c *Core) Log() *ErrorLog

Log returns the structured logging subsystem.

c.Log().Info("started", "port", 8080)
Example

ExampleCore_Log returns the structured logger through `Core.Log`.

Println(New().Log() != nil)
Output:
true

func (*Core) LogError

func (c *Core) LogError(err error, op, msg string) Result

LogError logs an error and returns the Result from ErrorLog.

c := core.New()
err := core.NewError("homelab unreachable")
r := c.LogError(err, "agent.Ping", "health check failed")
if !r.OK { return r }
Example

ExampleCore_LogError logs an error through `Core.LogError` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New()
r := c.LogError(nil, "example", "nothing to log")
Println(r.OK)
Output:
true

func (*Core) LogWarn

func (c *Core) LogWarn(err error, op, msg string) Result

LogWarn logs a warning and returns the Result from ErrorLog.

c := core.New()
err := core.NewError("config.host missing")
r := c.LogWarn(err, "config.Load", "using default host")
if !r.OK { return r }
Example

ExampleCore_LogWarn logs a warning through `Core.LogWarn` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New()
r := c.LogWarn(nil, "example", "nothing to warn")
Println(r.OK)
Output:
true

func (*Core) Must

func (c *Core) Must(err error, op, msg string)

Must logs and panics if err is not nil.

c := core.New()
c.Must(nil, "agent.Start", "startup failed")
Example

ExampleCore_Must unwraps a successful Result through `Core.Must` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New()
c.Must(nil, "example", "no panic")
Println("ok")
Output:
ok

func (*Core) Options

func (c *Core) Options() *Options

Options returns the input configuration passed to core.New().

opts := c.Options()
name := opts.String("name")
Example

ExampleCore_RegistryOf retrieves a named registry through `Core.RegistryOf` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade. ExampleCore_Options returns the key-value options store through `Core.Options`.

c := New(WithOption("env", "prod"))
Println(c.Options() != nil)
Output:
true

func (*Core) PerformAsync

func (c *Core) PerformAsync(action string, opts Options) Result

PerformAsync dispatches a named action in a background goroutine. Broadcasts ActionTaskStarted, ActionTaskProgress, and ActionTaskCompleted as IPC messages so other services can track progress.

r := c.PerformAsync("agentic.dispatch", opts)
taskID := r.Value.(string)
Example

ExampleCore_PerformAsync starts asynchronous work through `Core.PerformAsync` for background task progress. Asynchronous work reports progress through Core task helpers.

c := New()
c.Action("bg.work", func(_ Context, _ Options) Result {
	return Result{Value: "done", OK: true}
})

r := c.PerformAsync("bg.work", NewOptions())
Println(HasPrefix(r.Value.(string), "id-"))
Output:
true

func (*Core) Process

func (c *Core) Process() *Process

Process returns the process management primitive.

c.Process().Run(ctx, "git", "log")
Example
c := New()
// No go-process registered — permission by registration
Println(c.Process().Exists())

// Register a mock process handler
c.Action("process.run", func(_ Context, opts Options) Result {
	return Result{Value: Concat("output of ", opts.String("command")), OK: true}
})
Println(c.Process().Exists())

r := c.Process().Run(Background(), "echo", "hello")
Println(r.Value)
Output:
false
true
output of echo
Example (Accessor)

ExampleCore_Process_accessor reads the accessor method through `Core.Process` for managed process execution. Process launches and lifecycle controls flow through Core.Process.

c := New()
Println(c.Process() != nil)
Output:
true

func (*Core) Progress

func (c *Core) Progress(taskID string, progress float64, message string, action string)

Progress broadcasts a progress update for a background task.

c.Progress(taskID, 0.5, "halfway done", "agentic.dispatch")
Example
c := New()
var progress float64
var message string
c.RegisterAction(func(_ *Core, msg Message) Result {
	if ev, ok := msg.(ActionTaskProgress); ok {
		progress = ev.Progress
		message = ev.Message
	}
	return Result{OK: true}
})

c.Progress("task-1", 0.5, "halfway", "deploy")
Println(progress)
Println(message)
Output:
0.5
halfway

func (*Core) QUERY

func (c *Core) QUERY(q Query) Result

QUERY sends a request — first handler to return OK wins.

r := c.QUERY(MyQuery{Name: "brain"})
Example

ExampleCore_QUERY calls the uppercase query helper through `Core.QUERY` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New()
c.RegisterQuery(func(_ *Core, q Query) Result {
	return Result{Value: Concat("query:", q.(string)), OK: true}
})

r := c.QUERY("status")
Println(r.Value)
Output:
query:status

func (*Core) QUERYALL

func (c *Core) QUERYALL(q Query) Result

QUERYALL sends a request — collects all OK responses.

r := c.QUERYALL(countQuery{})
results := r.Value.([]any)
Example

ExampleCore_QUERYALL calls every matching uppercase query through `Core.QUERYALL` for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New()
c.RegisterQuery(func(_ *Core, q Query) Result {
	return Result{Value: Concat("a:", q.(string)), OK: true}
})
c.RegisterQuery(func(_ *Core, q Query) Result {
	return Result{Value: Concat("b:", q.(string)), OK: true}
})

r := c.QUERYALL("status")
Println(r.Value)
Output:
[a:status b:status]

func (*Core) Query

func (c *Core) Query(q Query) Result

Query dispatches a request — first handler to return OK wins.

r := c.Query(MyQuery{})
Example

ExampleCore_Query runs or declares a query through `Core.Query` for Core message dispatch. Actions and queries share one Core dispatch pattern for messages.

c := New()
c.RegisterQuery(func(_ *Core, q Query) Result {
	if q == "status" {
		return Result{Value: "ready", OK: true}
	}
	return Result{}
})

Println(c.Query("status").Value)
Output:
ready

func (*Core) QueryAll

func (c *Core) QueryAll(q Query) Result

QueryAll dispatches a request — collects all OK responses.

r := c.QueryAll(countQuery{})
results := r.Value.([]any)
Example

ExampleCore_QueryAll runs all matching queries through `Core.QueryAll` for Core message dispatch. Actions and queries share one Core dispatch pattern for messages.

c := New()
c.RegisterQuery(func(_ *Core, _ Query) Result { return Result{Value: "api", OK: true} })
c.RegisterQuery(func(_ *Core, _ Query) Result { return Result{Value: "worker", OK: true} })

Println(c.QueryAll("services").Value)
Output:
[api worker]

func (*Core) RecordUsage

func (c *Core) RecordUsage(action string, quantity ...int)

RecordUsage records consumption after a gated action succeeds. Delegates to the registered UsageRecorder. No-op if none registered.

e := c.Entitled("ai.credits", 10)
if e.Allowed {
    doWork()
    c.RecordUsage("ai.credits", 10)
}
Example
c := New()
var recorded string
c.SetUsageRecorder(func(action string, qty int, _ Context) {
	recorded = Concat(action, ":", Sprint(qty))
})

c.RecordUsage("ai.credits", 10)
Println(recorded)
Output:
ai.credits:10

func (*Core) RegisterAction

func (c *Core) RegisterAction(handler func(*Core, Message) Result)

RegisterAction registers a broadcast handler for ACTION messages.

c.RegisterAction(func(c *core.Core, msg core.Message) core.Result {
    if ev, ok := msg.(AgentCompleted); ok { ... }
    return core.Result{OK: true}
})
Example

ExampleCore_RegisterAction registers an action through `Core.RegisterAction` for Core message dispatch. Actions and queries share one Core dispatch pattern for messages.

c := New()
seen := ""
c.RegisterAction(func(_ *Core, msg Message) Result {
	seen = msg.(string)
	return Result{OK: true}
})

c.ACTION("started")
Println(seen)
Output:
started

func (*Core) RegisterActions

func (c *Core) RegisterActions(handlers ...func(*Core, Message) Result)

RegisterActions registers multiple broadcast handlers.

c := core.New()
c.RegisterActions(
    func(c *core.Core, msg core.Message) core.Result { return core.Result{OK: true} },
    func(c *core.Core, msg core.Message) core.Result { return core.Result{OK: true} },
)
Example

ExampleCore_RegisterActions registers a group of actions through `Core.RegisterActions` for Core message dispatch. Actions and queries share one Core dispatch pattern for messages.

c := New()
var seen []string
c.RegisterActions(
	func(_ *Core, msg Message) Result {
		seen = append(seen, Concat("a:", msg.(string)))
		return Result{OK: true}
	},
	func(_ *Core, msg Message) Result {
		seen = append(seen, Concat("b:", msg.(string)))
		return Result{OK: true}
	},
)

c.ACTION("started")
Println(seen)
Output:
[a:started b:started]

func (*Core) RegisterQuery

func (c *Core) RegisterQuery(handler QueryHandler)

RegisterQuery registers a handler for QUERY dispatch.

c.RegisterQuery(func(_ *core.Core, q core.Query) core.Result { ... })
Example

ExampleCore_RegisterQuery registers a query through `Core.RegisterQuery` for Core message dispatch. Actions and queries share one Core dispatch pattern for messages.

c := New()
c.RegisterQuery(func(_ *Core, _ Query) Result { return Result{Value: "registered", OK: true} })
Println(c.Query("anything").Value)
Output:
registered

func (*Core) RegisterService

func (c *Core) RegisterService(name string, instance any) Result

RegisterService registers a service instance by name. Auto-discovers Startable, Stoppable, and HandleIPCEvents interfaces on the instance and wires them into the lifecycle and IPC bus.

c.RegisterService("display", displayInstance)
Example

ExampleCore_RegisterService registers a service through `Core.RegisterService` for service registration. Services register by name and can be recovered with typed helpers.

c := New()
r := c.RegisterService("worker", &exampleRegisteredService{name: "worker"})
Println(r.OK)
Println(c.Service("worker").Value.(*exampleRegisteredService).name)
Output:
true
worker

func (*Core) RegistryOf

func (c *Core) RegistryOf(name string) Result

RegistryOf returns a point-in-time snapshot of a named registry, wrapped in a Result, for cross-cutting queries (Names/Len/Has/List). Known names: "services", "commands", "actions", "tasks", "locks", "data", "drive", "api", "embed", "features". An unknown name yields Result{OK:false} — distinguishable from a known-but-empty registry. The snapshot is a copy taken at call time and does NOT track later changes; call again for a fresh view.

r := c.RegistryOf("services")
if r.OK { names := r.Value.(*core.Registry[any]).Names() }
Example
c := New()
c.Action("agent.deploy", func(_ Context, _ Options) Result { return Result{OK: true} })
r := c.RegistryOf("actions")
Println(r.OK)
Println(r.Value.(*Registry[any]).Names())
Println(c.RegistryOf("missing").OK)
Output:
true
[core.actions core.info core.health agent.deploy]
false

func (*Core) Reloadables added in v0.12.0

func (c *Core) Reloadables() Result

Reloadables returns services that have an OnReload function, in registration order.

c := core.New()
r := c.Reloadables()
if r.OK { services := r.Value.([]*core.Service); _ = services }
Example

ExampleCore_Reloadables lists services carrying an OnReload hook.

c := New()
c.RegisterService("cache", &reloadableCache{})
r := c.Reloadables()
Println(len(r.Value.([]*Service)))
Output:
1

func (*Core) RemoteAction

func (c *Core) RemoteAction(name string, ctx Context, opts Options) Result

RemoteAction resolves "host:action.name" syntax for transparent remote dispatch. If the action name contains ":", the prefix is the endpoint and the suffix is the action.

c.Action("charon:agentic.status")  // → c.API().Call("charon", "agentic.status", opts)
Example

ExampleCore_RemoteAction resolves an action name locally before a remote drive prefix is needed. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

c := New()
// Local action
c.Action("agent.status", func(_ Context, _ Options) Result {
	return Result{Value: "running", OK: true}
})

// No colon — resolves locally
r := c.RemoteAction("agent.status", Background(), NewOptions())
Println(r.Value)
Output:
running

func (*Core) Run

func (c *Core) Run()

Run starts all services, runs the CLI, then shuts down. Calls c.Exit(1) on failure (graceful shutdown chain, 30s timeout). For programmatic error handling use RunResult().

c := core.New(core.WithService(myService.Register))
c.Run()
Example

ExampleCore_Run runs `Core.Run` with representative caller inputs for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

_ = New().Run

func (*Core) RunResult

func (c *Core) RunResult() Result

RunResult starts all services, runs the CLI, then shuts down. Returns Result so main() can decide how to handle failure. ServiceShutdown is always called via defer, even on startup failure or panic.

r := c.RunResult()
if !r.OK { core.Exit(1) }
Example

ExampleCore_RunResult runs `Core.RunResult` through the Result-returning startup path for Core orchestration. Core keeps orchestration helpers reachable from one predictable facade.

c := New()
Println(c.RunResult().OK)
Output:
true

func (*Core) Service

func (c *Core) Service(name string, service ...Service) Result

Service gets or registers a service by name.

c.Service("auth", core.Service{OnStart: startFn})
r := c.Service("auth")
Example

ExampleCore_Service retrieves a service through `Core.Service` for service registration. Services register by name and can be recovered with typed helpers.

c := New()
c.Service("cache", Service{})
Println(c.Service("cache").OK)
Output:
true

func (*Core) ServiceReload added in v0.12.0

func (c *Core) ServiceReload(ctx Context) Result

ServiceReload runs OnReload for all registered services that have one, in registration order — the top-level runner the OnReload field was waiting for (W3-5). A failing reload stops the chain and returns that result. Broadcasts ActionServiceReload on success.

r := c.ServiceReload(c.Context())
if !r.OK { return r }
Example

ExampleCore_ServiceReload runs every service's OnReload in registration order — trigger from a signal handler or admin action.

c := New()
c.RegisterService("cache", &reloadableCache{})
c.ServiceReload(Background())
Output:
cache reloaded

func (*Core) ServiceShutdown

func (c *Core) ServiceShutdown(ctx Context) Result

ServiceShutdown drains background tasks, then stops all registered services.

c := core.New()
r := c.ServiceShutdown(Background())
if !r.OK { return r }
Example

ExampleCore_ServiceShutdown runs service shutdown through `Core.ServiceShutdown` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

stopped := false
c := New()
c.Service("worker", Service{OnStop: func() Result {
	stopped = true
	return Result{OK: true}
}})

r := c.ServiceShutdown(Background())
Println(r.OK)
Println(stopped)
Output:
true
true

func (*Core) ServiceStartup

func (c *Core) ServiceStartup(ctx Context, options any) Result

ServiceStartup runs OnStart for all registered services that have one.

c := core.New()
r := c.ServiceStartup(Background(), nil)
if !r.OK { return r }
Example

ExampleCore_ServiceStartup runs service startup through `Core.ServiceStartup` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

started := false
c := New()
c.Service("worker", Service{OnStart: func() Result {
	started = true
	return Result{OK: true}
}})

r := c.ServiceStartup(Background(), nil)
Println(r.OK)
Println(started)
c.ServiceShutdown(Background())
Output:
true
true

func (*Core) Services

func (c *Core) Services() []string

Services returns all registered service names in registration order.

names := c.Services()
Example

ExampleCore_Services lists registered services through `Core.Services` for service registration. Services register by name and can be recovered with typed helpers.

c := New(WithCli())
c.Service("cache", Service{})
c.Service("worker", Service{})
Println(c.Services())
Output:
[cli cache worker]

func (*Core) SetEntitlementChecker

func (c *Core) SetEntitlementChecker(checker EntitlementChecker)

SetEntitlementChecker replaces the default (permissive) checker. Called by go-entitlements or commerce-matrix during OnStartup.

func (s *EntitlementService) OnStartup(ctx Context) core.Result {
    s.Core().SetEntitlementChecker(s.check)
    return core.Result{OK: true}
}
Example

ExampleCore_SetEntitlementChecker installs an entitlement checker through `Core.SetEntitlementChecker` for usage-gated agent features. Usage checks separate policy decisions from the action body.

c := New()
c.SetEntitlementChecker(func(action string, qty int, _ Context) Entitlement {
	limits := map[string]int{"social.accounts": 5, "ai.credits": 100}
	usage := map[string]int{"social.accounts": 3, "ai.credits": 95}

	limit, ok := limits[action]
	if !ok {
		return Entitlement{Allowed: false, Reason: "not in package"}
	}
	used := usage[action]
	remaining := limit - used
	if qty > remaining {
		return Entitlement{Allowed: false, Limit: limit, Used: used, Remaining: remaining, Reason: "limit exceeded"}
	}
	return Entitlement{Allowed: true, Limit: limit, Used: used, Remaining: remaining}
})

Println(c.Entitled("social.accounts", 2).Allowed)
Println(c.Entitled("social.accounts", 5).Allowed)
Println(c.Entitled("ai.credits").NearLimit(0.9))
Output:
true
false
true

func (*Core) SetUsageRecorder

func (c *Core) SetUsageRecorder(recorder UsageRecorder)

SetUsageRecorder registers a usage tracking function. Called by go-entitlements during OnStartup.

c := core.New()
c.SetUsageRecorder(func(action string, quantity int, ctx Context) {
    core.Info("usage recorded", "action", action, "quantity", quantity)
})
Example

ExampleCore_RecordUsage records metered usage through `Core.RecordUsage` for usage-gated agent features. Usage checks separate policy decisions from the action body. ExampleCore_SetUsageRecorder installs a usage recorder through `Core.SetUsageRecorder`.

c := New()
c.SetUsageRecorder(nil) // nil clears the recorder; pass a UsageRecorder to capture usage

func (*Core) Signal

func (c *Core) Signal() *Signal

Signal returns the signal-handling primitive.

c.Signal().Stop()
Example

ExampleCore_Signal accesses signal handling through `Core.Signal` for process signal handling. OS signal integration is represented as action-backed Core behaviour.

c := New()
Println(c.Signal() != nil)
Output:
true
Example (Exists)

ExampleCore_Signal_exists checks whether signal handling has been registered in Core. OS signal integration is represented as action-backed Core behaviour.

c := New()
if c.Signal().Exists() {
	Println("signal handling available")
} else {
	Println("no signal service registered")
}
Output:
no signal service registered
Example (Subscribe)

ExampleCore_Signal_subscribe registers the action that a process signal service invokes on receipt. OS signal integration is represented as action-backed Core behaviour.

c := New()
c.Action("signal.received", func(_ Context, opts Options) Result {
	Println("got", opts.String("name"))
	return Result{OK: true}
})
// In production this fires on SIGINT/SIGTERM/SIGHUP:
c.Action("signal.received").Run(c.Context(),
	NewOptions(Option{Key: "name", Value: "SIGINT"}))
Output:
got SIGINT

func (*Core) Startables

func (c *Core) Startables() Result

Startables returns services that have an OnStart function, in registration order.

c := core.New()
r := c.Startables()
if r.OK { services := r.Value.([]*core.Service); _ = services }
Example

ExampleCore_Startables lists startup hooks through `Core.Startables` for lifecycle locking. Lifecycle locks coordinate startup and shutdown without exposing sync primitives directly.

c := New()
c.Service("worker", Service{OnStart: func() Result { return Result{OK: true} }})
r := c.Startables()
Println(len(r.Value.([]*Service)))
Output:
1

func (*Core) Stoppables

func (c *Core) Stoppables() Result

Stoppables returns services that have an OnStop function, in registration order.

c := core.New()
r := c.Stoppables()
if r.OK { services := r.Value.([]*core.Service); _ = services }
Example

ExampleCore_Stoppables lists shutdown hooks through `Core.Stoppables` for lifecycle locking. Lifecycle locks coordinate startup and shutdown without exposing sync primitives directly.

c := New()
c.Service("worker", Service{OnStop: func() Result { return Result{OK: true} }})
r := c.Stoppables()
Println(len(r.Value.([]*Service)))
Output:
1

func (*Core) Task

func (c *Core) Task(name string, def ...Task) *Task

Task gets or registers a named task. With a Task argument: registers the task. Without: returns the task for invocation.

c.Task("deploy", core.Task{Steps: steps})  // register
c.Task("deploy").Run(ctx, c, opts)             // invoke
Example
c := New()
order := ""

c.Action("step.a", func(_ Context, _ Options) Result {
	order += "a"
	return Result{Value: "from-a", OK: true}
})
c.Action("step.b", func(_ Context, opts Options) Result {
	order += "b"
	return Result{OK: true}
})

c.Task("pipeline", Task{
	Steps: []Step{
		{Action: "step.a"},
		{Action: "step.b", Input: "previous"},
	},
})

c.Task("pipeline").Run(Background(), c, NewOptions())
Println(order)
Output:
ab
Example (Action)

ExampleCore_Task_action registers the action-oriented path through `Core.Task` for an agent dispatch workflow. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

c := New()
c.Task("deploy", Task{Steps: []Step{{Action: "deploy.plan"}}})
Println(c.Tasks())
Output:
[deploy]

func (*Core) Tasks

func (c *Core) Tasks() []string

Tasks returns all registered task names.

c := core.New()
names := c.Tasks()
core.Println(core.Join(", ", names...))
Example

ExampleCore_Tasks lists task names through `Core.Tasks` for an agent dispatch workflow. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

c := New()
c.Task("deploy", Task{})
c.Task("test", Task{})
Println(c.Tasks())
Output:
[deploy test]

func (*Core) WithContext added in v0.10.4

func (c *Core) WithContext(ctx Context) *Core

WithContext returns a shallow clone of c whose lifecycle context is derived from ctx — for request-scoped context derivation (auth substrate etc.). The derived Core shares services/data/config (every heavy subsystem) with the parent by pointer; only the context, its cancel, and the per-Core lifecycle bookkeeping (waitGroup / shutdown flag / task counter) are fresh.

Cancellation is one-directional: the derived Core's cancel does NOT cancel the parent, but a parent shutdown propagates DOWN to the derived context when ctx chains from the parent (the usual case — pass core.WithValue(c.Context(), …)). The clone re-wraps ctx in a fresh WithCancel so callers that retain the parent stay unaffected.

type userKey struct{}
rc := c.WithContext(core.WithValue(c.Context(), userKey{}, user))
id := rc.Context().Value(userKey{})  // round-trips on the clone
Example

ExampleCore_WithContext derives a Core bound to a context through `Core.WithContext`.

Println(New().WithContext(Background()) != nil)
Output:
true

type CoreOption

type CoreOption func(*Core) Result

CoreOption is a functional option applied during Core construction. Returns Result — if !OK, New() stops and returns the error.

core.New(
    core.WithService(agentic.Register),
    core.WithService(monitor.Register),
    core.WithServiceLock(),
)
Example

ExampleCoreOption declares a Core option function through `CoreOption` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

var opt CoreOption = WithOption("name", "ops")
c := New(opt)
Println(c.App().Name)
Output:
ops

func WithBundle added in v0.12.0

func WithBundle(prefix string, other *Core) CoreOption

WithBundle mounts another Core's capability surface under a dotted prefix — sealed toolkits composing into applications. The bundle's actions become "<prefix>.<name>" (delegated: the bundle's own entitlements and metering fire first, then the host gates the prefixed name — double-gated enclave semantics). Its data mounts and drive handles become "<prefix>.<name>". Collisions fail the option loudly. Mount before WithServiceLock so the seal freezes the composed surface.

var Widgets = core.MustNew(core.WithService(widgets.Register), core.WithServiceLock())

c := core.New(
    core.WithBundle("widgets", Widgets),
    core.WithServiceLock(),
)
c.Action("widgets.render").Run(ctx, opts)
Example

ExampleWithBundle composes a sealed toolkit into a host under a prefix — the bundle's own gates still apply, then the host's.

bundle := New()
bundle.Action("render", func(Context, Options) Result { return Ok("rendered") })

host := New(WithBundle("widgets", bundle))
r := host.Action("widgets.render").Run(Background(), NewOptions())
Println(r.String())
Output:
rendered

func WithCli added in v0.11.0

func WithCli() CoreOption

WithCli registers the built-in CLI command framework as service "cli". core.New no longer auto-registers it — opt in here for a package's basic compile-and-run binary, or bring an intentional CLI (dappco.re/go/cli).

core.New(core.WithCli())
Example

ExampleWithServiceLock_contract documents the locking contract through `WithServiceLock` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks. ExampleWithCli enables the CLI subsystem at construction through `WithCli`.

c := New(WithCli())
Println(c.Cli() != nil)
Output:
true

func WithConfigFile added in v0.12.0

func WithConfigFile(path string) CoreOption

WithConfigFile loads a JSON config file into c.Config() during construction. A missing or malformed file fails the option — MustNew panics, New logs and continues. For optional files call c.Config().Load at runtime instead.

core.New(core.WithConfigFile("/etc/myapp/config.json"))
Example

ExampleWithConfigFile loads config at construction — a missing file fails the option, so MustNew bundles fail loudly at import.

c := New(WithConfigFile("/etc/myapp/config.json"))
Println(c.Config() != nil)
Output:
true

func WithCrashFile added in v0.12.0

func WithCrashFile(path string) CoreOption

WithCrashFile sets the crash-report file for panic recovery — the exported seam for ErrorPanic's report sink. Recover appends reports there; Reports reads them back.

core.New(core.WithCrashFile("/var/log/myapp/crash.json"))
Example

ExampleWithCrashFile wires the crash-report sink at construction — Recover appends reports there, Reports reads them back.

c := New(WithCrashFile("/var/log/myapp/crash.json"))
Println(c.Error() != nil)
Output:
true

func WithEnvConfig added in v0.12.0

func WithEnvConfig(prefix string) CoreOption

WithEnvConfig imports prefixed environment variables into c.Config() during construction (MYAPP_DATABASE_HOST → "database.host").

core.New(core.WithEnvConfig("MYAPP_"))
Example

ExampleWithEnvConfig binds prefixed environment into the store.

c := New(WithEnvConfig("MYAPP_"))
Println(c.Config() != nil)
Output:
true

func WithName

func WithName(name string, factory func(*Core) Result) CoreOption

WithName registers a service with an explicit name (no reflect discovery).

core.WithName("ws", func(c *Core) Result {
    return Result{Value: hub, OK: true}
})
Example

ExampleWithName applies a service name through `WithName` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

c := New(WithName("lifecycle", func(_ *Core) Result {
	return Result{Value: &contractLifecycleService{}, OK: true}
}))
Println(c.Service("lifecycle").OK)
Output:
true

func WithOption

func WithOption(key string, value any) CoreOption

WithOption is a convenience for setting a single key-value option.

core.New(
    core.WithOption("name", "myapp"),
    core.WithOption("port", 8080),
)
Example

ExampleWithOption applies one option through `WithOption` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

c := New(WithOption("name", "ops"))
Println(c.Options().String("name"))
Println(c.App().Name)
Output:
ops
ops

func WithOptions

func WithOptions(opts Options) CoreOption

WithOptions applies key-value configuration to Core.

core.WithOptions(core.NewOptions(core.Option{Key: "name", Value: "myapp"}))
Example

ExampleWithOptions applies options through `WithOptions` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

c := New(WithOptions(NewOptions(Option{Key: "debug", Value: true})))
Println(c.Options().Bool("debug"))
Output:
true

func WithReloadOnSIGHUP added in v0.12.0

func WithReloadOnSIGHUP() CoreOption

WithReloadOnSIGHUP completes the daemon loop: when a signal service (e.g. go-process) broadcasts signal.received with SIGHUP, run ServiceReload. Fails when "signal.received" already has a handler — call ServiceReload from that handler instead (the signal contract is single-handler by design; see signal.go).

core.New(core.WithService(process.Register), core.WithReloadOnSIGHUP())
Example

ExampleWithReloadOnSIGHUP completes the daemon loop: SIGHUP from the signal service triggers ServiceReload.

c := New(WithReloadOnSIGHUP())
Println(c.Action("signal.received").Exists())
Output:
true

func WithService

func WithService(factory func(*Core) Result) CoreOption

WithService registers a service via its factory function. If the factory returns a non-nil Value, WithService auto-discovers the service name from the factory's package path (last path segment, lowercase, with any "_test" suffix stripped) and calls RegisterService on the instance. IPC handler auto-registration is handled by RegisterService.

If the factory returns nil Value (it registered itself), WithService returns success without a second registration.

core.WithService(agentic.Register)
core.WithService(display.Register(nil))
Example

ExampleWithService injects a service through `WithService` for service registration. Services register by name and can be recovered with typed helpers.

started := false
c := New(
	WithService(func(c *Core) Result {
		return c.Service("worker", Service{
			OnStart: func() Result { started = true; return Result{OK: true} },
		})
	}),
)
c.ServiceStartup(Background(), nil)
Println(started)
c.ServiceShutdown(Background())
Output:
true
Example (Factory)

ExampleWithService_factory wires a service factory through `WithService` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

c := New(WithService(func(c *Core) Result {
	return c.Service("worker", Service{OnStart: func() Result { return Result{OK: true} }})
}))
Println(c.Service("worker").OK)
Output:
true

func WithServiceLock

func WithServiceLock() CoreOption

WithServiceLock prevents further service registration after construction.

core.New(
    core.WithService(auth.Register),
    core.WithServiceLock(),
)
Example

ExampleWithServiceLock injects service locking through `WithServiceLock` for service registration. Services register by name and can be recovered with typed helpers.

c := New(
	WithService(func(c *Core) Result {
		return c.Service("allowed", Service{})
	}),
	WithServiceLock(),
)

// Can't register after lock
r := c.Service("blocked", Service{})
Println(r.OK)
Output:
false
Example (Contract)
c := New(WithServiceLock())
r := c.Service("late", Service{})
Println(r.OK)
Output:
false

type CrashReport

type CrashReport struct {
	Timestamp Time              `json:"timestamp"`
	Error     string            `json:"error"`
	Stack     string            `json:"stack"`
	System    CrashSystem       `json:"system,omitempty"`
	Meta      map[string]string `json:"meta,omitempty"`
}

CrashReport represents a single crash event.

report := core.CrashReport{Error: "panic: agent failed", Meta: map[string]string{"service": "agent"}}
core.Println(report.Error)
Example

ExampleCrashReport builds a crash report through `CrashReport` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

report := CrashReport{Error: "panic: boom", System: CrashSystem{OperatingSystem: "darwin"}}
Println(report.Error)
Println(report.System.OperatingSystem)
Output:
panic: boom
darwin

type CrashSystem

type CrashSystem struct {
	OperatingSystem string `json:"operatingsystem"`
	Architecture    string `json:"architecture"`
	Version         string `json:"go_version"`
}

CrashSystem holds system information at crash time.

system := core.CrashSystem{OperatingSystem: "linux", Architecture: "amd64", Version: "go1.26"}
core.Println(system.OperatingSystem)
Example

ExampleCrashSystem collects crash reports through `CrashSystem` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

system := CrashSystem{OperatingSystem: "darwin", Architecture: "arm64", Version: "go1.26"}
Println(system.OperatingSystem)
Println(system.Architecture)
Output:
darwin
arm64

type DB

type DB = sql.DB

DB is a connection-pooled handle to a SQL database.

r := core.SQLOpen("sqlite3", "file:./data/homelab.db")
if !r.OK { return r }
db := r.Value.(*core.DB)
defer db.Close()

type Data

type Data struct {
	*Registry[*Embed]
	// contains filtered or unexported fields
}

Data manages mounted embedded filesystems from core packages. Embeds Registry[*Embed] for thread-safe named storage.

c := core.New()
r := c.Data().ReadString("agent/persona/developer.md")
if r.OK { core.Println(r.Value.(string)) }

A view bound to one mount reads relative to it (see On / c.Data(name)):

r = c.Data("agent").ReadString("persona/developer.md")

func (*Data) Exists added in v0.12.0

func (d *Data) Exists() bool

Exists reports whether the bound mount is registered — the capability check for named content.

if c.Data("brain").Exists() { ... }
Example

ExampleData_Exists is the capability check for named mounts.

c := New()
Println(c.Data("ghost").Exists())
Output:
false

func (*Data) Extract

func (d *Data) Extract(path, targetDir string, templateData any) Result

Extract copies a template directory to targetDir.

r := c.Data().Extract("agent/workspace/default", "/tmp/ws", templateData)
Example

ExampleData_Extract extracts embedded files through `Data.Extract` for embedded Lethean data. Mounted data can be read, listed, and extracted through Result-returning helpers.

fs := (&Fs{}).New("/")
source := MustCast[string](fs.TempDir("core-data-source"))
target := MustCast[string](fs.TempDir("core-data-target"))
defer fs.DeleteAll(source)
defer fs.DeleteAll(target)

fs.Write(Path(source, "templates", "README.md.tmpl"), "hello {{.Name}}")

c := New()
c.Data().New(NewOptions(
	Option{Key: "name", Value: "starter"},
	Option{Key: "source", Value: DirFS(source)},
	Option{Key: "path", Value: "templates"},
))

r := c.Data().Extract("starter/.", target, map[string]string{"Name": "codex"})
Println(r.OK)
Println(fs.Read(Path(target, "README.md")).Value)
Output:
true
hello codex

func (*Data) List

func (d *Data) List(path string) Result

List returns directory entries at a path.

r := c.Data().List("agent/persona/code")
if r.OK { entries := r.Value.([]core.FsDirEntry) }
Example

ExampleData_List lists entries through `Data.List` for embedded Lethean data. Mounted data can be read, listed, and extracted through Result-returning helpers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-data-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "prompts", "hello.txt"), "hello")

c := New()
c.Data().New(NewOptions(
	Option{Key: "name", Value: "agent"},
	Option{Key: "source", Value: DirFS(dir)},
	Option{Key: "path", Value: "prompts"},
))

r := c.Data().List("agent/.")
Println(r.OK)
Output:
true

func (*Data) ListNames

func (d *Data) ListNames(path string) Result

ListNames returns filenames (without extensions) at a path.

r := c.Data().ListNames("agent/flow")
if r.OK { names := r.Value.([]string) }
Example

ExampleData_ListNames lists entry names through `Data.ListNames` for embedded Lethean data. Mounted data can be read, listed, and extracted through Result-returning helpers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-data-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "prompts", "hello.txt"), "hello")

c := New()
c.Data().New(NewOptions(
	Option{Key: "name", Value: "agent"},
	Option{Key: "source", Value: DirFS(dir)},
	Option{Key: "path", Value: "prompts"},
))

r := c.Data().ListNames("agent/.")
Println(r.Value)
Output:
[hello]

func (*Data) MountDir added in v0.12.0

func (d *Data) MountDir(name, dir string) Result

MountDir mounts a real directory on disk as a Data mount under name, so dev-mode assets read straight from disk serve identically to a prod embed.FS mounted through New — both end up behind the same c.Data(name) accessor.

r := c.Data().MountDir("brain", "/srv/agent/prompts")
if r.OK { content := c.Data("brain").ReadString("coding.md") }
Example

ExampleData_MountDir mounts a real directory on disk as a Data mount, so dev-mode assets read straight from disk serve identically to embedded prod assets mounted through New.

c := New()
r := c.Data().MountDir("docs", "tests/data")
Println(r.OK)

read := c.Data("docs").ReadString("test.txt")
Println(read.Value)
Output:
true
hello from testdata

func (*Data) Mounts

func (d *Data) Mounts() []string

Mounts returns the names of all mounted content in registration order.

names := c.Data().Mounts()
Example

ExampleData_Mounts lists mounted data sources through `Data.Mounts` for embedded Lethean data. Mounted data can be read, listed, and extracted through Result-returning helpers.

c := New()
Println(c.Data().Mounts())
Output:
[]

func (*Data) New

func (d *Data) New(opts Options) Result

New registers an embedded filesystem under a named prefix.

c.Data().New(core.NewOptions(
    core.Option{Key: "name", Value: "brain"},
    core.Option{Key: "source", Value: brainFS},
    core.Option{Key: "path", Value: "prompts"},
))
Example

ExampleData_New mounts a prompts directory as named embedded Lethean data. Mounted data can be read, listed, and extracted through Result-returning helpers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-data-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "prompts", "hello.txt"), "hello")

c := New()
r := c.Data().New(NewOptions(
	Option{Key: "name", Value: "agent"},
	Option{Key: "source", Value: DirFS(dir)},
	Option{Key: "path", Value: "prompts"},
))

Println(r.OK)
Println(c.Data().Mounts())
Output:
true
[agent]

func (*Data) On added in v0.12.0

func (d *Data) On(name string) *Data

On returns a view of Data bound to a named mount. Paths on the view are relative to that mount — no name prefix. The view shares the mount registry with the parent; only the binding is new. Sugar reached via c.Data(name).

brain := c.Data().On("brain")
r := brain.ReadString("coding.md")   // reads brain/coding.md
Example

ExampleData_On binds a mount so paths become relative to it — the named-resource accessor for embedded content.

c := New()
c.Data().New(NewOptions(
	Option{Key: "name", Value: "brain"},
	Option{Key: "source", Value: EmbeddedTestFS},
	Option{Key: "path", Value: "tests/data"},
))
r := c.Data("brain").ReadString("test.txt")
Println(r.OK)
Output:
true

func (*Data) ReadFile

func (d *Data) ReadFile(path string) Result

ReadFile reads a file by full path.

r := c.Data().ReadFile("brain/prompts/coding.md")
if r.OK { data := r.Value.([]byte) }
Example

ExampleData_ReadFile reads a named file through `Data.ReadFile` for embedded Lethean data. Mounted data can be read, listed, and extracted through Result-returning helpers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-data-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "prompts", "hello.txt"), "hello")

c := New()
c.Data().New(NewOptions(
	Option{Key: "name", Value: "agent"},
	Option{Key: "source", Value: DirFS(dir)},
	Option{Key: "path", Value: "prompts"},
))

r := c.Data().ReadFile("agent/hello.txt")
Println(string(r.Value.([]byte)))
Output:
hello

func (*Data) ReadString

func (d *Data) ReadString(path string) Result

ReadString reads a file as a string.

r := c.Data().ReadString("agent/flow/deploy/to/homelab.yaml")
if r.OK { content := r.Value.(string) }
Example

ExampleData_ReadString reads text content through `Data.ReadString` for embedded Lethean data. Mounted data can be read, listed, and extracted through Result-returning helpers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-data-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "prompts", "hello.txt"), "hello")

c := New()
c.Data().New(NewOptions(
	Option{Key: "name", Value: "agent"},
	Option{Key: "source", Value: DirFS(dir)},
	Option{Key: "path", Value: "prompts"},
))

r := c.Data().ReadString("agent/hello.txt")
Println(r.Value)
Output:
hello

type Dialer

type Dialer = net.Dialer

Dialer holds connection-establishment options.

dialer := &core.Dialer{Timeout: 5 * core.Second}
conn, err := dialer.Dial("tcp", "127.0.0.1:8080")
if err == nil { defer conn.Close() }

type Drive

type Drive struct {
	*Registry[*DriveHandle]
	// contains filtered or unexported fields
}

Drive manages named transport handles. Embeds Registry[*DriveHandle].

c := core.New()
c.Drive().New(core.NewOptions(
    core.Option{Key: "name", Value: "homelab"},
    core.Option{Key: "transport", Value: "ssh://agent@10.69.69.165"},
))

A view bound to one handle answers for it directly (see On / c.Drive(name)):

if c.Drive("homelab").Exists() { transport := c.Drive("homelab").Transport() }
Example

ExampleDrive reaches drive registration through `Drive` for remote drive metadata. Drive handles carry names and transports before remote API calls use them.

d := &Drive{Registry: NewRegistry[*DriveHandle]()}
d.New(NewOptions(Option{Key: "name", Value: "forge"}))
Println(d.Names())
Output:
[forge]

func (*Drive) Exists added in v0.12.0

func (d *Drive) Exists() bool

Exists reports whether the bound handle is registered — the capability check for named transports.

if c.Drive("forge").Exists() { ... }
Example

ExampleDrive_Exists is the capability check for named transports.

Println(New().Drive("ghost").Exists())
Output:
false

func (*Drive) Handle added in v0.12.0

func (d *Drive) Handle() Result

Handle returns the bound transport handle. Fails with operation "drive.Handle" when the view has no binding or the handle is missing.

r := c.Drive("forge").Handle()
if r.OK { handle := r.Value.(*core.DriveHandle) }
Example

ExampleDrive_Handle retrieves the bound handle as a Result.

c := New()
c.Drive().New(NewOptions(
	Option{Key: "name", Value: "forge"},
	Option{Key: "transport", Value: "https://api.lthn.ai"},
))
r := c.Drive("forge").Handle()
Println(r.OK)
Output:
true

func (*Drive) New

func (d *Drive) New(opts Options) Result

New registers a transport handle.

c.Drive().New(core.NewOptions(
    core.Option{Key: "name", Value: "api"},
    core.Option{Key: "transport", Value: "https://api.lthn.ai"},
))
Example

ExampleDrive_New registers a remote drive handle from name and transport options. Drive handles carry names and transports before remote API calls use them.

c := New()
c.Drive().New(NewOptions(
	Option{Key: "name", Value: "forge"},
	Option{Key: "transport", Value: "https://forge.lthn.ai"},
))

Println(c.Drive().Has("forge"))
Println(c.Drive().Names())
Output:
true
[forge]

func (*Drive) On added in v0.12.0

func (d *Drive) On(name string) *Drive

On returns a view of Drive bound to a named handle. The view shares the handle registry with the parent; only the binding is new. Sugar reached via c.Drive(name).

forge := c.Drive().On("forge")
if forge.Exists() { ... }
Example

ExampleDrive_On binds a named transport handle.

c := New()
c.Drive().New(NewOptions(
	Option{Key: "name", Value: "homelab"},
	Option{Key: "transport", Value: "ssh://agent@10.69.69.165"},
))
Println(c.Drive("homelab").Exists())
Output:
true

func (*Drive) Transport added in v0.12.0

func (d *Drive) Transport() string

Transport returns the bound handle's transport URL, "" when the binding is absent — the Options-getter contract for named transports.

url := c.Drive("homelab").Transport()  // "ssh://agent@10.69.69.165"
Example

ExampleDrive_Transport reads the bound transport URL, "" when absent.

c := New()
c.Drive().New(NewOptions(
	Option{Key: "name", Value: "homelab"},
	Option{Key: "transport", Value: "ssh://agent@10.69.69.165"},
))
Println(c.Drive("homelab").Transport())
Output:
ssh://agent@10.69.69.165

type DriveHandle

type DriveHandle struct {
	Name      string
	Transport string
	Options   Options
}

DriveHandle holds a named transport resource.

handle := &core.DriveHandle{Name: "homelab", Transport: "ssh://agent@10.69.69.165"}
core.Println(handle.Transport)
Example

ExampleDriveHandle defines drive handle metadata through `DriveHandle` for remote drive metadata. Drive handles carry names and transports before remote API calls use them.

handle := DriveHandle{Name: "forge", Transport: "https://forge.example"}
Println(handle.Name)
Println(handle.Transport)
Output:
forge
https://forge.example

type Duration

type Duration = time.Duration

Duration is a time span — alias of time.Duration so consumers can pass timeouts and intervals without importing the time package.

timeout := 5 * core.Second
ctx, cancel := core.WithTimeout(core.Background(), timeout)

type Embed

type Embed struct {
	// contains filtered or unexported fields
}

Embed wraps an FS with a basedir for scoped access. All paths are relative to basedir.

r := core.Mount(core.DirFS("testdata"), "prompts")
if !r.OK { return r }
emb := r.Value.(*core.Embed)
core.Println(emb.BaseDirectory())

func (*Embed) BaseDirectory

func (s *Embed) BaseDirectory() string

BaseDirectory returns the base directory this Embed is anchored at.

r := core.Mount(core.DirFS("testdata"), "prompts")
if !r.OK { return r }
emb := r.Value.(*core.Embed)
base := emb.BaseDirectory()
core.Println(base)
Example

ExampleEmbed_BaseDirectory reports the embedded base directory through `Embed.BaseDirectory` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-embed-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "docs", "hello.txt"), "hello")

emb := Mount(DirFS(dir), "docs").Value.(*Embed)
Println(emb.BaseDirectory())
Output:
docs

func (*Embed) EmbedFS

func (s *Embed) EmbedFS() embed.FS

EmbedFS returns the underlying embed.FS if mounted from one. Returns zero embed.FS if mounted from a non-embed source.

var assets embed.FS
r := core.MountEmbed(assets, "locales")
if r.OK {
    emb := r.Value.(*core.Embed)
    _ = emb.EmbedFS()
}
Example

ExampleEmbed_EmbedFS exposes the underlying embed filesystem through `Embed.EmbedFS` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

emb := &Embed{}
_ = emb.EmbedFS()

func (*Embed) FS

func (s *Embed) FS() FS

FS returns the underlying FS.

r := core.Mount(core.DirFS("testdata"), "prompts")
if !r.OK { return r }
emb := r.Value.(*core.Embed)
fsys := emb.FS()
_ = fsys
Example

ExampleEmbed_FS exposes a filesystem through `Embed.FS` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-embed-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "docs", "hello.txt"), "hello")

emb := Mount(DirFS(dir), "docs").Value.(*Embed)
Println(emb.FS() != nil)
Output:
true

func (*Embed) Open

func (s *Embed) Open(name string) Result

Open opens the named file for reading.

r := emb.Open("test.txt")
if r.OK { file := r.Value.(core.FsFile); _ = file }
Example

ExampleEmbed_Open opens a mounted asset for streaming reads from an embedded package. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-embed-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "docs", "hello.txt"), "hello")

emb := Mount(DirFS(dir), "docs").Value.(*Embed)
r := emb.Open("hello.txt")
Println(r.OK)
CloseStream(r.Value)
Output:
true

func (*Embed) ReadDir

func (s *Embed) ReadDir(name string) Result

ReadDir reads the named directory.

r := core.Mount(core.DirFS("testdata"), "prompts")
if !r.OK { return r }
emb := r.Value.(*core.Embed)
entries := emb.ReadDir(".")
if !entries.OK { return entries }
Example

ExampleEmbed_ReadDir lists directory entries through `Embed.ReadDir` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-embed-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "docs", "hello.txt"), "hello")

emb := Mount(DirFS(dir), "docs").Value.(*Embed)
r := emb.ReadDir(".")
Println(r.OK)
Output:
true

func (*Embed) ReadFile

func (s *Embed) ReadFile(name string) Result

ReadFile reads the named file.

r := emb.ReadFile("test.txt")
if r.OK { data := r.Value.([]byte) }
Example

ExampleEmbed_ReadFile reads a named file through `Embed.ReadFile` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-embed-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "docs", "hello.txt"), "hello")

emb := Mount(DirFS(dir), "docs").Value.(*Embed)
r := emb.ReadFile("hello.txt")
Println(string(r.Value.([]byte)))
Output:
hello

func (*Embed) ReadString

func (s *Embed) ReadString(name string) Result

ReadString reads the named file as a string.

r := emb.ReadString("test.txt")
if r.OK { content := r.Value.(string) }
Example

ExampleEmbed_ReadString reads text content through `Embed.ReadString` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-embed-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "docs", "hello.txt"), "hello")

emb := Mount(DirFS(dir), "docs").Value.(*Embed)
Println(emb.ReadString("hello.txt").Value)
Output:
hello

func (*Embed) Sub

func (s *Embed) Sub(subDir string) Result

Sub returns a new Embed anchored at a subdirectory within this mount.

r := emb.Sub("testdata")
if r.OK { sub := r.Value.(*Embed) }
Example

ExampleEmbed_Sub opens a subdirectory through `Embed.Sub` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-embed-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "docs", "nested", "hello.txt"), "hello")

emb := Mount(DirFS(dir), "docs").Value.(*Embed)
sub := emb.Sub("nested").Value.(*Embed)
Println(sub.ReadString("hello.txt").Value)
Output:
hello

type EmbedFS

type EmbedFS = embed.FS

EmbedFS is embed.FS re-exported for tests and consumers using go:embed.

var assets core.EmbedFS
_ = assets

type Entitlement

type Entitlement struct {
	Allowed   bool   // permission granted
	Unlimited bool   // no cap (agency tier, admin, trusted conclave)
	Limit     int    // total allowed (0 = boolean gate)
	Used      int    // current consumption
	Remaining int    // Limit - Used
	Reason    string // denial reason — for UI and audit logging
}

Entitlement is the result of a permission check. Carries context for both boolean gates (Allowed) and usage limits (Limit/Used/Remaining).

e := c.Entitled("social.accounts", 3)
e.Allowed     // true
e.Limit       // 5
e.Used        // 2
e.Remaining   // 3
e.NearLimit(0.8) // false

func (Entitlement) NearLimit

func (e Entitlement) NearLimit(threshold float64) bool

NearLimit returns true if usage exceeds the threshold percentage.

if e.NearLimit(0.8) { showUpgradePrompt() }
Example
e := Entitlement{Allowed: true, Limit: 100, Used: 85, Remaining: 15}
Println(e.NearLimit(0.8))
Println(e.UsagePercent())
Output:
true
85
Example (Threshold)

ExampleEntitlement_NearLimit_threshold checks the near-limit threshold through `Entitlement.NearLimit` for usage-gated agent features. Usage checks separate policy decisions from the action body.

e := Entitlement{Limit: 100, Used: 90}
Println(e.NearLimit(0.8))
Output:
true

func (Entitlement) UsagePercent

func (e Entitlement) UsagePercent() float64

UsagePercent returns current usage as a percentage of the limit.

pct := e.UsagePercent() // 75.0
Example

ExampleEntitlement_UsagePercent calculates usage percentage through `Entitlement.UsagePercent` for usage-gated agent features. Usage checks separate policy decisions from the action body.

e := Entitlement{Limit: 100, Used: 75}
Println(e.UsagePercent())
Output:
75

type EntitlementChecker

type EntitlementChecker func(action string, quantity int, ctx Context) Entitlement

EntitlementChecker answers "can [subject] do [action] with [quantity]?" Subject comes from context (workspace, entity, user — consumer's concern).

checker := func(action string, quantity int, ctx Context) core.Entitlement {
    return core.Entitlement{Allowed: action == "process.run", Limit: 10, Used: quantity}
}
core.New().SetEntitlementChecker(core.EntitlementChecker(checker))
Example

ExampleEntitlementChecker declares an entitlement checker through `EntitlementChecker` for usage-gated agent features. Usage checks separate policy decisions from the action body.

var checker EntitlementChecker = func(action string, quantity int, _ Context) Entitlement {
	return Entitlement{Allowed: action == "deploy" && quantity <= 1}
}
Println(checker("deploy", 1, Background()).Allowed)
Output:
true

type Err

type Err struct {
	Operation string // Operation being performed (e.g., "user.Save")
	Message   string // Human-readable message
	Cause     error  // Underlying error (optional)
	Code      string // Error code (optional, e.g., "VALIDATION_FAILED")
}

Err represents a structured error with operational context. It implements the error interface and supports unwrapping.

err := &core.Err{Operation: "config.Load", Message: "missing config.host", Code: "CONFIG_MISSING"}
core.Println(err.Error())

func (*Err) Error

func (e *Err) Error() string

Error implements the error interface.

err := &core.Err{Operation: "agent.Run", Message: "failed"}
msg := err.Error()
core.Println(msg)
Example

ExampleErr_Error writes or renders an error through `Err.Error` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := &Err{Operation: "cache.Get", Message: "missing", Code: "NOT_FOUND"}
Println(err.Error())
Output:
cache.Get: missing [NOT_FOUND]

func (*Err) Unwrap

func (e *Err) Unwrap() error

Unwrap returns the underlying error for use with errors.Is and errors.As.

cause := core.NewError("connection refused")
err := &core.Err{Operation: "agent.Ping", Message: "homelab unreachable", Cause: cause}
root := err.Unwrap()
core.Println(root)
Example

ExampleErr_Unwrap unwraps an error through `Err.Unwrap` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

cause := NewError("root")
err := &Err{Operation: "cache.Get", Message: "missing", Cause: cause}
Println(err.Unwrap() == cause)
Output:
true

type ErrorLog

type ErrorLog struct {
	// contains filtered or unexported fields
}

ErrorLog combines error creation with logging. Primary action: return an error. Secondary: log it.

c := core.New()
r := c.LogError(core.NewError("offline"), "agent.Ping", "homelab unreachable")
if !r.OK { return r }

func (*ErrorLog) Error

func (el *ErrorLog) Error(err error, op, msg string) Result

Error logs at Error level and returns a Result with the wrapped error.

err := &core.Err{Operation: "agent.Run", Message: "failed"}
msg := err.Error()
core.Println(msg)
Example

ExampleErrorLog_Error writes or renders an error through `ErrorLog.Error` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

var log ErrorLog
Println(log.Error(nil, "example", "ok").OK)
Output:
true

func (*ErrorLog) Must

func (el *ErrorLog) Must(err error, op, msg string)

Must logs and panics if err is not nil.

c := core.New()
c.Log().Must(nil, "agent.Start", "startup failed")
Example

ExampleErrorLog_Must unwraps a successful Result through `ErrorLog.Must` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

var log ErrorLog
log.Must(nil, "example", "ok")
Println("ok")
Output:
ok

func (*ErrorLog) Warn

func (el *ErrorLog) Warn(err error, op, msg string) Result

Warn logs at Warn level and returns a Result with the wrapped error.

c := core.New()
r := c.Log().Warn(core.NewError("missing config.host"), "config.Load", "using default host")
if !r.OK { return r }
Example

ExampleErrorLog_Warn writes a warning event through `ErrorLog.Warn` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

var log ErrorLog
Println(log.Warn(nil, "example", "ok").OK)
Output:
true

type ErrorPanic

type ErrorPanic struct {
	// contains filtered or unexported fields
}

ErrorPanic manages panic recovery and crash reporting.

c := core.New()
defer c.Error().Recover()

func (*ErrorPanic) Recover

func (h *ErrorPanic) Recover()

Recover captures a panic and creates a crash report. Use as: defer c.Error().Recover()

c := core.New()
defer c.Error().Recover()
Example

ExampleErrorPanic_Recover documents panic recovery when no panic is active. Operations, codes, roots, and crash reports remain inspectable through core errors.

h := &ErrorPanic{}
defer h.Recover()

func (*ErrorPanic) Reports

func (h *ErrorPanic) Reports(n int) Result

Reports returns the last n crash reports from the file.

c := core.New()
r := c.Error().Reports(5)
if r.OK { reports := r.Value.([]core.CrashReport); _ = reports }
Example

ExampleErrorPanic_Reports lists captured reports through `ErrorPanic.Reports` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

h := &ErrorPanic{}
Println(h.Reports(1).OK)
Output:
false

func (*ErrorPanic) SafeGo

func (h *ErrorPanic) SafeGo(fn func())

SafeGo runs a function in a goroutine with panic recovery.

c := core.New()
c.Error().SafeGo(func() {
    core.Info("agent worker started")
})
Example

ExampleErrorPanic_SafeGo launches protected work that reports panics instead of crashing the caller. Operations, codes, roots, and crash reports remain inspectable through core errors.

h := &ErrorPanic{}
h.SafeGo(func() { /* no-op goroutine body demonstrates safe launch */ })

type ErrorSink

type ErrorSink interface {
	Error(msg string, keyvals ...any)
	Warn(msg string, keyvals ...any)
}

ErrorSink is the shared interface for error reporting. Implemented by ErrorLog (structured logging) and ErrorPanic (panic recovery).

var sink core.ErrorSink = core.Default()
sink.Warn("homelab degraded", "service", "agent")
Example

ExampleErrorSink declares an error sink through `ErrorSink` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

var sink ErrorSink = NewLog(LogOptions{Output: NewBuffer()})
sink.Warn("example")

type ExitOptions

type ExitOptions struct {
	// Code is the process exit code passed to core.Exit.
	Code int
	// Timeout bounds how long ServiceShutdown may run before the process
	// terminates anyway. Zero means wait forever (legacy behaviour).
	Timeout Duration
}

ExitOptions configures graceful exit behaviour.

c.ExitWith(core.ExitOptions{Code: 1, Timeout: 5 * core.Second})

type ExtractOptions

type ExtractOptions struct {
	// TemplateFilters identifies template files by substring match.
	// Default: [".tmpl"]
	TemplateFilters []string

	// IgnoreFiles is a set of filenames to skip during extraction.
	IgnoreFiles map[string]struct{}

	// RenameFiles maps original filenames to new names.
	RenameFiles map[string]string
}

ExtractOptions configures template extraction.

opts := core.ExtractOptions{
    TemplateFilters: []string{".tmpl"},
    RenameFiles: map[string]string{"README.tmpl": "README.md"},
}
_ = opts
Example

ExampleExtractOptions declares extraction options through `ExtractOptions` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

opts := ExtractOptions{
	TemplateFilters: []string{".gotmpl"},
	RenameFiles:     map[string]string{"README.md": "WELCOME.md"},
}
Println(opts.TemplateFilters)
Println(opts.RenameFiles["README.md"])
Output:
[.gotmpl]
WELCOME.md

type F

type F = testing.F

F is the canonical Go fuzz harness, exported as core.F so fuzz files stay on the single-import pattern. Used in FuzzXxx(f *F) signatures.

func FuzzURLParse(f *F) {
    f.Add("https://example.com/path?q=1")
    f.Fuzz(func(t *T, raw string) { ... })
}

type FS

type FS = fs.FS

FS is a generic filesystem accepted by Mount and Extract.

fsys := core.DirFS("templates")
r := core.Mount(fsys, ".")

func DirFS

func DirFS(dir string) FS

DirFS returns an FS rooted at the given directory path.

fsys := core.DirFS("/path/to/templates")
Example

ExampleDirFS creates a directory-backed filesystem through `DirFS` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
f.Write(Path(dir, "hello.txt"), "hello")

emb := Mount(DirFS(dir), ".").Value.(*Embed)
Println(emb.ReadString("hello.txt").Value)
Output:
hello
Example (ReadFile)

ExampleDirFS_readFile roots an FS at a directory through `DirFS`, then reads a known file back through it via ReadFSFile (fs_example_test.go's `ExampleDirFS` already covers the Mount/Embed route, so this variant sticks to the plain fs.FS read path).

dir := TempDir()
path := PathJoin(dir, "core-example-dirfs.txt")
WriteFile(path, []byte("dirfs"), 0o644)
defer Remove(path)

fsys := DirFS(dir)
r := ReadFSFile(fsys, "core-example-dirfs.txt")
Println(string(r.Value.([]byte)))
Output:
dirfs

type Feature added in v0.11.0

type Feature struct {
	// contains filtered or unexported fields
}

Feature is a keyed handle to a single feature flag, bound to a Config.

f := c.Feature("dark-mode")
f.Enable()
if f.Enabled() { core.Println("on") }

func (Feature) Disable added in v0.11.0

func (f Feature) Disable()

Disable deactivates the feature.

c.Feature("dark-mode").Disable()
Example

ExampleFeature_Disable deactivates a feature through `Feature.Disable`.

c := New()
f := c.Feature("beta")
f.Enable()
f.Disable()
Println(f.Enabled())
Output:
false

func (Feature) Enable added in v0.11.0

func (f Feature) Enable()

Enable activates the feature.

c.Feature("dark-mode").Enable()
Example

ExampleFeature_Enable activates a feature through `Feature.Enable`.

c := New()
c.Feature("beta").Enable()
Println(c.Feature("beta").Enabled())
Output:
true

func (Feature) Enabled added in v0.11.0

func (f Feature) Enabled() bool

Enabled reports whether the feature is active.

if c.Feature("dark-mode").Enabled() { core.Println("on") }
Example

ExampleFeature_Enabled reports whether a feature is active through `Feature.Enabled`.

Println(New().Feature("unset").Enabled())
Output:
false

func (Feature) Name added in v0.11.0

func (f Feature) Name() string

Name returns the feature's name.

c.Feature("dark-mode").Name() // "dark-mode"
Example

ExampleFeature_Name returns the feature's name through `Feature.Name`.

Println(New().Feature("dark-mode").Name())
Output:
dark-mode

type FileMode

type FileMode = os.FileMode

FileMode is an alias for os.FileMode — file mode bits and permissions.

mode := core.FileMode(0o600)
core.Println(mode.Perm())
Example

ExampleFileMode uses file mode aliases through `FileMode` for process IO access. File modes and standard streams are exposed through core aliases.

var mode FileMode = 0644
Println((mode & ModePerm) == 0644)
Output:
true

type Flusher added in v0.10.0

type Flusher = http.Flusher

Flusher is the canonical HTTP flusher interface — used by handlers that stream responses (Server-Sent Events, chunked transfer) to push bytes to the client without buffering.

if f, ok := w.(core.Flusher); ok { f.Flush() }
Example

ExampleFlusher demonstrates type-asserting a ResponseWriter to Flusher for streaming responses. The handler pushes one chunk and flushes immediately — the canonical Server-Sent Events / chunked-transfer shape.

handler := HandlerFunc(func(w ResponseWriter, _ *Request) {
	WriteString(w, "tick")
	if f, ok := w.(Flusher); ok {
		f.Flush()
	}
})
srv := NewHTTPTestServer(handler)
defer srv.Close()

r := HTTPGet(srv.URL)
defer r.Value.(*Response).Body.Close()
body := ReadAll(r.Value.(*Response).Body)
Println(body.Value)
Output:
tick

type Fs

type Fs struct {
	// contains filtered or unexported fields
}

Fs is a sandboxed local filesystem backend.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.EnsureDir("logs")
if !r.OK { return r }

func (*Fs) Append

func (m *Fs) Append(p string) Result

Append opens the named file for appending, creating it if it doesn't exist.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.Append("logs/agent.log")
if !r.OK { return r }
defer r.Value.(core.WriteCloser).Close()
Example

ExampleFs_Append appends content through `Fs.Append` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
path := Path(dir, "hello.txt")
f.Write(path, "hello")

r := f.Append(path)
WriteAll(r.Value, " world")
Println(f.Read(path).Value)
Output:
hello world

func (*Fs) Create

func (m *Fs) Create(p string) Result

Create creates or truncates the named file.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.WriteStream("logs/agent.log")
if !r.OK { return r }
defer r.Value.(core.WriteCloser).Close()
Example

ExampleFs_Create creates a resource through `Fs.Create` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
path := Path(dir, "hello.txt")

r := f.Create(path)
WriteAll(r.Value, "hello")
Println(f.Read(path).Value)
Output:
hello

func (*Fs) Delete

func (m *Fs) Delete(p string) Result

Delete removes a file or empty directory.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.Delete("logs/old-agent.log")
if !r.OK { return r }
Example

ExampleFs_Delete deletes a value through `Fs.Delete` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
path := Path(dir, "hello.txt")
f.Write(path, "hello")
Println(f.Delete(path).OK)
Println(f.Exists(path).OK)
Output:
true
false

func (*Fs) DeleteAll

func (m *Fs) DeleteAll(p string) Result

DeleteAll removes a file or directory recursively.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.DeleteAll("tmp/session-42")
if !r.OK { return r }
Example

ExampleFs_DeleteAll deletes a tree through `Fs.DeleteAll` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
f.Write(Path(dir, "nested", "hello.txt"), "hello")
Println(f.DeleteAll(dir).OK)
Println(f.Exists(dir).OK)
Output:
true
false

func (*Fs) EnsureDir

func (m *Fs) EnsureDir(p string) Result

EnsureDir creates directory if it doesn't exist.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.EnsureDir("logs/agent")
if !r.OK { return r }
Example

ExampleFs_EnsureDir creates missing directories through `Fs.EnsureDir` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)

r := f.EnsureDir(Path(dir, "logs"))
Println(r.OK)
Println(f.IsDir(Path(dir, "logs")).OK)
Output:
true
true

func (*Fs) Exists

func (m *Fs) Exists(p string) Result

Exists reports whether path exists via Result.OK. A non-existent path is a valid answer (OK=false), not a swallowed error; a path-validation failure is returned as its own Result.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
if fsys.Exists("config/agent.json").OK { core.Println("config present") }
Example

ExampleFs_Exists checks whether a sandboxed path exists after writing a file. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
path := Path(dir, "hello.txt")
f.Write(path, "hello")
Println(f.Exists(path).OK)
Output:
true

func (*Fs) IsDir

func (m *Fs) IsDir(p string) Result

IsDir reports whether path is a directory via Result.OK. The false path carries the reason — a validation/stat error, or "not a directory" when the path exists but is something else — so callers can tell "absent" from "wrong kind".

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
if fsys.IsDir("logs").OK { core.Println("logs ready") }
Example

ExampleFs_IsDir checks directory state through `Fs.IsDir` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
Println(f.IsDir(dir).OK)
Output:
true

func (*Fs) IsFile

func (m *Fs) IsFile(p string) Result

IsFile reports whether path is a regular file via Result.OK. The false path carries the reason — a validation/stat error, or "not a regular file" when the path exists but is a directory or special file.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
if fsys.IsFile("config/agent.json").OK { core.Println("config ready") }
Example

ExampleFs_IsFile checks file state through `Fs.IsFile` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
path := Path(dir, "hello.txt")
f.Write(path, "hello")
Println(f.IsFile(path).OK)
Output:
true

func (*Fs) List

func (m *Fs) List(p string) Result

List returns directory entries.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.List("config")
if !r.OK { return r }
Example

ExampleFs_List lists entries through `Fs.List` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
f.Write(Path(dir, "hello.txt"), "hello")
Println(f.List(dir).OK)
Output:
true

func (*Fs) New

func (m *Fs) New(root string) *Fs

New initialises an Fs with the given root directory. Root "/" means unrestricted access. Empty root defaults to "/".

fs := (&core.Fs{}).New("/")
Example

ExampleFs_New creates a sandboxed filesystem rooted at a workspace path. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/srv/workspaces")
Println(f.Root())
Output:
/srv/workspaces

func (*Fs) NewUnrestricted

func (m *Fs) NewUnrestricted() *Fs

NewUnrestricted returns a new Fs with root "/", granting full filesystem access. Use this instead of unsafe.Pointer to bypass the sandbox.

fs := c.Fs().NewUnrestricted()
fs.Read("/etc/hostname")  // works — no sandbox
Example

ExampleFs_NewUnrestricted creates an unrestricted filesystem through `Fs.NewUnrestricted` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("example"))
defer f.DeleteAll(dir)

// Write outside sandbox using Core's Fs
outside := Path(dir, "outside.txt")
f.Write(outside, "hello")

sandbox := (&Fs{}).New(Path(dir, "sandbox"))
unrestricted := sandbox.NewUnrestricted()

r := unrestricted.Read(outside)
Println(r.Value)
Output:
hello

func (*Fs) Open

func (m *Fs) Open(p string) Result

Open opens the named file for reading.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.ReadStream("config/agent.json")
if !r.OK { return r }
defer r.Value.(core.ReadCloser).Close()
Example

ExampleFs_Open opens a sandboxed file for streaming reads. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
path := Path(dir, "hello.txt")
f.Write(path, "hello")

r := f.Open(path)
Println(r.OK)
CloseStream(r.Value)
Output:
true

func (*Fs) Read

func (m *Fs) Read(p string) Result

Read returns file contents as string.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.Read("config/agent.json")
if r.OK { core.Println(r.Value.(string)) }
Example

ExampleFs_Read reads content through `Fs.Read` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
f.Write(Path(dir, "hello.txt"), "hello")

Println(f.Read(Path(dir, "hello.txt")).Value)
Output:
hello

func (*Fs) ReadStream

func (m *Fs) ReadStream(path string) Result

ReadStream returns a reader for the file content.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.ReadStream("config/agent.json")
if !r.OK { return r }
defer r.Value.(core.ReadCloser).Close()
Example

ExampleFs_ReadStream opens a read stream through `Fs.ReadStream` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
path := Path(dir, "hello.txt")
f.Write(path, "hello")

r := f.ReadStream(path)
Println(ReadAll(r.Value).Value)
Output:
hello

func (*Fs) Rename

func (m *Fs) Rename(oldPath, newPath string) Result

Rename moves a file or directory.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.Rename("config/agent.tmp", "config/agent.json")
if !r.OK { return r }
Example

ExampleFs_Rename renames a path through `Fs.Rename` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
oldPath := Path(dir, "old.txt")
newPath := Path(dir, "new.txt")
f.Write(oldPath, "hello")
Println(f.Rename(oldPath, newPath).OK)
Println(f.Read(newPath).Value)
Output:
true
hello

func (*Fs) Root

func (m *Fs) Root() string

Root returns the sandbox root path.

root := c.Fs().Root()  // e.g. "/home/agent/.core"
Example

ExampleFs_Root reports the root value through `Fs.Root` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/srv/workspaces")
Println(f.Root())
Output:
/srv/workspaces

func (*Fs) Stat

func (m *Fs) Stat(p string) Result

Stat returns file info.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.Stat("config/agent.json")
if !r.OK { return r }
Example

ExampleFs_Stat reads metadata through `Fs.Stat` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
path := Path(dir, "hello.txt")
f.Write(path, "hello")
Println(f.Stat(path).OK)
Output:
true

func (*Fs) TempDir

func (m *Fs) TempDir(prefix string) Result

TempDir creates a temporary directory, returning its path in Result.Value. The caller is responsible for cleanup via fs.DeleteAll(). Returns Result{OK: false} carrying the error if the directory could not be created.

r := fs.TempDir("agent-workspace")
if !r.OK {
	return r
}
dir := r.Value.(string)
defer fs.DeleteAll(dir)
Example

ExampleFs_TempDir creates a temporary directory through `Fs.TempDir` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
r := f.TempDir("core-fs-example")
if !r.OK {
	return
}
dir := r.Value.(string)
defer f.DeleteAll(dir)

Println(PathBase(dir) != "")
Output:
true

func (*Fs) WalkSeq

func (m *Fs) WalkSeq(root string) Seq2[FsEntry, error]

WalkSeq walks the directory tree rooted at root within the Fs sandbox, yielding every entry depth-first. Iteration stops on caller break.

Symlinks are not followed: validatePath rejects any symlink that resolves outside the sandbox before descent, and the underlying walker uses PathWalkDir which does not traverse into symlinked directories.

for entry, err := range c.Fs().WalkSeq("./") {
	if err != nil { break }
	if !entry.IsDir { /* file */ }
}
Example

ExampleFs_WalkSeq walks a tree through `Fs.WalkSeq` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
f.Write(Path(dir, "main.go"), "package main")

for entry, err := range f.WalkSeq(dir) {
	if err == nil && !entry.IsDir {
		Println(entry.Name)
	}
}
Output:
main.go

func (*Fs) WalkSeqSkip

func (m *Fs) WalkSeqSkip(root string, skipNames ...string) Seq2[FsEntry, error]

WalkSeqSkip walks like WalkSeq but skips any directory whose basename appears in skipNames (e.g. "vendor", "node_modules", ".git"). Skipped directories are not descended into; their contents are never yielded. The walk root itself is never skipped, even if its basename matches.

for entry, err := range c.Fs().WalkSeqSkip("./", "vendor", "node_modules", ".git") {
	if err != nil { break }
	if !entry.IsDir { /* file */ }
}
Example
f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
f.Write(Path(dir, "src", "main.go"), "package main")
f.Write(Path(dir, "vendor", "dep.go"), "package dep")

var names []string
for entry, err := range f.WalkSeqSkip(dir, "vendor") {
	if err == nil && !entry.IsDir {
		names = append(names, entry.Name)
	}
}
Println(names)
Output:
[main.go]

func (*Fs) Write

func (m *Fs) Write(p, content string) Result

Write saves content to file, creating parent directories as needed. Files are created with mode 0644. For sensitive files (keys, secrets), use WriteMode with 0600.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.Write("config/agent.json", `{"host":"homelab.lthn.sh"}`)
if !r.OK { return r }
Example

ExampleFs_Write writes content through `Fs.Write` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)

r := f.Write(Path(dir, "hello.txt"), "hello")
Println(r.OK)
Println(f.Read(Path(dir, "hello.txt")).Value)
Output:
true
hello

func (*Fs) WriteAtomic

func (m *Fs) WriteAtomic(p, content string) Result

WriteAtomic writes content by writing to a temp file then renaming. Rename is atomic on POSIX — concurrent readers never see a partial file. Use this for status files, config, or any file read from multiple goroutines.

r := fs.WriteAtomic("/status.json", jsonData)
Example

ExampleFs_WriteAtomic writes content atomically through `Fs.WriteAtomic` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("example"))
defer f.DeleteAll(dir)

path := Path(dir, "status.json")
f.WriteAtomic(path, `{"status":"completed"}`)

r := f.Read(path)
Println(r.Value)
Output:
{"status":"completed"}

func (*Fs) WriteMode

func (m *Fs) WriteMode(p, content string, mode FileMode) Result

WriteMode saves content to file with explicit permissions. Use 0600 for sensitive files (encryption output, private keys, auth hashes).

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.WriteMode("secrets/token", "lethean-token", 0o600)
if !r.OK { return r }
Example

ExampleFs_WriteMode writes content with explicit permissions through `Fs.WriteMode` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)

r := f.WriteMode(Path(dir, "secret.txt"), "secret", 0600)
Println(r.OK)
Output:
true

func (*Fs) WriteStream

func (m *Fs) WriteStream(path string) Result

WriteStream returns a writer for the file content.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.WriteStream("logs/agent.log")
if !r.OK { return r }
defer r.Value.(core.WriteCloser).Close()
Example

ExampleFs_WriteStream opens a write stream through `Fs.WriteStream` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

f := (&Fs{}).New("/")
dir := MustCast[string](f.TempDir("core-fs-example"))
defer f.DeleteAll(dir)
path := Path(dir, "hello.txt")

r := f.WriteStream(path)
WriteAll(r.Value, "hello")
Println(f.Read(path).Value)
Output:
hello

type FsDirEntry

type FsDirEntry = fs.DirEntry

FsDirEntry is a directory entry returned by filesystem walkers.

r := emb.ReadDir(".")
if r.OK { entries := r.Value.([]core.FsDirEntry); _ = entries }

type FsEntry

type FsEntry struct {
	Path  string // relative to walk root, OS-native separator
	Name  string // basename
	IsDir bool
	Mode  fs.FileMode
}

FsEntry is a directory entry yielded by WalkSeq and WalkSeqSkip. Path is relative to the walk root.

entry := core.FsEntry{Path: "config/agent.json", Name: "agent.json", IsDir: false, Mode: 0o644}
core.Println(entry.Path)
Example

ExampleFsEntry reads a walked filesystem entry through `FsEntry` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

entry := FsEntry{Path: "src/main.go", Name: "main.go", IsDir: false}
Println(entry.Path)
Println(entry.Name)
Println(entry.IsDir)
Output:
src/main.go
main.go
false

type FsFile

type FsFile = fs.File

FsFile is a file opened from an FS.

r := emb.Open("README.md")
if r.OK { file := r.Value.(core.FsFile); _ = file }

type FsFileInfo

type FsFileInfo = fs.FileInfo

FsFileInfo describes a file returned by Stat and PathWalk.

info := stat.Value.(core.FsFileInfo)
_ = info

type FuncMap

type FuncMap = template.FuncMap

FuncMap is a map of named functions exposed to templates.

funcs := core.FuncMap{"upper": core.Upper}
tmpl := core.NewTemplate("status").Funcs(funcs)
_, _ = tmpl.Parse("{{upper .Name}}")

type Group

type Group = user.Group

Group represents a system user group. Alias of os/user.Group.

g := core.UserGroupLookup("staff").Value.(*core.Group)
core.Println(g.Name, g.Gid)

type HTTPClient

type HTTPClient = http.Client

HTTPClient is an HTTP client. Named HTTPClient for symmetry with HTTPServer.

client := &core.HTTPClient{}
resp, err := client.Get("https://api.lethean.example/health")
if err == nil {
    defer resp.Body.Close()
}

type HTTPFileSystem added in v0.10.0

type HTTPFileSystem = http.FileSystem

HTTPFileSystem is the interface served by HTTPFileServer. Construct via HTTPFS to wrap a Lethean FS, or pass a stdlib http.Dir directly.

mux.Handle("/static/", core.HTTPFileServer(core.HTTPFS(embedded)))
Example

ExampleHTTPFileSystem documents the type alias for HTTP file servers. Construct via HTTPFS to wrap a Lethean FS, or pass a stdlib http.Dir.

var _ HTTPFileSystem = HTTPFS(DirFS("/tmp"))
Println("aliased")
Output:
aliased

func HTTPFS added in v0.10.0

func HTTPFS(fsys FS) HTTPFileSystem

HTTPFS converts a Lethean FS to an HTTPFileSystem suitable for HTTPFileServer. Useful for serving an embed.FS through net/http.

mux.Handle("/static/", core.HTTPFileServer(core.HTTPFS(embedded)))
Example

ExampleHTTPFS converts a Lethean FS to an HTTPFileSystem suitable for HTTPFileServer. Combined with embed.FS, the pattern serves static assets without a network read.

hfs := HTTPFS(DirFS("/tmp"))
_ = hfs

type HTTPServer

type HTTPServer = http.Server

HTTPServer is an HTTP server. Named HTTPServer (not Server) because core may grow other server types; this keeps the namespace clean.

srv := &core.HTTPServer{Addr: ":8080", Handler: &core.ServeMux{}}
go srv.ListenAndServe()
defer srv.Close()

type HTTPTestRecorder

type HTTPTestRecorder = httptest.ResponseRecorder

HTTPTestRecorder is an http.ResponseWriter that records the response for handler tests.

rec := core.NewHTTPTestRecorder()
req := core.NewHTTPTestRequest("GET", "/health", nil)
handler := core.HandlerFunc(func(w core.ResponseWriter, r *core.Request) { core.WriteString(w, "ok") })
handler.ServeHTTP(rec, req)

func NewHTTPTestRecorder

func NewHTTPTestRecorder() *HTTPTestRecorder

NewHTTPTestRecorder returns a fresh ResponseRecorder for handler tests.

rec := core.NewHTTPTestRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != 200 { ... }
Example

ExampleNewHTTPTestRecorder records response status for handler validation. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

rec := NewHTTPTestRecorder()
rec.WriteHeader(202)
Println(rec.Code)
Output:
202

type HTTPTestServer

type HTTPTestServer = httptest.Server

HTTPTestServer is a test HTTP server, useful for exercising clients against a real listener without external dependencies.

server := core.NewHTTPTestServer(core.HandlerFunc(func(w core.ResponseWriter, r *core.Request) {
    core.WriteString(w, "ok\n")
}))
defer server.Close()
_ = core.HTTPGet(server.URL)

func NewHTTPTestServer

func NewHTTPTestServer(handler Handler) *HTTPTestServer

NewHTTPTestServer starts a new test server with the given handler. Caller must Close() the returned server.

srv := core.NewHTTPTestServer(handler)
defer srv.Close()
resp := core.HTTPGet(srv.URL)
Example

ExampleNewHTTPTestServer creates an HTTP fixture server for handler validation. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

srv := NewHTTPTestServer(HandlerFunc(func(w ResponseWriter, _ *Request) {
	WriteString(w, "ok")
}))
defer srv.Close()

Println(HasPrefix(srv.URL, "http://"))
Output:
true

func NewHTTPTestTLSServer

func NewHTTPTestTLSServer(handler Handler) *HTTPTestServer

NewHTTPTestTLSServer starts a new test server using TLS.

server := core.NewHTTPTestTLSServer(core.HandlerFunc(func(w core.ResponseWriter, r *core.Request) {
    core.WriteString(w, "secure\n")
}))
defer server.Close()
Example

ExampleNewHTTPTestTLSServer creates a TLS fixture server for HTTPS handler validation. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

srv := NewHTTPTestTLSServer(HandlerFunc(func(w ResponseWriter, _ *Request) {
	WriteString(w, "ok")
}))
defer srv.Close()

Println(HasPrefix(srv.URL, "https://"))
Output:
true

type Handler

type Handler = http.Handler

Handler is the canonical HTTP handler interface.

var handler core.Handler = core.HandlerFunc(func(w core.ResponseWriter, r *core.Request) {
    core.WriteString(w, "ready\n")
})
_ = handler

func HTTPFileServer added in v0.10.0

func HTTPFileServer(root HTTPFileSystem) Handler

HTTPFileServer returns a Handler that serves HTTP requests with the contents of the file system rooted at root. Pair with HTTPFS to serve a Lethean FS or embed.FS without importing net/http.

mux.Handle("/static/", core.HTTPFileServer(core.HTTPFS(embedded)))
Example

ExampleHTTPFileServer constructs a Handler that serves a file tree under any mux path. Pair with HTTPFS to serve a Lethean FS or embed.FS root.

mux := NewServeMux()
mux.Handle("/static/", HTTPStripPrefix("/static/", HTTPFileServer(HTTPFS(DirFS("/tmp")))))
_ = mux

func HTTPStripPrefix added in v0.10.0

func HTTPStripPrefix(prefix string, h Handler) Handler

HTTPStripPrefix returns a Handler that serves requests by removing the given prefix from the URL path before delegating to h. Useful for mounting a sub-application under a path.

api := core.HTTPStripPrefix("/api/v1", apiHandler)
Example

ExampleHTTPStripPrefix mounts an inner handler under /api/v1/* by stripping the prefix before delegation. Used to compose sub-apps under a versioned path.

inner := HandlerFunc(func(w ResponseWriter, r *Request) {
	WriteString(w, r.URL.Path)
})
mux := NewServeMux()
mux.Handle("/api/v1/", HTTPStripPrefix("/api/v1", inner))
srv := NewHTTPTestServer(mux)
defer srv.Close()

r := HTTPGet(srv.URL + "/api/v1/users")
defer r.Value.(*Response).Body.Close()
body := ReadAll(r.Value.(*Response).Body)
Println(body.Value)
Output:
/users

type HandlerFunc

type HandlerFunc = http.HandlerFunc

HandlerFunc is the canonical HTTP handler-as-function adapter.

handler := core.HandlerFunc(func(w core.ResponseWriter, r *core.Request) {
    core.WriteString(w, "accepted\n")
})
core.NewHTTPTestServer(handler).Close()
type Header = http.Header

Header is the canonical HTTP header map.

headers := core.Header{}
headers.Set("Authorization", "Bearer lethean-token")
headers.Set("X-Agent", "codex")

type I18n

type I18n struct {
	// contains filtered or unexported fields
}

I18n manages locale collection and translation dispatch.

c := core.New()
r := c.I18n().Translate("cmd.deploy.description")
if r.OK { core.Println(r.Value.(string)) }

func (*I18n) AddLocales

func (i *I18n) AddLocales(mounts ...*Embed)

AddLocales adds locale mounts (called during service registration).

c := core.New()
r := core.Mount(core.DirFS("locales"), ".")
if r.OK { c.I18n().AddLocales(r.Value.(*core.Embed)) }
Example

ExampleI18n_AddLocales adds locale tables through `I18n.AddLocales` for operator-facing localisation. Language selection and translation stay behind the I18n service.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-i18n-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "locales", "en.yaml"), "hello: Hello")

mount := Mount(DirFS(dir), "locales").Value.(*Embed)
i := &I18n{}
i.AddLocales(mount)

r := i.Locales()
Println(len(r.Value.([]*Embed)))
Output:
1

func (*I18n) AvailableLanguages

func (i *I18n) AvailableLanguages() []string

AvailableLanguages returns all loaded language codes.

c := core.New()
languages := c.I18n().AvailableLanguages()
core.Println(core.Join(", ", languages...))
Example

ExampleI18n_AvailableLanguages lists available languages through `I18n.AvailableLanguages` for operator-facing localisation. Language selection and translation stay behind the I18n service.

i := &I18n{}
i.SetTranslator(&exampleTranslator{})
Println(i.AvailableLanguages())
Output:
[en fr]

func (*I18n) Language

func (i *I18n) Language() string

Language returns the current language code, or "en" if not set.

c := core.New()
c.I18n().SetLanguage("en-GB")
lang := c.I18n().Language()
core.Println(lang)
Example

ExampleI18n_Language reads the active language through `I18n.Language` for operator-facing localisation. Language selection and translation stay behind the I18n service.

i := &I18n{}
Println(i.Language())
Output:
en

func (*I18n) Locales

func (i *I18n) Locales() Result

Locales returns all collected locale mounts.

c := core.New()
r := c.I18n().Locales()
if r.OK { mounts := r.Value.([]*core.Embed); _ = mounts }
Example

ExampleI18n_Locales lists locale tables through `I18n.Locales` for operator-facing localisation. Language selection and translation stay behind the I18n service.

i := &I18n{}
r := i.Locales()
Println(r.OK)
Println(len(r.Value.([]*Embed)))
Output:
true
0

func (*I18n) SetLanguage

func (i *I18n) SetLanguage(lang string) Result

SetLanguage sets the active language and forwards to the translator if registered.

c := core.New()
r := c.I18n().SetLanguage("en-GB")
if !r.OK { return r }
Example

ExampleI18n_SetLanguage sets the active language through `I18n.SetLanguage` for operator-facing localisation. Language selection and translation stay behind the I18n service.

i := &I18n{}
i.SetLanguage("fr")
Println(i.Language())
Output:
fr

func (*I18n) SetTranslator

func (i *I18n) SetTranslator(t Translator)

SetTranslator registers the translation implementation. Called by go-i18n's Srv during startup.

c := core.New()
c.I18n().SetTranslator(nil)
Example

ExampleI18n_SetTranslator installs a translator through `I18n.SetTranslator` for operator-facing localisation. Language selection and translation stay behind the I18n service.

i := &I18n{}
tr := &exampleTranslator{}
i.SetLanguage("fr")
i.SetTranslator(tr)

Println(tr.Language())
Output:
fr

func (*I18n) Translate

func (i *I18n) Translate(messageID string, args ...any) Result

Translate translates a message. Returns the key as-is if no translator is registered.

c := core.New()
r := c.I18n().Translate("cmd.deploy.description")
if r.OK { core.Println(r.Value.(string)) }
Example

ExampleI18n_Translate translates a key through `I18n.Translate` for operator-facing localisation. Language selection and translation stay behind the I18n service.

i := &I18n{}
i.SetTranslator(&exampleTranslator{lang: "en"})
r := i.Translate("hello %s", "codex")
Println(r.Value)
Output:
hello codex

func (*I18n) Translator

func (i *I18n) Translator() Result

Translator returns the registered translation implementation, or nil.

c := core.New()
r := c.I18n().Translator()
if r.OK { tr := r.Value.(core.Translator); core.Println(tr.Language()) }
Example

ExampleI18n_Translator declares a translator through `I18n.Translator` for operator-facing localisation. Language selection and translation stay behind the I18n service.

i := &I18n{}
i.SetTranslator(&exampleTranslator{lang: "en"})
Println(i.Translator().OK)
Output:
true

type IP

type IP = net.IP

IP is a single IP address.

ip := core.ParseIP("192.0.2.10")
if ip != nil { core.Println(ip.String()) }

func ParseIP

func ParseIP(s string) IP

ParseIP parses an IPv4 or IPv6 textual address. Returns nil on malformed input — same shape as net.ParseIP.

ip := core.ParseIP("2001:db8::1")
Example

ExampleParseIP parses an IP address through `ParseIP` for network health checks. Network primitives are reached through core wrappers and Result-shaped calls.

ip := ParseIP("192.0.2.10")
Println(ip.String())
Output:
192.0.2.10

type IPMask

type IPMask = net.IPMask

IPMask is the mask portion of an IPNet.

mask := core.IPMask{255, 255, 255, 0}
core.Println(core.IP(mask).String())

type IPNet

type IPNet = net.IPNet

IPNet is an IP network (address + mask).

r := core.ParseCIDR("192.0.2.0/24")
if !r.OK { return r }
network := r.Value.([]any)[1].(*core.IPNet)
core.Println(network.String())

type Ipc

type Ipc struct {
	// contains filtered or unexported fields
}

Ipc holds IPC dispatch data and the named action registry.

ipc := (&core.Ipc{}).New()
Example

ExampleIpc declares IPC registration through `Ipc` for Core message dispatch. Actions and queries share one Core dispatch pattern for messages.

c := New()
Println(c.IPC() != nil)
Output:
true

type JSONDecoder added in v0.10.4

type JSONDecoder = json.Decoder

JSONDecoder is an alias for json.Decoder — the streaming reader that pulls JSON values from an io.Reader. Construct via JSONNewDecoder.

var dec *core.JSONDecoder = core.JSONNewDecoder(r)

func JSONNewDecoder added in v0.10.4

func JSONNewDecoder(r Reader) *JSONDecoder

JSONNewDecoder returns a streaming JSON decoder reading from r. Prefer it over JSONUnmarshal when consuming a stream of values or a body of unknown length — it decodes one value at a time and can switch to JSONNumber mode via dec.UseNumber().

dec := core.JSONNewDecoder(resp.Body)
var msg Message
for dec.More() { if err := dec.Decode(&msg); err != nil { break } }
Example

ExampleJSONNewDecoder pulls a single value from a reader, the streaming counterpart to JSONUnmarshal.

type cfg struct {
	Port int `json:"port"`
}
var c cfg
JSONNewDecoder(NewReader(`{"port":8080}`)).Decode(&c)
Println(c.Port)
Output:
8080

type JSONDelim added in v0.10.4

type JSONDelim = json.Delim

JSONDelim is an alias for json.Delim — one of the four structural tokens ( [ ] { } ) returned by JSONDecoder.Token during streaming token walks.

tok, _ := dec.Token()
if d, ok := tok.(core.JSONDelim); ok && d == '[' { /* array start */ }

type JSONEncoder added in v0.10.4

type JSONEncoder = json.Encoder

JSONEncoder is an alias for json.Encoder — the streaming writer that emits JSON values to an io.Writer one at a time. Construct via JSONNewEncoder.

var enc *core.JSONEncoder = core.JSONNewEncoder(w)

func JSONNewEncoder added in v0.10.4

func JSONNewEncoder(w Writer) *JSONEncoder

JSONNewEncoder returns a streaming JSON encoder writing to w. Prefer it over JSONMarshal when emitting many values to a stream (HTTP response, JSONL file) — it writes incrementally without buffering every value into one []byte.

enc := core.JSONNewEncoder(core.Stdout())
for _, row := range rows { enc.Encode(row) }  // one JSON value per line
Example

ExampleJSONNewEncoder streams two values straight to stdout as JSONL — one JSON object per line — without buffering the whole batch. Encode writes the trailing newline itself.

type row struct {
	Name string `json:"name"`
}
enc := JSONNewEncoder(Stdout())
enc.Encode(row{Name: "a"})
enc.Encode(row{Name: "b"})
Output:
{"name":"a"}
{"name":"b"}

type JSONMarshaler added in v0.10.4

type JSONMarshaler = json.Marshaler

JSONMarshaler is an alias for json.Marshaler — the interface a type implements to control its own JSON encoding.

func (id AgentID) MarshalJSON() ([]byte, error) { ... }
var _ core.JSONMarshaler = AgentID{}

type JSONNumber added in v0.10.4

type JSONNumber = json.Number

JSONNumber is an alias for json.Number — a JSON numeric literal kept as its original string so callers choose int vs float decoding (and avoid float64 precision loss on large integers). Pairs with the UseNumber() option on JSONDecoder.

var n core.JSONNumber = "9007199254740993"
r := n.Int64()  // exact, no float rounding

type JSONUnmarshaler added in v0.10.4

type JSONUnmarshaler = json.Unmarshaler

JSONUnmarshaler is an alias for json.Unmarshaler — the interface a type implements to control its own JSON decoding.

func (id *AgentID) UnmarshalJSON(b []byte) error { ... }
var _ core.JSONUnmarshaler = (*AgentID)(nil)

type Kind

type Kind = reflect.Kind

Kind classifies a Type into one of the basic Go kinds (Bool, Int, String, Struct, Map, Slice, etc.).

if core.TypeOf(opts).Kind() == core.KindStruct { ... }
Example

ExampleKind reads a reflection kind through `Kind` for runtime inspection. Reflection stays behind a narrow core surface for rare inspection code.

k := TypeOf("x").Kind()
Println(k == KindString)
Output:
true

type LSPDiagnostic

type LSPDiagnostic struct {
	Range    LSPRange `json:"range"`
	Severity int      `json:"severity"`
	Source   string   `json:"source"`
	Message  string   `json:"message"`
	Code     string   `json:"code,omitempty"`
}

LSPDiagnostic is one drift finding at a specific document range. Severity uses the LSPSeverity* constants. Source identifies the producing rule (e.g. "test-imports", "spor", "ax-7").

d := core.LSPDiagnostic{
    Range:    core.LSPRange{Start: core.LSPPosition{Line: 4}, End: core.LSPPosition{Line: 4, Character: 80}},
    Severity: core.LSPSeverityWarning,
    Source:   "test-imports",
    Message:  "imports 'context' — use core.Background()/core.Context",
}
Example
d := LSPDiagnostic{
	Range:    LSPRange{Start: LSPPosition{Line: 4}, End: LSPPosition{Line: 4, Character: 80}},
	Severity: LSPSeverityWarning,
	Source:   "test-imports",
	Message:  "imports 'context' — use core.Background()",
}
Println(d.Source)
Println(d.Message)
Println(d.Range.End.Character)
Output:
test-imports
imports 'context' — use core.Background()
80

func LSPComputeDiagnostics

func LSPComputeDiagnostics(uri string, content []byte) []LSPDiagnostic

LSPComputeDiagnostics runs every registered source against (uri, content) and concatenates the results. Used internally by LSPServe and exposed here so tests/agents can compute diagnostics without spinning up the full server.

diags := core.LSPComputeDiagnostics("file:///path/to/foo_test.go", content)
for _, d := range diags { core.Println(d.Message) }
Example
// Register a diagnostic source, then compute diagnostics for a document
// without starting the full server. Output is omitted: registered sources
// are global process state, so the result depends on what else the process
// has registered.
LSPRegisterDiagnostic("example-todo", func(uri string, content []byte) []LSPDiagnostic {
	if Contains(string(content), "TODO") {
		return []LSPDiagnostic{{Message: "contains TODO", Source: "example-todo"}}
	}
	return nil
})
_ = LSPComputeDiagnostics("file:///x.go", []byte("// TODO\n"))
_ = LSPDiagnosticSources()

type LSPDiagnosticSource

type LSPDiagnosticSource func(uri string, content []byte) []LSPDiagnostic

LSPDiagnosticSource produces diagnostics for one document. uri is the LSP document URI ("file:///abs/path"); content is the current file body. Return an empty slice when nothing applies.

core.LSPRegisterDiagnostic("test-imports", func(uri string, content []byte) []core.LSPDiagnostic {
    if !core.HasSuffix(uri, "_test.go") { return nil }
    // ... parse imports, return diagnostics ...
    return nil
})

type LSPPosition

type LSPPosition struct {
	Line      int `json:"line"`
	Character int `json:"character"`
}

LSPPosition is a 0-based line/character location inside a document.

pos := core.LSPPosition{Line: 12, Character: 0}

type LSPRange

type LSPRange struct {
	Start LSPPosition `json:"start"`
	End   LSPPosition `json:"end"`
}

LSPRange spans Start..End within a document.

r := core.LSPRange{Start: core.LSPPosition{Line: 12}, End: core.LSPPosition{Line: 12, Character: 80}}

type Level

type Level int

Level defines logging verbosity.

level := core.LevelInfo
core.SetLevel(level)
const (
	// LevelQuiet suppresses all log output.
	//
	//	core.SetLevel(core.LevelQuiet)
	LevelQuiet Level = iota
	// LevelError shows only error messages.
	//
	//	core.SetLevel(core.LevelError)
	//	core.Error("agent failed", "service", "homelab")
	LevelError
	// LevelWarn shows warnings and errors.
	//
	//	core.SetLevel(core.LevelWarn)
	//	core.Warn("agent degraded", "service", "homelab")
	LevelWarn
	// LevelInfo shows informational messages, warnings, and errors.
	//
	//	core.SetLevel(core.LevelInfo)
	//	core.Info("agent started", "service", "homelab")
	LevelInfo
	// LevelDebug shows all messages including debug details.
	//
	//	core.SetLevel(core.LevelDebug)
	//	core.Debug("agent trace", "task", "task-42")
	LevelDebug
)

Logging level constants ordered by increasing verbosity.

func (Level) String

func (l Level) String() string

String returns the level name.

name := core.LevelInfo.String()
core.Println(name)
Example

ExampleLevel_String renders `Level.String` as a stable string for operator logging. Loggers support levels, redaction, and default routing for operator output.

Println(LevelInfo.String())
Println(LevelQuiet.String())
Output:
info
quiet

type Listener

type Listener = net.Listener

Listener accepts inbound connections.

r := core.NetListen("tcp", "127.0.0.1:0")
if !r.OK { return r }
ln := r.Value.(core.Listener)
defer ln.Close()

type LocaleProvider

type LocaleProvider interface {
	Locales() *Embed
}

LocaleProvider is implemented by services that ship their own translation files. Core discovers this interface during service registration and collects the locale mounts. The i18n service loads them during startup.

Usage in a service package:

//go:embed locales
var localeFS embed.FS

func (s *MyService) Locales() *Embed {
    m, _ := Mount(localeFS, "locales")
    return m
}
Example

ExampleLocaleProvider declares a locale provider through `LocaleProvider` for operator-facing localisation. Language selection and translation stay behind the I18n service.

var provider LocaleProvider = exampleLocaleProvider{}
Println(provider.Locales() == nil)
Output:
true

type Location added in v0.10.4

type Location = time.Location

Location maps instants to the zone in use at that time — alias of time.Location so consumers can pass zones without importing the time package. Use the UTC and Local package variables for the common cases.

ts := core.Date(2026, core.January, 1, 0, 0, 0, 0, core.UTC)

type Lock

type Lock struct {
	Name  string
	Mutex *RWMutex
}

Lock is the DTO for a named mutex — pure data, no embedded cache. The per-Core cache of *Lock wrappers lives in Core's locks Registry.

Mutex is the backing core.RWMutex.

c := core.New()
lock := c.Lock("service-registry")
lock.Lock(); defer lock.Unlock()

func (*Lock) Lock

func (l *Lock) Lock()

Lock acquires the named mutex for write.

c.Lock("drain").Lock()
defer c.Lock("drain").Unlock()
Example

ExampleLock_Lock acquires a lock through `Lock.Lock` for lifecycle locking. Lifecycle locks coordinate startup and shutdown without exposing sync primitives directly.

c := New()
lock := c.Lock("drain")
lock.Lock()
Println("locked")
lock.Unlock()
Output:
locked

func (*Lock) RLock

func (l *Lock) RLock()

RLock acquires the named mutex for read.

c.Lock("cache").RLock()
defer c.Lock("cache").RUnlock()
Example

ExampleLock_RLock acquires a read lock through `Lock.RLock` for lifecycle locking. Lifecycle locks coordinate startup and shutdown without exposing sync primitives directly.

c := New()
lock := c.Lock("cache")
lock.RLock()
Println("read-locked")
lock.RUnlock()
Println("read-unlocked")
Output:
read-locked
read-unlocked

func (*Lock) RUnlock

func (l *Lock) RUnlock()

RUnlock releases the named mutex from read.

c.Lock("cache").RUnlock()
Example

ExampleLock_RUnlock releases a read lock through `Lock.RUnlock` for lifecycle locking. Lifecycle locks coordinate startup and shutdown without exposing sync primitives directly.

c := New()
lock := c.Lock("cache")
lock.RLock()
lock.RUnlock()
Println("read-unlocked")
Output:
read-unlocked

func (*Lock) TryLock

func (l *Lock) TryLock() Result

TryLock attempts to acquire the write mutex without blocking. Returns Result{OK: true} when acquired, Result{OK: false} when held.

if c.Lock("drain").TryLock().OK {
    defer c.Lock("drain").Unlock()
    // ...
}
Example

ExampleLock_TryLock attempts a non-blocking write lock through `Lock.TryLock` for lifecycle locking. Lifecycle locks coordinate startup and shutdown without exposing sync primitives directly.

c := New()
lock := c.Lock("drain")
if lock.TryLock().OK {
	Println("acquired")
	lock.Unlock()
}
Output:
acquired

func (*Lock) Unlock

func (l *Lock) Unlock()

Unlock releases the named mutex from write.

c.Lock("drain").Unlock()
Example

ExampleLock_Unlock releases a lock through `Lock.Unlock` for lifecycle locking. Lifecycle locks coordinate startup and shutdown without exposing sync primitives directly.

c := New()
lock := c.Lock("drain")
lock.Lock()
lock.Unlock()
Println("unlocked")
Output:
unlocked

type Log

type Log struct {

	// Style functions for formatting (can be overridden)
	StyleTimestamp func(string) string
	StyleDebug     func(string) string
	StyleInfo      func(string) string
	StyleWarn      func(string) string
	StyleError     func(string) string
	StyleSecurity  func(string) string
	// contains filtered or unexported fields
}

Log provides structured logging.

log := core.NewLog(core.LogOptions{Level: core.LevelInfo, Output: core.Stdout()})
log.Info("agent started", "service", "homelab")

func Default

func Default() *Log

Default returns the default logger.

log := core.Default()
log.Info("agent started")
Example

ExampleDefault reads the default logger through `Default` for operator logging. Loggers support levels, redaction, and default routing for operator output.

Println(Default() != nil)
Output:
true

func NewLog

func NewLog(opts LogOptions) *Log

New creates a new Log with the given options.

log := core.NewLog(core.LogOptions{Level: core.LevelDebug, Output: core.Stdout()})
log.Debug("agent trace", "task", "task-42")
Example

ExampleNewLog creates a logger through `NewLog` for operator logging. Loggers support levels, redaction, and default routing for operator output.

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelInfo, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
log.Info("server started", "port", 8080)
Println(Contains(buf.String(), "00:00:00 [INF] server started port=8080"))
Output:
true

func (*Log) Debug

func (l *Log) Debug(msg string, keyvals ...any)

Debug logs a debug message with optional key-value pairs.

log := core.NewLog(core.LogOptions{Level: core.LevelDebug, Output: core.Stdout()})
log.Debug("agent trace", "task", "task-42")
Example

ExampleLog_Debug writes a debug event through `Log.Debug` for operator logging. Loggers support levels, redaction, and default routing for operator output.

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelDebug, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
log.Debug("trace")
Println(Contains(buf.String(), "[DBG] trace"))
Output:
true

func (*Log) Error

func (l *Log) Error(msg string, keyvals ...any)

Error logs an error message with optional key-value pairs.

log := core.NewLog(core.LogOptions{Level: core.LevelError, Output: core.Stdout()})
log.Error("agent failed", "service", "homelab")
Example

ExampleLog_Error writes or renders an error through `Log.Error` for operator logging. Loggers support levels, redaction, and default routing for operator output.

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelError, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
log.Error("failed")
Println(Contains(buf.String(), "[ERR] failed"))
Output:
true

func (*Log) Info

func (l *Log) Info(msg string, keyvals ...any)

Info logs an info message with optional key-value pairs.

log := core.NewLog(core.LogOptions{Level: core.LevelInfo, Output: core.Stdout()})
log.Info("agent started", "service", "homelab")
Example

ExampleLog_Info writes an info event through `Log.Info` for operator logging. Loggers support levels, redaction, and default routing for operator output.

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelInfo, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
log.Info("ready")
Println(Contains(buf.String(), "[INF] ready"))
Output:
true

func (*Log) Level

func (l *Log) Level() Level

Level returns the current log level.

log := core.NewLog(core.LogOptions{Level: core.LevelInfo})
level := log.Level()
core.Println(level.String())
Example

ExampleLog_Level reads a logger level through `Log.Level` for operator logging. Loggers support levels, redaction, and default routing for operator output.

log := NewLog(LogOptions{Level: LevelError, Output: NewBuffer()})
Println(log.Level())
Output:
error

func (*Log) Security

func (l *Log) Security(msg string, keyvals ...any)

Security logs a security event with optional key-value pairs. It uses LevelError to ensure security events are visible even in restrictive log configurations.

log := core.NewLog(core.LogOptions{Level: core.LevelError, Output: core.Stdout()})
log.Security("entitlement.denied", "action", "process.run")
Example

ExampleLog_Security writes a security event through `Log.Security` for operator logging. Loggers support levels, redaction, and default routing for operator output.

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelError, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
log.Security("denied")
Println(Contains(buf.String(), "[SEC] denied"))
Output:
true

func (*Log) SetLevel

func (l *Log) SetLevel(level Level)

SetLevel changes the log level.

log := core.NewLog(core.LogOptions{Output: core.Stdout()})
log.SetLevel(core.LevelDebug)
Example

ExampleLog_SetLevel changes log level through `Log.SetLevel` for operator logging. Loggers support levels, redaction, and default routing for operator output.

log := NewLog(LogOptions{Level: LevelWarn, Output: NewBuffer()})
log.SetLevel(LevelDebug)
Println(log.Level())
Output:
debug

func (*Log) SetOutput

func (l *Log) SetOutput(w goio.Writer)

SetOutput changes the output writer.

log := core.NewLog(core.LogOptions{Level: core.LevelInfo})
log.SetOutput(core.Stdout())
Example

ExampleLog_SetOutput redirects output through `Log.SetOutput` for operator logging. Loggers support levels, redaction, and default routing for operator output.

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelInfo})
log.StyleTimestamp = func(string) string { return "00:00:00" }
log.SetOutput(buf)
log.Info("ready")
Println(Contains(buf.String(), "[INF] ready"))
Output:
true

func (*Log) SetRedactKeys

func (l *Log) SetRedactKeys(keys ...string)

SetRedactKeys sets the keys to be redacted.

log := core.NewLog(core.LogOptions{Level: core.LevelInfo})
log.SetRedactKeys("token", "authorization")
Example

ExampleLog_SetRedactKeys configures redaction keys through `Log.SetRedactKeys` for operator logging. Loggers support levels, redaction, and default routing for operator output.

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelInfo, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
log.SetRedactKeys("token")
log.Info("auth", "token", "secret")
Println(Contains(buf.String(), `token="[REDACTED]"`))
Output:
true

func (*Log) Warn

func (l *Log) Warn(msg string, keyvals ...any)

Warn logs a warning message with optional key-value pairs.

log := core.NewLog(core.LogOptions{Level: core.LevelWarn, Output: core.Stdout()})
log.Warn("agent degraded", "service", "homelab")
Example

ExampleLog_Warn writes a warning event through `Log.Warn` for operator logging. Loggers support levels, redaction, and default routing for operator output.

buf := NewBuffer()
log := NewLog(LogOptions{Level: LevelWarn, Output: buf})
log.StyleTimestamp = func(string) string { return "00:00:00" }
log.Warn("slow")
Println(Contains(buf.String(), "[WRN] slow"))
Output:
true

type LogErr

type LogErr struct {
	// contains filtered or unexported fields
}

LogErr logs structured information extracted from errors. Primary action: log. Secondary: extract error context.

logger := core.NewLogErr(core.Default())
logger.Log(core.E("agent.Run", "failed", nil))

func NewLogErr

func NewLogErr(log *Log) *LogErr

NewLogErr creates a LogErr bound to the given logger.

logger := core.NewLogErr(core.Default())
logger.Log(core.E("agent.Run", "failed", nil))
Example

ExampleNewLogErr creates an error logging sink through `NewLogErr` for operator logging. Loggers support levels, redaction, and default routing for operator output.

logErr := NewLogErr(NewLog(LogOptions{Output: NewBuffer()}))
Println(logErr != nil)
Output:
true

func (*LogErr) Log

func (le *LogErr) Log(err error)

Log extracts context from an Err and logs it at Error level.

logger := core.NewLogErr(core.Default())
logger.Log(core.E("agent.Run", "failed", nil))
Example

ExampleLogErr_Log logs through `LogErr.Log` for operator logging. Loggers support levels, redaction, and default routing for operator output.

logErr := NewLogErr(NewLog(LogOptions{Output: NewBuffer()}))
logErr.Log(nil)
Println("ok")
Output:
ok

type LogOptions

type LogOptions struct {
	Level Level
	// Output is the destination for log messages. If Rotation is provided,
	// Output is ignored and logs are written to the rotating file instead.
	Output goio.Writer
	// Rotation enables log rotation to file. If provided, Filename must be set.
	Rotation *RotationLogOptions
	// RedactKeys is a list of keys whose values should be masked in logs.
	RedactKeys []string
}

LogOptions configures a Log.

opts := core.LogOptions{Level: core.LevelInfo, Output: core.Stdout(), RedactKeys: []string{"token"}}
log := core.NewLog(opts)
log.Info("agent started")
Example

ExampleLogOptions declares logger settings through `LogOptions` for operator logging. Loggers support levels, redaction, and default routing for operator output.

opts := LogOptions{Level: LevelInfo, Output: NewBuffer(), RedactKeys: []string{"token"}}
Println(opts.Level)
Println(opts.RedactKeys)
Output:
info
[token]

type LogPanic

type LogPanic struct {
	// contains filtered or unexported fields
}

LogPanic logs panic context without crash file management. Primary action: log. Secondary: recover panics.

guard := core.NewLogPanic(core.Default())
defer guard.Recover()

func NewLogPanic

func NewLogPanic(log *Log) *LogPanic

NewLogPanic creates a LogPanic bound to the given logger.

guard := core.NewLogPanic(core.Default())
defer guard.Recover()
Example

ExampleNewLogPanic creates a panic logging helper through `NewLogPanic` for operator logging. Loggers support levels, redaction, and default routing for operator output.

panicLog := NewLogPanic(NewLog(LogOptions{Output: NewBuffer()}))
Println(panicLog != nil)
Output:
true

func (*LogPanic) Recover

func (lp *LogPanic) Recover()

Recover captures a panic and logs it. Does not write crash files. Use as: defer core.NewLogPanic(logger).Recover()

guard := core.NewLogPanic(core.Default())
defer guard.Recover()
Example

ExampleLogPanic_Recover documents panic logging recovery when no panic is active. Loggers support levels, redaction, and default routing for operator output.

panicLog := NewLogPanic(NewLog(LogOptions{Output: NewBuffer()}))
defer panicLog.Recover()

type Message

type Message any

Message is the type for IPC broadcasts (fire-and-forget).

c := core.New()
var msg core.Message = core.ActionTaskStarted{TaskIdentifier: "task-42", Action: "agent.run"}
c.ACTION(msg)
Example

ExampleMessage assigns a lifecycle event to the message contract through `Message` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

var msg Message = ActionServiceStartup{}
Println(Sprint(msg))
Output:
{}

type Month added in v0.10.4

type Month = time.Month

Month specifies a month of the year (January = 1, ...) — alias of time.Month so callers can build dates without importing the time package.

m := core.January

type MultipartFile

type MultipartFile = multipart.File

MultipartFile is an open file from a multipart upload.

var file core.MultipartFile
if file != nil {
    defer file.Close()
}

type MultipartFileHeader

type MultipartFileHeader = multipart.FileHeader

MultipartFileHeader is the header of a multipart upload file.

header := &core.MultipartFileHeader{Filename: "agent-report.json"}
core.Println(header.Filename)

type MultipartForm

type MultipartForm = multipart.Form

MultipartForm is a parsed multipart/form-data form.

form := &core.MultipartForm{Value: map[string][]string{"agent": {"codex"}}}
agents := form.Value["agent"]
core.Println(core.Join(", ", agents...))

type MultipartReader

type MultipartReader = multipart.Reader

MultipartReader streams a multipart body.

body := core.NewBufferString("--agent-boundary\r\n\r\n--agent-boundary--\r\n")
reader := core.NewMultipartReader(body, "agent-boundary")
if part, err := reader.NextPart(); err == nil {
    defer part.Close()
}

func NewMultipartReader

func NewMultipartReader(r Reader, boundary string) *MultipartReader

NewMultipartReader returns a multipart reader for the given body and boundary.

r := core.NewMultipartReader(req.Body, boundary)
Example

ExampleNewMultipartReader reads multipart form data through `NewMultipartReader` for a Lethean drive integration. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

buf := NewBuffer()
writer := NewMultipartWriter(buf)
writer.WriteField("name", "codex")
boundary := writer.Boundary()
writer.Close()

reader := NewMultipartReader(buf, boundary)
part, _ := reader.NextPart()
data := ReadAll(part)
Println(part.FormName())
Println(data.Value)
Output:
name
codex

type MultipartWriter

type MultipartWriter = multipart.Writer

MultipartWriter assembles a multipart body.

buf := core.NewBuffer()
writer := core.NewMultipartWriter(buf)
field, _ := writer.CreateFormField("agent")
core.WriteString(field, "codex")
writer.Close()

func NewMultipartWriter

func NewMultipartWriter(w Writer) *MultipartWriter

NewMultipartWriter returns a multipart writer that writes to w. The caller closes the writer to flush the trailing boundary.

w := core.NewMultipartWriter(buf)
w.WriteField("name", "value")
w.Close()
Example

ExampleNewMultipartWriter creates multipart form data through `NewMultipartWriter` for a Lethean drive integration. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

buf := NewBuffer()
writer := NewMultipartWriter(buf)
writer.WriteField("name", "codex")
boundary := writer.Boundary()
writer.Close()

Println(boundary != "")
Println(Contains(buf.String(), "codex"))
Output:
true
true

type Mutex

type Mutex struct {
	// contains filtered or unexported fields
}

Mutex is a mutual exclusion lock. Embed in your struct to protect internal state.

type Counter struct {
    mu    core.Mutex
    value int
}

func (c *Counter) Inc() {
    c.mu.Lock(); defer c.mu.Unlock()
    c.value++
}
Example

ExampleMutex uses a mutual exclusion lock through `Mutex` for concurrent service coordination. Concurrency helpers mirror the stdlib shapes while keeping ownership in core.

var mu Mutex
mu.Lock()
Println("locked")
mu.Unlock()
Println("unlocked")
Output:
locked
unlocked

func (*Mutex) Lock

func (m *Mutex) Lock()

Lock acquires the mutex.

var mu core.Mutex
mu.Lock()
defer mu.Unlock()
Example

ExampleWaitGroup waits for concurrent work through `WaitGroup` for concurrent service coordination. Concurrency helpers mirror the stdlib shapes while keeping ownership in core. ExampleMutex_Lock acquires exclusive access through `Mutex.Lock`.

var mu Mutex
mu.Lock()
defer mu.Unlock()
// critical section

func (*Mutex) TryLock

func (m *Mutex) TryLock() Result

TryLock attempts to acquire the mutex without blocking. Returns Result{OK: true} on acquire, Result{OK: false} if already held.

if c.mu.TryLock().OK {
    defer c.mu.Unlock()
    // ...
}
Example

ExampleMutex_TryLock attempts a non-blocking write lock through `Mutex.TryLock` for concurrent service coordination. Concurrency helpers mirror the stdlib shapes while keeping ownership in core.

var mu Mutex
if mu.TryLock().OK {
	Println("acquired")
	mu.Unlock()
}
Output:
acquired

func (*Mutex) Unlock

func (m *Mutex) Unlock()

Unlock releases the mutex.

var mu core.Mutex
mu.Lock()
mu.Unlock()
Example

ExampleMutex_Unlock releases exclusive access through `Mutex.Unlock`.

var mu Mutex
mu.Lock()
mu.Unlock()

type NullBool

type NullBool = sql.NullBool

NullBool is sql.NullBool — bool column that may be NULL.

enabled := core.NullBool{Bool: true, Valid: true}
if enabled.Valid && enabled.Bool { core.Println("enabled") }

type NullFloat64

type NullFloat64 = sql.NullFloat64

NullFloat64 is sql.NullFloat64 — float64 column that may be NULL.

progress := core.NullFloat64{Float64: 0.75, Valid: true}
if progress.Valid { core.Println(progress.Float64) }

type NullInt64

type NullInt64 = sql.NullInt64

NullInt64 is sql.NullInt64 — int64 column that may be NULL.

count := core.NullInt64{Int64: 42, Valid: true}
if count.Valid { core.Println(count.Int64) }

type NullString

type NullString = sql.NullString

NullString is sql.NullString — string column that may be NULL.

name := core.NullString{String: "codex", Valid: true}
if name.Valid { core.Println(name.String) }
Example

ExampleNullString declares a nullable string through `NullString` for database adapter setup. Database opening and sentinel checks use aliases without importing database/sql directly.

value := NullString{String: "optional", Valid: true}
Println(value.String)
Println(value.Valid)
Output:
optional
true

type NullTime

type NullTime = sql.NullTime

NullTime is sql.NullTime — time.Time column that may be NULL.

seen := core.NullTime{Time: core.Now(), Valid: true}
if seen.Valid { core.Println(core.TimeFormat(seen.Time, "2006-01-02")) }

type OSFile

type OSFile = os.File

OSFile is an alias for os.File.

r := core.Create("agent.log")
if r.OK { file := r.Value.(*core.OSFile); _ = file }

type Once

type Once struct {
	// contains filtered or unexported fields
}

Once runs a function exactly once across all callers.

type Service struct {
    initOnce core.Once
    ready    bool
}

func (s *Service) ensure() {
    s.initOnce.Do(func() { s.ready = true })
}
Example

ExampleOnce runs work once through `Once` for concurrent service coordination. Concurrency helpers mirror the stdlib shapes while keeping ownership in core.

var o Once
o.Do(func() { Println("ran") })
o.Do(func() { Println("not printed") })
Output:
ran

func (*Once) Do

func (o *Once) Do(fn func())

Do calls the function fn if and only if Do is being called for the first time for this instance of Once.

var once core.Once
once.Do(func() { core.Println("agent init") })
Example

ExampleOnce_Do runs an initialiser exactly once through `Once.Do`.

var once Once
for i := 0; i < 3; i++ {
	once.Do(func() { Println("init") })
}
Output:
init

func (*Once) Reset

func (o *Once) Reset()

Reset clears the once so Do can fire again. Use for re-initialisation patterns where the resource is closed and re-opened.

s.closeStateStore()
s.initOnce.Reset()  // next Do() runs the init function again

Semantics match stdlib sync.Once{} reset: the previous Once is replaced outright. If a Do(fn) is concurrently in flight, behaviour is undefined — callers must serialise Reset against any concurrent Do calls.

Example

ExampleOnce_Reset resets one-shot state through `Once.Reset` for concurrent service coordination. Concurrency helpers mirror the stdlib shapes while keeping ownership in core.

var o Once
o.Do(func() { Println("first") })
o.Reset()
o.Do(func() { Println("again") })
Output:
first
again

type Option

type Option struct {
	Key   string
	Value any
}

Option is a single key-value configuration pair.

core.Option{Key: "name", Value: "brain"}
core.Option{Key: "port", Value: 8080}
Example

ExampleOption declares a key-value option through `Option` for agent options. Options carry loosely typed inputs while typed accessors keep call sites small.

opt := Option{Key: "port", Value: 8080}
Println(opt.Key)
Println(opt.Value)
Output:
port
8080

type Options

type Options struct {
	// contains filtered or unexported fields
}

Options is the universal input type for Core operations. A structured collection of key-value pairs with typed accessors.

opts := core.NewOptions(
    core.Option{Key: "name", Value: "myapp"},
    core.Option{Key: "port", Value: 8080},
)
name := opts.String("name")

func NewOptions

func NewOptions(items ...Option) Options

NewOptions creates an Options collection from key-value pairs.

opts := core.NewOptions(
    core.Option{Key: "name", Value: "brain"},
    core.Option{Key: "path", Value: "prompts"},
)
Example
opts := NewOptions(
	Option{Key: "name", Value: "brain"},
	Option{Key: "port", Value: 8080},
	Option{Key: "debug", Value: true},
)
Println(opts.String("name"))
Println(opts.Int("port"))
Println(opts.Bool("debug"))
Output:
brain
8080
true
Example (WithItems)

ExampleNewOptions_withItems loads initial items through `NewOptions` for agent options. Options carry loosely typed inputs while typed accessors keep call sites small.

opts := NewOptions(
	Option{Key: "name", Value: "api"},
	Option{Key: "port", Value: 8080},
)
Println(opts.Len())
Output:
2

func (Options) Bool

func (o Options) Bool(key string) bool

Bool retrieves a bool value, false if missing.

debug := opts.Bool("debug")
Example

ExampleOptions_Bool reads a boolean through `Options.Bool` for agent options. Options carry loosely typed inputs while typed accessors keep call sites small.

opts := NewOptions(Option{Key: "debug", Value: true})
Println(opts.Bool("debug"))
Output:
true

func (Options) Duration

func (o Options) Duration(key string) Duration

Duration retrieves a Duration value, 0 if missing or wrong type. Accepts a Duration directly or a string parsed via ParseDuration.

timeout := opts.Duration("timeout")
Example

ExampleOptions_Duration reads a duration option through `Options.Duration`.

opts := NewOptions(Option{Key: "timeout", Value: Second})
Println(opts.Duration("timeout"))
Output:
1s

func (Options) Float64

func (o Options) Float64(key string) float64

Float64 retrieves a float64 value, 0 if missing or wrong type. Promotes int/int64 to float64 so JSON-decoded numbers work uniformly.

weight := opts.Float64("weight")
Example

ExampleOptions_Items returns all entries through `Options.Items` for agent options. Options carry loosely typed inputs while typed accessors keep call sites small. ExampleOptions_Float64 reads a float option through `Options.Float64`.

opts := NewOptions(Option{Key: "ratio", Value: 0.5})
Println(opts.Float64("ratio"))
Output:
0.5

func (Options) Get

func (o Options) Get(key string) Result

Get retrieves a value by key.

r := opts.Get("name")
if r.OK { name := r.Value.(string) }
Example

ExampleOptions_Get retrieves a value through `Options.Get` for agent options. Options carry loosely typed inputs while typed accessors keep call sites small.

opts := NewOptions(Option{Key: "name", Value: "api"})
r := opts.Get("name")
Println(r.Value)
Println(opts.Get("missing").OK)
Output:
api
false

func (Options) Has

func (o Options) Has(key string) bool

Has returns true if a key exists.

if opts.Has("debug") { ... }
Example

ExampleOptions_Has checks for a value through `Options.Has` for agent options. Options carry loosely typed inputs while typed accessors keep call sites small.

opts := NewOptions(Option{Key: "debug", Value: true})
Println(opts.Has("debug"))
Output:
true

func (Options) Int

func (o Options) Int(key string) int

Int retrieves an int value, 0 if missing.

port := opts.Int("port")
Example

ExampleOptions_Int reads an integer through `Options.Int` for agent options. Options carry loosely typed inputs while typed accessors keep call sites small.

opts := NewOptions(Option{Key: "port", Value: 8080})
Println(opts.Int("port"))
Output:
8080

func (Options) Items

func (o Options) Items() []Option

Items returns a copy of the underlying option slice.

opts := core.NewOptions(core.Option{Key: "agent", Value: "codex"})
items := opts.Items()
core.Println(items[0].Key)
Example
opts := NewOptions(Option{Key: "name", Value: "api"})
items := opts.Items()
items[0].Value = "worker"

Println(opts.String("name"))
Println(items[0].Value)
Output:
api
worker

func (Options) Len

func (o Options) Len() int

Len returns the number of options.

opts := core.NewOptions(core.Option{Key: "agent", Value: "codex"})
count := opts.Len()
core.Println(count)
Example

ExampleOptions_Len counts entries through `Options.Len` for agent options. Options carry loosely typed inputs while typed accessors keep call sites small.

opts := NewOptions(Option{Key: "name", Value: "api"})
Println(opts.Len())
Output:
1

func (*Options) Set

func (o *Options) Set(key string, value any)

Set adds or updates a key-value pair.

opts.Set("port", 8080)
Example

ExampleOptions_Set sets a value through `Options.Set` for agent options. Options carry loosely typed inputs while typed accessors keep call sites small.

opts := NewOptions()
opts.Set("name", "api")
opts.Set("name", "worker")
Println(opts.String("name"))
Println(opts.Len())
Output:
worker
1

func (Options) String

func (o Options) String(key string) string

String retrieves a string value, empty string if missing.

name := opts.String("name")
Example

ExampleOptions_String renders `Options.String` as a stable string for agent options. Options carry loosely typed inputs while typed accessors keep call sites small.

opts := NewOptions(Option{Key: "name", Value: "api"})
Println(opts.String("name"))
Output:
api

type Ordered

type Ordered = cmp.Ordered

Ordered is the canonical ordered constraint for Core generic helpers. Alias of cmp.Ordered so consumers stay on the core surface.

func sortAgents[T core.Ordered](xs []T) { core.SliceSort(xs) }

type PacketConn

type PacketConn = net.PacketConn

PacketConn is a connectionless packet-oriented connection (UDP, etc.).

r := core.NetListenPacket("udp", "127.0.0.1:0")
if !r.OK { return r }
pc := r.Value.(core.PacketConn)
defer pc.Close()

type PathWalkDirFunc

type PathWalkDirFunc = WalkDirFunc

PathWalkDirFunc visits one path during a directory walk.

fn := func(path string, d core.FsDirEntry, err error) error { return err }
_ = fn

type PathWalkFunc

type PathWalkFunc = filepath.WalkFunc

PathWalkFunc visits one path during a filesystem walk.

var fn core.PathWalkFunc
_ = fn

type PinnedView added in v0.10.3

type PinnedView struct {
	// contains filtered or unexported fields
}

PinnedView pins a Go slice to a stable address so its first-element pointer can be safely handed to C across the cgo boundary. The GC is prevented from moving the backing array while the view is held, which lets C callers retain the pointer beyond a single call (e.g. async kernels, model weights mlx keeps a reference to). Always pair with Release; the pinner table holds the slice live until then.

Use for slices that:

  • C may retain across more than one cgo invocation, OR
  • are large enough that copy-into-C-memory dominates the call.

For one-shot reads where C consumes the pointer during the call, the cgo runtime already prevents GC movement — use unsafe.SliceData / unsafe.Pointer directly without a PinnedView.

SAFETY CONTRACT:

  • The slice must NOT contain Go pointers (only numeric/byte elements). cgo memory rules forbid passing nested Go pointers through C; runtime.Pinner will panic in race mode if violated.
  • The slice must outlive every C use of Ptr(). Caller owns lifetime; PinnedView keeps the slice live, but does not own it. Don't reslice or grow the source after pinning.
  • Release exactly once. Double-release is a no-op; missing release leaks the pin until process exit.

Example:

var view core.PinnedView
core.PinSlice(weights, &view)
defer view.Release()
C.kernel_run(view.Ptr(), C.size_t(view.Bytes()))

func (*PinnedView) Active added in v0.10.3

func (p *PinnedView) Active() bool

Active reports whether the view holds a live pin.

Example

ExamplePinnedView_Active reports whether the view holds a live pin through `PinnedView.Active`.

var view PinnedView
PinSlice([]int32{1}, &view)
defer view.Release()
Println(view.Active())
Output:
true

func (*PinnedView) Bytes added in v0.10.3

func (p *PinnedView) Bytes() int

Bytes returns the byte length of the pinned slice.

Example

ExamplePinnedView_Bytes returns the pinned byte length through `PinnedView.Bytes`.

var view PinnedView
PinSlice([]int32{1, 2, 3, 4}, &view)
defer view.Release()
Println(view.Bytes())
Output:
16

func (*PinnedView) Len added in v0.10.3

func (p *PinnedView) Len() int

Len returns the element count of the pinned slice.

Example

ExamplePinnedView_Len returns the pinned element count through `PinnedView.Len`.

var view PinnedView
PinSlice([]int32{1, 2, 3}, &view)
defer view.Release()
Println(view.Len())
Output:
3

func (*PinnedView) Ptr added in v0.10.3

func (p *PinnedView) Ptr() unsafe.Pointer

Ptr returns the pinned start-of-slice pointer for C consumption. Returns nil on a zero or released view.

Example

ExamplePinnedView_Ptr returns the pinned start-of-slice pointer through `PinnedView.Ptr`.

var view PinnedView
PinSlice([]int32{1, 2, 3}, &view)
defer view.Release()
_ = view.Ptr() // hand to C across the cgo boundary

func (*PinnedView) Release added in v0.10.3

func (p *PinnedView) Release()

Release unpins the slice. Safe to call on a zero view or repeatedly.

Example

ExamplePinnedView_Release unpins the slice through `PinnedView.Release`.

var view PinnedView
PinSlice([]int32{1}, &view)
view.Release()
Println(view.Active())
Output:
false

type Policy added in v0.12.0

type Policy struct {
	// contains filtered or unexported fields
}

Policy is a declarative entitlement rulebook: exact action names or "prefix.*" globs mapping to "allow", "deny", or an integer quota. Checker gates at Action.Run; Recorder decrements consumption through the metering loop — wire both and quotas enforce themselves. Unruled actions default to allowed (rules restrict, absence permits).

p := core.NewPolicy(core.NewOptions(
    core.Option{Key: "agentic.*", Value: "allow"},
    core.Option{Key: "admin.purge", Value: "deny"},
    core.Option{Key: "ai.credits", Value: 100},
))
c.SetEntitlementChecker(p.Checker())
c.SetUsageRecorder(p.Recorder())

func NewPolicy added in v0.12.0

func NewPolicy(rules Options) *Policy

NewPolicy builds a Policy from a rule set. Rule values: "allow", "deny", or an int quota. Exact keys beat globs; longer globs beat shorter ones.

p := core.NewPolicy(core.NewOptions(core.Option{Key: "admin.*", Value: "deny"}))
Example

ExampleNewPolicy declares entitlements as data: allow, deny, quota.

p := NewPolicy(NewOptions(
	Option{Key: "agentic.*", Value: "allow"},
	Option{Key: "admin.purge", Value: "deny"},
	Option{Key: "ai.credits", Value: 100},
))
Println(p.Checker()("admin.purge", 1, Background()).Allowed)
Output:
false

func (*Policy) Checker added in v0.12.0

func (p *Policy) Checker() EntitlementChecker

Checker returns the EntitlementChecker enforcing this policy.

c.SetEntitlementChecker(p.Checker())
Example

ExamplePolicy_Checker gates actions; quota rules carry live telemetry.

p := NewPolicy(NewOptions(Option{Key: "ai.credits", Value: 100}))
e := p.Checker()("ai.credits", 1, Background())
Println(e.Allowed, e.Remaining)
Output:
true 100

func (*Policy) Recorder added in v0.12.0

func (p *Policy) Recorder() UsageRecorder

Recorder returns the UsageRecorder that decrements quotas — pair it with Checker via SetUsageRecorder so successful gated actions consume.

c.SetUsageRecorder(p.Recorder())
Example

ExamplePolicy_Recorder pairs with Checker so successful gated actions consume quota through the metering loop.

p := NewPolicy(NewOptions(Option{Key: "ai.credits", Value: 100}))
p.Recorder()("ai.credits", 25, Background())
Println(p.Checker()("ai.credits", 1, Background()).Remaining)
Output:
75

type Pool added in v0.11.0

type Pool[T any] struct {
	// contains filtered or unexported fields
}

Pool is a concurrency-safe LIFO free-list of reusable T values — the zero-alloc recycling primitive behind hot-path scratch buffers and device handles. Get pops a recycled value (or the zero T when empty, so the caller builds a fresh one); Put returns one for reuse. Unlike sync.Pool it never drops entries on GC, so a warm pool stays warm — the right trade when the pooled value owns a resource (a device buffer, a mapping) the caller Closes explicitly rather than letting the GC reclaim.

The zero Pool is ready to use. T is typically a pointer, so Get's empty sentinel (the zero T == nil) reads naturally at the call site:

var pool core.Pool[*scratch]
s := pool.Get()
if s == nil {
    s = newScratch()
}
defer pool.Put(s)

func (*Pool[T]) Get added in v0.11.0

func (p *Pool[T]) Get() T

Get pops and returns the most-recently-Put value, or the zero T when the pool is empty (the caller then builds a fresh one). LIFO keeps a small working set hot.

s := pool.Get()
if s == nil {
    s = newScratch()
}

func (*Pool[T]) Len added in v0.11.0

func (p *Pool[T]) Len() int

Len reports how many values are currently pooled — for diagnostics and tests.

core.Println(pool.Len())

func (*Pool[T]) Put added in v0.11.0

func (p *Pool[T]) Put(s T)

Put returns a value to the pool for reuse. The caller guards against pooling an invalid value (a nil pointer, a closed buffer) before calling Put — Pool is value-agnostic and stores whatever it is handed.

pool.Put(s)

type Process

type Process struct {
	// contains filtered or unexported fields
}

Process is the Core primitive for process management. Zero dependencies — delegates to named Actions.

c := core.New()
proc := c.Process()
if proc.Exists() {
    _ = proc.Run(Background(), "git", "status", "--short")
}

func (*Process) Exists

func (p *Process) Exists() bool

Exists returns true if any process execution capability is registered.

if c.Process().Exists() { /* can run commands */ }
Example

ExampleProcess_Exists checks whether process actions are registered before and after installation. Process launches and lifecycle controls flow through Core.Process.

c := New()
Println(c.Process().Exists())
c.Action("process.run", func(_ Context, _ Options) Result { return Result{OK: true} })
Println(c.Process().Exists())
Output:
false
true

func (*Process) Kill

func (p *Process) Kill(ctx Context, opts Options) Result

Kill terminates a managed process by ID or PID.

c.Process().Kill(ctx, core.NewOptions(core.Option{Key: "id", Value: processID}))
Example

ExampleProcess_Kill terminates a process through `Process.Kill` for managed process execution. Process launches and lifecycle controls flow through Core.Process.

c := New()
c.Action("process.kill", func(_ Context, opts Options) Result {
	return Result{Value: Concat("stopped:", opts.String("id")), OK: true}
})

r := c.Process().Kill(c.Context(), NewOptions(Option{Key: "id", Value: "worker"}))
Println(r.Value)
Output:
stopped:worker

func (*Process) Run

func (p *Process) Run(ctx Context, command string, args ...string) Result

Run executes a command synchronously and returns the output.

r := c.Process().Run(ctx, "git", "log", "--oneline")
if r.OK { output := r.Value.(string) }
Example

ExampleProcess_Run runs `Process.Run` with representative caller inputs for managed process execution. Process launches and lifecycle controls flow through Core.Process.

c := New()
c.Action("process.run", func(_ Context, opts Options) Result {
	return Result{Value: Join(" ", append([]string{opts.String("command")}, opts.Get("args").Value.([]string)...)...), OK: true}
})

r := c.Process().Run(c.Context(), "go", "test", "./...")
Println(r.Value)
Output:
go test ./...

func (*Process) RunIn

func (p *Process) RunIn(ctx Context, dir string, command string, args ...string) Result

RunIn executes a command in a specific directory.

r := c.Process().RunIn(ctx, "/repo", "go", "test", "./...")
Example

ExampleProcess_RunIn runs a process in a chosen working directory through `Process.RunIn` for managed process execution. Process launches and lifecycle controls flow through Core.Process.

c := New()
c.Action("process.run", func(_ Context, opts Options) Result {
	return Result{Value: opts.String("dir"), OK: true}
})

r := c.Process().RunIn(c.Context(), "/repo", "go", "test")
Println(r.Value)
Output:
/repo

func (*Process) RunWithEnv

func (p *Process) RunWithEnv(ctx Context, dir string, env []string, command string, args ...string) Result

RunWithEnv executes with additional environment variables.

r := c.Process().RunWithEnv(ctx, dir, []string{"GOWORK=off"}, "go", "test")
Example

ExampleProcess_RunWithEnv runs a process with environment overrides through `Process.RunWithEnv` for managed process execution. Process launches and lifecycle controls flow through Core.Process.

c := New()
c.Action("process.run", func(_ Context, opts Options) Result {
	return Result{Value: opts.Get("env").Value.([]string)[0], OK: true}
})

r := c.Process().RunWithEnv(c.Context(), "/repo", []string{"GOWORK=off"}, "go", "test")
Println(r.Value)
Output:
GOWORK=off

func (*Process) Start

func (p *Process) Start(ctx Context, opts Options) Result

Start spawns a detached/background process.

r := c.Process().Start(ctx, ProcessStartOptions{Command: "docker", Args: []string{"run", "..."}})
Example

ExampleProcess_Start starts a process through `Process.Start` for managed process execution. Process launches and lifecycle controls flow through Core.Process.

c := New()
c.Action("process.start", func(_ Context, opts Options) Result {
	return Result{Value: opts.String("id"), OK: true}
})

r := c.Process().Start(c.Context(), NewOptions(Option{Key: "id", Value: "worker"}))
Println(r.Value)
Output:
worker

type Query

type Query any

Query is the type for read-only IPC requests.

c := core.New()
var query core.Query = core.NewOptions(core.Option{Key: "name", Value: "agent"})
_ = c.Query(query)
Example

ExampleQuery runs or declares a query through `Query` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

var q Query = "status"
Println(q)
Output:
status

type QueryHandler

type QueryHandler func(*Core, Query) Result

QueryHandler handles Query requests. Returns Result{Value, OK}.

handler := func(c *core.Core, q core.Query) core.Result {
    opts := q.(core.Options)
    return core.Result{Value: opts.String("name"), OK: true}
}
core.New().RegisterQuery(core.QueryHandler(handler))
Example

ExampleQueryHandler declares a query handler contract through `QueryHandler` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

var handler QueryHandler = func(_ *Core, q Query) Result {
	return Result{Value: Concat("query:", q.(string)), OK: true}
}
Println(handler(New(), "status").Value)
Output:
query:status

type RWMutex

type RWMutex struct {
	// contains filtered or unexported fields
}

RWMutex is a read-write mutex. Many readers OR one writer.

type Cache struct {
    mu   core.RWMutex
    data map[string]string
}

func (c *Cache) Get(k string) string {
    c.mu.RLock(); defer c.mu.RUnlock()
    return c.data[k]
}

func (c *Cache) Set(k, v string) {
    c.mu.Lock(); defer c.mu.Unlock()
    c.data[k] = v
}
Example

ExampleRWMutex uses a read-write lock through `RWMutex` for concurrent service coordination. Concurrency helpers mirror the stdlib shapes while keeping ownership in core.

var mu RWMutex
mu.RLock()
Println("read-locked")
mu.RUnlock()
mu.Lock()
Println("write-locked")
mu.Unlock()
Output:
read-locked
write-locked

func (*RWMutex) Lock

func (m *RWMutex) Lock()

Lock acquires the mutex for write (exclusive).

var mu core.RWMutex
mu.Lock()
defer mu.Unlock()
Example

ExampleRWMutex_Lock acquires the write lock through `RWMutex.Lock`.

var mu RWMutex
mu.Lock()
defer mu.Unlock()
// exclusive write section

func (*RWMutex) RLock

func (m *RWMutex) RLock()

RLock acquires the mutex for read (shared).

var mu core.RWMutex
mu.RLock()
defer mu.RUnlock()
Example

ExampleRWMutex_RLock acquires a shared read lock through `RWMutex.RLock`.

var mu RWMutex
mu.RLock()
defer mu.RUnlock()
// concurrent read section

func (*RWMutex) RUnlock

func (m *RWMutex) RUnlock()

RUnlock releases the mutex from read.

var mu core.RWMutex
mu.RLock()
mu.RUnlock()
Example

ExampleRWMutex_RUnlock releases a shared read lock through `RWMutex.RUnlock`.

var mu RWMutex
mu.RLock()
mu.RUnlock()

func (*RWMutex) TryLock

func (m *RWMutex) TryLock() Result

TryLock attempts to acquire the write mutex without blocking.

if c.mu.TryLock().OK { defer c.mu.Unlock() }
Example

ExampleRWMutex_TryLock attempts a non-blocking write lock through `RWMutex.TryLock` for concurrent service coordination. Concurrency helpers mirror the stdlib shapes while keeping ownership in core.

var mu RWMutex
if mu.TryLock().OK {
	Println("write")
	mu.Unlock()
}
Output:
write

func (*RWMutex) TryRLock

func (m *RWMutex) TryRLock() Result

TryRLock attempts to acquire the read mutex without blocking.

if c.mu.TryRLock().OK { defer c.mu.RUnlock() }
Example

ExampleRWMutex_TryRLock attempts a non-blocking read lock through `RWMutex.TryRLock` for concurrent service coordination. Concurrency helpers mirror the stdlib shapes while keeping ownership in core.

var mu RWMutex
if mu.TryRLock().OK {
	Println("read")
	mu.RUnlock()
}
Output:
read

func (*RWMutex) Unlock

func (m *RWMutex) Unlock()

Unlock releases the mutex from write.

var mu core.RWMutex
mu.Lock()
mu.Unlock()
Example

ExampleRWMutex_Unlock releases the write lock through `RWMutex.Unlock`.

var mu RWMutex
mu.Lock()
mu.Unlock()

type RawMessage added in v0.10.0

type RawMessage = json.RawMessage

RawMessage is an alias for json.RawMessage — a deferred-decode JSON fragment. Lets HTTP / MCP / IPC handlers accept JSON parameters without committing to a concrete struct, then decode when the shape is known.

func HandleBridgeCall(args core.RawMessage) core.Result {
    var req DeployRequest
    if r := core.JSONUnmarshal(args, &req); !r.OK { return r }
    return core.Ok(req)
}
Example

ExampleRawMessage defers JSON decoding through the `RawMessage` alias for envelope-then-payload parsing. Serialisation and parsing return core Results for configuration payloads.

type envelope struct {
	Type string     `json:"type"`
	Data RawMessage `json:"data"`
}
var env envelope
JSONUnmarshal([]byte(`{"type":"ping","data":{"port":8080}}`), &env)
Println(env.Type)
Println(string(env.Data))
Output:
ping
{"port":8080}

type ReadCloser

type ReadCloser = io.ReadCloser

ReadCloser composes Reader and Closer.

r := core.HTTPGet("https://api.lethean.example/health")
if !r.OK { return r }
body := r.Value.(*core.Response).Body
var reader core.ReadCloser = body
defer reader.Close()

type ReadWriteCloser

type ReadWriteCloser = io.ReadWriteCloser

ReadWriteCloser composes Reader, Writer, and Closer.

a, b := core.NetPipe()
defer a.Close()
defer b.Close()
var rwc core.ReadWriteCloser = a
_ = rwc

type ReadWriter

type ReadWriter = io.ReadWriter

ReadWriter composes Reader and Writer.

buf := core.NewBufferString("agent payload")
var rw core.ReadWriter = buf
core.WriteString(rw, " acknowledged")

type Reader

type Reader = io.Reader

Reader is the canonical io.Reader interface, exported as core.Reader.

var reader core.Reader = core.NewReader("agent payload")
r := core.Copy(core.Stdout(), reader)
if !r.OK { return r }
Example

ExampleReader declares a reader through `Reader` for streaming payloads. Stream copying, EOF checks, and writes avoid direct io imports in consumers.

var r Reader = NewReader("hello")
data := ReadAll(r)
Println(data.Value)
Output:
hello

func LimitReader added in v0.10.0

func LimitReader(r Reader, n int64) Reader

LimitReader returns a Reader that reads from r but stops with EOF after n bytes. Useful for bounding HTTP body reads at a maximum size to prevent memory blow-ups from oversized responses.

body := core.ReadAll(core.LimitReader(resp.Body, 4<<20))
if !body.OK { return body }
bytes := body.Value.([]byte)
Example

ExampleLimitReader bounds a stream read at n bytes through `LimitReader` for streaming payloads. Pair with ReadAll to cap HTTP body reads at a safe maximum size.

src := NewReader("hello world")
bounded := LimitReader(src, 5)
r := ReadAll(bounded)
Println(r.Value)
Output:
hello

func Stdin

func Stdin() Reader

Stdin returns the canonical standard input stream as an io.Reader.

scanner := core.NewLineScanner(core.Stdin())
Example

ExampleStdin reads standard input through `Stdin` for process IO access. File modes and standard streams are exposed through core aliases.

Println(Stdin() != nil)
Output:
true

type Regexp

type Regexp struct {
	// contains filtered or unexported fields
}

Regexp is a compiled regular expression. Construct with Regex(pattern). Named Regexp (matching stdlib) so the package-level constructor can be the bare verb Regex.

r := core.Regex(`agent-[0-9]+`)
if !r.OK { return r }
rx := r.Value.(*core.Regexp)
core.Println(rx.String())

func (*Regexp) FindAllString

func (r *Regexp) FindAllString(s string, n int) []string

FindAllString returns successive matches. n controls max matches; n<0 means all.

rx.FindAllString("a1 b2 c3", -1)  // ["1","2","3"]
Example

ExampleRegexp_FindAllString finds all string matches through `Regexp.FindAllString` for route parsing. Compiled patterns expose common matching and replacement operations through core wrappers.

rx := Regex(`\d+`).Value.(*Regexp)
Println(rx.FindAllString("a1 b22 c333", -1))
Output:
[1 22 333]

func (*Regexp) FindString

func (r *Regexp) FindString(s string) string

FindString returns the leftmost match in s, or "" if none.

rx.FindString("hello 42 world")  // "42"
Example

ExampleRegexp_FindString returns the leftmost match through `Regexp.FindString`.

rx := Regex(`\d+`).Value.(*Regexp)
Println(rx.FindString("abc123def"))
Output:
123

func (*Regexp) FindStringSubmatch

func (r *Regexp) FindStringSubmatch(s string) []string

FindStringSubmatch returns the leftmost match plus its submatches, or nil if no match.

rx := core.Regex(`(\w+)=(\d+)`).Value.(*core.Regexp)
rx.FindStringSubmatch("count=42")  // ["count=42", "count", "42"]
Example

ExampleRegexp_FindStringSubmatch captures submatches through `Regexp.FindStringSubmatch` for route parsing. Compiled patterns expose common matching and replacement operations through core wrappers.

rx := Regex(`(\w+)=(\d+)`).Value.(*Regexp)
Println(rx.FindStringSubmatch("port=8080"))
Output:
[port=8080 port 8080]

func (*Regexp) MatchString

func (r *Regexp) MatchString(s string) bool

MatchString reports whether s contains any match.

rx.MatchString("foo123bar")  // true
Example

ExampleRegexp_String renders `Regexp.String` as a stable string for route parsing. Compiled patterns expose common matching and replacement operations through core wrappers. ExampleRegexp_MatchString reports whether a string matches through `Regexp.MatchString`.

rx := Regex(`\d+`).Value.(*Regexp)
Println(rx.MatchString("abc123"))
Output:
true

func (*Regexp) ReplaceAllString

func (r *Regexp) ReplaceAllString(s, repl string) string

ReplaceAllString returns a copy of s with all matches replaced by repl.

rx.ReplaceAllString("a1b2", "X")  // "aXbX"
Example

ExampleRegexp_ReplaceAllString replaces matches through `Regexp.ReplaceAllString` for route parsing. Compiled patterns expose common matching and replacement operations through core wrappers.

rx := Regex(`\d+`).Value.(*Regexp)
Println(rx.ReplaceAllString("api:8080 admin:9090", "PORT"))
Output:
api:PORT admin:PORT

func (*Regexp) Split

func (r *Regexp) Split(s string, n int) []string

Split splits s into substrings separated by the regex. n<0 means all.

rx := core.Regex(`,+`).Value.(*core.Regexp)
rx.Split("a,b,,c", -1)  // ["a","b","c"]
Example

ExampleRegexp_Split splits text through `Regexp.Split` for route parsing. Compiled patterns expose common matching and replacement operations through core wrappers.

rx := Regex(`,+`).Value.(*Regexp)
Println(rx.Split("alpha,bravo,,charlie", -1))
Output:
[alpha bravo charlie]

func (*Regexp) String

func (r *Regexp) String() string

String returns the source pattern.

r := core.Regex(`agent-[0-9]+`)
if !r.OK { return r }
pattern := r.Value.(*core.Regexp).String()
core.Println(pattern)
Example
rx := Regex(`\d+`).Value.(*Regexp)
Println(rx.String())
Output:
\d+

type Registry

type Registry[T any] struct {
	// contains filtered or unexported fields
}

Registry is a thread-safe named collection. The universal brick for all named registries in Core.

r := core.NewRegistry[*Service]()
r.Set("brain", svc)
if r.Has("brain") { ... }

func NewRegistry

func NewRegistry[T any]() *Registry[T]

NewRegistry creates an empty registry in Open mode.

r := core.NewRegistry[*Service]()
Example
r := NewRegistry[string]()
r.Set("alpha", "first")
r.Set("bravo", "second")

Println(r.Has("alpha"))
Println(r.Names())
Println(r.Len())
Output:
true
[alpha bravo]
2
Example (Registry)

ExampleNewRegistry_registry constructs a registry through `NewRegistry` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
Println(r.Len())
Output:
0

func (*Registry[T]) Delete

func (r *Registry[T]) Delete(name string) Result

Delete removes an item. Returns Result{OK: false} if locked or not found.

r.Delete("old-service")
Example

ExampleRegistry_Delete deletes a value through `Registry.Delete` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("temp", "value")
Println(r.Has("temp"))

r.Delete("temp")
Println(r.Has("temp"))
Output:
true
false

func (*Registry[T]) Disable

func (r *Registry[T]) Disable(name string) Result

Disable soft-disables an item. It still exists but Get/Has/List/Each skip it, so it cannot be resolved or dispatched until Enable is called. Inspect or re-enable it via GetIncludingDisabled / Disabled. Returns Result{OK: false} if not found.

r.Disable("broken-handler")
Example

ExampleRegistry_Disable hides a registered name from iteration without deleting it. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("alpha", "first")
r.Set("bravo", "second")
r.Disable("alpha")

var names []string
r.Each(func(name string, _ string) { names = append(names, name) })
Println(names)
Output:
[bravo]

func (*Registry[T]) Disabled

func (r *Registry[T]) Disabled(name string) bool

Disabled returns true if the item is soft-disabled.

r := core.NewRegistry[string]()
r.Set("agent", "codex")
r.Disable("agent")
if r.Disabled("agent") { core.Println("disabled") }
Example

ExampleRegistry_Disabled checks disabled state through `Registry.Disabled` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("alpha", "first")
r.Disable("alpha")
Println(r.Disabled("alpha"))
Output:
true

func (*Registry[T]) Each

func (r *Registry[T]) Each(fn func(string, T))

Each iterates over all items in insertion order, calling fn for each. Disabled items are skipped.

r.Each(func(name string, svc *Service) {
    fmt.Println(name, svc)
})
Example

ExampleRegistry_Each iterates entries through `Registry.Each` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[int]()
r.Set("a", 1)
r.Set("b", 2)
r.Set("c", 3)

sum := 0
r.Each(func(_ string, v int) { sum += v })
Println(sum)
Output:
6

func (*Registry[T]) Enable

func (r *Registry[T]) Enable(name string) Result

Enable re-enables a disabled item.

r.Enable("fixed-handler")
Example

ExampleRegistry_Enable restores a disabled registry entry to normal iteration. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("alpha", "first")
r.Disable("alpha")
Println(r.Disabled("alpha"))
r.Enable("alpha")
Println(r.Disabled("alpha"))
Output:
true
false

func (*Registry[T]) Get

func (r *Registry[T]) Get(name string) Result

Get retrieves an item by name. A soft-disabled item resolves as absent (Result{OK:false}) so dispatch and resolution skip it — use GetIncludingDisabled to inspect or re-enable a disabled entry.

res := r.Get("brain")
if res.OK { svc := res.Value.(*Service) }
Example

ExampleRegistry_Get retrieves a value through `Registry.Get` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("alpha", "first")
Println(r.Get("alpha").Value)
Println(r.Get("missing").OK)
Output:
first
false

func (*Registry[T]) GetIncludingDisabled added in v0.11.0

func (r *Registry[T]) GetIncludingDisabled(name string) Result

GetIncludingDisabled retrieves an item by name even when it is soft-disabled. Get/Has treat a disabled entry as absent (so dispatch skips it); this variant is for inspection, re-enable, and registration existence-checks that must see every registered key.

res := r.GetIncludingDisabled("broken-handler")
Example

ExampleRegistry_GetIncludingDisabled resolves even soft-disabled entries through `Registry.GetIncludingDisabled`.

r := NewRegistry[string]()
r.Set("agent", "codex")
r.Disable("agent")
Println(r.Get("agent").OK)
Println(r.GetIncludingDisabled("agent").OK)
Output:
false
true

func (*Registry[T]) GetOrSet added in v0.11.0

func (r *Registry[T]) GetOrSet(name string, make func() T) Result

GetOrSet returns the existing item for name, or atomically stores and returns make() when the name is absent. make() runs only on a miss, so callers racing the first lookup converge on a single stored value (the LoadOrStore idiom). The common hit path takes only a read lock. Returns Result{OK: false} when the registry is sealed or locked and the key is new.

r := reg.GetOrSet("drain", func() *Lock { return &Lock{Name: "drain", Mutex: &RWMutex{}} })
lock := r.Value.(*Lock)
Example

ExampleRegistry_Open reopens a locked registry so later writes can succeed. Registries can list, lock, seal, disable, and reopen named services predictably. ExampleRegistry_GetOrSet returns an existing entry or creates one through `Registry.GetOrSet`.

r := NewRegistry[int]()
v := r.GetOrSet("count", func() int { return 5 })
Println(v.Value)
Output:
5

func (*Registry[T]) Has

func (r *Registry[T]) Has(name string) bool

Has returns true if the name exists and is enabled. A soft-disabled item reports false (consistent with Get); use GetIncludingDisabled to check raw existence regardless of disabled state.

if r.Has("brain") { ... }
Example

ExampleRegistry_Has checks for a value through `Registry.Has` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("alpha", "first")
Println(r.Has("alpha"))
Println(r.Has("missing"))
Output:
true
false

func (*Registry[T]) Len

func (r *Registry[T]) Len() int

Len returns the number of registered items (including disabled).

count := r.Len()
Example

ExampleRegistry_Len counts entries through `Registry.Len` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("alpha", "first")
r.Set("bravo", "second")
Println(r.Len())
Output:
2

func (*Registry[T]) List

func (r *Registry[T]) List(pattern string) []T

List returns items whose names match the glob pattern. Uses PathMatch semantics: "*" matches any sequence, "?" matches one char.

services := r.List("process.*")
Example

ExampleRegistry_List lists entries through `Registry.List` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("process.run", "run")
r.Set("process.kill", "kill")
r.Set("brain.recall", "recall")

items := r.List("process.*")
Println(len(items))
Output:
2

func (*Registry[T]) Lock

func (r *Registry[T]) Lock()

Lock fully freezes the registry. No Set, no Delete.

r.Lock() // after startup, prevent late registration
Example
r := NewRegistry[string]()
r.Set("alpha", "first")
r.Lock()

result := r.Set("beta", "second")
Println(result.OK)
Output:
false
Example (Freeze)

ExampleRegistry_Lock_freeze freezes registry mutation through `Registry.Lock` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("alpha", "first")
r.Lock()
Println(r.Locked())
Println(r.Set("bravo", "second").OK)
Output:
true
false

func (*Registry[T]) Locked

func (r *Registry[T]) Locked() bool

Locked returns true if the registry is fully frozen.

r := core.NewRegistry[string]()
r.Lock()
if r.Locked() { core.Println("locked") }
Example

ExampleRegistry_Locked checks locked state through `Registry.Locked` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
Println(r.Locked())
r.Lock()
Println(r.Locked())
Output:
false
true

func (*Registry[T]) Names

func (r *Registry[T]) Names() []string

Names returns all registered names in insertion order.

names := r.Names() // ["brain", "monitor", "process"]
Example

ExampleRegistry_Names lists names through `Registry.Names` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[int]()
r.Set("charlie", 3)
r.Set("alpha", 1)
r.Set("bravo", 2)
Println(r.Names())
Output:
[charlie alpha bravo]

func (*Registry[T]) Open

func (r *Registry[T]) Open()

Open resets the registry to open mode (default).

r.Open() // re-enable writes for testing
Example
r := NewRegistry[string]()
r.Lock()
r.Open()
Println(r.Locked())
Println(r.Set("alpha", "first").OK)
Output:
false
true

func (*Registry[T]) Seal

func (r *Registry[T]) Seal()

Seal prevents new keys but allows updates to existing keys. Use for hot-reload: shape is fixed, implementations can change.

r.Seal() // no new capabilities, but handlers can be swapped
Example
r := NewRegistry[string]()
r.Set("alpha", "first")
r.Seal()

// Can update existing
Println(r.Set("alpha", "updated").OK)
// Can't add new
Println(r.Set("beta", "new").OK)
Output:
true
false
Example (Shape)

ExampleRegistry_Seal_shape documents the sealed shape through `Registry.Seal` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("alpha", "first")
r.Seal()
Println(r.Sealed())
Println(r.Set("alpha", "updated").OK)
Println(r.Set("bravo", "second").OK)
Output:
true
true
false

func (*Registry[T]) Sealed

func (r *Registry[T]) Sealed() bool

Sealed returns true if the registry is sealed (no new keys).

r := core.NewRegistry[string]()
r.Set("agent", "codex")
r.Seal()
if r.Sealed() { core.Println("sealed") }
Example

ExampleRegistry_Sealed checks sealed state through `Registry.Sealed` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
Println(r.Sealed())
r.Seal()
Println(r.Sealed())
Output:
false
true

func (*Registry[T]) Set

func (r *Registry[T]) Set(name string, item T) Result

Set registers an item by name. Returns Result{OK: false} if the registry is locked, or if sealed and the key doesn't already exist.

r.Set("brain", brainSvc)
Example

ExampleRegistry_Set sets a value through `Registry.Set` for service registries. Registries can list, lock, seal, disable, and reopen named services predictably.

r := NewRegistry[string]()
r.Set("alpha", "first")
r.Set("bravo", "second")
Println(r.Get("alpha").Value)
Output:
first

type Reloadable added in v0.12.0

type Reloadable interface {
	OnReload(ctx Context) Result
}

Reloadable is implemented by services that support configuration reload. ServiceReload is the top-level runner; trigger it from a signal handler, a config watcher, or an admin action.

func (s *MyService) OnReload(ctx Context) core.Result {
    return s.reconnect(ctx)
}

type Request

type Request = http.Request

Request is the canonical HTTP request, exported as core.Request.

r := core.NewHTTPRequest("GET", "https://api.lethean.example/health", nil)
if !r.OK {
    return r
}
req := r.Value.(*core.Request)
req.Header.Set("User-Agent", "dappcore-agent/1.0")

func NewHTTPTestRequest

func NewHTTPTestRequest(method, target string, body Reader) *Request

NewHTTPTestRequest constructs an *http.Request suitable for handler tests. Wraps httptest.NewRequest with Result-shape — though httptest.NewRequest itself never errors, the Result shape keeps the API uniform with NewHTTPRequest.

req := core.NewHTTPTestRequest("GET", "/path", nil)
Example

ExampleNewHTTPTestRequest builds a request fixture for a status route. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

req := NewHTTPTestRequest("GET", "/status", nil)
Println(req.Method)
Println(req.URL.Path)
Output:
GET
/status

type Resolver

type Resolver = net.Resolver

Resolver looks up host names.

resolver := &core.Resolver{}
addrs, err := resolver.LookupHost(context.Background(), "api.lethean.example")
if err == nil { core.Println(core.Join(", ", addrs...)) }

type Response

type Response = http.Response

Response is the canonical HTTP response.

r := core.HTTPGet("https://api.lethean.example/health")
if !r.OK {
    return r
}
resp := r.Value.(*core.Response)
defer resp.Body.Close()

type ResponseWriter

type ResponseWriter = http.ResponseWriter

ResponseWriter is the canonical HTTP response-writer interface used by handlers.

handler := core.HandlerFunc(func(w core.ResponseWriter, r *core.Request) {
    core.WriteString(w, "ok\n")
})
_ = handler

type Result

type Result struct {
	Value any
	OK    bool
}

Result is the universal return type for Core operations. Replaces the (value, error) pattern — errors flow through Core internally.

r := c.Data().New(opts)
if !r.OK { core.Error("failed", "err", r.Error()) }
Example
r := Result{Value: "hello", OK: true}
if r.OK {
	Println(r.Value)
}
Output:
hello

func Arg

func Arg(index int, args ...any) Result

Arg extracts a value from variadic args at the given index. Type-checks and delegates to the appropriate typed extractor. Returns Result — OK is false if index is out of bounds.

r := core.Arg(0, args...)
if r.OK { path = r.Value.(string) }
Example

ExampleArg reads a positional argument through `Arg` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

r := Arg(1, "deploy", 8080, true)
Println(r.Value)
Println(Arg(9, "deploy").OK)
Output:
8080
false

func Atoi

func Atoi(s string) Result

Atoi converts a decimal string to an int.

r := core.Atoi("42")
if r.OK { n := r.Value.(int) }
Example

ExampleAtoi parses decimal text through `Atoi` for CLI argument conversion. Numeric parsing and formatting use core helpers for CLI-friendly values.

r := Atoi("42")
Println(r.Value)
Output:
42

func Base64Decode

func Base64Decode(s string) Result

Base64Decode decodes a standard base64 string into bytes.

r := core.Base64Decode("aGVsbG8=")
if r.OK { b := r.Value.([]byte) }
Example

ExampleBase64Decode decodes base64 text through `Base64Decode` for token and payload encoding. Byte and string encoders return predictable wrapper values for tokens and payloads.

r := Base64Decode("aGVsbG8=")
Println(string(r.Value.([]byte)))
Output:
hello

func Base64URLDecode

func Base64URLDecode(s string) Result

Base64URLDecode decodes a URL-safe base64 string into bytes.

r := core.Base64URLDecode("aGVsbG8=")
if r.OK { b := r.Value.([]byte) }
Example

ExampleBase64URLDecode decodes URL-safe base64 text through `Base64URLDecode` for token and payload encoding. Byte and string encoders return predictable wrapper values for tokens and payloads.

r := Base64URLDecode("aGVsbG8_")
Println(string(r.Value.([]byte)))
Output:
hello?

func Chdir

func Chdir(dir string) Result

Chdir changes the current working directory.

r := core.Chdir("/tmp")
Example

ExampleChdir changes the working directory through `Chdir`.

_ = Chdir(TempDir())

func Chmod added in v0.10.4

func Chmod(p string, mode FileMode) Result

Chmod changes the mode of the named file. Unlike c.Fs() operations this is unsandboxed boundary I/O — reach for it only when extracting archives or fixing up permissions outside a workspace root.

r := core.Chmod("bin/agent", 0o755)
Example

ExampleChmod sets a file's permission bits at the OS boundary, then reads them back through Stat. Chmod is the unsandboxed sibling of the c.Fs() permission helpers.

path := PathJoin(TempDir(), "core-example-chmod")
WriteFile(path, []byte("#!/bin/sh\n"), 0o644)
defer Remove(path)

Chmod(path, 0o755)
info := Stat(path)
Println(info.Value.(FsFileInfo).Mode().Perm() == 0o755)
Output:
true

func CliRegister

func CliRegister(c *Core) Result

Register creates a Cli service factory for core.WithService.

core.New(core.WithService(core.CliRegister))
Example

ExampleCliRegister wires the CLI action bridge into a Core through `CliRegister`.

_ = CliRegister(New(WithCli())) // r.OK once the CLI commands are registered

func Copy

func Copy(dst Writer, src Reader) Result

Copy copies from src to dst until EOF on src or an error occurs. Returns Result wrapping the number of bytes copied (int64).

r := core.Copy(dst, src)
if !r.OK { return r }
n := r.Value.(int64)
Example

ExampleCopy copies a stream through `Copy` for streaming payloads. Stream copying, EOF checks, and writes avoid direct io imports in consumers.

dst := NewBuffer()
r := Copy(dst, NewReader("hello"))
Println(r.Value)
Println(dst.String())
Output:
5
hello

func CopyN

func CopyN(dst Writer, src Reader, n int64) Result

CopyN copies n bytes (or until an error) from src to dst.

r := core.CopyN(dst, src, 1024)
Example

ExampleCopyN copies a bounded stream through `CopyN` for streaming payloads. Stream copying, EOF checks, and writes avoid direct io imports in consumers.

dst := NewBuffer()
r := CopyN(dst, NewReader("hello"), 2)
Println(r.Value)
Println(dst.String())
Output:
2
he

func Create

func Create(p string) Result

Create creates or truncates the named file.

r := core.Create("logs/agent.log")
if r.OK { file := r.Value.(*core.OSFile); _ = file }
Example

ExampleCreate creates or truncates a file through `Create`.

_ = Create(PathJoin(TempDir(), "new.txt"))

func CreateTemp added in v0.10.4

func CreateTemp(dir, pattern string) Result

CreateTemp creates and opens a new temporary file. A "*" in pattern is replaced by a random string; an empty dir uses TempDir(). The file-form sibling of MkdirTemp — close and remove it when done.

r := core.CreateTemp("", "openapi-*.json")
if r.OK { f := r.Value.(*core.OSFile); defer core.Remove(f.Name()) }
Example

ExampleCreateTemp creates a uniquely-named temp file through `CreateTemp`.

_ = CreateTemp(TempDir(), "ex-*")

func Executable added in v0.10.4

func Executable() Result

Executable returns the absolute path of the binary that started the current process. Use it to locate sibling assets shipped next to the binary; prefer Args()[0] only when the launch path itself matters.

r := core.Executable()
if r.OK { dir := core.PathDir(r.Value.(string)); _ = dir }
Example

ExampleExecutable returns the running binary's path through `Executable`.

_ = Executable()

func ExecuteTemplate

func ExecuteTemplate(t *Template, w Writer, data any) Result

ExecuteTemplate runs the template with the given data, writing to w.

r := core.ExecuteTemplate(tmpl, &buf, data)
if !r.OK { return r }
Example
tmpl := ParseTemplate("greeting", "hello {{.Name}}").Value.(*Template)
buf := NewBuffer()
r := ExecuteTemplate(tmpl, buf, map[string]string{"Name": "codex"})
Println(r.OK)
Println(buf.String())
Output:
true
hello codex

func Extract

func Extract(fsys FS, targetDir string, data any, opts ...ExtractOptions) Result

Extract copies a template directory from an FS to targetDir, processing Go text/template in filenames and file contents.

Files containing a template filter substring (default: ".tmpl") have their contents processed through text/template with the given data. The filter is stripped from the output filename.

Directory and file names can contain Go template expressions: {{.Name}}/main.go → myproject/main.go

Data can be any struct or map[string]string for template substitution.

fsys := core.DirFS("templates/agent")
data := map[string]string{"Name": "homelab"}
r := core.Extract(fsys, "/tmp/agent-workspace", data)
if !r.OK { return r }
Example

ExampleExtract extracts embedded files through `Extract` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
source := MustCast[string](fs.TempDir("core-extract-source"))
target := MustCast[string](fs.TempDir("core-extract-target"))
defer fs.DeleteAll(source)
defer fs.DeleteAll(target)

fs.Write(Path(source, "README.md.tmpl"), "hello {{.Name}}")
r := Extract(DirFS(source), target, map[string]string{"Name": "codex"})
Println(r.OK)
Println(fs.Read(Path(target, "README.md")).Value)
Output:
true
hello codex

func Fail

func Fail(err error) Result

Fail wraps err in a failed Result. The canonical "sad path" constructor — pair Result.Code() / Result.Error() to introspect. (Named Fail rather than Err to avoid colliding with the *Err type in error.go.)

if err := decode(b); err != nil { return core.Fail(err) }
Example

ExampleFail wraps an error in a failed Result through `Fail` for Result-based control flow. Success, fallback, casting, and error inspection all use the same Result shape.

r := Fail(NewError("boom"))
Println(r.OK)
Println(r.Error())
Output:
false
boom

func GeneratePack

func GeneratePack(pkg ScannedPackage) Result

GeneratePack creates Go source code that embeds the scanned assets.

pkg := core.ScannedPackage{PackageName: "agent", BaseDirectory: "./agent"}
r := core.GeneratePack(pkg)
if !r.OK { return r }
source := r.Value.(string)
core.Println(source)
Example

ExampleGeneratePack generates an asset pack through `GeneratePack` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-pack-example"))
defer fs.DeleteAll(dir)

fs.Write(Path(dir, "assets", "message.txt"), "hello")
fs.Write(Path(dir, "main.go"), `package sample

import core "dappco.re/go"

func message() string {
	return core.GetAsset("assets", "message.txt").Value.(string)
}
`)

scanned := ScanAssets([]string{Path(dir, "main.go")}).Value.([]ScannedPackage)
pack := GeneratePack(scanned[0])
source := pack.Value.(string)
Println(pack.OK)
Println(Contains(source, `core.AddAsset("assets", "message.txt"`))
Output:
true
true

func GetAsset

func GetAsset(group, name string) Result

GetAsset retrieves and decompresses a packed asset.

r := core.GetAsset("mygroup", "greeting")
if r.OK { content := r.Value.(string) }
Example

ExampleGetAsset retrieves an embedded asset through `GetAsset` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

AddAsset("example.asset", "hello.txt", "H4sIAAAAAAAC/8pIzcnJBwQAAP//hqYQNgUAAAA=")
r := GetAsset("example.asset", "hello.txt")
Println(r.Value)
Output:
hello

func GetAssetBytes

func GetAssetBytes(group, name string) Result

GetAssetBytes retrieves a packed asset as bytes.

r := core.GetAssetBytes("mygroup", "file")
if r.OK { data := r.Value.([]byte) }
Example

ExampleGetAssetBytes retrieves embedded asset bytes through `GetAssetBytes` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

AddAsset("example.bytes", "hello.txt", "H4sIAAAAAAAC/8pIzcnJBwQAAP//hqYQNgUAAAA=")
r := GetAssetBytes("example.bytes", "hello.txt")
Println(string(r.Value.([]byte)))
Output:
hello

func Getwd

func Getwd() Result

Getwd returns the current working directory.

r := core.Getwd()
Example

ExampleGetwd returns the working directory through `Getwd`.

_ = Getwd()

func HKDF

func HKDF(algo string, secret, salt, info []byte, length int) Result

HKDF derives length bytes from secret using salt, info, and algo wrapped in a Result. OK=false with Code "crypto.algo.unsupported" for unsupported algorithms or "crypto.hkdf.failed" on derivation failure.

r := core.HKDF("sha256", secret, salt, []byte("session"), 32)
if r.OK { sessionKey := r.Value.([]byte) }
Example

ExampleHKDF derives a session key from a master secret, salt, context label, and output length. Callers stay on the core wrapper surface while receiving fixed-size digests or Result values.

r := HKDF("sha256", []byte("secret"), []byte("salt"), []byte("session"), 32)
if r.OK {
	key := r.Value.([]byte)
	Println(len(key))
	Println(HexEncode(key)[:8])
}
Output:
32
2baf2709

func HMAC

func HMAC(algo string, key, data []byte) Result

HMAC returns the HMAC digest for data using key and algo wrapped in a Result. OK=false with Code "crypto.algo.unsupported" when algo isn't "sha256" or "sha512".

r := core.HMAC("sha256", []byte("key"), []byte("payload"))
if r.OK { digest := r.Value.([]byte) }
Example

ExampleHMAC signs a payload with a shared secret for session-token validation. Callers stay on the core wrapper surface while receiving fixed-size digests or Result values.

r := HMAC("sha256", []byte("secret"), []byte("payload"))
if r.OK {
	digest := r.Value.([]byte)
	Println(len(digest))
	Println(HexEncode(digest)[:8])
}
Output:
32
b82fcb79

func HTTPGet

func HTTPGet(url string) Result

HTTPGet performs an HTTP GET. Returns Result wrapping *Response on success or the error.

r := core.HTTPGet("https://api.example.com/health")
if !r.OK { return r }
defer r.Value.(*Response).Body.Close()
Example

ExampleHTTPGet fetches a local health endpoint through the core HTTP client wrapper for a Lethean drive integration. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

srv := NewHTTPTestServer(HandlerFunc(func(w ResponseWriter, _ *Request) {
	WriteString(w, "ok")
}))
defer srv.Close()

r := HTTPGet(srv.URL)
defer r.Value.(*Response).Body.Close()
body := ReadAll(r.Value.(*Response).Body)
Println(body.Value)
Output:
ok

func HTTPListenAndServe added in v0.10.0

func HTTPListenAndServe(addr string, handler Handler) Result

HTTPListenAndServe runs an HTTPServer on the given address with the given handler, blocking until the server stops. A graceful shutdown (ErrHTTPServerClosed) yields Result{OK: true}; any other error yields Result{OK: false} carrying it.

r := core.HTTPListenAndServe(":8080", mux)
if !r.OK {
    core.Error("listen", "err", r.Error())
}
Example

ExampleHTTPListenAndServe documents the function signature without actually starting a server (would block forever). In production, pair with a Shutdown call on signal.received via a goroutine.

mux := NewServeMux()
_ = HTTPListenAndServe // documented; not invoked
_ = mux

func HTTPPost

func HTTPPost(url, contentType string, body Reader) Result

HTTPPost performs an HTTP POST with the given content type and body.

r := core.HTTPPost(url, "application/json", body)
Example

ExampleHTTPPost sends a reader-backed payload through the core HTTP client wrapper for a Lethean drive integration. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

srv := NewHTTPTestServer(HandlerFunc(func(w ResponseWriter, _ *Request) {
	WriteString(w, "created")
}))
defer srv.Close()

r := HTTPPost(srv.URL, "text/plain", NewReader("payload"))
defer r.Value.(*Response).Body.Close()
body := ReadAll(r.Value.(*Response).Body)
Println(body.Value)
Output:
created

func HTTPPostForm

func HTTPPostForm(target string, data URLValues) Result

HTTPPostForm performs an HTTP POST with form-encoded values.

r := core.HTTPPostForm(url, core.URLValues{"key": {"value"}})
Example

ExampleHTTPPostForm submits form data through the core HTTP client wrapper for a Lethean drive integration. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

srv := NewHTTPTestServer(HandlerFunc(func(w ResponseWriter, _ *Request) {
	WriteString(w, "submitted")
}))
defer srv.Close()

r := HTTPPostForm(srv.URL, nil)
defer r.Value.(*Response).Body.Close()
body := ReadAll(r.Value.(*Response).Body)
Println(body.Value)
Output:
submitted

func HexDecode

func HexDecode(s string) Result

HexDecode decodes a hexadecimal string into bytes.

r := core.HexDecode("68656c6c6f")
if r.OK { b := r.Value.([]byte) }
Example

ExampleHexDecode decodes hex text through `HexDecode` for token and payload encoding. Byte and string encoders return predictable wrapper values for tokens and payloads.

r := HexDecode("68656c6c6f")
Println(string(r.Value.([]byte)))
Output:
hello

func Hostname

func Hostname() Result

Hostname returns the kernel host name.

r := core.Hostname()
Example

ExampleHostname returns the host name through `Hostname`.

_ = Hostname() // r.Value is the host name on success

func JSONMarshal

func JSONMarshal(v any) Result

JSONMarshal serialises a value to JSON bytes.

r := core.JSONMarshal(myStruct)
if r.OK { data := r.Value.([]byte) }
Example
type config struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}
r := JSONMarshal(config{Host: "localhost", Port: 8080})
Println(string(r.Value.([]byte)))
Output:
{"host":"localhost","port":8080}
Example (Config)

ExampleJSONMarshal_config initialises configuration values through `JSONMarshal` for configuration serialisation. Serialisation and parsing return core Results for configuration payloads.

type appConfig struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}
r := JSONMarshal(appConfig{Host: "localhost", Port: 8080})
Println(string(r.Value.([]byte)))
Output:
{"host":"localhost","port":8080}

func JSONMarshalIndent

func JSONMarshalIndent(v any, prefix, indent string) Result

JSONMarshalIndent serialises a value to indented JSON bytes.

r := core.JSONMarshalIndent(report, "", "  ")
if r.OK { data := r.Value.([]byte) }
Example

ExampleJSONMarshalIndent renders indented JSON through `JSONMarshalIndent`.

r := JSONMarshalIndent(map[string]int{"count": 3}, "", "  ")
Println(string(r.Value.([]byte)))
Output:
{
  "count": 3
}

func JSONUnmarshal

func JSONUnmarshal(data []byte, target any) Result

JSONUnmarshal deserialises JSON bytes into a target.

var cfg Config
r := core.JSONUnmarshal(data, &cfg)
Example

ExampleJSONUnmarshal parses JSON bytes through `JSONUnmarshal` for configuration serialisation. Serialisation and parsing return core Results for configuration payloads.

type appConfig struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}
var cfg appConfig
JSONUnmarshal([]byte(`{"host":"localhost","port":8080}`), &cfg)
Println(cfg.Host, cfg.Port)
Output:
localhost 8080

func JSONUnmarshalString

func JSONUnmarshalString(s string, target any) Result

JSONUnmarshalString deserialises a JSON string into a target.

var cfg Config
r := core.JSONUnmarshalString(`{"port":8080}`, &cfg)

Zero-copy: json.Unmarshal treats its input as read-only and does not alias the buffer into the unmarshalled values (Strings are copied via SetString), so AsBytes is safe here. Saves one alloc per call — load-bearing on JSONL hot paths (one call per dataset row, thousands per training run).

Example
type config struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}
var cfg config
JSONUnmarshalString(`{"host":"localhost","port":8080}`, &cfg)
Println(cfg.Host, cfg.Port)
Output:
localhost 8080
Example (Config)

ExampleJSONUnmarshalString_config initialises configuration values through `JSONUnmarshalString` for configuration serialisation. Serialisation and parsing return core Results for configuration payloads.

type appConfig struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}
var cfg appConfig
JSONUnmarshalString(`{"host":"localhost","port":8080}`, &cfg)
Println(cfg.Host, cfg.Port)
Output:
localhost 8080

func LSPServe

func LSPServe(ctx Context) Result

LSPServe starts the language server. Reads JSON-RPC messages from stdin and writes responses + notifications to stdout. Blocks until stdin closes (EOF) or ctx cancels.

core.LSPServe(core.Background())

Output is interleaved with diagnostic notifications; stderr remains available for log output. Editor clients connect via the standard stdio transport.

Example

ExampleLSPServe runs the language-server loop over stdio through `LSPServe`.

if false {
	LSPServe(Background()) // blocks serving LSP over stdin/stdout until ctx is cancelled
}

func Lstat

func Lstat(p string) Result

Lstat returns file information for p without following a final symlink.

r := core.Lstat("config/current")
Example

ExampleLstat returns link metadata without following it through `Lstat`.

_ = Lstat(PathJoin(TempDir(), "f"))

func Mkdir

func Mkdir(p string, mode FileMode) Result

Mkdir creates one directory.

r := core.Mkdir("logs", 0o755)
Example

ExampleMkdir creates a single directory through `Mkdir`.

_ = Mkdir(PathJoin(TempDir(), "newdir"), 0o755)

func MkdirAll

func MkdirAll(p string, mode FileMode) Result

MkdirAll creates a directory path and all missing parents.

r := core.MkdirAll("logs/agent", 0o755)
Example

ExampleMkdirAll creates a directory tree through `MkdirAll`.

_ = MkdirAll(PathJoin(TempDir(), "a", "b"), 0o755)

func MkdirTemp

func MkdirTemp(dir, pattern string) Result

MkdirTemp creates a new temporary directory.

r := core.MkdirTemp("", "agent-*")
Example

ExampleMkdirTemp creates a uniquely-named temp directory through `MkdirTemp`.

_ = MkdirTemp(TempDir(), "ex-*")

func Mount

func Mount(fsys FS, basedir string) Result

Mount creates a scoped view of an FS anchored at basedir.

r := core.Mount(myFS, "lib/prompts")
if r.OK { emb := r.Value.(*Embed) }
Example

ExampleMount mounts embedded assets through `Mount` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-mount-example"))
defer fs.DeleteAll(dir)
fs.Write(Path(dir, "docs", "hello.txt"), "hello")

r := Mount(DirFS(dir), "docs")
emb := r.Value.(*Embed)
Println(emb.BaseDirectory())
Println(emb.ReadString("hello.txt").Value)
Output:
docs
hello

func MountEmbed

func MountEmbed(efs embed.FS, basedir string) Result

MountEmbed creates a scoped view of an embed.FS.

r := core.MountEmbed(myFS, "testdata")
Example

ExampleMountEmbed mounts an embed filesystem through `MountEmbed` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

_ = MountEmbed((&Embed{}).EmbedFS(), ".")

func NetDial

func NetDial(network, address string) Result

NetDial opens a connection to the given network/address.

r := core.NetDial("tcp", "127.0.0.1:8080")
if !r.OK { return r }
conn := r.Value.(Conn)
Example

ExampleNetDial dials a network address through `NetDial` for network health checks. Network primitives are reached through core wrappers and Result-shaped calls.

ln := NetListen("tcp", "127.0.0.1:0").Value.(Listener)
defer ln.Close()

r := NetDial("tcp", ln.Addr().String())
Println(r.OK)
if r.OK {
	r.Value.(Conn).Close()
}
Output:
true

func NetDialTimeout

func NetDialTimeout(network, address string, timeout Duration) Result

NetDialTimeout opens a connection with a deadline.

r := core.NetDialTimeout("tcp", "host:port", 5*core.Second)
Example

ExampleNetDialTimeout dials a network address with a timeout through `NetDialTimeout` for network health checks. Network primitives are reached through core wrappers and Result-shaped calls.

ln := NetListen("tcp", "127.0.0.1:0").Value.(Listener)
defer ln.Close()

r := NetDialTimeout("tcp", ln.Addr().String(), 0)
Println(r.OK)
if r.OK {
	r.Value.(Conn).Close()
}
Output:
true

func NetListen

func NetListen(network, address string) Result

NetListen binds a listener on the given network/address.

r := core.NetListen("tcp", ":0")
if !r.OK { return r }
ln := r.Value.(Listener)
Example

ExampleNetListen listens on a network address through `NetListen` for network health checks. Network primitives are reached through core wrappers and Result-shaped calls.

r := NetListen("tcp", "127.0.0.1:0")
Println(r.OK)
if r.OK {
	r.Value.(Listener).Close()
}
Output:
true

func NetListenPacket

func NetListenPacket(network, address string) Result

NetListenPacket binds a packet-oriented listener (UDP etc.).

r := core.NetListenPacket("udp", "127.0.0.1:0")
if !r.OK { return r }
pc := r.Value.(core.PacketConn)
defer pc.Close()
Example

ExampleNetListenPacket listens for packets through `NetListenPacket` for network health checks. Network primitives are reached through core wrappers and Result-shaped calls.

r := NetListenPacket("udp", "127.0.0.1:0")
Println(r.OK)
if r.OK {
	r.Value.(PacketConn).Close()
}
Output:
true

func NewHTTPRequest

func NewHTTPRequest(method, target string, body Reader) Result

NewHTTPRequest constructs an *http.Request with the given method, URL, and body. Returns Result wrapping the request.

r := core.NewHTTPRequest("GET", url, nil)
if !r.OK { return r }
req := r.Value.(*Request)
Example

ExampleNewHTTPRequest builds a POST request with a payload for a deployment endpoint. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

r := NewHTTPRequest("POST", "https://example.com/deploy", NewReader("payload"))
req := r.Value.(*Request)
Println(req.Method)
Println(req.URL.Path)
Output:
POST
/deploy

func NewHTTPRequestContext

func NewHTTPRequestContext(ctx Context, method, target string, body Reader) Result

NewHTTPRequestContext is NewHTTPRequest with a Context attached.

ctx := Background()
body := core.NewBufferString(`{"agent":"codex"}`)
r := core.NewHTTPRequestContext(ctx, "POST", "https://api.lethean.example/v1/tasks", body)
if !r.OK {
    return r
}
req := r.Value.(*core.Request)
req.Header.Set("Content-Type", "application/json")
Example

ExampleNewHTTPRequestContext builds a request bound to the active Core context for a status endpoint. Transport details stay behind the API wrapper while callers exchange drives, streams, and Results.

ctx := New().Context()
r := NewHTTPRequestContext(ctx, "GET", "https://example.com/status", nil)
req := r.Value.(*Request)
Println(req.Context() == ctx)
Println(req.Method)
Output:
true
GET

func NewRuntime

func NewRuntime(app any) Result

NewRuntime creates a Runtime with no custom services.

r := core.NewRuntime(nil)
if !r.OK { return r }
runtime := r.Value.(*core.Runtime)
_ = runtime.Core
Example

ExampleNewRuntime constructs a runtime through `NewRuntime` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

r := NewRuntime("gui")
rt := r.Value.(*Runtime)
Println(r.OK)
Println(rt.ServiceName())
Output:
true
Core

func NewWithFactories

func NewWithFactories(app any, factories map[string]ServiceFactory) Result

NewWithFactories creates a Runtime with the provided service factories.

factories := map[string]core.ServiceFactory{
    "agent": func() core.Result { return core.Result{Value: core.Service{}, OK: true} },
}
r := core.NewWithFactories(nil, factories)
if !r.OK { return r }
Example

ExampleNewWithFactories constructs Core with service factories through `NewWithFactories` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

r := NewWithFactories("gui", map[string]ServiceFactory{
	"beta":  func() Result { return Result{Value: Service{}, OK: true} },
	"alpha": func() Result { return Result{Value: Service{}, OK: true} },
})
rt := r.Value.(*Runtime)

Println(r.OK)
Println(rt.Core.App().Runtime)
Println(rt.Core.Services())
Output:
true
gui
[alpha beta]

func Ok

func Ok(v any) Result

Ok wraps v in a successful Result. The canonical "happy path" constructor — replaces the awkward `Result{v, true}` literal.

return core.Ok(parsed)
Example

ExampleOk wraps a value in a successful Result through `Ok` for Result-based control flow. Success, fallback, casting, and error inspection all use the same Result shape.

r := Ok(42)
Println(r.OK, r.Value)
Output:
true 42

func Open

func Open(p string) Result

Open opens the named file for reading.

r := core.Open("config/agent.json")
Example

ExampleOpen opens a file for reading through `Open`.

_ = Open(PathJoin(TempDir(), "data.txt"))

func OpenFile

func OpenFile(p string, flag int, mode FileMode) Result

OpenFile opens the named file with explicit flags and mode.

r := core.OpenFile("logs/agent.log", core.O_APPEND|core.O_CREATE|core.O_WRONLY, 0o644)
Example

ExampleOpenFile opens a file with flags and mode through `OpenFile`.

_ = OpenFile(PathJoin(TempDir(), "log.txt"), 0, 0o644)

func ParseCIDR

func ParseCIDR(s string) Result

ParseCIDR parses a CIDR notation IP/mask. Returns Result wrapping (IP, *IPNet) on success.

r := core.ParseCIDR("10.0.0.0/24")
Example

ExampleParseCIDR parses a CIDR range through `ParseCIDR` for network health checks. Network primitives are reached through core wrappers and Result-shaped calls.

r := ParseCIDR("192.0.2.0/24")
parts := r.Value.([]any)
Println(parts[0])
Println(parts[1])
Output:
192.0.2.0
192.0.2.0/24

func ParseDuration

func ParseDuration(s string) Result

ParseDuration parses a duration string and returns a Result containing time.Duration.

r := core.ParseDuration("250ms")
if r.OK { timeout := r.Value.(time.Duration) }
Example

ExampleParseDuration parses duration text through `ParseDuration` for health-check timing. Durations, parsing, and timestamps use core time wrappers for service code.

r := ParseDuration("250ms")
Println(r.Value)
Output:
250ms

func ParseInt

func ParseInt(s string, base int, bitSize int) Result

ParseInt converts a string in the given base and bit size to an int64.

r := core.ParseInt("ff", 16, 64)
if r.OK { n := r.Value.(int64) }
Example

ExampleParseInt parses an integer with a base through `ParseInt` for CLI argument conversion. Numeric parsing and formatting use core helpers for CLI-friendly values.

r := ParseInt("ff", 16, 64)
Println(r.Value)
Output:
255

func ParseTemplate

func ParseTemplate(name, text string) Result

ParseTemplate creates and parses a template from a string in one call. Returns Result wrapping *Template on success.

r := core.ParseTemplate("status", "Hello {{.Name}}!")
if !r.OK { return r }
tmpl := r.Value.(*Template)
Example

ExampleParseTemplate parses template text through `ParseTemplate` for operator-facing templates. Parsing and execution use core template wrappers for operator-facing text.

r := ParseTemplate("greeting", "hello {{.Name}}")
buf := NewBuffer()
ExecuteTemplate(r.Value.(*Template), buf, map[string]string{"Name": "codex"})
Println(buf.String())
Output:
hello codex

func ParseTemplateFS

func ParseTemplateFS(fsys FS, patterns ...string) Result

ParseTemplateFS parses one or more templates from fsys.

r := core.ParseTemplateFS(fsys, "README.md.tmpl")
Example

ExampleExecuteTemplate executes a template through `ExecuteTemplate` for operator-facing templates. Parsing and execution use core template wrappers for operator-facing text. ExampleParseTemplateFS parses templates from a filesystem through `ParseTemplateFS`.

r := ParseTemplateFS(DirFS("."), "*.tmpl")
_ = r // r.Value is the parsed *Template set on success

func ParseTemplateFiles

func ParseTemplateFiles(filenames ...string) Result

ParseTemplateFiles parses one or more named template files into a single Template. The first file's basename becomes the template's name.

r := core.ParseTemplateFiles("layout.tmpl", "body.tmpl")
Example

ExampleParseTemplateFiles parses templates from files through `ParseTemplateFiles` for operator-facing templates. Parsing and execution use core template wrappers for operator-facing text.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-template-example"))
defer fs.DeleteAll(dir)

path := Path(dir, "greeting.tmpl")
fs.Write(path, "hello {{.Name}}")

r := ParseTemplateFiles(path)
buf := NewBuffer()
ExecuteTemplate(r.Value.(*Template), buf, map[string]string{"Name": "codex"})
Println(buf.String())
Output:
hello codex

func PathAbs

func PathAbs(p string) Result

PathAbs returns the absolute representation of p, anchored to the current working directory when p is relative.

core.PathAbs("./relative/path")   // "/cwd/relative/path"
core.PathAbs("/already/absolute") // "/already/absolute"
Example

ExamplePathAbs calculates an absolute path through `PathAbs` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

r := PathAbs(".")
Println(r.OK)
Println(PathIsAbs(r.Value.(string)))
Output:
true
true
func PathEvalSymlinks(p string) Result

PathEvalSymlinks returns p after resolving symbolic links.

r := core.PathEvalSymlinks("/tmp/current")
if r.OK { resolved := r.Value.(string); _ = resolved }

func PathMatch

func PathMatch(pattern, name string) Result

PathMatch reports whether name matches the shell file name pattern.

r := core.PathMatch("process.*", "process.run")
if r.OK && r.Value.(bool) { core.Println("matched") }
Example

ExamplePathMatch tests a name against a shell pattern through `PathMatch`.

Println(PathMatch("*.go", "agent.go").Value)
Output:
true

func PathRel

func PathRel(base, target string) Result

PathRel returns target expressed as a path relative to base. Both arguments must be either both absolute or both relative; otherwise the call returns Result.OK=false with the underlying error.

core.PathRel("/var/lib/foo", "/var/lib/foo/bar/baz")  // Result.Value="bar/baz"
core.PathRel("/a", "/b")                              // Result.Value="../b"
Example

ExamplePathRel calculates a relative path through `PathRel` for workspace path handling. Path joins, cleanup, globbing, and extension changes use core wrappers.

r := PathRel("/srv/app", "/srv/app/config/settings.yaml")
Println(r.Value)
Output:
config/settings.yaml

func PathWalk

func PathWalk(root string, fn PathWalkFunc) Result

PathWalk walks the file tree rooted at root.

r := core.PathWalk("/tmp/workspace", fn)
if !r.OK { return r }
Example

ExamplePathWalk walks a file tree through `PathWalk`.

PathWalk(TempDir(), func(path string, info FsFileInfo, err error) error {
	return err
})

func PathWalkDir

func PathWalkDir(root string, fn PathWalkDirFunc) Result

PathWalkDir walks the file tree rooted at root using directory entries.

r := core.PathWalkDir("/tmp/workspace", fn)
if !r.OK { return r }
Example

ExamplePathWalkDir walks a file tree by directory entry through `PathWalkDir`.

PathWalkDir(TempDir(), func(path string, d FsDirEntry, err error) error {
	return err
})

func RandRead added in v0.10.0

func RandRead(b []byte) Result

RandRead fills b with cryptographically secure random bytes. Returns Result.OK true on success; on failure r.Value holds the underlying error. Use this when callers need to fill an existing slice rather than allocate via RandomBytes.

buf := make([]byte, 32)
if r := core.RandRead(buf); !r.OK {
    return core.Fail(core.E("seed", "rand: "+r.Error(), nil))
}
Example

ExampleRandRead fills an existing buffer with cryptographically secure random bytes through `RandRead` for session nonce generation. Use this when callers need to fill a pre-allocated slice rather than allocate via RandomBytes.

buf := make([]byte, 16)
r := RandRead(buf)
Println(r.OK)
Println(len(buf))
Output:
true
16

func RandomBytes

func RandomBytes(n int) Result

RandomBytes returns n cryptographically secure random bytes wrapped in a Result. Returns OK=false when n is negative or the OS entropy source fails. Code is "random.length.invalid" or "random.entropy.failed".

r := core.RandomBytes(32)
if !r.OK { return r }
token := r.Value.([]byte)
Example

ExampleRandomBytes generates random bytes through `RandomBytes` for session nonce generation. Nonces, strings, and bounded integers return Results suitable for session work.

r := RandomBytes(8)
if r.OK {
	Println(len(r.Value.([]byte)))
}
Output:
8

func RandomInt

func RandomInt(min, max int) Result

RandomInt returns a cryptographically secure integer in the half-open range [min, max). Returns OK=false when max <= min (Code "random.range.empty") or when crypto/rand fails (Code "random.entropy.failed").

r := core.RandomInt(10, 20)
if r.OK { delay := r.Value.(int) }
Example

ExampleRandomInt generates a bounded integer through `RandomInt` for session nonce generation. Nonces, strings, and bounded integers return Results suitable for session work.

r := RandomInt(10, 20)
if r.OK {
	n := r.Value.(int)
	Println(n >= 10 && n < 20)
}
Output:
true

func RandomString

func RandomString(n int) Result

RandomString returns n cryptographically secure random bytes encoded as lowercase hex. The Value is a string of length n*2. Code mirrors RandomBytes when the underlying source fails.

r := core.RandomString(16)
if r.OK { token := r.Value.(string) }
Example

ExampleRandomString generates random text through `RandomString` for session nonce generation. Nonces, strings, and bounded integers return Results suitable for session work.

r := RandomString(8)
if r.OK {
	Println(len(r.Value.(string)))
}
Output:
16

func ReadAll

func ReadAll(reader any) Result

ReadAll reads all bytes from reader and closes it when it implements Closer.

r := core.ReadAll(core.NewReader("hello"))
if r.OK { core.Println(r.Value.(string)) }
Example

ExampleReadAll reads a reader to completion through `ReadAll`.

r := ReadAll(NewReader("agent ready"))
Println(r.Value)
Output:
agent ready

func ReadDir

func ReadDir(fsys FS, name string) Result

ReadDir reads a directory from fsys.

r := core.ReadDir(core.DirFS("templates"), ".")
Example

ExampleFs_WalkSeqSkip walks a tree through `Fs.WalkSeqSkip` while skipping a branch for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs. ExampleReadDir lists a directory's entries through `ReadDir`.

r := ReadDir(DirFS("."), ".")
_ = r // r.Value is []FsDirEntry on success

func ReadFSFile

func ReadFSFile(fsys FS, name string) Result

ReadFSFile reads a file from fsys.

r := core.ReadFSFile(core.DirFS("templates"), "README.md")
Example

ExampleReadFSFile reads a named file from a filesystem through `ReadFSFile`.

r := ReadFSFile(DirFS("."), "go.mod")
_ = r // r.Value is []byte on success

func ReadFile

func ReadFile(p string) Result

ReadFile reads the named file and returns its bytes.

r := core.ReadFile("config/agent.json")
if r.OK { data := r.Value.([]byte); _ = data }
Example

ExampleReadFile reads a file's bytes through `ReadFile`.

r := ReadFile(PathJoin(TempDir(), "config.json"))
_ = r // r.Value is []byte on success
func Readlink(p string) Result

Readlink returns the destination of the named symbolic link. To resolve a whole chain to its final target use core.PathEvalSymlinks; Readlink reads only the single link's stored value.

r := core.Readlink("current")
if r.OK { target := r.Value.(string); _ = target }

func Regex

func Regex(pattern string) Result

Regex compiles pattern. Returns Result wrapping *Regexp on success or the compile error if the pattern is invalid.

r := core.Regex(`\d+`)
if !r.OK { return r }
rx := r.Value.(*Regexp)
Example

ExampleRegex compiles a pattern through `Regex` for route parsing. Compiled patterns expose common matching and replacement operations through core wrappers.

r := Regex(`\d+`)
rx := r.Value.(*Regexp)

Println(rx.MatchString("build 42"))
Println(rx.FindString("build 42"))
Output:
true
42

func Remove

func Remove(p string) Result

Remove removes the named file or empty directory.

r := core.Remove("logs/old-agent.log")
Example

ExampleRemove deletes a file or empty directory through `Remove`.

_ = Remove(PathJoin(TempDir(), "f"))

func RemoveAll

func RemoveAll(p string) Result

RemoveAll removes a path and any children.

r := core.RemoveAll("tmp/session-42")
Example

ExampleRemoveAll deletes a path and any children through `RemoveAll`.

_ = RemoveAll(PathJoin(TempDir(), "dir"))

func Rename

func Rename(oldPath, newPath string) Result

Rename renames oldPath to newPath.

r := core.Rename("config.tmp", "config.json")
Example

ExampleRename moves a file through `Rename`.

_ = Rename(PathJoin(TempDir(), "a"), PathJoin(TempDir(), "b"))

func ResultOf

func ResultOf(v any, err error) Result

ResultOf adapts a stdlib (value, error) pair into a Result — OK=false carrying err when err != nil, OK=true carrying v otherwise. The replacement for Result{}.New(v, err).

r := core.ResultOf(os.ReadFile(path))
if !r.OK { return r }
Example

ExampleResultOf adapts a (value, error) pair through `ResultOf` for Result-based control flow. Success, fallback, casting, and error inspection all use the same Result shape.

r := ResultOf("data", nil)
Println(r.OK, r.Value)
Output:
true data

func SQLOpen

func SQLOpen(driverName, dataSourceName string) Result

SQLOpen opens a database handle for the given driver and data source name. The driver must be imported for its side-effect registration.

r := core.SQLOpen("sqlite3", "file:./data.db")
if !r.OK { return r }
db := r.Value.(*DB)
Example

ExampleSQLOpen opens a SQL database through `SQLOpen` for database adapter setup. Database opening and sentinel checks use aliases without importing database/sql directly.

r := SQLOpen("missing-driver", "")
Println(r.OK)
Output:
false

func ScanAssets

func ScanAssets(filenames []string) Result

ScanAssets parses Go source files and finds asset references. Looks for calls to: core.GetAsset("group", "name"), core.AddAsset, etc.

r := core.ScanAssets([]string{"cmd/agent/main.go"})
if !r.OK {
    return r
}
pkgs := r.Value.([]core.ScannedPackage)
_ = pkgs
Example

ExampleScanAssets scans embedded assets through `ScanAssets` for embedded asset packaging. Asset packing, mounting, and extraction stay declarative for consumers.

fs := (&Fs{}).New("/")
dir := MustCast[string](fs.TempDir("core-scan-example"))
defer fs.DeleteAll(dir)

fs.Write(Path(dir, "main.go"), `package sample

import core "dappco.re/go"

func message() string {
	return core.GetAsset("assets", "message.txt").Value.(string)
}
`)

r := ScanAssets([]string{Path(dir, "main.go")})
pkgs := r.Value.([]ScannedPackage)
Println(r.OK)
Println(pkgs[0].PackageName)
Println(pkgs[0].Assets[0].Group)
Println(pkgs[0].Assets[0].Name)
Output:
true
sample
assets
message.txt

func Setenv

func Setenv(key, value string) Result

Setenv sets an environment variable. Returns Result with OK=false + Code "env.invalid" when the OS rejects the assignment (e.g. key containing '=' or NUL).

r := core.Setenv("FORGE_TOKEN", token)
if !r.OK { return r }
Example

ExampleSetenv sets an environment variable through `Setenv` for process environment setup. Process environment mutation goes through core helpers in tests and services.

Setenv("CORE_EXAMPLE_ENV", "enabled")
defer Unsetenv("CORE_EXAMPLE_ENV")

Println(Env("CORE_EXAMPLE_ENV"))
Output:
enabled
Example (InvalidKey)

ExampleSetenv_invalidKey sets an environment variable through `Setenv`, showing the OK=false path when the OS rejects the key (env_example_test.go already covers the happy path via `ExampleSetenv`, so this variant covers the documented rejection case instead of redeclaring the same scenario under this file's required name).

r := Setenv("CORE_EXAMPLE=BAD", "x") // '=' in the key is rejected by the OS
Println(r.OK)
Output:
false

func Stat

func Stat(p string) Result

Stat returns file information for p.

r := core.Stat("config/agent.json")
Example

ExampleStat returns file metadata through `Stat`.

_ = Stat(PathJoin(TempDir(), "f"))

func Sub

func Sub(fsys FS, dir string) Result

Sub returns an FS rooted at dir inside fsys.

r := core.Sub(core.DirFS("templates"), "agent")
Example

ExampleSub returns a filesystem rooted at a subdirectory through `Sub`.

r := Sub(DirFS("."), "docs")
_ = r // r.Value is an FS scoped to docs/
func Symlink(oldPath, newPath string) Result

Symlink creates newPath as a symbolic link to oldPath.

r := core.Symlink("releases/v2", "current")

func TimeParse

func TimeParse(layout, value string) Result

TimeParse parses value into a time.Time using the given layout. Returns Result wrapping time.Time on success or the parse error.

r := core.TimeParse(core.TimeRFC3339, "2026-04-28T07:00:00Z")
if r.OK { ts := r.Value.(time.Time) }
Example

ExampleTimeParse parses a timestamp through `TimeParse` for health-check timing. Durations, parsing, and timestamps use core time wrappers for service code.

r := TimeParse(TimeRFC3339, "2026-04-28T07:00:00Z")
Println(Contains(Sprint(r.Value), "2026-04-28 07:00:00"))
Output:
true

func Try

func Try(fn func() any) (r Result)

Try runs fn and converts its outcome into a Result. A nil error or a returned value sets OK=true; a returned error or a panic sets OK=false. Bridges legacy code that panics or returns (T, error).

r := core.Try(func() any {
    return riskyParse(input)  // may panic
})
if !r.OK { core.Error("parse failed", "err", r.Error()) }
Example

ExampleTry converts panic-prone work into a Result through `Try` for Result-based control flow. Success, fallback, casting, and error inspection all use the same Result shape.

r := Try(func() any {
	return 42
})
Println(r.OK, r.Value)
Output:
true 42

func URLDecode

func URLDecode(s string) Result

URLDecode unescapes a URL query component string.

r := core.URLDecode("hello+world")
if r.OK { s := r.Value.(string) }
Example

ExampleURLDecode decodes query text through `URLDecode` for remote endpoint handling. Endpoint parsing, escaping, and normalisation use core URL wrappers.

r := URLDecode("hello+world")
Println(r.Value)
Output:
hello world

func URLParse

func URLParse(rawURL string) Result

URLParse parses a raw URL string.

r := core.URLParse("https://example.com/path")
if r.OK { u := r.Value.(*core.URL) }
Example

ExampleURLParse parses an endpoint through `URLParse` for remote endpoint handling. Endpoint parsing, escaping, and normalisation use core URL wrappers.

r := URLParse("https://example.com/search?q=core")
Println(r.Value)
Output:
https://example.com/search?q=core

func Unsetenv

func Unsetenv(key string) Result

Unsetenv removes an environment variable. Returns Result with OK=false + Code "env.invalid" when the OS rejects the removal.

r := core.Unsetenv("FORGE_TOKEN")
if !r.OK { return r }
Example

ExampleUnsetenv unsets an environment variable through `UnsetEnv` for process environment setup. Process environment mutation goes through core helpers in tests and services.

Setenv("CORE_EXAMPLE_ENV", "enabled")
Unsetenv("CORE_EXAMPLE_ENV")

Println(Env("CORE_EXAMPLE_ENV"))
Example (Idempotent)

ExampleUnsetenv_idempotent removes an environment variable through `Unsetenv`, then shows a second removal of the same already-gone key still reports OK (env_example_test.go covers the single-removal happy path via `ExampleUnsetenv`).

Setenv("CORE_EXAMPLE_IDEMPOTENT", "x")
Unsetenv("CORE_EXAMPLE_IDEMPOTENT")
r := Unsetenv("CORE_EXAMPLE_IDEMPOTENT") // already gone; still OK
Println(r.OK)
Output:
true

func UserCacheDir

func UserCacheDir() Result

UserCacheDir returns the default root directory for user cache data.

r := core.UserCacheDir()
Example

ExampleUserCacheDir returns the user's cache directory through `UserCacheDir`.

_ = UserCacheDir()

func UserConfigDir

func UserConfigDir() Result

UserConfigDir returns the default root directory for user configuration.

r := core.UserConfigDir()
Example

ExampleUserConfigDir returns the user's config directory through `UserConfigDir`.

_ = UserConfigDir()

func UserCurrent

func UserCurrent() Result

UserCurrent returns the current process's user wrapped in a Result. OK=false with Code "user.lookup.failed" when the lookup fails (e.g. in containers without a /etc/passwd entry).

r := core.UserCurrent()
if r.OK { home := r.Value.(*core.User).HomeDir }
Example
// Succeeds on a normal host; in a bare container without /etc/passwd it
// returns OK=false. Shown without asserted output because the username and
// home dir are host-specific.
r := UserCurrent()
if r.OK {
	_ = r.Value.(*User).HomeDir
}

func UserGroupLookup

func UserGroupLookup(name string) Result

UserGroupLookup finds a group by name. OK=false with Code "user.group.notfound" when the group doesn't exist.

r := core.UserGroupLookup("staff")
if r.OK { gid := r.Value.(*core.Group).Gid }
Example
r := UserGroupLookup("definitely-not-a-group-9z9z9z")
Println(r.OK)
Output:
false

func UserHomeDir

func UserHomeDir() Result

UserHomeDir returns the current user's home directory.

r := core.UserHomeDir()
Example

ExampleUserHomeDir returns the user's home directory through `UserHomeDir`.

_ = UserHomeDir()

func UserLookup

func UserLookup(username string) Result

UserLookup finds a user by username. OK=false with Code "user.notfound" when the username doesn't exist on the system.

r := core.UserLookup("snider")
if r.OK { uid := r.Value.(*core.User).Uid }
Example
r := UserLookup("definitely-not-a-user-9z9z9z")
Println(r.OK)
Output:
false

func UserLookupID

func UserLookupID(uid string) Result

UserLookupID finds a user by uid string. OK=false with Code "user.notfound" when no user has that uid.

r := core.UserLookupID("1000")
if r.OK { username := r.Value.(*core.User).Username }
Example
// Output omitted: uid existence is OS-synthesized (e.g. macOS maps high
// uids to "nobody"), so there is no portably-absent uid to assert on.
r := UserLookupID("0")
if r.OK {
	_ = r.Value.(*User).Username
}

func ValidateName

func ValidateName(name string) Result

ValidateName checks that a string is a valid service/action/command name. Rejects empty, ".", "..", and names containing path separators.

r := core.ValidateName("brain")      // Result{"brain", true}
r := core.ValidateName("")           // Result{error, false}
r := core.ValidateName("../escape")  // Result{error, false}
Example
Println(ValidateName("brain").OK)
Println(ValidateName("").OK)
Println(ValidateName("..").OK)
Println(ValidateName("path/traversal").OK)
Output:
true
false
false
false
Example (Valid)

ExampleValidateName_valid accepts a valid name through `ValidateName` for CLI utility parsing. Small CLI argument utilities have predictable string and flag behaviour.

Println(ValidateName("agent").OK)
Println(ValidateName("../agent").OK)
Output:
true
false

func WalkDir

func WalkDir(fsys FS, root string, fn WalkDirFunc) Result

WalkDir walks fsys from root, calling fn for each file or directory. Returns Result{OK: true} on a complete walk, or Result{OK: false} carrying the error (the first fn error, or a traversal failure).

r := core.WalkDir(core.DirFS("templates"), ".", fn)
if !r.OK {
	return r
}
Example

ExampleWalkDir walks a filesystem tree by directory entry through `WalkDir`.

WalkDir(DirFS("."), ".", func(path string, d FsDirEntry, err error) error {
	return err
})

func WriteAll

func WriteAll(writer any, content string) Result

WriteAll writes content to a writer and closes it if it implements Closer.

r := fs.WriteStream(path)
core.WriteAll(r.Value, "content")
Example

ExampleWriteAll writes a complete payload through `WriteAll` for sandboxed file operations. File reads, writes, walks, and cleanup stay sandbox-aware through Fs.

buf := NewBuffer()
r := WriteAll(buf, "hello")
Println(r.OK)
Println(buf.String())
Output:
true
hello

func WriteFile

func WriteFile(p string, data []byte, mode FileMode) Result

WriteFile writes data to the named file with mode.

r := core.WriteFile("config/agent.json", []byte("{}"), 0o644)
Example

ExampleWriteFile writes bytes to a file through `WriteFile`.

_ = WriteFile(PathJoin(TempDir(), "out.txt"), []byte("data"), 0o644)

func WriteString

func WriteString(w Writer, s string) Result

WriteString writes the contents of s to w. Returns Result wrapping the number of bytes written (int).

r := core.WriteString(stdout, "hello\n")

Fast path: when the writer exposes a WriteString method we delegate straight to it (strings.Builder, bytes.Buffer, *os.File on most platforms). For writers without one, we use AsBytes to skip the []byte(s) copy that stdlib io.WriteString does in its fallback — safe because the io.Writer contract forbids retention or mutation of the slice past the call.

Example

ExampleWriteString writes text into a stream through `WriteString` for streaming payloads. Stream copying, EOF checks, and writes avoid direct io imports in consumers.

dst := NewBuffer()
r := WriteString(dst, "hello")
Println(r.Value)
Println(dst.String())
Output:
5
hello

func (Result) Bool added in v0.12.0

func (r Result) Bool() bool

Bool retrieves a bool Value, false when failed or not a bool.

enabled := c.QUERY(flagQuery{}).Bool()
Example

ExampleResult_Bool reads a typed bool, false on failure or wrong type.

Println(Ok(true).Bool())
Output:
true

func (Result) Bytes added in v0.12.0

func (r Result) Bytes() []byte

Bytes retrieves a []byte Value, nil when failed or not []byte. Returns the backing slice directly — no defensive copy (hot I/O path; callers that mutate must copy).

body := core.HTTPGet(url).Bytes()
Example

ExampleResult_Bytes reads a []byte Value directly — no copy, no assert.

Println(string(Ok([]byte("payload")).Bytes()))
Output:
payload

func (Result) Code

func (r Result) Code() string

Code returns the stable error code from the Result's failure, or "" when OK or when the failure isn't a *core.Err with a Code populated. Codes form a flat keyspace agents grep on (e.g. "fs.notfound", "json.invalid", "http.timeout", "crypto.algo.unsupported"). See the Stable codespace section in AGENTS.md for the canonical list.

r := c.Fs().Read("/missing")
if r.Code() == "fs.notfound" { core.Println("first run") }
switch r.Code() {
case "http.timeout": retry()
case "http.refused": fallback()
}
Example

ExampleResult_Code reads a Result error code through `Result.Code` for Result-based control flow. Success, fallback, casting, and error inspection all use the same Result shape.

r := Result{Value: NewCode("fs.notfound", "missing file"), OK: false}
Println(r.Code())
Output:
fs.notfound

func (Result) Duration added in v0.12.0

func (r Result) Duration() Duration

Duration retrieves a Duration Value, 0 when failed or wrong type. Accepts a Duration directly or a string parsed via ParseDuration — the same contract as Options.Duration.

timeout := core.ParseDuration("30s").Duration()
Example

ExampleResult_Duration accepts a Duration or a ParseDuration string.

Println(Ok("30s").Duration())
Output:
30s

func (Result) Err added in v0.11.0

func (r Result) Err() error

Err returns the failure as a Go error — nil when OK, the unwrapped error Value when it is one, otherwise the Result itself (which satisfies error via Result.Error). The idiomatic bridge from a Result to an error at an API boundary, replacing the hand-rolled "if !r.OK { return r.Value.(error) }" unwrap scattered across consumers.

if err := core.JSONUnmarshal(data, &cfg).Err(); err != nil {
    return err
}
Example

ExampleResult_Err returns the failure as an error — nil when OK, and never nil when failed.

Println(Ok("fine").Err() == nil)
Println(Fail(NewError("agent offline")).Err() != nil)
Output:
true
true

func (Result) Error

func (r Result) Error() string

Error returns the error message when the Result represents a failure, or "" when OK. Convenience for logging without unwrapping Value.

if !r.OK { core.Error("dispatch failed", "err", r.Error()) }
Example

ExampleResult_Error writes or renders an error through `Result.Error` for Result-based control flow. Success, fallback, casting, and error inspection all use the same Result shape.

r := Result{Value: NewError("bad config"), OK: false}
Println(r.Error())
Output:
bad config

func (Result) Float64 added in v0.12.0

func (r Result) Float64() float64

Float64 retrieves a float64 Value, 0 when failed or wrong type. Promotes int/int64/float32 so JSON-decoded numbers work uniformly — the same promotion set as Options.Float64.

weight := c.QUERY(weightQuery{}).Float64()
Example

ExampleResult_Float64 promotes int/int64/float32, as Options.Float64 does.

Println(Ok(3).Float64())
Output:
3

func (Result) Int added in v0.12.0

func (r Result) Int() int

Int retrieves an int Value, 0 when failed or not an int. Strict — no numeric promotion, mirroring Options.Int.

port := c.QUERY(portQuery{}).Int()
Example

ExampleResult_Int reads a typed int with the Options accessor contract.

Println(Ok(8080).Int())
Output:
8080

func (Result) Must

func (r Result) Must() any

Must returns Value when OK; panics with the underlying error when not. Use for fast-fail paths — init, test setup, must-have config. Production request paths should check r.OK and return r.

cfg := core.JSONUnmarshal(data, &Config{}).Must().(*Config)
dir := core.PathAbs(".").Must().(string)
Example

ExampleResult_Must unwraps a successful Result through `Result.Must` for Result-based control flow. Success, fallback, casting, and error inspection all use the same Result shape.

v := (Result{Value: 42, OK: true}).Must()
Println(v)
Output:
42

func (Result) New deprecated

func (r Result) New(args ...any) Result

New adapts Go (value, error) pairs into a Result.

Deprecated: prefer core.ResultOf(value, err) for the (T, error) adapter or core.Ok(v) / core.Err(err) for direct construction. New's variadic-reflective shape is awkward to read; the explicit constructors document intent at the call site. Removed in v0.10.0.

r := core.Result{}.New(file, err)  // legacy
r := core.ResultOf(file, err)      // preferred
Example

ExampleResult_New creates a successful Result containing a created status for agent options. Options carry loosely typed inputs while typed accessors keep call sites small.

r := Result{}.New("created", nil)
Println(r.OK)
Println(r.Value)
Output:
true
created

func (Result) Or

func (r Result) Or(fallback any) any

Or returns Value when OK, fallback otherwise. Convenience for optional reads where a default is acceptable.

port := core.EnvGet("PORT").Or("8080").(string)
timeout := core.ParseDuration(s).Or(5 * core.Second).(Duration)
Example

ExampleResult_Or falls back from a failed Result through `Result.Or` for Result-based control flow. Success, fallback, casting, and error inspection all use the same Result shape.

v := (Result{OK: false}).Or("fallback")
Println(v)
Output:
fallback

func (Result) String added in v0.12.0

func (r Result) String() string

String renders the Result for humans and logs — Result implements Stringer through it. Returns the string Value verbatim when OK holds a string, Sprint(Value) for any other OK value, and the Error() text when failed. This is the ONE deliberate divergence from the strict getter contract, so `%v` of any Result reads well in logs. For a strict typed read use Cast[string](r).

name := core.EnvGet("USER").String()
core.Println(c.Fs().Read("/missing").String())  // error text, not ""
Example

ExampleResult_String shows the Stringer-first contract: the value when OK, the error text when failed — %v of any Result reads well in logs.

Println(Ok("brain").String())
Println(Fail(NewError("agent offline")).String())
Output:
brain
agent offline

type Return added in v0.12.0

type Return[T any] struct {
	Value T
	Err   error
}

Return is the typed single-value return: Value OR Err. A nil Err means success. The zero value is a successful Return carrying T's zero value.

r := core.ReturnOK(&Config{})
if r.OK() { cfg := r.Value }

func QueryFor added in v0.12.0

func QueryFor[T any](c *Core, q Query) Return[T]

QueryFor sends a QUERY and lifts the first responder's answer into a typed Return — no assertion at the call site.

user := core.QueryFor[*User](c, userQuery{ID: id}).Or(guest)
Example

ExampleQueryFor lifts a QUERY answer into a typed Return.

c := New()
type portQuery struct{}
c.RegisterQuery(func(_ *Core, q Query) Result {
	if _, ok := q.(portQuery); ok {
		return Ok(8080)
	}
	return Result{}
})
Println(QueryFor[int](c, portQuery{}).Or(0))
Output:
8080

func ReturnFail added in v0.12.0

func ReturnFail[T any](err error) Return[T]

ReturnFail wraps err in a failed Return — the typed Fail.

return core.ReturnFail[*Config](core.E("config.Load", "no file", nil))
Example

ExampleReturnFail wraps an error in a failed typed Return.

r := ReturnFail[string](NewError("agent offline"))
Println(r.OK())
Output:
false

func ReturnFrom added in v0.12.0

func ReturnFrom[T any](v T, err error) Return[T]

ReturnFrom adapts a stdlib (value, error) pair — the typed ResultOf.

return core.ReturnFrom(os.ReadFile(path))
Example

ExampleReturnFrom adapts a stdlib (value, error) pair.

parse := func(s string) (int, error) {
	if s == "" {
		return 0, NewError("empty input")
	}
	return len(s), nil
}
Println(ReturnFrom(parse("brain")).Or(0))
Println(ReturnFrom(parse("")).Or(-1))
Output:
5
-1

func ReturnOK added in v0.12.0

func ReturnOK[T any](v T) Return[T]

ReturnOK wraps v in a successful Return — the typed Ok.

return core.ReturnOK(parsed)
Example

ExampleReturnOK wraps a value in a successful typed Return.

r := ReturnOK("brain")
Println(r.OK(), r.Value)
Output:
true brain

func ReturnOf added in v0.12.0

func ReturnOf[T any](r Result) Return[T]

ReturnOf lifts a Result into a typed Return. A failed Result carries its error across (never nil — see Result.Err); an OK Result whose Value isn't T fails with operation "core.ReturnOf".

r := core.ReturnOf[*User](c.QUERY(userQuery{ID: id}))
Example

ExampleReturnOf lifts an untyped Result into a typed Return.

r := ReturnOf[string](Ok("brain"))
Println(r.Value)
Output:
brain

func ReturnTry added in v0.12.0

func ReturnTry[T any](fn func() T) (r Return[T])

ReturnTry runs fn and converts a panic into a failed Return — the typed Try. Bridges legacy code that panics.

r := core.ReturnTry(func() *Config { return riskyParse(input) })
if !r.OK() { return r }
Example

ExampleReturnTry converts a panic into a failed Return.

r := ReturnTry(func() int { panic(NewError("parser exploded")) })
Println(r.OK())
Output:
false

func (Return[T]) Code added in v0.12.0

func (r Return[T]) Code() string

Code returns the stable error code when Err is a *core.Err with a Code populated, "" otherwise — the same contract as Result.Code.

if r.Code() == "fs.notfound" { firstRun() }
Example

ExampleReturn_Code exposes the stable error code, as Result.Code does.

r := ReturnFail[int](NewCode("fs.notfound", "no such file"))
Println(r.Code())
Output:
fs.notfound

func (Return[T]) Log added in v0.12.0

func (r Return[T]) Log(op, msg string) Return[T]

Log reports the failure through the package log path and returns the Return unchanged for chaining — logging handled by Core, opted into per call site. No-op on success, so expected-failure branches stay silent unless the caller asks.

u := UserByName(n).Log("svc.Auth", "lookup failed").Or(guest)
Example

ExampleReturn_Log opts a failure into the package log path and chains.

r := ReturnOK("quiet").Log("svc.Op", "never logged — success is silent")
Println(r.Value)
Output:
quiet

func (Return[T]) Must added in v0.12.0

func (r Return[T]) Must() T

Must returns Value on success and panics with Err on failure. For fast-fail paths — init, test setup, must-have config.

cfg := core.ReturnOf[*Config](r).Must()
Example

ExampleReturn_Must unwraps for fast-fail paths.

Println(ReturnOK(8080).Must())
Output:
8080

func (Return[T]) OK added in v0.12.0

func (r Return[T]) OK() bool

OK reports success — Err is nil.

if !r.OK() { return r }
Example

ExampleReturn_OK reports success — Err is the only discriminant.

Println(ReturnOK(0).OK())
Output:
true

func (Return[T]) Or added in v0.12.0

func (r Return[T]) Or(fallback T) T

Or returns Value on success, fallback on failure — typed, no assertion ever.

u := UserByName(name).Or(guest)
Example

ExampleReturn_Or returns the value or a typed fallback — no assertion.

guest := "guest"
Println(ReturnFail[string](NewError("no session")).Or(guest))
Output:
guest

func (Return[T]) Result added in v0.12.0

func (r Return[T]) Result() Result

Result erases the type back to the universal bus shape: a failed Return carries Err as the failure Value, a successful one carries Value.

c.ACTION(TaskDone{Result: r.Result()})
Example

ExampleReturn_Result erases the type back to the universal bus shape.

r := ReturnOK("done").Result()
Println(r.OK, r.String())
Output:
true done

type RotationLogOptions

type RotationLogOptions struct {
	// Filename is the log file path. If empty, rotation is disabled.
	Filename string

	// MaxSize is the maximum size of the log file in megabytes before it gets rotated.
	// It defaults to 100 megabytes.
	MaxSize int

	// MaxAge is the maximum number of days to retain old log files based on their
	// file modification time. It defaults to 28 days.
	// Note: set to a negative value to disable age-based retention.
	MaxAge int

	// MaxBackups is the maximum number of old log files to retain.
	// It defaults to 5 backups.
	MaxBackups int

	// Compress determines if the rotated log files should be compressed using gzip.
	// It defaults to true.
	Compress bool
}

RotationLogOptions defines the log rotation and retention policy.

opts := core.RotationLogOptions{Filename: "/var/log/core/agent.log", MaxSize: 100, MaxBackups: 5, Compress: true}
_ = opts
Example

ExampleRotationLogOptions declares rotation settings through `RotationLogOptions` for operator logging. Loggers support levels, redaction, and default routing for operator output.

opts := RotationLogOptions{Filename: "app.log", MaxSize: 10, MaxBackups: 3}
Println(opts.Filename)
Println(opts.MaxSize)
Output:
app.log
10

type Row

type Row = sql.Row

Row is a single-row query result.

r := core.SQLOpen("sqlite3", "file:./data/homelab.db")
if !r.OK { return r }
db := r.Value.(*core.DB)
defer db.Close()
row := db.QueryRow("select name from agents where id = ?", 42)
_ = row

type Rows

type Rows = sql.Rows

Rows is the result of a query — iterate with rs.Next().

r := core.SQLOpen("sqlite3", "file:./data/homelab.db")
if !r.OK { return r }
db := r.Value.(*core.DB)
defer db.Close()
rows, err := db.Query("select name from agents")
if err == nil { defer rows.Close() }

type Runtime

type Runtime struct {
	Core *Core
	// contains filtered or unexported fields
}

Runtime is the container for GUI runtimes (e.g., Wails).

r := core.Runtime{Core: core.New()}
core.Println(r.ServiceName())

func (*Runtime) ServiceName

func (r *Runtime) ServiceName() string

ServiceName returns "Core" — the Runtime's service identity.

runtime := &core.Runtime{Core: core.New()}
name := runtime.ServiceName()
core.Println(name)
Example

ExampleRuntime_ServiceName reads a service name through `Runtime.ServiceName` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

rt := NewRuntime("gui").Value.(*Runtime)
Println(rt.ServiceName())
Output:
Core

func (*Runtime) ServiceShutdown

func (r *Runtime) ServiceShutdown(ctx Context) Result

ServiceShutdown stops all services via the embedded Core.

r := core.Runtime{Core: core.New()}
result := r.ServiceShutdown(Background())
if !result.OK { return result }
Example

ExampleRuntime_ServiceShutdown runs service shutdown through `Runtime.ServiceShutdown` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

rt := NewRuntime("gui").Value.(*Runtime)
Println(rt.ServiceShutdown(Background()).OK)
Output:
true

func (*Runtime) ServiceStartup

func (r *Runtime) ServiceStartup(ctx Context, options any) Result

ServiceStartup starts all services via the embedded Core.

r := core.Runtime{Core: core.New()}
result := r.ServiceStartup(Background(), nil)
if !result.OK { return result }
Example

ExampleRuntime_ServiceStartup runs service startup through `Runtime.ServiceStartup` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

rt := NewRuntime("gui").Value.(*Runtime)
Println(rt.ServiceStartup(Background(), nil).OK)
rt.ServiceShutdown(Background())
Output:
true

type SQLResult

type SQLResult = sql.Result

Result is shadowed by core.Result; the SQL exec result type is re-exported as SQLResult to disambiguate.

r := core.SQLOpen("sqlite3", "file:./data/homelab.db")
if !r.OK { return r }
db := r.Value.(*core.DB)
defer db.Close()
res, err := db.Exec("update agents set status = ? where name = ?", "ready", "codex")
if err == nil { affected, _ := res.RowsAffected(); core.Println(affected) }

type ScannedPackage

type ScannedPackage struct {
	PackageName   string
	BaseDirectory string
	Groups        []string
	Assets        []AssetRef
}

ScannedPackage holds all asset references from a set of source files.

pkg := core.ScannedPackage{PackageName: "agent", BaseDirectory: "./agent"}
pkg.Assets = append(pkg.Assets, core.AssetRef{Name: "developer.md", Group: "persona"})

type Seeker

type Seeker = io.Seeker

Seeker is the canonical io.Seeker interface.

reader := core.NewReader("agent payload")
var seeker core.Seeker = reader
seeker.Seek(0, 0)

type Seq

type Seq[V any] = iter.Seq[V]

Seq is a single-value iterator — a function that pushes elements one at a time to a yield callback until it returns false. Alias of iter.Seq.

var nums core.Seq[int] = func(yield func(int) bool) {
    for i := range 5 { if !yield(i) { return } }
}
for n := range nums { core.Println(n) }

func AllOperations

func AllOperations(err error) Seq[string]

AllOperations returns an iterator over all operational contexts in the error chain. It traverses the error tree using errors.Unwrap.

err := core.Wrap(core.E("net.Dial", "refused", nil), "agent.Ping", "homelab unreachable")
for op := range core.AllOperations(err) {
    core.Println(op)
}
Example

ExampleAllOperations lists wrapped operations through `AllOperations` for dAppCore error handling. Operations, codes, roots, and crash reports remain inspectable through core errors.

err := Wrap(Wrap(NewError("root"), "db.Query", "failed"), "api.Get", "failed")
var ops []string
for op := range AllOperations(err) {
	ops = append(ops, op)
}
Println(ops)
Output:
[api.Get db.Query]

type Seq2

type Seq2[K, V any] = iter.Seq2[K, V]

Seq2 is a two-value iterator — yielding (key, value) or (index, item) pairs. Alias of iter.Seq2. Returned by walkers and key/value scanners.

var entries core.Seq2[string, int] = func(yield func(string, int) bool) {
    if !yield("a", 1) { return }
    if !yield("b", 2) { return }
}
for k, v := range entries { core.Println(k, v) }

type ServeMux

type ServeMux = http.ServeMux

ServeMux is the canonical HTTP request multiplexer.

mux := &core.ServeMux{}
mux.Handle("/health", core.HandlerFunc(func(w core.ResponseWriter, r *core.Request) {
    core.WriteString(w, "ok\n")
}))

func NewServeMux added in v0.10.0

func NewServeMux() *ServeMux

NewServeMux returns a new *ServeMux. Compose handler maps without importing net/http directly.

mux := core.NewServeMux()
mux.HandleFunc("/health", healthHandler)
Example

ExampleNewServeMux composes a small mux + serves a request via the test server. Same shape consumers use to register agent endpoints without importing net/http directly.

mux := NewServeMux()
mux.HandleFunc("/health", func(w ResponseWriter, _ *Request) {
	WriteString(w, "ok")
})
srv := NewHTTPTestServer(mux)
defer srv.Close()

r := HTTPGet(srv.URL + "/health")
defer r.Value.(*Response).Body.Close()
body := ReadAll(r.Value.(*Response).Body)
Println(body.Value)
Output:
ok

type Service

type Service struct {
	Name     string
	Instance any // the raw service instance (for interface discovery)
	Options  Options
	OnStart  func() Result
	OnStop   func() Result
	OnReload func() Result
	// Optional marks a non-essential service: a failed OnStart logs a
	// warning and startup continues (degraded boot) instead of aborting.
	// Zero value keeps the strict contract — essential by default.
	Optional bool
}

Service is a managed component with optional lifecycle.

svc := core.Service{Name: "agent", OnStart: func() core.Result { return core.Result{OK: true} }}
core.New().Service("agent", svc)
Example

ExampleService retrieves a service through `Service` for service registration. Services register by name and can be recovered with typed helpers.

svc := Service{Name: "cache", Options: NewOptions(Option{Key: "size", Value: 128})}
Println(svc.Name)
Println(svc.Options.Int("size"))
Output:
cache
128

type ServiceFactory

type ServiceFactory func() Result

ServiceFactory defines a function that creates a Service.

factory := func() core.Result {
    return core.Result{Value: core.Service{Name: "agent"}, OK: true}
}
_ = core.ServiceFactory(factory)
Example

ExampleServiceFactory declares a service factory through `ServiceFactory` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

var factory ServiceFactory = func() Result {
	return Result{Value: Service{OnStart: func() Result { return Result{OK: true} }}, OK: true}
}
Println(factory().OK)
Output:
true

type ServiceRegistry

type ServiceRegistry struct {
	*Registry[*Service]
	// contains filtered or unexported fields
}

ServiceRegistry holds registered services. Embeds Registry[*Service] for thread-safe named storage with insertion order.

registry := &core.ServiceRegistry{Registry: core.NewRegistry[*core.Service]()}
registry.Set("agent", &core.Service{Name: "agent"})
Example

ExampleServiceRegistry declares a service registry through `ServiceRegistry` for service registration. Services register by name and can be recovered with typed helpers.

registry := &ServiceRegistry{Registry: NewRegistry[*Service]()}
registry.Set("cache", &Service{Name: "cache"})
Println(registry.Names())
Output:
[cache]

type ServiceRuntime

type ServiceRuntime[T any] struct {
	// contains filtered or unexported fields
}

ServiceRuntime is embedded in services to provide access to the Core and typed options.

c := core.New()
runtime := core.NewServiceRuntime(c, core.CliOptions{})
_ = runtime.Core()

func NewServiceRuntime

func NewServiceRuntime[T any](c *Core, opts T) *ServiceRuntime[T]

NewServiceRuntime creates a ServiceRuntime for a service constructor.

c := core.New()
runtime := core.NewServiceRuntime(c, core.CliOptions{})
_ = runtime.Options()
Example

ExampleNewServiceRuntime constructs a service runtime through `NewServiceRuntime` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

c := New()
rt := NewServiceRuntime(c, runtimeOptions{Name: "worker"})

Println(rt.Core() == c)
Println(rt.Options().Name)
Println(rt.Config() != nil)
Output:
true
worker
true

func (*ServiceRuntime[T]) Config

func (r *ServiceRuntime[T]) Config() *Config

Config is a shortcut to s.Core().Config().

host := s.Config().String("database.host")
Example

ExampleServiceRuntime_Config reads runtime configuration through `ServiceRuntime.Config` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

c := New()
c.Config().Set("host", "localhost")
rt := NewServiceRuntime(c, runtimeOptions{})
Println(rt.Config().String("host"))
Output:
localhost

func (*ServiceRuntime[T]) Core

func (r *ServiceRuntime[T]) Core() *Core

Core returns the Core instance this service is registered with.

c := s.Core()
Example

ExampleServiceRuntime_Core returns the Core instance through `ServiceRuntime.Core` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

c := New()
rt := NewServiceRuntime(c, runtimeOptions{})
Println(rt.Core() == c)
Output:
true

func (*ServiceRuntime[T]) Options

func (r *ServiceRuntime[T]) Options() T

Options returns the typed options this service was created with.

opts := s.Options()  // MyOptions{BufferSize: 1024, ...}
Example

ExampleServiceRuntime_Options reads runtime options through `ServiceRuntime.Options` for service runtime lifecycle. Service runtime setup joins Core, Config, Options, and factories in one lifecycle path.

rt := NewServiceRuntime(New(), runtimeOptions{Name: "worker"})
Println(rt.Options().Name)
Output:
worker

type Signal

type Signal struct {
	// contains filtered or unexported fields
}

Signal is the Core primitive for OS signal handling.

if c.Signal().Exists() { /* signals will be observed */ }

func (*Signal) Exists

func (s *Signal) Exists() bool

Exists reports whether a signal service is registered (and therefore whether consumers can expect signal.received broadcasts).

if !c.Signal().Exists() {
    Warn("signal handling unavailable — go-process not registered")
}
Example

ExampleSignal_Exists checks whether the signal action is registered before and after installation. OS signal integration is represented as action-backed Core behaviour.

c := New()
Println(c.Signal().Exists())
c.Action("signal.received", func(_ Context, _ Options) Result { return Result{OK: true} })
Println(c.Signal().Exists())
Output:
false
true

func (*Signal) Stop

func (s *Signal) Stop() Result

Stop instructs the signal service to unsubscribe from OS notifications. Idempotent. The service shutdown chain calls this automatically.

c.Signal().Stop()
Example

ExampleSignal_Stop stops a service through `Signal.Stop` for process signal handling. OS signal integration is represented as action-backed Core behaviour.

c := New()
c.Action("signal.stop", func(_ Context, _ Options) Result {
	return Result{Value: "stopped", OK: true}
})
r := c.Signal().Stop()
Println(r.Value)
Output:
stopped

type Startable

type Startable interface {
	OnStartup(ctx Context) Result
}

Startable is implemented by services that need startup initialisation.

func (s *MyService) OnStartup(ctx Context) core.Result {
    return core.Result{OK: true}
}
Example

ExampleStartable declares a startable service contract through `Startable` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

var _ Startable = (*contractLifecycleService)(nil)

type Step

type Step struct {
	Action string  // name of the Action to invoke
	With   Options // static options (merged with runtime opts)
	Async  bool    // run in background, don't block
	Input  string  // "previous" = output of last step piped as input
}

Step is a single step in a Task — references an Action by name.

core.Step{Action: "agentic.qa"}
core.Step{Action: "agentic.poke", Async: true}
core.Step{Action: "agentic.verify", Input: "previous"}
Example

ExampleStep declares one task step through `Step` for an agent dispatch workflow. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

step := Step{
	Action: "deploy",
	With:   NewOptions(Option{Key: "target", Value: "homelab"}),
	Input:  "previous",
}
Println(step.Action)
Println(step.With.String("target"))
Println(step.Input)
Output:
deploy
homelab
previous

type Stmt

type Stmt = sql.Stmt

Stmt is a prepared SQL statement.

r := core.SQLOpen("sqlite3", "file:./data/homelab.db")
if !r.OK { return r }
db := r.Value.(*core.DB)
defer db.Close()
stmt, err := db.Prepare("select name from agents where id = ?")
if err == nil { defer stmt.Close() }

type Stoppable

type Stoppable interface {
	OnShutdown(ctx Context) Result
}

Stoppable is implemented by services that need shutdown cleanup.

func (s *MyService) OnShutdown(ctx Context) core.Result {
    return core.Result{OK: true}
}
Example

ExampleStoppable declares a stoppable service contract through `Stoppable` for service contract wiring. Service lifecycle contracts remain small interfaces and option hooks.

var _ Stoppable = (*contractLifecycleService)(nil)

type Stream

type Stream interface {
	Send(data []byte) error
	Receive() ([]byte, error)
	Close() error
}

Stream is a bidirectional connection to a remote endpoint. Consumers implement this for each transport protocol.

type httpStream struct { ... }
func (s *httpStream) Send(data []byte) error { ... }
func (s *httpStream) Receive() ([]byte, error) { ... }
func (s *httpStream) Close() error { ... }

type StreamFactory

type StreamFactory func(handle *DriveHandle) (Stream, error)

StreamFactory creates a Stream from a DriveHandle's transport config. Registered per-protocol by consumer packages.

factory := func(handle *core.DriveHandle) (core.Stream, error) {
    return nil, core.NewError(core.Concat("protocol unavailable: ", handle.Transport))
}
core.New().API().RegisterProtocol("mcp", factory)

type StringReader added in v0.10.4

type StringReader = strings.Reader

StringReader is an alias for strings.Reader — the io.Reader/Seeker over an in-memory string returned by NewReader. Lets consumers declare reader-typed fields without importing strings. Named StringReader (not Reader) because core.Reader already aliases io.Reader.

var r *core.StringReader = core.NewReader("payload")

type StructField added in v0.10.4

type StructField = reflect.StructField

StructField is an alias for reflect.StructField — one field's descriptor (Name, Type, Tag, offset) returned by Type.Field during struct introspection.

f := core.TypeOf(opts).Field(0)
tag := f.Tag.Get("json")

type SyncMap

type SyncMap struct {
	// contains filtered or unexported fields
}

SyncMap is a concurrent map. Same semantics and memory model as sync.Map.

var cache core.SyncMap
cache.Store("config.host", "homelab.lthn.sh")
if value, ok := cache.Load("config.host"); ok {
    core.Println(value)
}

func (*SyncMap) Clear

func (m *SyncMap) Clear()

Clear deletes all entries.

m.Clear()
Example

ExampleSyncMap_Clear removes all entries through `SyncMap.Clear`.

var m SyncMap
m.Store("key", 1)
m.Clear()
_, ok := m.Load("key")
Println(ok)
Output:
false

func (*SyncMap) CompareAndDelete

func (m *SyncMap) CompareAndDelete(key, old any) (deleted bool)

CompareAndDelete deletes the entry for key only if the current value equals old.

if m.CompareAndDelete("key", expected) { /* deleted */ }
Example

ExampleSyncMap_CompareAndDelete deletes only if the current value matches through `SyncMap.CompareAndDelete`.

var m SyncMap
m.Store("key", 1)
Println(m.CompareAndDelete("key", 1))
Output:
true

func (*SyncMap) CompareAndSwap

func (m *SyncMap) CompareAndSwap(key, old, new any) (swapped bool)

CompareAndSwap stores new for key only if the current value equals old.

if m.CompareAndSwap("key", old, new) { /* swapped */ }
Example

ExampleSyncMap_CompareAndSwap swaps only if the current value matches through `SyncMap.CompareAndSwap`.

var m SyncMap
m.Store("key", 1)
Println(m.CompareAndSwap("key", 1, 2))
Output:
true

func (*SyncMap) Delete

func (m *SyncMap) Delete(key any)

Delete removes the value for key.

m.Delete("key")
Example

ExampleSyncMap_Delete removes a key through `SyncMap.Delete`.

var m SyncMap
m.Store("key", 1)
m.Delete("key")
_, ok := m.Load("key")
Println(ok)
Output:
false

func (*SyncMap) Load

func (m *SyncMap) Load(key any) (value any, ok bool)

Load returns the value stored for key, or nil and ok=false if not present.

if v, ok := m.Load("key"); ok { /* use v */ }
Example

ExampleSyncMap_Load reads a key through `SyncMap.Load`.

var m SyncMap
m.Store("key", "value")
v, ok := m.Load("key")
Println(v, ok)
Output:
value true

func (*SyncMap) LoadAndDelete

func (m *SyncMap) LoadAndDelete(key any) (value any, loaded bool)

LoadAndDelete deletes the value for key, returning the previous value if any.

v, loaded := m.LoadAndDelete("key")
Example

ExampleSyncMap_LoadAndDelete reads then removes a key through `SyncMap.LoadAndDelete`.

var m SyncMap
m.Store("key", 1)
v, loaded := m.LoadAndDelete("key")
Println(v, loaded)
Output:
1 true

func (*SyncMap) LoadOrStore

func (m *SyncMap) LoadOrStore(key, value any) (actual any, loaded bool)

LoadOrStore returns the existing value if present, otherwise stores and returns the given value. loaded is true if value was loaded, false if stored.

actual, loaded := m.LoadOrStore("key", defaultValue)
Example

ExampleSyncMap_LoadOrStore returns the existing value or stores a new one through `SyncMap.LoadOrStore`.

var m SyncMap
m.Store("key", 1)
actual, loaded := m.LoadOrStore("key", 2)
Println(actual, loaded)
Output:
1 true

func (*SyncMap) Range

func (m *SyncMap) Range(f func(key, value any) bool)

Range calls f sequentially for each key/value present. If f returns false, Range stops. f may be called concurrently with other operations on the map.

m.Range(func(k, v any) bool {
    Println(k, v)
    return true
})
Example

ExampleSyncMap_Range iterates over all entries through `SyncMap.Range`.

var m SyncMap
m.Store("only", 1)
count := 0
m.Range(func(_, _ any) bool {
	count++
	return true
})
Println(count)
Output:
1

func (*SyncMap) Store

func (m *SyncMap) Store(key, value any)

Store sets the value for key.

m.Store("key", value)
Example

ExampleSyncMap_Store writes a key through `SyncMap.Store`.

var m SyncMap
m.Store("agents", 3)
v, _ := m.Load("agents")
Println(v)
Output:
3

func (*SyncMap) Swap

func (m *SyncMap) Swap(key, value any) (previous any, loaded bool)

Swap stores value for key and returns the previous value, if any.

previous, loaded := m.Swap("key", new)
Example

ExampleSyncMap_Swap replaces a value and returns the previous one through `SyncMap.Swap`.

var m SyncMap
m.Store("key", 1)
prev, loaded := m.Swap("key", 2)
Println(prev, loaded)
Output:
1 true

type SysInfo

type SysInfo struct {
	// contains filtered or unexported fields
}

SysInfo holds read-only system information, populated once at init.

home := core.Env("DIR_HOME")
core.Println(home)
Example

ExampleSysInfo declares runtime system information through `SysInfo` for runtime diagnostics. Runtime and environment facts are exposed as stable diagnostic values.

var info *SysInfo
_ = info

type T

type T = testing.T

T is the canonical Go test handle, exported as core.T so test files don't need a separate `import "testing"` line. Go's test runner accepts *core.T in TestXxx signatures because the alias is type-identical to *testing.T.

func TestSomething_Good(t *core.T) {
    core.AssertEqual(t, expected, actual)
}
Example

ExampleT documents the testing alias through `T` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
_ = t

type TB

type TB = testing.TB

TB is the testing-handle interface (T + B), exported as core.TB so helpers can accept either Test or Benchmark contexts without importing testing.

func helper(t core.TB, ...) { t.Helper(); ... }
Example

ExampleTB documents the testing interface alias through `TB` for AX-native tests. Passing assertions are silent while failures stay one-line and AI-readable.

var t *T
var tb TB = t
_ = tb

type TCPAddr

type TCPAddr = net.TCPAddr

TCPAddr is a TCP endpoint address.

addr := &core.TCPAddr{IP: core.ParseIP("192.0.2.10"), Port: 443}
core.Println(addr.String())

type TCPConn

type TCPConn = net.TCPConn

TCPConn is a connected TCP socket.

r := core.NetDial("tcp", "127.0.0.1:8080")
if r.OK {
    conn := r.Value.(*core.TCPConn)
    defer conn.Close()
}

type TCPListener

type TCPListener = net.TCPListener

TCPListener accepts inbound TCP connections.

r := core.NetListen("tcp", "127.0.0.1:0")
if !r.OK { return r }
ln := r.Value.(*core.TCPListener)
defer ln.Close()

type Table

type Table struct {
	// contains filtered or unexported fields
}

Table writes tab-aligned rows to an underlying writer.

table := core.NewTable(out)
table.Row("Name", "Status").Row("api", "ok")
_ = table.Flush()

func NewTable

func NewTable(w Writer) *Table

NewTable creates a Table that writes tab-aligned rows to w.

table := core.NewTable(out)
Example

ExampleNewTable creates a table through `NewTable` for CLI table output. Tabular CLI output is built and flushed through the table wrapper.

buf := NewBuffer()
table := NewTable(buf)
table.Row("Name", "Status").Row("api", "ok")
table.Flush()

Println(Contains(buf.String(), "api"))
Output:
true

func (*Table) Flush

func (t *Table) Flush() Result

Flush flushes buffered table output to the underlying writer. Returns Result with OK=false + Code "table.flush.failed" when the underlying writer rejects the flush.

r := table.Flush()
if !r.OK { return r }
Example

ExampleTable_Flush flushes a table through `Table.Flush` for CLI table output. Tabular CLI output is built and flushed through the table wrapper.

buf := NewBuffer()
table := NewTable(buf)
table.Row("Name", "Status")
Println(table.Flush().OK)
Output:
true

func (*Table) Row

func (t *Table) Row(cells ...string) *Table

Row writes one row and returns the Table for chaining.

table.Row("Name", "Status").Row("api", "ok")
Example

ExampleTable_Row adds a row through `Table.Row` for CLI table output. Tabular CLI output is built and flushed through the table wrapper.

buf := NewBuffer()
NewTable(buf).Row("Service", "Port").Row("api", "8080").Flush()
Println(Contains(buf.String(), "8080"))
Output:
true

type Task

type Task struct {
	Name        string
	Description string
	Steps       []Step
}

Task is a named sequence of Steps.

c.Task("agent.completion", core.Task{
    Steps: []core.Step{
        {Action: "agentic.qa"},
        {Action: "agentic.auto-pr"},
        {Action: "agentic.verify"},
        {Action: "agentic.poke", Async: true},
    },
})
Example

ExampleTask declares a named task that points at a deployment planning step. Consumers copy the Result-shaped handler contract for dAppCore actions and tasks.

task := Task{Name: "deploy", Steps: []Step{{Action: "deploy.plan"}}}
Println(task.Name)
Println(task.Steps[0].Action)
Output:
deploy
deploy.plan

func (*Task) Run

func (t *Task) Run(ctx Context, c *Core, opts Options) Result

Run executes the task's steps in order. Sync steps run sequentially — if any fails, the chain stops. Async steps are dispatched and don't block. The "previous" input pipes the last sync step's output to the next step.

r := c.Task("deploy").Run(ctx, opts)
Example

ExampleAction_Task_Run runs `Task.Run` with representative caller inputs for background task progress. Asynchronous work reports progress through Core task helpers.

c := New()
var order string

c.Action("step.a", func(_ Context, _ Options) Result {
	order += "a"
	return Result{Value: "from-a", OK: true}
})
c.Action("step.b", func(_ Context, opts Options) Result {
	order += "b"
	input := opts.Get("_input")
	if input.OK {
		return Result{Value: "got:" + input.Value.(string), OK: true}
	}
	return Result{OK: true}
})

c.Task("pipe", Task{
	Steps: []Step{
		{Action: "step.a"},
		{Action: "step.b", Input: "previous"},
	},
})

r := c.Task("pipe").Run(Background(), c, NewOptions())
Println(order)
Println(r.Value)
Output:
ab
got:from-a

type Template

type Template = template.Template

Template is a parsed text template, ready to execute against data.

tmpl := core.NewTemplate("status")
r, err := tmpl.Parse("agent {{.Name}} ready")
if err == nil { _ = r }

func NewTemplate

func NewTemplate(name string) *Template

NewTemplate creates an empty named template.

tmpl := core.NewTemplate("status")
Example

ExampleNewTemplate creates a template through `NewTemplate` for operator-facing templates. Parsing and execution use core template wrappers for operator-facing text.

tmpl, _ := NewTemplate("greeting").Parse("hello {{.Name}}")
buf := NewBuffer()
ExecuteTemplate(tmpl, buf, map[string]string{"Name": "codex"})
Println(buf.String())
Output:
hello codex

type Ticker added in v0.10.0

type Ticker = time.Ticker

Ticker delivers Time values at regular intervals on its C channel. Stop the ticker with Stop() to release resources.

func NewTicker added in v0.10.0

func NewTicker(d Duration) *Ticker

NewTicker returns a new Ticker that fires every duration d on its C channel. The caller MUST call Stop() to release the underlying timer.

ticker := core.NewTicker(30 * core.Second)
defer ticker.Stop()
for range ticker.C {
    poll()
}
Example

ExampleNewTicker fires periodic ticks for poll loops. Caller MUST Stop the ticker to release the underlying timer; the example reads one tick + stops to keep the example test bounded.

ticker := NewTicker(10 * Millisecond)
defer ticker.Stop()
<-ticker.C
Println("tick")
Output:
tick

type Time

type Time = time.Time

Time is a moment — alias of time.Time so consumers can take timestamps without importing the time package.

deadline := core.Now().Add(2 * core.Minute)

func Date added in v0.10.4

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Date returns the Time corresponding to the given calendar fields in the given Location. Out-of-range values are normalised (e.g. month 13 rolls into the next year), mirroring the stdlib.

ts := core.Date(2026, core.April, 28, 7, 0, 0, 0, core.UTC)
Example

ExampleDate constructs a Time from calendar fields through `Date`.

t := Date(2024, January, 15, 10, 30, 0, 0, UTC)
Println(t.Year(), t.Month(), t.Day())
Output:
2024 January 15

func Unix added in v0.10.0

func Unix(sec, nsec int64) Time

Unix returns the Time at sec seconds + nsec nanoseconds since the Unix epoch. Mirrors the stdlib signature for callers that need sub-second precision; UnixTime is the sec-only shorthand.

ts := core.Unix(sec, nsec)
Example

ExampleUnix builds a timestamp from seconds + nanoseconds through `Unix` for health-check timing. Mirrors the stdlib two-arg signature; UnixTime is the sec-only shorthand.

Println(Contains(Sprint(Unix(0, 0)), "1970-01-01"))
Output:
true

func UnixMilli added in v0.10.0

func UnixMilli(ms int64) Time

UnixMilli returns the Time at the given milliseconds since the Unix epoch. Useful for parsing JSON timestamps and other ms-resolution APIs.

ts := core.UnixMilli(jsonField)
Example

ExampleUnixMilli builds a timestamp from milliseconds through `UnixMilli` for parsing JSON timestamps and other ms-resolution APIs without importing time directly.

Println(Contains(Sprint(UnixMilli(0)), "1970-01-01"))
Output:
true

type Timer added in v0.10.4

type Timer = time.Timer

Timer fires once on its C channel after a duration elapses. Stop the timer with Stop() to release resources if it has not fired.

func AfterFunc added in v0.10.4

func AfterFunc(d Duration, f func()) *Timer

AfterFunc waits for the duration to elapse and then calls f in its own goroutine. It returns a Timer that can be used to cancel the call with its Stop method.

timer := core.AfterFunc(2*core.Second, func() { cleanup() })
defer timer.Stop()
Example

ExampleAfterFunc runs a function after a delay through `AfterFunc`.

timer := AfterFunc(Hour, func() {})
defer timer.Stop()

func NewTimer added in v0.10.4

func NewTimer(d Duration) *Timer

NewTimer returns a new Timer that sends the current time on its C channel after at least duration d.

timer := core.NewTimer(5 * core.Second)
defer timer.Stop()
<-timer.C
Example

ExampleNewTimer fires once after a delay through `NewTimer`.

timer := NewTimer(Hour)
defer timer.Stop()

type Translator

type Translator interface {
	// Translate translates a message by its ID with optional arguments.
	Translate(messageID string, args ...any) Result
	// SetLanguage sets the active language (BCP47 tag, e.g., "en-GB", "de").
	SetLanguage(lang string) Result
	// Language returns the current language code.
	Language() string
	// AvailableLanguages returns all loaded language codes.
	AvailableLanguages() []string
}

Translator defines the interface for translation services. Implemented by go-i18n's Srv.

c := core.New()
if r := c.I18n().Translator(); r.OK {
    tr := r.Value.(core.Translator)
    _ = tr.SetLanguage("en-GB")
}
Example

ExampleTranslator declares a translator through `Translator` for operator-facing localisation. Language selection and translation stay behind the I18n service.

var tr Translator = &exampleTranslator{lang: "en"}
Println(tr.Language())
Output:
en

type Tx

type Tx = sql.Tx

Tx is an in-progress SQL transaction.

r := core.SQLOpen("sqlite3", "file:./data/homelab.db")
if !r.OK { return r }
db := r.Value.(*core.DB)
defer db.Close()
tx, err := db.Begin()
if err == nil { defer tx.Rollback() }

type Type

type Type = reflect.Type

Type is the runtime type descriptor returned by TypeOf.

t := core.TypeOf(opts)
name := t.Name()

func TypeFor added in v0.10.4

func TypeFor[T any]() Type

TypeFor returns the Type for the compile-time type T. The type-safe replacement for TypeOf((*T)(nil)).Elem() — no nil-pointer dance, no runtime value needed.

t := core.TypeFor[MyStruct]()
if t.Kind() == core.KindStruct { ... }
Example

ExampleTypeFor names a type at compile time through `TypeFor`, with no nil-pointer dance. Reflection stays behind a narrow core surface for rare inspection code.

Println(TypeFor[string]().Kind())
Output:
string

func TypeOf

func TypeOf(v any) Type

TypeOf returns the runtime type of v. Returns nil if v is a nil interface value.

t := core.TypeOf(opts)
if t.Kind() == core.KindStruct { ... }
Example

ExampleTypeOf reads a type through `TypeOf` for runtime inspection. Reflection stays behind a narrow core surface for rare inspection code.

t := TypeOf(42)
Println(t.Kind())
Output:
int

type UDPAddr

type UDPAddr = net.UDPAddr

UDPAddr is a UDP endpoint address.

addr := &core.UDPAddr{IP: core.ParseIP("192.0.2.10"), Port: 5353}
core.Println(addr.String())

type UDPConn

type UDPConn = net.UDPConn

UDPConn is a UDP packet connection.

r := core.NetListenPacket("udp", "127.0.0.1:0")
if r.OK {
    conn := r.Value.(*core.UDPConn)
    defer conn.Close()
}

type URL

type URL = url.URL

URL is the canonical parsed URL type.

r := core.URLParse("https://example.com/path")
if r.OK { u := r.Value.(*core.URL); _ = u }

type URLValues

type URLValues = url.Values

URLValues is the canonical URL form/query values map.

values := core.URLValues{"key": {"value"}}

type UnixAddr

type UnixAddr = net.UnixAddr

UnixAddr is a Unix-domain socket address.

addr := &core.UnixAddr{Name: "/tmp/agent.sock", Net: "unix"}
core.Println(addr.String())

type UnixConn

type UnixConn = net.UnixConn

UnixConn is a Unix-domain socket connection.

r := core.NetDial("unix", "/tmp/agent.sock")
if r.OK {
    conn := r.Value.(*core.UnixConn)
    defer conn.Close()
}

type UnixListener

type UnixListener = net.UnixListener

UnixListener accepts inbound Unix-domain connections.

r := core.NetListen("unix", "/tmp/agent.sock")
if r.OK {
    ln := r.Value.(*core.UnixListener)
    defer ln.Close()
}

type UsageRecorder

type UsageRecorder func(action string, quantity int, ctx Context)

UsageRecorder records consumption after a gated action succeeds. Consumer packages provide the implementation (database, cache, etc).

recorder := func(action string, quantity int, ctx Context) {
    core.Info("usage recorded", "action", action, "quantity", quantity)
}
core.New().SetUsageRecorder(core.UsageRecorder(recorder))
Example

ExampleUsageRecorder declares a usage recorder through `UsageRecorder` for usage-gated agent features. Usage checks separate policy decisions from the action body.

var recorded string
var recorder UsageRecorder = func(action string, quantity int, _ Context) {
	recorded = Sprintf("%s:%d", action, quantity)
}
recorder("ai.credits", 3, Background())
Println(recorded)
Output:
ai.credits:3

type User

type User = user.User

User represents a system user with username, uid, gid, and home dir. Alias of os/user.User.

u := core.UserCurrent().Value.(*core.User)
core.Println(u.Username, u.HomeDir)

type Value

type Value = reflect.Value

Value is the runtime value handle returned by ValueOf.

v := core.ValueOf(42)
n := v.Int()

func MakeFunc added in v0.10.4

func MakeFunc(t Type, fn func(args []Value) (results []Value)) Value

MakeFunc returns a new function Value of type t whose body calls fn with the in-arguments and returns fn's results. Used to synthesise functions (proxies, generic adapters) at runtime — reach for it only when a closure over a concrete signature genuinely cannot.

fn := core.MakeFunc(t, func(args []core.Value) []core.Value { ... })
Example

ExampleMakeFunc builds a callable Value at runtime through `MakeFunc`.

fn := MakeFunc(TypeFor[func()](), func(args []Value) []Value { return nil })
_ = fn // an invokable reflect.Value wrapping the synthesised function

func MakeMap added in v0.10.4

func MakeMap(t Type) Value

MakeMap returns a Value representing a new empty map of map type t.

m := core.MakeMap(core.TypeFor[map[string]int]())
Example

ExampleMakeMap allocates a typed map Value through `MakeMap`.

Println(MakeMap(TypeFor[map[string]int]()).Len())
Output:
0

func MakeMapWithSize added in v0.10.4

func MakeMapWithSize(t Type, n int) Value

MakeMapWithSize returns a new empty map of type t pre-sized for about n entries — the reflective make(map, n) hint.

m := core.MakeMapWithSize(core.TypeFor[map[string]int](), 64)
Example

ExampleMakeMapWithSize allocates a sized map Value through `MakeMapWithSize`.

Println(MakeMapWithSize(TypeFor[map[string]int](), 8).Len())
Output:
0

func MakeSlice added in v0.10.4

func MakeSlice(t Type, len, cap int) Value

MakeSlice returns a Value representing a new slice of element type's slice t with the given length and capacity. t must have Kind Slice; callers control that, so this stays infallible (panics on a non-slice type, matching the stdlib contract).

s := core.MakeSlice(core.TypeFor[[]int](), 0, 8)
Example

ExampleMakeSlice allocates a typed slice Value through `MakeSlice`.

s := MakeSlice(TypeFor[[]int](), 0, 4)
Println(s.Cap())
Output:
4

func NewValue added in v0.10.4

func NewValue(t Type) Value

NewValue returns a Value representing a pointer to a new zero value of type t — the reflective equivalent of new(T). Named NewValue (not New) because core.New is the framework constructor.

ptr := core.NewValue(core.TypeFor[Config]())  // *Config, zeroed
cfg := ptr.Elem().Interface().(Config)
Example

ExampleNewValue allocates a zeroed value of a reflected type through `NewValue` — the reflective new(T).

ptr := NewValue(TypeFor[int]())
ptr.Elem().SetInt(7)
Println(ptr.Elem().Int())
Output:
7

func ValueOf

func ValueOf(v any) Value

ValueOf returns a Value initialised to the concrete value stored in v. Returns the zero Value if v is a nil interface value.

val := core.ValueOf(42)
n := val.Int()  // 42
Example

ExampleValueOf reads a value wrapper through `ValueOf` for runtime inspection. Reflection stays behind a narrow core surface for rare inspection code.

v := ValueOf("hello")
Println(v.String())
Output:
hello

func Zero

func Zero(t Type) Value

Zero returns a Value representing the zero value for type t. Used for default-value comparison without an explicit zero literal.

t := core.TypeOf((*MyStruct)(nil))
zero := core.Zero(t.Elem()).Interface()
Example

ExampleZero builds the zero Value of a type through `Zero`.

Println(Zero(TypeFor[int]()).Int())
Output:
0

type WaitGroup

type WaitGroup struct {
	// contains filtered or unexported fields
}

WaitGroup waits for a collection of goroutines to finish.

var wg core.WaitGroup
for _, item := range items {
    wg.Add(1)
    go func(it Item) {
        defer wg.Done()
        process(it)
    }(item)
}
wg.Wait()
Example
var wg WaitGroup
wg.Add(1)
go func() {
	defer wg.Done()
	Println("worker done")
}()
wg.Wait()
Output:
worker done

func (*WaitGroup) Add

func (w *WaitGroup) Add(delta int)

Add adds delta, which may be negative, to the WaitGroup counter.

var wg core.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); core.Println("agent done") }()
wg.Wait()
Example

ExampleWaitGroup_Add registers pending work through `WaitGroup.Add`.

var wg WaitGroup
wg.Add(1)
wg.Done()
wg.Wait()

func (*WaitGroup) Done

func (w *WaitGroup) Done()

Done decrements the WaitGroup counter by one.

var wg core.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); core.Println("agent done") }()
wg.Wait()
Example

ExampleWaitGroup_Done marks one unit of work complete through `WaitGroup.Done`.

var wg WaitGroup
wg.Add(1)
wg.Done()
wg.Wait()

func (*WaitGroup) Go

func (w *WaitGroup) Go(fn func())

Go starts fn in a new goroutine, automatically incrementing the counter before launch and decrementing it (via Done) after fn returns. Equivalent to Add(1) + go fn() + defer Done() but race-safe against the WaitGroup being reused.

var wg core.WaitGroup
wg.Go(func() { core.Println("agent done") })
wg.Wait()
Example

ExampleWaitGroup_Go runs a function in a tracked goroutine through `WaitGroup.Go`.

var wg WaitGroup
wg.Go(func() { Println("done") })
wg.Wait()
Output:
done

func (*WaitGroup) Wait

func (w *WaitGroup) Wait()

Wait blocks until the WaitGroup counter is zero.

var wg core.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); core.Println("agent done") }()
wg.Wait()
Example

ExampleWaitGroup_Wait blocks until the counter reaches zero through `WaitGroup.Wait`.

var wg WaitGroup
wg.Wait() // returns immediately on a zero counter

type WalkDirFunc

type WalkDirFunc = fs.WalkDirFunc

WalkDirFunc visits one path during a filesystem walk.

fn := func(path string, d core.FsDirEntry, err error) error { return err }
_ = fn

type Weekday added in v0.10.4

type Weekday = time.Weekday

Weekday specifies a day of the week (Sunday = 0, ...) — alias of time.Weekday so callers can switch on Now().Weekday() without importing the time package.

if core.Now().Weekday() == core.Sunday { rest() }

type WriteCloser

type WriteCloser = io.WriteCloser

WriteCloser composes Writer and Closer.

fsys := (&core.Fs{}).New("/tmp/agent-workspace")
r := fsys.Create("logs/agent.log")
if !r.OK { return r }
writer := r.Value.(core.WriteCloser)
defer writer.Close()

type Writer

type Writer = io.Writer

Writer is the canonical io.Writer interface, exported as core.Writer.

var writer core.Writer = core.Stdout()
r := core.WriteString(writer, "agent ready\n")
if !r.OK { return r }
Example

ExampleWriter declares a writer through `Writer` for streaming payloads. Stream copying, EOF checks, and writes avoid direct io imports in consumers.

var w Writer = NewBuffer()
n := WriteString(w, "hello")
Println(n.Value)
Output:
5
var Discard Writer = io.Discard

Discard is a Writer on which all Write calls succeed without doing anything.

table := core.NewTable(core.Discard)

func Stderr

func Stderr() Writer

Stderr returns the canonical standard error stream as an io.Writer.

core.WriteString(core.Stderr(), "warning\n")
Example

ExampleStderr reads standard error through `Stderr` for process IO access. File modes and standard streams are exposed through core aliases.

Println(Stderr() != nil)
Output:
true

func Stdout

func Stdout() Writer

Stdout returns the canonical standard output stream as an io.Writer.

core.WriteString(core.Stdout(), "ready\n")
Example

ExampleStdout reads standard output through `Stdout` for process IO access. File modes and standard streams are exposed through core aliases.

Println(Stdout() != nil)
Output:
true

Directories

Path Synopsis
agent module
ai module
ansible module
api module
build module
cache module
cgo module
cli module
config module
container module
core module
ai module
ansible module
api module
blockchain module
build module
cache module
cli module
config module
container module
crypt module
devops module
docs module
forge module
html module
i18n module
inference module
infra module
io module
log module
ml module
mlx module
p2p module
process module
rag module
scm module
session module
store module
webview module
ws module
forge module
gui module
html module
i18n module
inference module
io module
lint module
log module
mcp module
ml module
mlx module
orm module
p2p module
process module
proxy module
rag module
ratelimit module
render module
scm module
store module
stream module
tests
ts module
update module
webview module
ws module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL