On this page
The codegen loop end to end๏
๐ต Expert ยท Lesson 12
THE CODEGEN LOOP, ACTUALLY RUN. Expert 07 introduced the room and named its three verbs. This drives them: an agent asks permission, writes code into a named world, and reads back what it did.
THE LOOP
validate_codegen(code, frame_name=...) may I? execute_codegen(code, frame_name=...) do it materialize_codegen(...) make it durable
A REFUSAL IS A RETURN VALUE, NOT AN EXCEPTION. validate_codegen hands back a CodegenValidationResult. Rejected code does not raise - and on the execute path a rejected validation returns a VALIDATION-FAILED CodegenExecutionResult without ever reaching compile or exec. An agent reads a verdict; it does not catch one. (Exceptions are reserved for malformed REQUESTS: empty code or an empty frame name raise ValueError. Bad input raises, bad code reports.)
VALIDATE IS A SEPARATE VERB, AND THAT IS THE WHOLE DESIGN. An agent can ask "would this be permitted" WITHOUT running anything. And execute_codegen VALIDATES FIRST anyway - the invariant is "validation runs before execution on the execute path", so the separate verb buys you the answer early, never a way around it. Every other safe-execution story collapses those into one call and forces you to attempt the thing to learn whether you were allowed to attempt it - which means the only way to discover a boundary is to cross it.
WHAT validate ACTUALLY ANSWERS Not "is this good code". It answers "does this code stay inside the posture this room was granted", against seven strategies: ast_structure, import_policy, builtin_policy, attribute_access, name_resolution, reflection_policy, recursive_control.
Read recursive_control twice. It exists because generated code that generates code is how a bounded system stops being bounded. Someone thought about an agent escaping its sandbox by writing a smaller one inside it.
THE ROOM REMEMBERS THE SOURCE, AND IT PUSHES Memory is not a describe-door you pull from the command system - it is room.memory_system, a RiftMemorySystem, and you SUBSCRIBE:
room.memory_system.register_memory_callback(fn) -> subscription id
memory_enabled is literally "does anyone have a callback registered", so emission costs nothing until something is listening. A paraphrase would be useless afterwards anyway - the question you ask later is always "what EXACTLY did it write".
AND THE RECORD IS ONE PER SUCCESSFUL TOP-LEVEL CALL. Two details make that precise, and both matter: - SUCCESSFUL. A refused command does not emit. Memory is a log of what happened, not of what was attempted. - TOP-LEVEL. The command system keeps a nested call-depth counter precisely to SUPPRESS duplicate emission when one public command calls another internally. You get the call you made, not the call tree underneath it.
frame_name IS REQUIRED ON BOTH. Generated code has to land in a named world and there is no sane default for that - a codegen call that guessed its target frame would be the worst possible bug.
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/12_the_codegen_loop_end_to_end.py
py -3.14t UX_and_AIX_experiences/04_expert/12_the_codegen_loop_end_to_end.py
Public surface๏
CodegenCommandSystem.validate_codegen / execute_codegen / research_preview, the CodegenValidationResult / CodegenExecutionResult verdicts, and RiftSpace.memory_system callbacks. materialize_codegen is DESCRIBED here, not called - the third rung is a separate decision and expert 26 takes it; running is not keeping.
Code๏
1"""
2TIER: expert (12)
3GOAL: THE CODEGEN LOOP, ACTUALLY RUN. Expert 07 introduced the room and
4 named its three verbs. This drives them: an agent asks permission,
5 writes code into a named world, and reads back what it did.
6
7 THE LOOP
8
9 validate_codegen(code, frame_name=...) may I?
10 execute_codegen(code, frame_name=...) do it
11 materialize_codegen(...) make it durable
12
13 A REFUSAL IS A RETURN VALUE, NOT AN EXCEPTION. `validate_codegen`
14 hands back a `CodegenValidationResult`. Rejected code does not
15 raise - and on the execute path a rejected validation returns a
16 VALIDATION-FAILED `CodegenExecutionResult` without ever reaching
17 compile or exec. An agent reads a verdict; it does not catch one.
18 (Exceptions are reserved for malformed REQUESTS: empty code or an
19 empty frame name raise `ValueError`. Bad input raises, bad code
20 reports.)
21
22 VALIDATE IS A SEPARATE VERB, AND THAT IS THE WHOLE DESIGN. An
23 agent can ask "would this be permitted" WITHOUT running anything.
24 And `execute_codegen` VALIDATES FIRST anyway - the invariant is
25 "validation runs before execution on the execute path", so the
26 separate verb buys you the answer early, never a way around it.
27 Every other safe-execution story collapses those into one call and
28 forces you to attempt the thing to learn whether you were allowed
29 to attempt it - which means the only way to discover a boundary is
30 to cross it.
31
32 WHAT `validate` ACTUALLY ANSWERS
33 Not "is this good code". It answers "does this code stay inside the
34 posture this room was granted", against seven strategies:
35 ast_structure, import_policy, builtin_policy, attribute_access,
36 name_resolution, reflection_policy, recursive_control.
37
38 Read `recursive_control` twice. It exists because generated code
39 that generates code is how a bounded system stops being bounded.
40 Someone thought about an agent escaping its sandbox by writing a
41 smaller one inside it.
42
43 THE ROOM REMEMBERS THE SOURCE, AND IT PUSHES
44 Memory is not a describe-door you pull from the command system - it
45 is `room.memory_system`, a `RiftMemorySystem`, and you SUBSCRIBE:
46
47 room.memory_system.register_memory_callback(fn) -> subscription id
48
49 `memory_enabled` is literally "does anyone have a callback
50 registered", so emission costs nothing until something is
51 listening. A paraphrase would be useless afterwards anyway - the
52 question you ask later is always "what EXACTLY did it write".
53
54 AND THE RECORD IS ONE PER SUCCESSFUL TOP-LEVEL CALL. Two details
55 make that precise, and both matter:
56 - SUCCESSFUL. A refused command does not emit. Memory is a log of
57 what happened, not of what was attempted.
58 - TOP-LEVEL. The command system keeps a nested call-depth counter
59 precisely to SUPPRESS duplicate emission when one public command
60 calls another internally. You get the call you made, not the
61 call tree underneath it.
62
63 frame_name IS REQUIRED ON BOTH. Generated code has to land in a
64 named world and there is no sane default for that - a codegen call
65 that guessed its target frame would be the worst possible bug.
66SURFACE EXERCISED: CodegenCommandSystem.validate_codegen /
67 execute_codegen / research_preview, the
68 CodegenValidationResult / CodegenExecutionResult
69 verdicts, and RiftSpace.memory_system callbacks.
70 materialize_codegen is DESCRIBED here, not called - the
71 third rung is a separate decision and expert 26 takes
72 it; running is not keeping.
73VERIFY: RUN GREEN 2026-08-03 on the owner's 3.14t harness. The SURFACE
74 line above was corrected 2026-08-05; executable code unchanged
75 since that run, so the green still stands.
76"""
77import melder as md
78
79
80SAFE = "result = 2 + 2\n"
81
82# Reaching for a module the posture never granted. This is what
83# import_policy is for.
84UNGRANTED = "import socket\nresult = socket\n"
85
86
87def main() -> None:
88 nexus = md.Nexus()
89 system_configuration = nexus.create_configuration()
90 system_configuration.with_rift_creation_enabled(True)
91 # Expert 11's gate A: the shipped allow-list is ("default",), so a
92 # world this Nexus has never been told about is refused before its
93 # posture is even read. Naming it here is the observer's half of the
94 # consent.
95 system_configuration.with_allowed_target_frame_names(["loop-world"])
96 nexus.activate(system_configuration)
97
98 rift_configuration = nexus.create_rift_configuration()
99 rift_configuration.with_space_type("codegen")
100 rift = nexus.create_rift(configuration=rift_configuration,
101 rift_name="loop")
102 rift.mark_active()
103 room = rift.space
104 commands = room.command_system
105
106 # A codegen room needs a target world, and the frame must have opted in
107 # (expert 11). No posture, no attachment, nothing to write into.
108 book = md.Spellbook(aetheric_frame="loop-world")
109 book.bind(spell=object, existence="many", binding_name="loop-world")
110 book.configure_aether_frame(
111 system_state="dynamic",
112 disposal=None,
113 disposal_method_names=None,
114 rift_enabled=True,
115 ai_native=True,
116 )
117 book.conjure(name="loop-root")
118 rift.create_frame_link("loop-world")
119 frame_name = "loop-world"
120 print("codegen room up:", type(room).__name__, "-> targets", frame_name)
121
122 # 1. ASK FIRST. Validation is a real answer, returned without running
123 # anything - which is the only reason an agent can explore a
124 # boundary safely.
125 verdict = commands.validate_codegen(SAFE, frame_name=frame_name)
126 print()
127 print("validate(safe) ->", verdict)
128
129 # 2. A REFUSAL COMES BACK AS A VALUE. No try/except - rejected code
130 # is a verdict object, and reading one is how an agent learns a
131 # boundary without crossing it.
132 denied = commands.validate_codegen(UNGRANTED, frame_name=frame_name)
133 print("validate(ungranted) ->", type(denied).__name__, "-", denied)
134
135 # ...and executing rejected code returns a VALIDATION-FAILED result
136 # rather than raising, because validation runs first on the execute
137 # path too. Nothing was compiled and nothing ran.
138 refused = commands.execute_codegen(UNGRANTED, frame_name=frame_name)
139 print("execute(ungranted) ->", type(refused).__name__)
140 print(" validation ran BEFORE execution - no compile, no exec")
141
142 # THE EXCEPTIONS ARE FOR MALFORMED REQUESTS, not for rejected code.
143 # Bad input raises; bad code reports.
144 for bad_code, bad_frame in (("", frame_name), ("result = 1\n", "")):
145 try:
146 commands.validate_codegen(bad_code, frame_name=bad_frame)
147 raise AssertionError("expected ValueError on an empty argument")
148 except ValueError:
149 pass
150 print("empty code / empty frame_name raise ValueError - malformed")
151 print(" REQUEST is a different failure from disallowed CODE")
152
153 # 3. NOW RUN IT. Same code, same frame, and this is the only call
154 # that changes the world.
155 outcome = commands.execute_codegen(SAFE, frame_name=frame_name)
156 print()
157 print("execute(safe) ->", type(outcome).__name__)
158
159 # 4. WHAT THE ROOM KEPT. Memory is a ROOM system and it PUSHES -
160 # subscribe before you act, or there is nothing to have kept.
161 # `memory_enabled` is exactly "is anyone listening", so a room with
162 # no subscriber pays nothing for the feature.
163 seen = []
164 assert room.memory_system.memory_enabled is False
165 subscription = room.memory_system.register_memory_callback(seen.append)
166 assert room.memory_system.memory_enabled is True
167 print()
168 print("subscribed to room memory ->", type(subscription).__name__)
169
170 commands.execute_codegen("result = 5\n", frame_name=frame_name)
171 print("records captured after one execute:", len(seen))
172 print(" ONE record - top-level only. Internal command-to-command")
173 print(" calls are suppressed by a call-depth counter, so you get")
174 print(" the call you made, not the tree underneath it")
175 print(" full source, not a summary - `what exactly did it write` is")
176 print(" the only question anyone asks afterwards")
177
178 room.memory_system.unregister_memory_callback(subscription)
179 assert room.memory_system.memory_enabled is False
180 print("unsubscribed - emission goes quiet again")
181
182 # 5. THE SECOND QUESTION - and it needs a LIVE research root.
183 # `research_preview` is part of the research family, which reaches
184 # the Aether-hosted MutationResearch through a NON-CONSTRUCTING
185 # peek: absent or inactive research refuses rather than quietly
186 # booting one behind your back.
187 research = md.MutationResearch()
188 research_configuration = research.create_configuration()
189 research_configuration.with_defaults().activate()
190 research.activate(research_configuration)
191 print()
192 print("mutation research activated - research commands need it live")
193
194 # `validate` asks "am I PERMITTED"; `research_preview` asks "what
195 # would this DO" - the read-only candidate mock. Give it a
196 # frame_name and it FOLDS THE VALIDATE VERDICT IN, so one call
197 # answers both questions. Nothing executes, binds, or records.
198 preview = commands.research_preview("result = 3\n", frame_name=frame_name)
199 print("research_preview ->", type(preview).__name__)
200 print(" would-be source, structural diff, blast radius - and the")
201 print(" validate verdict too, because frame_name was given")
202 print(" nothing executed, nothing bound, nothing recorded")
203
204 # 6. MATERIALIZE is the third rung and a SEPARATE decision, with its
205 # own argument: executing code and giving it a MODULE NAME are
206 # different acts. Running is not keeping.
207 print()
208 print("materialize_codegen(code, module_name=..., frame_name=...)")
209 print(" the module_name is the tell - durability needs an address")
210
211 # 7. frame_name IS REQUIRED. Not defaulted, not inferred.
212 import inspect
213 for verb in ("validate_codegen", "execute_codegen"):
214 parameters = inspect.signature(getattr(commands, verb)).parameters
215 assert parameters["frame_name"].default is inspect.Parameter.empty, (
216 f"{verb} must not default its target frame"
217 )
218 print("both verbs require frame_name - generated code lands somewhere")
219 print(" named, or it does not land")
220
221 print()
222 print("ask, then act, then read back what you did")
223 print("a boundary you can probe without crossing is the whole point")
224
225
226if __name__ == "__main__":
227 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.