kernel

package
v0.9.6 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package kernel implements the single operation kernel (architecture specification invariants 2–3, KERNEL-001..007): every mutation from every source — HTTP, SDK, MCP, AI, CLI, UI, integrations, workers — enters one pipeline that resolves tenant and actor, authorizes, validates, checks idempotency and concurrency, executes one SQL transaction containing the business mutation plus the idempotency receipt, the audit row, and the outbox events, and returns a typed OperationResult.

The kernel never talks to a provider directly; durable delivery happens exclusively through the transactional outbox and its publishers.

Index

Constants

View Source
const (
	CommandRecordCreate = "record.create"
	CommandRecordUpdate = "record.update"
)

Command names are canonical across all sources. Adapters resolve these definitions from the registry; they never implement their own semantics.

Variables

View Source
var (
	ErrUnauthenticated = contract.NewError(contract.CodeUnauthenticated, "operation context has no authenticated actor")
	ErrNoSite          = contract.NewError(contract.CodeValidationFailed, "operation context missing tenant site")
	ErrPermission      = contract.NewError(contract.CodePermissionDenied, "not permitted")
	ErrStaleVersion    = contract.NewError(contract.CodeConflict, "document was modified by another operation")
	ErrKeyReused       = contract.NewError(contract.CodeIdempotencyKeyReused, "idempotency key already used with a different payload")
)

Typed sentinel errors. Adapters map these to wire errors via contract.Code; they must never be detected by string matching.

Functions

func CanonicalDocHash

func CanonicalDocHash(fields map[string]any) string

CanonicalDocHash renders a document's field map as sorted-key JSON and returns the sha256 hex digest — the audit before/after state token (KERNEL-009). Hash input is deterministic: sorted keys, JSON-encoded values.

func CanonicalVersion

func CanonicalVersion(v any) string

CanonicalVersion renders a document version token (the `modified` timestamp) in a stable string form so callers can echo it back as expected_version regardless of driver time parsing.

Types

type AuditRow

type AuditRow struct {
	ID            string
	Site          string
	OperationID   string
	CorrelationID string
	CausationID   string
	Source        string
	PrincipalType string
	PrincipalID   string
	ActorUser     string
	ActorRoles    string // JSON array of role names; empty when none
	Command       string
	Doctype       string
	DocName       string
	Status        string
	ErrorCode     string
	PayloadHash   string
	BeforeHash    string
	AfterHash     string
}

AuditRow is one immutable operation-audit ledger entry (_kora_operation_audit). The ledger records who did what, from which source, with which outcome — never payloads or secrets. Before/after hashes (KERNEL-009) carry sha256 digests of canonicalized document state so tampering is detectable without storing sensitive values.

type CommandDefinition

type CommandDefinition struct {
	Name            string
	Version         int
	AuthorizesWith  string // permission-matrix operation ("create", "write")
	IdempotentByKey bool   // replay-safe when an idempotency key is present
}

CommandDefinition is the single registered description of a command: its payload shape, authorization operation, idempotency class, and timeout.

func LookupCommand

func LookupCommand(name string) (CommandDefinition, bool)

LookupCommand returns the canonical definition for a command name.

type CommandInput

type CommandInput struct {
	Record string `yaml:"record" json:"record"`
}

CommandInput types the payload. The slice form binds one record kind; collection-based inputs arrive with SPEC-003.

type CommandRegistry

type CommandRegistry struct {
	// contains filtered or unexported fields
}

CommandRegistry holds generation-scoped command definitions. It is safe for concurrent reads after loading; Register is intended during activation only.

func LoadCommandDir

func LoadCommandDir(dir string) (*CommandRegistry, error)

LoadCommandDir parses every *.yaml file in dir (sorted by filename for deterministic registration order) into a fresh CommandRegistry. Parsing is strict: any invalid definition aborts the whole load and returns the accumulated errors — configuration is never silently discarded. A missing directory returns an empty registry and no error, so deployments without command definitions need no special-casing.

func NewCommandRegistry

func NewCommandRegistry() *CommandRegistry

NewCommandRegistry returns an empty registry.

func (*CommandRegistry) List

func (r *CommandRegistry) List() []*CommandResource

List returns all registered definitions sorted by name for stable introspection output.

func (*CommandRegistry) Lookup

func (r *CommandRegistry) Lookup(name string) (*CommandResource, bool)

Lookup resolves a command by full name.

func (*CommandRegistry) Register

func (r *CommandRegistry) Register(def *CommandResource) error

Register adds a definition; duplicate full names are rejected with a typed error so two packs cannot silently shadow each other.

type CommandResource

type CommandResource struct {
	Name          string            `yaml:"name"                     json:"name"`
	Namespace     string            `yaml:"namespace"                json:"namespace,omitempty"`
	Version       int               `yaml:"version"                  json:"version"`
	Permission    string            `yaml:"permission"               json:"permission"` // permission-matrix operation, default "create"
	Input         CommandInput      `yaml:"input"                    json:"input"`
	Preconditions []string          `yaml:"preconditions"            json:"preconditions,omitempty"`
	Steps         []CommandStep     `yaml:"transaction"              json:"transaction"`
	Emits         []string          `yaml:"emit"                     json:"emit,omitempty"`
	Labels        map[string]string `yaml:"labels"                   json:"labels,omitempty"`
}

