On this page

An agent builds a working system๏ƒ

๐Ÿ”ต Expert ยท Lesson 36

NOTHING IN THIS FILE EXISTS WHEN THE PROCESS STARTS. Three classes are written as text at runtime, become real importable modules with no file on disk, get bound as spells, and come out as LIVE OBJECTS that do actual work. Then we make more of them.

This is the demo. Everything else in the tier explains a rule; this one just does the thing.

THE LOOP, ONE MORE TIME BUT WITH A PAYOFF validate_codegen may this exist? materialize_codegen make it a real module import it resolves like anything else bind it becomes a spell with custody meld you get an OBJECT Five steps from a string to something you can call a method on.

AND THE OBJECTS ARE ORDINARY. That is the part worth sitting with. Once melded, a generated class is not a special "dynamic" thing you handle with tongs. It is an object. It has state, you call methods on it, you pass it around, it participates in the same lifecycle as a class you typed by hand. The generated-ness stops mattering the moment it lands.

MULTIPLE OBJECTS FROM ONE GENERATED CLASS. existence="many" means every meld builds a NEW instance, so an agent can write one class and you can run a hundred independent copies of it - separate state, no shared surprises. existence="unique" gives you the same object back every time. Same generated source, two population models, and you choose per binding.

WHY THIS SURVIVES A REBOOT, IN ONE LINE: the module has no file, so its SOURCE IS THE RECORD (expert 33). A world made of generated code is reproducible rather than merely re-runnable - which is what makes any of this more than a clever trick.

Before you run๏ƒ

Use the Expert guide for prerequisite concepts. Run from a checkout with Melder installed and Python 3.14 free-threading selected. The collection download includes the level's local helper modules.

Run the saved script๏ƒ

python UX_and_AIX_experiences/04_expert/36_an_agent_builds_a_working_system.py
py -3.14t UX_and_AIX_experiences/04_expert/36_an_agent_builds_a_working_system.py

Download this collection ยท Source on GitHub

Public surface๏ƒ

validate_codegen / materialize_codegen, Spellbook.bind with existence unique and many, Conduit.meld, and the generated objects actually running

