// Command mindsicle is the bootstrapper — thaws a frozen lattice, emits Go // source, compiles, and runs the result. // // Usage: // // mindsicle frozen.json thaw → emit → repair → compile → run // mindsicle -emit frozen.json thaw → emit only (no compile/run) // mindsicle -out DIR frozen.json set output directory // mindsicle -auto -repo . autonomous mode: iterate until walk exhausts repo package main import ( "bytes" "context" "flag" "fmt" "os" "os/exec" "os/signal" "path/filepath" "strings" "time" "git.mleku.dev/mleku/dendrite/pkg/axiom" "git.mleku.dev/mleku/dendrite/pkg/emit" "git.mleku.dev/mleku/dendrite/pkg/enzyme" "git.mleku.dev/mleku/dendrite/pkg/ewma" "git.mleku.dev/mleku/dendrite/pkg/fitness" "git.mleku.dev/mleku/dendrite/pkg/grow" "git.mleku.dev/mleku/dendrite/pkg/hexagram" "git.mleku.dev/mleku/dendrite/pkg/lattice" "git.mleku.dev/mleku/dendrite/pkg/memory" "git.mleku.dev/mleku/dendrite/pkg/mindsicle" "git.mleku.dev/mleku/dendrite/pkg/ratio" "git.mleku.dev/mleku/dendrite/pkg/spore" "git.mleku.dev/mleku/dendrite/pkg/walk" ) // tagConstraint is the simplest constraint: admits elements with matching type. type tagConstraint struct{ tag string } func (c tagConstraint) Tag() string { return c.tag } func (c tagConstraint) Admits(e axiom.Element) bool { return e.Type() == c.tag } func constraintFactory(tag string) axiom.Constraint { return tagConstraint{tag} } var goRoot string func init() { goRoot = os.Getenv("GOROOT") if goRoot == "" { goRoot = "/home/mleku/go" } } func main() { // Shared flags. outDir := flag.String("out", "_output", "output directory") // Bootstrap mode flags. emitOnly := flag.Bool("emit", false, "emit Go source without compiling or running") maxPasses := flag.Int("passes", 5, "max compile-repair passes") // Autonomous mode flags. autoMode := flag.Bool("auto", false, "autonomous mode: iterate until ergodic walk exhausts repo") repoDir := flag.String("repo", ".", "repository root for ergodic walk") ewmaWindow := flag.Int("ewma-window", 10, "EWMA smoothing window") crossings := flag.Int("crossings", 6, "reversal threshold for oscillation detection") seed := flag.Uint64("seed", 0, "PRNG seed for ergodic walk (0 = time-based)") memDir := flag.String("memory-dir", "", "persistent memory database (default: /memory)") feedPct := flag.Int("feed-pct", 50, "feed-back threshold percentage") maxEpochs := flag.Int("max-epochs", 0, "maximum epochs (0 = unlimited)") flag.Parse() if *autoMode { runAuto(*repoDir, *outDir, *memDir, *ewmaWindow, *crossings, *seed, *feedPct, *maxEpochs) return } // --- Bootstrap mode --- args := flag.Args() if len(args) < 1 { fmt.Fprintf(os.Stderr, "usage: mindsicle [flags] frozen.json\n") fmt.Fprintf(os.Stderr, " mindsicle -auto -repo .\n") os.Exit(1) } runBootstrap(args[0], *outDir, *emitOnly, *maxPasses) } func runBootstrap(inputFile, outDir string, emitOnly bool, maxPasses int) { // Read the mindsicle. f, err := os.Open(inputFile) if err != nil { fmt.Fprintf(os.Stderr, "open: %v\n", err) os.Exit(1) } m, err := mindsicle.ReadMindsicle(f) f.Close() if err != nil { fmt.Fprintf(os.Stderr, "read mindsicle: %v\n", err) os.Exit(1) } fmt.Printf("mindsicle: %d nodes, version %d, frozen at %s\n", len(m.Nodes), m.Version, m.FrozenAt.Format("2006-01-02 15:04:05")) // Thaw. l := m.Thaw(constraintFactory) fmt.Printf("thaw: %d nodes live\n", l.Size()) // Harvest and emit. files := emit.Harvest(l) var allFrags []emit.Fragment for _, frags := range files { allFrags = append(allFrags, frags...) } fmt.Printf("harvest: %d fragments\n", len(allFrags)) var source strings.Builder if err := emit.EmitGo(allFrags, &source); err != nil { fmt.Fprintf(os.Stderr, "emit: %v\n", err) os.Exit(1) } os.MkdirAll(outDir, 0o755) base := filepath.Base(inputFile) base = strings.TrimSuffix(base, filepath.Ext(base)) goFile := filepath.Join(outDir, base+".go") if emitOnly { if err := os.WriteFile(goFile, []byte(source.String()), 0o644); err != nil { fmt.Fprintf(os.Stderr, "write: %v\n", err) os.Exit(1) } fmt.Printf("emit: %s (%d bytes)\n", goFile, source.Len()) return } repaired, err := emit.CompileAndRepair(source.String(), goRoot, maxPasses) if err != nil { fmt.Fprintf(os.Stderr, "repair: %v\n", err) os.WriteFile(goFile, []byte(source.String()), 0o644) fmt.Fprintf(os.Stderr, "unrepaired source written to %s\n", goFile) os.Exit(1) } if err := os.WriteFile(goFile, []byte(repaired), 0o644); err != nil { fmt.Fprintf(os.Stderr, "write: %v\n", err) os.Exit(1) } fmt.Printf("repair: %s (%d bytes)\n", goFile, len(repaired)) binFile := filepath.Join(outDir, base) if err := fitness.CompileTo(goFile, binFile, goRoot); err != nil { fmt.Fprintf(os.Stderr, "compile: %v\n", err) os.Exit(1) } fmt.Printf("compile: %s\n", binFile) fmt.Println("--- running offspring ---") cmd := exec.Command(binFile) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { fmt.Fprintf(os.Stderr, "run: %v\n", err) os.Exit(1) } fmt.Println("--- offspring done ---") } // runAuto implements the autonomous driver loop. func runAuto(repoDir, outDir, memDir string, ewmaWindow, crossingThreshold int, prngSeed uint64, feedPct, maxEpochs int) { if memDir == "" { memDir = filepath.Join(outDir, "memory") } os.MkdirAll(outDir, 0o755) os.MkdirAll(memDir, 0o755) // Open persistent memory. mem, err := memory.Open(memDir) if err != nil { fmt.Fprintf(os.Stderr, "memory open: %v\n", err) os.Exit(1) } defer mem.Close() // PRNG seed. if prngSeed == 0 { prngSeed = uint64(time.Now().UnixNano()) } fmt.Printf("seed: %d\n", prngSeed) // Try resuming walker state from checkpoint. var walker *walk.Walker var epochNum uint32 var genNum uint32 currentSeed := prngSeed if cp, err := mem.LoadWalkerCheckpoint(); err == nil { manifest := &walk.Manifest{Files: cp.Files, Root: cp.Root, Seed: cp.Seed} walker = walk.Resume(manifest, cp.Position) epochNum = cp.Epoch genNum = cp.GenNum currentSeed = cp.Seed fmt.Printf("resume: epoch %d, position %d/%d, gen %d\n", epochNum, cp.Position, len(cp.Files), genNum) } else { // Build ergodic walk manifest. manifest, err := walk.Build(repoDir, prngSeed, walk.DefaultExclude) if err != nil { fmt.Fprintf(os.Stderr, "walk build: %v\n", err) os.Exit(1) } fmt.Printf("manifest: %d files in %s\n", len(manifest.Files), repoDir) if len(manifest.Files) == 0 { fmt.Fprintf(os.Stderr, "no source files found\n") os.Exit(1) } walker = walk.NewWalker(manifest) } // Try to resume lattice state. var l *lattice.Lattice // Check for existing mindsicle in args or memory. args := flag.Args() if len(args) > 0 { // Thaw from provided mindsicle file. f, err := os.Open(args[0]) if err != nil { fmt.Fprintf(os.Stderr, "open mindsicle: %v\n", err) os.Exit(1) } m, err := mindsicle.ReadMindsicle(f) f.Close() if err != nil { fmt.Fprintf(os.Stderr, "read mindsicle: %v\n", err) os.Exit(1) } l = m.Thaw(constraintFactory) fmt.Printf("thaw: %d nodes from %s\n", l.Size(), args[0]) } else { // Try loading latest mindsicle from memory. gen, data, err := mem.LatestMindsicle() if err == nil && len(data) > 0 { m, err := mindsicle.ReadMindsicle(bytes.NewReader(data)) if err == nil { l = m.Thaw(constraintFactory) fmt.Printf("thaw: %d nodes from memory gen %d\n", l.Size(), gen) } } } if l == nil { // Abiogenesis — start with empty lattice with code-aware sites. l = abiogenesis() fmt.Printf("abiogenesis: %d nodes\n", l.Size()) } // Create oscillation detector. detector := ewma.NewDetector(ewmaWindow, 0, crossingThreshold) // Try restoring detector state. _, ewmaData, err := mem.LoadLatestEWMAState() if err == nil && len(ewmaData) > 0 { restored, err := ewma.UnmarshalDetector(ewmaData) if err == nil { detector = restored fmt.Printf("ewma: restored detector state\n") } } // Set up signal handler for graceful shutdown. sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, os.Interrupt) feedThreshold := ratio.New(int64(feedPct), 100) // Feed first file and track which file is being processed. solution := make(chan axiom.Element, 1024) currentFile := feedFile(walker, solution) // Stability-triggered feeding state. const stabilityCooldown uint32 = 5 var lastStabilityFeedGen uint32 stabilityMinSustain := ratio.New(9, 10) // 90% stabilityMaxYoung := ratio.New(5, 100) // 5% // Per-epoch generation counter for safety limit. epochStartGen := genNum fmt.Printf("=== autonomous loop (epoch %d) ===\n", epochNum) for { select { case <-sigCh: fmt.Println("\ninterrupt — freezing state...") freezeState(l, genNum, outDir, mem, detector, walker, epochNum) return default: } genNum++ fmt.Printf("\n--- gen %d (epoch %d, walk: %s, %d remaining) ---\n", genNum, epochNum, walker.Progress(), walker.Remaining()) // Run one generation. Oscillation is now endogenous — the engine // breathes on its own schedule. The detector's state is used only // for diagnostic logging. rawCount, accretedCount, adsrDist := runAutoGeneration(l, solution, genNum, mem) fmt.Printf("gen %d: raw=%d accreted=%d ratio=%.1f%%\n", genNum, rawCount, accretedCount, float64(accretedCount)*100/max64(float64(rawCount), 1)) // Record per-file accretion score. if currentFile != "" && mem != nil { mem.RecordFileScore(currentFile, rawCount, accretedCount) } // Feed into oscillation detector. oscillating := detector.Observe(rawCount, accretedCount) if oscillating { fmt.Printf("oscillation detected (reversals=%d) — ", detector.Reversals) detector.Reset() // Check if we should feed lattice back into itself. if rawCount > 0 { accretedRatio := ratio.New(accretedCount, rawCount) if accretedRatio.Greater(feedThreshold) || accretedRatio.Equal(feedThreshold) { fmt.Printf("self-feeding (accreted %.0f%% >= %d%%)\n", accretedRatio.Float64()*100, feedPct) feedLatticeIntoItself(l, solution) } else { fmt.Println("below feed threshold") } } // Feed next file — start new epoch if walk exhausted. if walker.Done() { epochNum++ if maxEpochs > 0 && epochNum >= uint32(maxEpochs) { fmt.Println("max epochs reached") break } walker, currentSeed = startNewEpoch(repoDir, currentSeed, mem) fmt.Printf("\n=== epoch %d (%d files, seed=%d) ===\n", epochNum, len(walker.Manifest.Files), currentSeed) epochStartGen = genNum detector.Reset() } currentFile = feedFile(walker, solution) lastStabilityFeedGen = genNum // reset stability cooldown } else if genNum >= lastStabilityFeedGen+stabilityCooldown { // Stability-triggered feeding: material absorbed, ready for more. if checkStability(adsrDist, mem, stabilityMinSustain, stabilityMaxYoung) { fmt.Println("stability reached — feeding next file") if walker.Done() { epochNum++ if maxEpochs > 0 && epochNum >= uint32(maxEpochs) { fmt.Println("max epochs reached") break } walker, currentSeed = startNewEpoch(repoDir, currentSeed, mem) fmt.Printf("\n=== epoch %d (%d files, seed=%d) ===\n", epochNum, len(walker.Manifest.Files), currentSeed) epochStartGen = genNum } currentFile = feedFile(walker, solution) lastStabilityFeedGen = genNum detector.Reset() // new material invalidates EWMA history } } // Periodic freeze (every 10 generations). if genNum%10 == 0 { freezeState(l, genNum, outDir, mem, detector, walker, epochNum) } // Per-epoch safety limit: force epoch transition if stuck. if walker.Done() && !oscillating { if genNum-epochStartGen > uint32(len(walker.Manifest.Files)*20) { epochNum++ if maxEpochs > 0 && epochNum >= uint32(maxEpochs) { fmt.Println("max epochs reached (safety limit)") break } fmt.Println("epoch safety limit — starting new epoch") walker, currentSeed = startNewEpoch(repoDir, currentSeed, mem) fmt.Printf("\n=== epoch %d (%d files, seed=%d) ===\n", epochNum, len(walker.Manifest.Files), currentSeed) epochStartGen = genNum detector.Reset() currentFile = feedFile(walker, solution) lastStabilityFeedGen = genNum } } } // Final freeze. fmt.Println("\n=== final freeze ===") freezeState(l, genNum, outDir, mem, detector, walker, epochNum) fmt.Printf("autonomous run complete: %d generations, %d epochs, %d/%d files in current epoch\n", genNum, epochNum+1, walker.Position, len(walker.Manifest.Files)) } // abiogenesis creates an initial lattice with code-aware constraint sites. func abiogenesis() *lattice.Lattice { l := lattice.New() codeTags := map[string]int{ "literal": 16, "ident": 12, "func": 12, "method": 12, "type": 12, "field": 8, "import": 8, "package": 8, "struct": 6, "interface": 6, "comment": 6, "file": 6, "assign": 6, "return": 6, "if": 6, "for": 6, "word": 16, "punct": 4, "select": 4, "switch": 4, "go": 4, "send": 4, "expr": 6, "defer": 4, "decl": 4, "branch": 3, "case": 4, "comm": 3, "directive": 3, "var": 6, } var allNodes []*lattice.Node for tag, count := range codeTags { for range count { n := l.AddNode([]axiom.Constraint{tagConstraint{tag}}) n.SetEnergy(true) allNodes = append(allNodes, n) } } // Connect in a ring with cross-links. for i, n := range allNodes { l.Connect(n, allNodes[(i+1)%len(allNodes)]) if i%4 == 0 && i+7 < len(allNodes) { l.Connect(n, allNodes[i+7]) } } return l } // runAutoGeneration runs one generation on the live lattice. // Returns raw element count and accreted (bonded) count. // oscillating indicates whether the EWMA detector sees sustained reversals; // when true, the hexagram engine halves the sustain threshold so more // Sustain-phase nodes destabilize into Release. func runAutoGeneration(l *lattice.Lattice, solution chan axiom.Element, genNum uint32, mem *memory.DB) (rawCount, accretedCount int64, adsrDist [4]int) { growDuration := 3 * time.Second engineDuration := 2 * time.Second // === GROWTH === ctx, cancel := context.WithTimeout(context.Background(), growDuration) defer cancel() growEvents := make(chan grow.Event, 512) go func() { grow.Run(ctx, l, solution, grow.Config{ MaxSteps: 500, Workers: 4, }, growEvents) close(growEvents) }() var bondRecords []memory.BondRecord for ev := range growEvents { rawCount++ // every event is one element attempt switch ev.Type { case grow.EventBonded: accretedCount++ if mem != nil && ev.Element != nil { bondRecords = append(bondRecords, memory.BondRecord{ Tag: ev.Element.Type(), SiteID: uint32(ev.NodeID), }) } } } // === SELF-GOVERNANCE === engineCtx, engineCancel := context.WithTimeout(context.Background(), engineDuration) defer engineCancel() engineEvents := make(chan hexagram.Event, 512) go func() { hexagram.RunEngine(engineCtx, l, hexagram.EngineConfig{ Interval: 16 * time.Millisecond, // 2^4 ms — epoch-aligns with dissolve at 10^2 ms Solution: solution, MaxNewSites: 32, MinOccupancy: ratio.New(2, 5), SustainThreshold: ratio.New(4, 10), Oscillating: false, }, engineEvents) close(engineEvents) }() opCounts := make(map[hexagram.Op]int) for ev := range engineEvents { opCounts[ev.Op]++ if ev.Op == hexagram.OpAccrete { accretedCount++ } } // Report engine ops. opNames := map[hexagram.Op]string{ hexagram.OpNone: "none", hexagram.OpAccrete: "accrete", hexagram.OpDissolve: "dissolve", hexagram.OpNucleate: "nucleate", hexagram.OpPrune: "prune", hexagram.OpStrengthen: "strengthen", hexagram.OpExplore: "explore", hexagram.OpCollapse: "collapse", hexagram.OpRecycle: "recycle", } fmt.Print(" engine: ") for op, count := range opCounts { name := opNames[op] if name == "" { name = fmt.Sprintf("op_%d", op) } fmt.Printf("%s=%d ", name, count) } fmt.Println() // Record to memory. if mem != nil { mem.RecordBonds(genNum, bondRecords) hexOps := make(map[byte]uint32, len(opCounts)) for op, count := range opCounts { hexOps[byte(op)] = uint32(count) } mem.RecordHexagramOps(genNum, hexOps) // Health snapshot. occupied := 0 total := l.Size() for i := range total { if l.Node(lattice.NodeID(i)).Occupied() { occupied++ } } mem.RecordHealth(genNum, uint32(occupied), uint32(total), ratio.Zero) } // Report ADSR phase distribution. total := l.Size() for i := range total { n := l.Node(lattice.NodeID(i)) if n.Occupied() { age := n.Age() if age < 4 { adsrDist[age]++ } } } fmt.Printf(" adsr: A=%d D=%d S=%d R=%d\n", adsrDist[0], adsrDist[1], adsrDist[2], adsrDist[3]) // Record ADSR to memory. if mem != nil { var u32 [4]uint32 for i := range 4 { u32[i] = uint32(adsrDist[i]) } mem.RecordADSR(genNum, u32) } // Sporulate. sp := spore.Extract(l) if sp != nil { fmt.Printf(" spore: occupied=%d/%d types=%d\n", sp.Occupied, sp.TotalNodes, len(sp.TypeSignature)) } return rawCount, accretedCount, adsrDist } // feedFile opens the next file from the walker and feeds its elements // into the solution channel. Returns the relative path of the file fed, // or "" if the walker is exhausted. func feedFile(walker *walk.Walker, solution chan axiom.Element) string { ch, ok := walker.DigestNext() if !ok { return "" } var filePath string if walker.Position > 0 && walker.Position <= len(walker.Manifest.Files) { filePath = walker.Manifest.Files[walker.Position-1] } go func() { for elem := range ch { solution <- elem } }() if filePath != "" { fmt.Printf(" feed: %s\n", filePath) } return filePath } // feedLatticeIntoItself harvests occupied elements from the lattice, // decomposes their string values through Text enzyme, and feeds // the resulting tokens back into the solution channel. func feedLatticeIntoItself(l *lattice.Lattice, solution chan axiom.Element) { var texts []string for i := range l.Size() { n := l.Node(lattice.NodeID(i)) if !n.Occupied() { continue } val := n.Occupant().Value() if s, ok := val.(string); ok && len(s) > 0 { texts = append(texts, s) } } if len(texts) == 0 { return } combined := strings.Join(texts, " ") fmt.Printf(" self-feed: %d elements, %d bytes\n", len(texts), len(combined)) go func() { ch := enzyme.Text{}.Digest(strings.NewReader(combined)) for elem := range ch { if elem.Type() == "space" { continue } solution <- elem } }() } // startNewEpoch re-scans the repository with a new seed and weighted // permutation based on historical file accretion scores. func startNewEpoch(repoDir string, prevSeed uint64, mem *memory.DB) (*walk.Walker, uint64) { newSeed := walk.DeriveNextSeed(prevSeed) scoresByHash, _ := mem.LoadFileScores() if len(scoresByHash) > 0 { // Do a plain scan first to get the file list for weight computation. plain, err := walk.Build(repoDir, newSeed, walk.DefaultExclude) if err == nil && len(plain.Files) > 0 { weights := computeFileWeights(plain.Files, scoresByHash) weighted, err := walk.BuildWeighted(repoDir, newSeed, walk.DefaultExclude, weights, 2.0) if err == nil { return walk.NewWalker(weighted), newSeed } } } // Fallback: uniform shuffle. manifest, _ := walk.Build(repoDir, newSeed, walk.DefaultExclude) return walk.NewWalker(manifest), newSeed } // computeFileWeights converts per-file accretion scores into weights for // the Efraimidis-Spirakis weighted permutation. // Weight = 2.0 - accretionRate, range [1.0, 2.0]. // Files with no history get 2.0 (maximum priority). func computeFileWeights(files []string, scoresByHash map[[8]byte][2]int64) map[string]float64 { weights := make(map[string]float64, len(files)) for _, f := range files { h := memory.TagHash(f) scores, ok := scoresByHash[h] if !ok || scores[1] == 0 { weights[f] = 2.0 continue } rate := float64(scores[0]) / float64(scores[1]) if rate > 1.0 { rate = 1.0 } if rate < 0.0 { rate = 0.0 } weights[f] = 2.0 - rate } return weights } // checkStability returns true when the lattice has fully absorbed its current // material: high Sustain fraction, low young (Attack+Decay) fraction, and // neither occupancy nor fitness still rising. func checkStability(adsrDist [4]int, mem *memory.DB, minSustain, maxYoung ratio.Ratio) bool { occupied := adsrDist[0] + adsrDist[1] + adsrDist[2] + adsrDist[3] if occupied == 0 { return false } sustainFrac := ratio.New(int64(adsrDist[2]), int64(occupied)) youngFrac := ratio.New(int64(adsrDist[0]+adsrDist[1]), int64(occupied)) if sustainFrac.Less(minSustain) { return false } if maxYoung.Less(youngFrac) { return false } // Check cross-generational trends from memory. if mem == nil { return true } digest := mem.WalkDigest(nil, 5) if digest == nil { return true // <2 gens of data — trust ADSR alone } if digest.OccupancyTrend == memory.TrendRising { return false } if digest.FitnessTrend == memory.TrendRising { return false } return true } // freezeState persists the current lattice, detector, and walker state. func freezeState(l *lattice.Lattice, genNum uint32, outDir string, mem *memory.DB, detector *ewma.OscillationDetector, walker *walk.Walker, epochNum uint32) { sp := spore.Extract(l) m := mindsicle.Freeze(l, sp) // Write to file. fileName := filepath.Join(outDir, fmt.Sprintf("dendrite.gen%d.mindsicle", genNum)) var buf bytes.Buffer m.WriteTo(&buf) os.WriteFile(fileName, buf.Bytes(), 0o644) fmt.Printf(" freeze: %s (%d bytes)\n", fileName, buf.Len()) // Write to memory DB. if mem != nil { var mbuf bytes.Buffer m.WriteTo(&mbuf) mem.RecordMindsicle(genNum, mbuf.Bytes()) // Persist detector state. detectorData, err := detector.Marshal() if err == nil { mem.RecordEWMAState(genNum, detectorData) } // Persist walker checkpoint for exact resume. mem.RecordWalkerCheckpoint(memory.WalkerCheckpoint{ Epoch: epochNum, Seed: walker.Manifest.Seed, Position: walker.Position, GenNum: genNum, Files: walker.Manifest.Files, Root: walker.Manifest.Root, }) } } func max64(a, b float64) float64 { if a > b { return a } return b }