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
- Variables
- func CanonicalDocHash(fields map[string]any) string
- func CanonicalVersion(v any) string
- type AuditRow
- type CommandDefinition
- type CommandInput
- type CommandRegistry
- type CommandResource
- type CommandStep
- type Kernel
- type Operation
- type OperationContext
- type RecordCreatePayload
- type RecordMutationBundleItem
- type RecordMutationBundlePayload
- type RecordUpdatePayload
- type RecordWorkflowTransitionPayload
- type RelatedRecordResult
- type ResultData
- type Source
- type StepCreate
- type StepUpdate
Constants ¶
const ( CommandRecordCreate = "record.create" CommandRecordMutateBundle = "record.mutate_bundle" CommandRecordUpdate = "record.update" CommandRecordDelete = "record.delete" CommandRecordWorkflowTransition = "record.workflow_transition" CommandPublicFormSubmit = "public_form.submit" )
Command names are canonical across all sources. Adapters resolve these definitions from the registry; they never implement their own semantics.
Variables ¶
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 ¶
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 ¶
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
// TxManager supplies request-scoped ORM lifecycle hooks and script runtime.
// Database, registry, dialect, site, user, and outbox are rebound per Execute.
TxManager *orm.TxManager
// 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 ¶
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")
Owner string // internal owner override; adapters must not populate this from user data
UserRole string // primary role used by workflow policy
Roles []string // roles used for permission-matrix lookup
SkipHookScripts []string // trusted internal stack prevents recursive execution of active lifecycle scripts
AllowReadOnlyFields bool // trusted internal writers may update UI-read-only fields
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"`
PublicRoute string `json:"public_route,omitempty"`
}
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 RecordMutationBundlePayload ¶
type RecordMutationBundlePayload struct {
Doctype string `json:"doctype"`
Records []RecordMutationBundleItem `json:"records"`
}
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 RecordWorkflowTransitionPayload ¶
type RecordWorkflowTransitionPayload struct {
Doctype string `json:"doctype"`
Name string `json:"name"`
Action string `json:"action"`
ExpectedRevision uint64 `json:"expected_revision,omitempty"`
}
RecordWorkflowTransitionPayload applies a configured transition to one record without exposing its workflow state as an ordinary field update.
type RelatedRecordResult ¶
type ResultData ¶
type ResultData struct {
Doctype string `json:"doctype"`
Name string `json:"name"`
Created bool `json:"created"`
Deleted bool `json:"deleted,omitempty"`
Document map[string]any `json:"document,omitempty"`
AuditID string `json:"audit_id"`
Operation string `json:"operation_id"`
Related []RelatedRecordResult `json:"related,omitempty"`
}
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.