Code๏ƒ

  1"""
  2TIER: expert (36)
  3GOAL: NOTHING IN THIS FILE EXISTS WHEN THE PROCESS STARTS. Three classes
  4      are written as text at runtime, become real importable modules with
  5      no file on disk, get bound as spells, and come out as LIVE OBJECTS
  6      that do actual work. Then we make more of them.
  7
  8      This is the demo. Everything else in the tier explains a rule; this
  9      one just does the thing.
 10
 11      THE LOOP, ONE MORE TIME BUT WITH A PAYOFF
 12        validate_codegen     may this exist?
 13        materialize_codegen  make it a real module
 14        import               it resolves like anything else
 15        bind                 it becomes a spell with custody
 16        meld                 you get an OBJECT
 17      Five steps from a string to something you can call a method on.
 18
 19      AND THE OBJECTS ARE ORDINARY. That is the part worth sitting with.
 20      Once melded, a generated class is not a special "dynamic" thing you
 21      handle with tongs. It is an object. It has state, you call methods
 22      on it, you pass it around, it participates in the same lifecycle as
 23      a class you typed by hand. The generated-ness stops mattering the
 24      moment it lands.
 25
 26      MULTIPLE OBJECTS FROM ONE GENERATED CLASS. `existence="many"` means
 27      every meld builds a NEW instance, so an agent can write one class
 28      and you can run a hundred independent copies of it - separate state,
 29      no shared surprises. `existence="unique"` gives you the same object
 30      back every time. Same generated source, two population models, and
 31      you choose per binding.
 32
 33      WHY THIS SURVIVES A REBOOT, IN ONE LINE: the module has no file, so
 34      its SOURCE IS THE RECORD (expert 33). A world made of generated code
 35      is reproducible rather than merely re-runnable - which is what makes
 36      any of this more than a clever trick.
 37SURFACE EXERCISED: validate_codegen / materialize_codegen, Spellbook.bind
 38                   with existence unique and many, Conduit.meld, and the
 39                   generated objects actually running
 40VERIFY: authored 2026-08-05; not yet run.
 41"""
 42import importlib
 43
 44import melder as md
 45
 46
 47FRAME = "build-world"
 48
 49# An agent's output. Three cooperating pieces, written as text.
 50TOKENIZER = '''"""Generated: split raw text into words."""
 51
 52
 53class Tokenizer:
 54    def __init__(self) -> None:
 55        self.calls = 0
 56
 57    def run(self, text: str) -> list:
 58        self.calls = self.calls + 1
 59        return [word.strip(".,!?").lower()
 60                for word in text.split()
 61                if word.strip(".,!?")]
 62'''
 63
 64COUNTER = '''"""Generated: count how often each word appears."""
 65
 66
 67class Counter:
 68    def __init__(self) -> None:
 69        self.total = 0
 70
 71    def run(self, words: list) -> dict:
 72        counts: dict = {}
 73        for word in words:
 74            counts[word] = counts.get(word, 0) + 1
 75            self.total = self.total + 1
 76        return counts
 77'''
 78
 79REPORTER = '''"""Generated: turn counts into a readable line."""
 80
 81
 82class Reporter:
 83    def __init__(self) -> None:
 84        self.rendered = 0
 85
 86    def run(self, counts: dict) -> str:
 87        self.rendered = self.rendered + 1
 88        top = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
 89        return ", ".join("%s=%d" % (word, n) for word, n in top[:3])
 90'''
 91
 92# A fourth piece, for the population demo. It gets its OWN class name
 93# rather than re-binding Counter: two INDEPENDENT binds of one class
 94# would put two visible spells under the name "Counter", and the
 95# structural validator refuses that outright (expert 30).
 96WORKER = '''"""Generated: an independent accumulator."""
 97
 98
 99class Worker:
100    def __init__(self) -> None:
101        self.total = 0
102
103    def run(self, jobs: list) -> int:
104        self.total = self.total + len(jobs)
105        return self.total
106'''
107
108PARTS = (
109    ("build_tokenizer", TOKENIZER, "Tokenizer"),
110    ("build_counter", COUNTER, "Counter"),
111    ("build_reporter", REPORTER, "Reporter"),
112)
113
114TEXT = ("the record is the record and the record outlives the runtime, "
115        "so the record is what you trust")
116
117
118def main() -> None:
119    crystallizer = md.Crystallizer()
120    crystallizer.activate(
121        md.CrystallizerConfigurationBuilder().with_defaults().activate(),
122    )
123
124    spellbook_configuration = (
125        md.SpellbookConfiguration(FRAME).with_defaults().finalize()
126    )
127    book = md.Spellbook(aetheric_frame=FRAME,
128                        configuration=spellbook_configuration)
129    book.configure_aether_frame(
130        system_state="dynamic",
131        disposal=None,
132        disposal_method_names=None,
133        rift_enabled=True,
134        ai_native=True,
135    )
136    conduit = book.conjure(name="build-root")
137
138    nexus = md.Nexus()
139    system_configuration = nexus.create_configuration()
140    system_configuration.with_rift_creation_enabled(True)
141    system_configuration.with_allowed_target_frame_names([FRAME])
142    nexus.activate(system_configuration)
143    rift_configuration = nexus.create_rift_configuration()
144    rift_configuration.with_space_type("codegen")
145    rift = nexus.create_rift(configuration=rift_configuration,
146                             rift_name="builder")
147    rift.mark_active()
148    rift.create_frame_link(FRAME)
149    commands = rift.space.command_system
150
151    print("the process is up and NONE of the three classes exist yet")
152    print()
153
154    # WRITE THEM. Validate, materialize, import, bind - per piece.
155    classes = {}
156    for module_name, source, class_name in PARTS:
157        verdict = commands.validate_codegen(source, frame_name=FRAME)
158        assert verdict["accepted"] is True, verdict
159        kept = commands.materialize_codegen(
160            source, module_name=module_name, frame_name=FRAME,
161        )
162        assert kept["materialized"] is True, kept
163        module = importlib.import_module(module_name)
164        classes[class_name] = getattr(module, class_name)
165        book.bind(spell=classes[class_name], existence="unique",
166                  permissions="create", binding_name=class_name.lower())
167        print("wrote %-9s -> module %-16s -> bound as '%s'"
168              % (class_name, module_name, class_name.lower()))
169
170    # MELD THEM. Now they are objects.
171    tokenizer = conduit.meld(spell=classes["Tokenizer"],
172                             binding_name="tokenizer")
173    counter = conduit.meld(spell=classes["Counter"], binding_name="counter")
174    reporter = conduit.meld(spell=classes["Reporter"],
175                            binding_name="reporter")
176    print()
177    print("melded three OBJECTS:", type(tokenizer).__name__,
178          type(counter).__name__, type(reporter).__name__)
179
180    # RUN THE THING. This is real work done by code that did not exist
181    # when this script started.
182    words = tokenizer.run(TEXT)
183    counts = counter.run(words)
184    line = reporter.run(counts)
185    print()
186    print("input :", TEXT[:58], "...")
187    print("output:", line)
188    assert "record" in line, line
189    assert counts["record"] == 4, counts
190    print()
191    print("that answer was computed by three classes an agent wrote as")
192    print("strings, in this process, a few milliseconds ago")
193
194    # THEY HAVE STATE, like any object.
195    assert tokenizer.calls == 1
196    assert counter.total == len(words)
197    assert reporter.rendered == 1
198    print()
199    print("and they are ORDINARY objects: tokenizer.calls =",
200          tokenizer.calls, "| counter.total =", counter.total)
201    print("  no tongs required. Generated-ness stopped mattering the")
202    print("  moment they landed")
203
204    # UNIQUE MEANS THE SAME OBJECT BACK.
205    again = conduit.meld(spell=classes["Tokenizer"],
206                         binding_name="tokenizer")
207    assert again is tokenizer, "existence='unique' returns the same object"
208    print()
209    print("melding 'tokenizer' again -> the SAME object:",
210          again is tokenizer)
211
212    # MANY MEANS A NEW ONE EVERY TIME - a population from one generated
213    # class. This is its own class rather than a second binding of
214    # Counter: two independent binds of one class would put two visible
215    # spells under the same name, which the validator refuses (expert 30).
216    commands.validate_codegen(WORKER, frame_name=FRAME)
217    kept = commands.materialize_codegen(
218        WORKER, module_name="build_worker", frame_name=FRAME,
219    )
220    assert kept["materialized"] is True, kept
221    worker_class = importlib.import_module("build_worker").Worker
222    book.bind(spell=worker_class, existence="many", permissions="create",
223              binding_name="worker")
224
225    workers = [conduit.meld(spell=worker_class, binding_name="worker")
226               for _ in range(5)]
227    assert len({id(worker) for worker in workers}) == 5, (
228        "existence='many' must build a NEW instance per meld"
229    )
230    for index, worker in enumerate(workers):
231        worker.run(["job"] * (index + 1))
232    totals = [worker.total for worker in workers]
233    assert totals == [1, 2, 3, 4, 5], totals
234    print()
235    print("a fourth generated class, bound existence='many':")
236    print("  5 melds ->", len({id(w) for w in workers}), "distinct objects")
237    print("  independent state:", totals)
238    print("  one class an agent wrote, a population you control")
239
240    print()
241    print("string -> module -> spell -> object -> answer")
242    print("and the module has no file, so its SOURCE IS THE RECORD -")
243    print("which is why this world can be rebuilt, not just re-run")
244
245
246if __name__ == "__main__":
247    main()

Check the outcome๏ƒ

The script contains its own assertions or demonstrated refusal paths. Run it to evaluate those checks against your installed version. The code above is taken directly from the saved file; no run output is invented here.

More expert examples ยท Level guide

API contracts๏ƒ