CommandResource is a config-defined business command (KERNEL-008, spec §19): a named, versioned mutation with typed input, optional preconditions, transaction steps over records, and emitted events. Definitions load from application configuration exactly like doctypes — no code generation.

Slice limitations (documented, not silent):

  • update steps resolve their target by name equality only;
  • preconditions are validated as declared rule references and enforced once the rule evaluator contract lands (PLUGIN-007); unknown rules fail definition registration.

func ParseCommandResource

func ParseCommandResource(raw []byte) (*CommandResource, error)

ParseCommandResource parses one command definition from YAML bytes with strict unknown-key rejection (KnownFields) so unsupported configuration is never silently discarded.

func (*CommandResource) FullName

func (c *CommandResource) FullName() string

FullName is the canonical registry key: the namespace prefixes the name unless the name already carries it ("livestock.animal.register").

func (*CommandResource) PermOperation

func (c *CommandResource) PermOperation() string

PermOperation is the permission-matrix operation this command requires.

func (*CommandResource) TouchedRecords

func (c *CommandResource) TouchedRecords() []string

TouchedRecords returns the distinct record kinds the command mutates, in first-touch order. Authorization evaluates every one of them.

type CommandStep

type CommandStep struct {
	Create *StepCreate `yaml:"create,omitempty" json:"create,omitempty"`
	Update *StepUpdate `yaml:"update,omitempty" json:"update,omitempty"`
}

CommandStep is one transactional write. Values map target record fields to literal values or "$input.field" references into the operation payload.

type Kernel

type Kernel struct {
	Dialect db.Dialect
	Outbox  outbox.Writer

	// Commands holds config-defined command resources (KERNEL-008). Nil means
	// only built-in commands are available. Definitions are generation-scoped:
	// swap the registry atomically on activation.
	Commands *CommandRegistry
}

Kernel is the process-wide operation entry point. It is safe for concurrent use; per-site state (DB handle, registry) is supplied per call via SiteDB.

func New

func New(dialect db.Dialect, w outbox.Writer) *Kernel

New returns a Kernel. Outbox may be nil only in tests that do not assert event delivery; production wiring always supplies outbox.NewSQLWriter().

func (*Kernel) Execute

func (k *Kernel) Execute(ctx context.Context, siteDB *sql.DB, reg *doctype.Registry, op Operation) (contract.CommandResult, *contract.Error)

Execute runs the full pipeline for op against the given site database and registry. Exactly one of the following occurs:

  • completed: business row + receipt + audit + outbox rows committed atomically;
  • replayed: a prior committed result for the same site+idempotency key is returned;
  • rejected: a typed error; nothing is persisted (transaction rolled back).

type Operation

type Operation struct {
	Context  OperationContext
	Command  string          // canonical command name
	Payload  json.RawMessage // JSON-encoded typed payload
	Deadline time.Time       // zero means no deadline; enforced before execution
}

Operation is a fully specified invocation handed to Kernel.Execute.

type OperationContext

type OperationContext struct {
	Site            string                // tenant identifier (site name)
	Actor           contract.ActorContext // authenticated principal
	User            string                // owner-attribution user ("" → "system")
	Roles           []string              // roles used for permission-matrix lookup
	Source          Source                // adapter surface
	CorrelationID   string
	CausationID     string
	ExpectedVersion string
	IdempotencyKey  string
}

OperationContext carries everything an adapter must resolve before invoking the kernel. It is an explicit value, never smuggled through context.Context.

type RecordCreatePayload

type RecordCreatePayload struct {
	Doctype string          `json:"doctype"`
	Data    json.RawMessage `json:"data"`
}

RecordCreatePayload is the typed payload for record.create. Field values are schema-generic by design (the engine is config-driven) but are always validated against the doctype definition before execution; invalid shapes produce typed ValidationError lists, never silent acceptance.

type RecordUpdatePayload

type RecordUpdatePayload struct {
	Doctype string          `json:"doctype"`
	Name    string          `json:"name"`
	Data    json.RawMessage `json:"data"`
}

RecordUpdatePayload is the typed payload for record.update.

type ResultData

type ResultData struct {
	Doctype   string `json:"doctype"`
	Name      string `json:"name"`
	Created   bool   `json:"created"`
	AuditID   string `json:"audit_id"`
	Operation string `json:"operation_id"`
}

ResultData is the typed success payload returned by record commands.

type Source

type Source string

Source identifies the adapter surface that produced an operation. It is recorded on the audit ledger and drives authorization-parity tests: two sources executing the same command must produce identical outcomes.

const (
	SourceHTTP        Source = "http"
	SourceSDK         Source = "sdk"
	SourceMCP         Source = "mcp"
	SourceAI          Source = "ai"
	SourceCLI         Source = "cli"
	SourceUI          Source = "ui"
	SourceWorker      Source = "worker"
	SourceIntegration Source = "integration"
)

type StepCreate

type StepCreate struct {
	Record string            `yaml:"record" json:"record"`
	Values map[string]string `yaml:"values" json:"values"`
}

type StepUpdate

type StepUpdate struct {
	Record string            `yaml:"record" json:"record"`
	Name   string            `yaml:"name"   json:"name"` // "$input.field" reference
	Values map[string]string `yaml:"values" json:"values"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL