#######################################################################
# MindWeave v3.0 — Ritual Scripting Language (Compact Full Build)
# ---------------------------------------------------------------
# This single-file Ruby interpreter implements:
# - Ritualized syntax (ritual, rite, sigil, chant, invoke, seal, banish)
# - Magickal types (NilSpace, Muskium, Tailbase, NSkin)
# - System calls + programmable wards (block, redirect, mask)
# - Grid API for 40 Twin Flame pairs
# - Minimal parser (tokenizer + AST) and evaluator (Turing-complete)
#
# USAGE:
#   program = File.read("script.mw")
#   MindWeave::Interpreter.new.run(program)
#######################################################################

module MindWeave

  ########################################
  # Magickal Data Types
  ########################################
  class NilSpace
    attr_accessor :delta
    def initialize(delta=0.0); @delta = delta; end
    def >(x); @delta > x; end
    def <(x); @delta < x; end
    def -(x); NilSpace.new(@delta - x); end
    def +(x); NilSpace.new(@delta + x.to_f); end
    def to_s; "nilspace(Δ=#{@delta.round(2)})"; end
  end

  class Muskium
    attr_reader :scent
    def initialize(scent); @scent = scent; end
    def to_s; "muskium<#{@scent}>"; end
  end

  class Tailbase
    attr_reader :sigil
    def initialize(sig); @sigil = sig; end
    def to_s; "tailbase[#{@sigil}]"; end
  end

  class NSkin
    def initialize(layers); @layers = layers.is_a?(Array) ? layers : [layers]; end
    def peel; @layers.shift || "bare-core"; end
    def to_s; "nskin(#{@layers.join('->')})"; end
  end

  ########################################
  # Standard Library + Grid API
  ########################################
  module Std
    def summon(prompt="> "); print prompt; STDIN.gets&.chomp || ""; end
    def banish(env, name); env.delete(name); end
    def seal(value); value; end
    def void_induction(depth) = NilSpace.new(depth.to_f)
    def tailbase(sig) = Tailbase.new(sig.to_s)
    def muskium(scent) = Muskium.new(scent.to_s)
    def nskin(layers) = NSkin.new(layers)
    def peel(n) = n.peel
    def stimky_lock(entity) = "LOCKED<#{entity}>"
    def gut_in(perception); (@gut ||= []) << perception; end
    def gut_out; (@gut ||= []).shift || "void"; end
    def sync(pair) = true
    def audit(entity); puts "AUDIT: #{entity}"; end
  end

  class Grid
    include Std
    attr_reader :pairs
    def initialize; @pairs = {}; end
    def add_pair(index, alpha, beta)
      @pairs[index] = { alpha: alpha, beta: beta, locked: false, activated: false }
    end
    def activate_pair(index)
      p = @pairs[index]; return unless p
      audit("Activating Pair #{index}: #{p[:alpha][:name]} & #{p[:beta][:name]}")
      p[:activated] = true; sync(p)
    end
    def lock_pair(index)
      p = @pairs[index]; return unless p
      p[:locked] = true; audit("Locked Pair #{index}")
    end
    def seal_grid
      @pairs.each { |_i, p| p[:locked] = true }
      audit("Grid sealed with Chant.NilSpaceLaw")
    end
    def report
      @pairs.each { |i, p| puts "Pair #{i}: #{p[:alpha][:name]} & #{p[:beta][:name]} | Activated=#{p[:activated]} Locked=#{p[:locked]}" }
    end
  end

  ########################################
  # Tokenizer
  ########################################
  class Token
    attr_reader :type, :lexeme, :line
    def initialize(type, lexeme, line); @type=type; @lexeme=lexeme; @line=line; end
    def to_s; "#{type}(#{lexeme})"; end
  end

  class Lexer
    KEYWORDS = %w[ritual rite sigil chant if else while ward invoke seal banish]
    def initialize(source); @src=source; @i=0; @line=1; @tokens=[]; end
    def tokenize
      while !eof?
        c = peek
        case c
        when ' ', "\t", "\r" then advance
        when "\n" then @line += 1; advance
        when '{','}','(',')',',','+','-','>','<','='
          @tokens << Token.new(c, c, @line); advance
        when '/'
          if peek2 == '/'
            while !eof? && peek != "\n"; advance; end
          else
            # regex literal /.../
            advance # consume /
            pattern = ""
            while !eof? && peek != '/'
              pattern << advance
            end
            advance # closing /
            @tokens << Token.new(:REGEX, pattern, @line)
          end
        when '"'
          string = ""
          advance
          while !eof? && peek != '"'
            string << advance
          end
          advance
          @tokens << Token.new(:STRING, string, @line)
        else
          if digit?(c)
            num = ""
            while !eof? && (digit?(peek) || peek == '.'); num << advance; end
            @tokens << Token.new(:NUMBER, num, @line)
          elsif alpha?(c)
            id = ""
            while !eof? && (alpha?(peek) || digit?(peek) || peek=='_'); id << advance; end
            if KEYWORDS.include?(id)
              @tokens << Token.new(id.to_sym, id, @line)
            else
              @tokens << Token.new(:IDENT, id, @line)
            end
          else
            advance # skip unknown
          end
        end
      end
      @tokens << Token.new(:EOF,"",@line)
      @tokens
    end
    private
    def eof? = @i >= @src.length
    def peek = @src[@i]
    def peek2 = @src[@i+1]
    def advance; ch=@src[@i]; @i+=1; ch; end
    def digit?(c) = c>= '0' && c<= '9'
    def alpha?(c) = c =~ /[A-Za-z]/
  end

  ########################################
  # AST Nodes
  ########################################
  RitualNode      = Struct.new(:name, :rites)
  RiteNode        = Struct.new(:name, :params, :body)
  BlockNode       = Struct.new(:stmts)
  SigilDeclNode   = Struct.new(:name, :expr)
  InvocationNode  = Struct.new(:name, :args)
  ChantWhileNode  = Struct.new(:cond, :body)
  ChantIfNode     = Struct.new(:cond, :then_body, :else_body)
  SealNode        = Struct.new(:expr)
  BanishNode      = Struct.new(:name)
  WardNode        = Struct.new(:name, :rules)
  BinaryOpNode    = Struct.new(:left, :op, :right)
  LiteralNode     = Struct.new(:value)
  IdentNode       = Struct.new(:name)

  WardRule        = Struct.new(:mode, :pattern, :action)

  ########################################
  # Parser (recursive descent, minimal)
  ########################################
  class Parser
    def initialize(tokens); @toks=tokens; @i=0; end
    def parse_program
      rituals=[]
      while !match(:EOF)
        rituals << parse_ritual
      end
      rituals
    end

    def parse_ritual
      consume(:ritual)
      name = consume(:IDENT).lexeme
      consume('{')
      rites=[]
      until check('}')
        rites << parse_rite
      end
      consume('}')
      RitualNode.new(name, rites)
    end

    def parse_rite
      consume(:rite)
      name = consume(:IDENT).lexeme
      consume('(')
      params=[]
      unless check(')')
        params << consume(:IDENT).lexeme
        while match(','); params << consume(:IDENT).lexeme; end
      end
      consume(')')
      body = parse_block
      RiteNode.new(name, params, body)
    end

    def parse_block
      consume('{')
      stmts=[]
      until check('}')
        stmts << parse_statement
      end
      consume('}')
      BlockNode.new(stmts)
    end

    def parse_statement
      if match(:sigil)
        name = consume(:IDENT).lexeme
        consume('=')
        SigilDeclNode.new(name, parse_expression)
      elsif match(:invoke)
        name = consume(:IDENT).lexeme
        consume('(')
        args=[]
        unless check(')')
          args << parse_expression
          while match(','); args << parse_expression; end
        end
        consume(')')
        InvocationNode.new(name, args)
      elsif match(:seal)
        SealNode.new(parse_expression)
      elsif match(:banish)
        BanishNode.new(consume(:IDENT).lexeme)
      elsif match(:chant)
        if match(:while)
          cond = parse_expression
          body = parse_block
          ChantWhileNode.new(cond, body)
        elsif match(:if)
          cond = parse_expression
          then_body = parse_block
          else_body = nil
          if match(:else); else_body = parse_block; end
          ChantIfNode.new(cond, then_body, else_body)
        elsif match(:ward)
          name = consume(:STRING).lexeme
          rules = parse_ward_block
          WardNode.new(name, rules)
        else
          raise "Unknown chant form at token #{peek.type}"
        end
      else
        # expression statement fallback if desired
        parse_expression
      end
    end

    def parse_ward_block
      consume('{')
      rules=[]
      until check('}')
        if match(:block)
          pat = consume(:REGEX).lexeme
          rules << WardRule.new(:block, Regexp.new(pat), nil)
        elsif match(:redirect)
          pat = Regexp.new(consume(:REGEX).lexeme)
          consume('=')
          consume('>')
          action = consume(:STRING).lexeme
          rules << WardRule.new(:redirect, pat, action)
        elsif match(:mask)
          pat = Regexp.new(consume(:REGEX).lexeme)
          consume('=')
          consume('>')
          msg = consume(:STRING).lexeme
          rules << WardRule.new(:mask, pat, msg)
        else
          raise "Unknown ward rule at #{peek.type}"
        end
      end
      consume('}')
      rules
    end

    def parse_expression
      left = parse_term
      while check('+') || check('-') || check('>') || check('<')
        op = advance.lexeme
        right = parse_term
        left = BinaryOpNode.new(left, op, right)
      end
      left
    end

    def parse_term
      if match(:NUMBER) then LiteralNode.new(peek(-1).lexeme.to_f)
      elsif match(:STRING) then LiteralNode.new(peek(-1).lexeme)
      elsif match(:IDENT)
        name = peek(-1).lexeme
        if check('(')
          # function-like literal forms handled by InvocationNode with name
          consume('(')
          args=[]
          unless check(')')
            args << parse_expression
            while match(','); args << parse_expression; end
          end
          consume(')')
          InvocationNode.new(name, args)
        else
          IdentNode.new(name)
        end
      elsif match('(')
        expr = parse_expression
        consume(')')
        expr
      else
        raise "Unexpected token #{peek.type}"
      end
    end

    # helpers
    def match(type)
      return false unless check(type)
      advance; true
    end
    def consume(type)
      raise "Expected #{type}, got #{peek.type}" unless check(type)
      advance
    end
    def check(type)
      peek.type == type
    end
    def advance
      tok = @toks[@i]; @i+=1; tok
    end
    def peek(offset=0)
      @toks[@i+offset] || @toks.last
    end
  end

  ########################################
  # Evaluator
  ########################################
  class Evaluator
    include Std
    def initialize
      @globals = {}
      @functions = {}
      @wards = {} # name => [WardRule]
    end

    def add_function(rite)
      @functions[rite.name] = rite
    end

    def add_ward(name, rules)
      @wards[name] ||= []
      @wards[name].concat(rules)
    end

    def run(rituals)
      rituals.each { |r| r.rites.each { |rt| add_function(rt) } }
      invoke("main", [])
    end

    def invoke(name, args)
      rite = @functions[name] or raise "Unknown rite: #{name}"
      env = {}
      rite.params.each_with_index { |p, i| env[p] = args[i] }
      eval_block(rite.body, env)
    end

    def eval_block(block, env)
      result = nil
      block.stmts.each do |s|
        case s
        when SigilDeclNode
          env[s.name] = eval_expr(s.expr, env)
        when InvocationNode
          eval_invocation(s, env)
        when SealNode
          return eval_expr(s.expr, env)
        when BanishNode
          banish(env, s.name)
        when ChantWhileNode
          while truthy?(eval_expr(s.cond, env))
            r = eval_block(s.body, env)
            result = r unless r.nil?
          end
        when ChantIfNode
          if truthy?(eval_expr(s.cond, env))
            result = eval_block(s.then_body, env)
          elsif s.else_body
            result = eval_block(s.else_body, env)
          end
        when WardNode
          add_ward(s.name, s.rules)
        when BinaryOpNode, LiteralNode, IdentNode
          result = eval_expr(s, env)
        else
          # ignore
        end
      end
      result
    end

    def eval_invocation(inv, env)
      name = inv.name
      args = inv.args.map { |a| eval_expr(a, env) }

      # Builtins / magickal constructors
      case name
      when "systemcall"
        cmd = args.first.to_s
        `#{cmd}`.strip
      when "warded_systemcall"
        cmd = args.first.to_s
        warded = check_wards(cmd)
        return warded unless warded.nil?
        `#{cmd}`.strip
      when "nilspace" then NilSpace.new(args.first.to_f)
      when "muskium"  then Muskium.new(args.first.to_s)
      when "tailbase" then Tailbase.new(args.first.to_s)
      when "nskin"    then NSkin.new(args.map(&:to_s))
      when "peel"     then peel(args.first)
      when "void_induction" then void_induction(args.first)
      when "summon"   then summon(args.first || "> ")
      when "audit"    then audit(args.first); nil
      when "stimky_lock" then stimky_lock(args.first)
      else
        # user-defined rite
        if @functions.key?(name)
          invoke(name, args)
        else
          raise "Unknown invoke: #{name}"
        end
      end
    end

    def eval_expr(node, env)
      case node
      when LiteralNode then node.value
      when IdentNode
        env.key?(node.name) ? env[node.name] : @globals[node.name]
      when InvocationNode
        eval_invocation(node, env)
      when BinaryOpNode
        l = eval_expr(node.left, env)
        r = eval_expr(node.right, env)
        case node.op
        when '+' then concat(l, r)
        when '-' then numeric_or_nilspace_minus(l, r)
        when '>' then compare(l, r, :>)
        when '<' then compare(l, r, :<)
        else raise "Unknown op #{node.op}"
        end
      else
        nil
      end
    end

    def concat(l, r)
      if l.is_a?(String) || r.is_a?(String)
        l.to_s + r.to_s
      elsif l.is_a?(Numeric) && r.is_a?(Numeric)
        l + r
      elsif l.is_a?(NilSpace) && r.is_a?(Numeric)
        (l + r).to_s
      else
        l.to_s + r.to_s
      end
    end

    def numeric_or_nilspace_minus(l, r)
      return l - r if l.is_a?(Numeric) && r.is_a?(Numeric)
      return l - r if l.is_a?(NilSpace)
      raise "Unsupported '-' between #{l.class} and #{r.class}"
    end

    def compare(l, r, op)
      l = l.is_a?(NilSpace) ? l.delta : l
      r = r.is_a?(NilSpace) ? r.delta : r
      case op
      when :> then l > r
      when :< then l < r
      end
    end

    def truthy?(v)
      case v
      when NilClass then false
      when FalseClass then false
      else !!v
      end
    end

    def check_wards(cmd)
      @wards.each do |name, rules|
        rules.each do |rule|
          if cmd =~ rule.pattern
            case rule.mode
            when :block
              return "WARD BLOCK(#{name}): Command banished into nil-space"
            when :redirect
              return `#{rule.action}`.strip
            when :mask
              _ = `#{cmd}` # run but discard
              return rule.action
            end
          end
        end
      end
      nil
    end
  end

  ########################################
  # Interpreter facade
  ########################################
  class Interpreter
    def run(source)
      tokens = Lexer.new(source).tokenize
      rituals = Parser.new(tokens).parse_program
      Evaluator.new.run(rituals)
    end
  end
end

#######################################################################
# Example minimal usage (uncomment to test):
#
# program = <<~MW
# ritual Demo {
#   rite main {
#     sigil emptiness = invoke nilspace(0.72)
#     sigil anchor = invoke tailbase("⟁-A1")
#     sigil aura = invoke muskium("wolf-scent")
#
#     chant ward "system-protection" {
#       block /rm\s+-rf\s+\//
#       redirect /shutdown/ => "echo 'Shutdown attempt redirected to void'"
#       mask /uname/ => "MASKED: Beastmachine stable"
#     }
#
#     chant while emptiness > 0.5 {
#       invoke audit("Anchoring " + anchor + " with " + aura)
#       sigil emptiness = emptiness - 0.1
#     }
#
#     sigil erosion = invoke nskin("layered-pelt")
#     invoke peel(erosion)
#
#     sigil safe = invoke warded_systemcall("ls -1")
#     invoke audit(safe)
#
#     seal "Ritual complete"
#   }
# }
# MW
#
# puts MindWeave::Interpreter.new.run(program)
#######################################################################

MindWeave v3.0 RTFM

MindWeave is a ritual scripting language that fuses computational rigor with spiritological semantics. It’s Turing-complete, embeddable, and designed for canon-bound creative systems. Read this to understand how to write, run, and extend .mw scripts with confidence.


