// Package organ manages WASM modules that the organism can compile, // load, evaluate, share, and hot-swap at runtime. // // Each organ is a TinyGo-compiled WASM module loaded via wazero. // Organs specialize in a task: digestion (enzyme), emission (emitter), // evaluation (evaluator), self-governance (governor), or compilation // (compiler). The host process loads organs into a Registry, calls them // through a uniform byte-oriented interface, and destroys them when // they are superseded or fail fitness. // // Organs supplement but never replace host-side Go code. The host // implementation is always available as a fallback. package organ import ( "crypto/sha256" "encoding/hex" "sync/atomic" "time" "git.mleku.dev/mleku/dendrite/pkg/ratio" ) // OrganType classifies what role an organ fills. type OrganType string const ( TypeEnzyme OrganType = "enzyme" TypeEmitter OrganType = "emitter" TypeEvaluator OrganType = "evaluator" TypeGovernor OrganType = "governor" TypeCompiler OrganType = "compiler" ) // OrganID is a content-addressable identifier: sha256 of the .wasm bytes. type OrganID [32]byte // ComputeID returns the OrganID for the given WASM bytes. func ComputeID(wasmBytes []byte) OrganID { return sha256.Sum256(wasmBytes) } // String returns the hex-encoded ID (first 16 chars for readability). func (id OrganID) String() string { return hex.EncodeToString(id[:8]) } // Manifest describes a compiled organ for exchange and evaluation. // It is serializable and can travel between instances. type Manifest struct { ID OrganID `json:"id"` Type OrganType `json:"type"` Version uint64 `json:"version"` Size int `json:"size"` // .wasm byte count Hash uint64 `json:"hash"` // organ_hash() from the module SourceGen int `json:"source_gen"` // generation that produced this organ SourceID uint32 `json:"source_id"` // instance ID that compiled it Fitness ratio.Ratio `json:"fitness"` // evaluated fitness at source } // OrganStatus tracks the lifecycle of a loaded organ. type OrganStatus int const ( StatusPending OrganStatus = iota // received, not yet evaluated StatusLoaded // instantiated and callable StatusFailed // failed fitness or runtime error StatusEvicted // dissolved — module closed ) // Organ is a loaded WASM module with its runtime state. type Organ struct { Manifest Manifest WasmBytes []byte // raw module bytes for sharing Status OrganStatus Loaded time.Time CallCount atomic.Uint64 LastCall time.Time } // Opcodes are the operation codes prepended to input bytes when // calling an organ's process function. const ( // Enzyme opcodes. OpCanDigest byte = 0x01 OpDigest byte = 0x02 // Emitter opcodes. OpEmit byte = 0x01 // Evaluator opcodes. OpEvaluate byte = 0x01 // Governor opcodes. OpDerive byte = 0x01 OpTable byte = 0x02 // Compiler opcodes. OpCompile byte = 0x01 )