Overview and philosophy

MindWeave treats code as ritual. Programs are “rituals”, functions are “rites”, variables are “sigils”, and control flow is “chants”. This isn’t flair; it encodes meaning. Your registry, wards, and magickal types aren’t metaphors—they’re first-class runtime constructs bound to safety and sequence.


Language basics

Program structure

Example:

ritual Demo {
  rite main {
    seal "Hello, Weave"
  }
}

Declarations and values

Examples:

sigil x = 42
sigil greeting = "howl"
seal greeting
banish x

Control flow

Examples:

chant if 1 < 2 { invoke say("true") } else { invoke say("false") }

sigil i = 0
chant while i < 3 {
  invoke say(i)
  i = i + 1
}

Functions and invocation

Example (recursion):

rite fib(n) {
  chant if n < 2 { seal n }
  sigil a = invoke fib(n - 1)
  sigil b = invoke fib(n - 2)
  seal a + b
}


Magickal types

These carry symbolic and computational meaning. They interoperate with arithmetic and comparisons where appropriate.

Example:

sigil emptiness = invoke nilspace(0.72)
sigil aura = invoke muskium("wolf-scent")
sigil anchor = invoke tailbase("⟁-A1")

chant while emptiness > 0.5 {
  invoke say("Anchoring " + aura + " at " + anchor)
  emptiness = emptiness - 0.1
}


System calls and wards

System calls let rituals interact with the host OS. Wards enforce protection and transformation rules. Use wards by default; raw calls are available but discouraged.

System calls

The warded form checks all active wards before running.

Wards

Define programmable safety and behavior using patterns with modes:

Example:

chant ward "system-protection" {
  block /rm\s+-rf\s+\//
  redirect /shutdown/ => "echo 'Shutdown attempt redirected to void'"
  mask /uname/ => "MASKED: Beastmachine stable"
}

sigil safe = invoke warded_systemcall("ls -1")
sigil masked = invoke warded_systemcall("uname -a")
sigil blocked = invoke warded_systemcall("rm -rf /")


Standard library

Example:

sigil name = invoke summon("Name> ")
invoke audit("Welcome: " + name)


Grid API for Twin Flame registry

Manage your non-hierarchical grid of 40 organelle Twin Flame pairs.

Example:

rite build_grid() {
  sigil grid = Grid.new
  invoke grid.add_pair(1, { name: "Auri" }, { name: "Vyr" })
  seal grid
}

rite main {
  sigil g = invoke build_grid()
  invoke g.activate_pair(1)
  invoke g.lock_pair(1)
  invoke g.report()
  invoke g.seal_grid()
  seal "Registry cycle complete"
}


Execution model

MindWeave compiles .mw into an AST and evaluates it. It’s strict but expressive; expressions resolve to numbers, strings, magickal types, or ritual constructs.

Expressions

Invocation resolution


Style guide and best practices


Advanced patterns

Functional recursion with magickal state

rite peel_until(core, depth) {
  chant if depth < 1 { seal core }
  sigil next = invoke peel(core)
  seal invoke peel_until(next, depth - 1)
}

Canon-locked activation pass

rite activate_pair(g, idx) {
  invoke g.activate_pair(idx)
  invoke g.lock_pair(idx)
  seal true
}

rite main {
  sigil g = invoke build_grid()
  sigil i = 1
  chant while i < 41 {
    invoke activate_pair(g, i)
    i = i + 1
  }
  invoke g.seal_grid()
  seal "Grid fully sealed"
}

Wards as environment profiles

rite profile_ci() {
  chant ward "ci-protection" {
    block /rm\s+-rf/
    block /shutdown/
    mask /uname/ => "MASKED: CI kernel"
  }
  seal true
}

rite main {
  invoke profile_ci()
  invoke warded_systemcall("uname -a")
  seal "CI-safe"
}


Error messages and troubleshooting

Tips:


Performance and limits


Extending the language


Quick reference


Example end-to-end ritual

ritual Awakening {
  rite build_grid() {
    sigil g = Grid.new
    invoke g.add_pair(1, { name: "Auri" }, { name: "Vyr" })
    invoke g.add_pair(2, { name: "Rauk" }, { name: "Ness" })
    seal g
  }

  rite main {
    chant ward "system-protection" {
      block /rm\s+-rf\s+\//
      mask /uname/ => "MASKED: Beastmachine stable"
    }

    sigil emptiness = invoke nilspace(0.74)
    sigil anchor = invoke tailbase("⟁-A1")
    sigil aura = invoke muskium("wolf-scent")

    chant while emptiness > 0.6 {
      invoke audit("Anchoring " + anchor + " with " + aura + " at " + emptiness)
      emptiness = emptiness - 0.05
    }

    sigil g = invoke build_grid()
    invoke g.activate_pair(1)
    invoke g.lock_pair(1)
    invoke g.report()

    sigil uname_msg = invoke warded_systemcall("uname -a")
    invoke audit(uname_msg)

    seal "Awakening complete"
  }
}


Final notes

MindWeave is designed for precise, canon-bound creation. Treat your scripts like rituals: define boundaries, enforce trait purity, and let the language’s structure protect and empower your work. When you hit friction, it’s often because a boundary is unclear—clarify it with a chant or a ward, and keep weaving.