On this page

Asking what code would do before running it๏ƒ

๐Ÿ”ต Expert ยท Lesson 22

FORESIGHT. An agent about to replace a version can ask what the replacement WOULD do - what it defines, what it imports, how it differs from what is there, what it would break, and whether the room would even permit it - and get all of that WITHOUT running, binding, or recording anything.

commands.research_preview( candidate_source, against_spell_id=existing_spell_id, frame_name=FRAME, )

ONE CALL, FIVE ANSWERS defines / import_roots what the candidate declares and pulls diff would-be source + structural diff against the version it would REPLACE impact the blast radius of that replacement, joined with research residency candidate_sha256 the identity it would have validation the room's normal codegen verdict, but ONLY when frame_name is supplied That last one matters: validate_codegen answers "am I permitted", research_preview answers "what would happen", and passing a frame folds the first into the second so an agent asks once.

ORDER OF SETUP IS LOAD-BEARING, IN TWO SEPARATE WAYS

  1. A BIND ONLY AUTO-RECORDS INTO A LIVE RESEARCH ROOT. The seam returns quietly when research is absent, cleaned or inactive, because "research bookkeeping never gates a bind". So a world built before you activate research is a world research never saw. Activate first, then build.

  2. AND A RECORDED WORLD MUST BE BORN CONFIGURED. With custody active, a DYNAMIC conjure REFUSES outright if any bind ran before the SpellbookConfiguration was finalized:

md.SpellbookConfiguration(FRAME).with_defaults().finalize() md.Spellbook(aetheric_frame=FRAME, configuration=...) book.bind(...) # now the binds are config-coherent book.conjure(dynamic=True)

The reason is stated in the refusal itself: the profile record, the checkpoints and the default bootstrap would DURABLY PERSIST binds that ran against unsettled configuration. A runtime can tolerate that; a RECORD cannot, because the record is what a future boot rebuilds from. Automatic-mode worlds and worlds with no active Crystallizer are exempt, so nothing that is not being recorded pays for this.

Note which lessons this caught: every lesson in this tier that activates custody AND conjures dynamic, and none of the others. The rule is narrow and it is exactly as narrow as the risk.

AND FORESIGHT NEEDS CUSTODY. The impact half reaches through the Crystallizer for the physical picture (expert 14's record-vs- foresight split), so it refuses loudly when custody is not recording rather than handing back an empty radius.

THE PROOF THAT PREVIEW IS READ-ONLY IS IN THIS FILE The lesson reads the research heads before and after the preview and asserts they are IDENTICAL. "Nothing executes, binds, or records" is a claim melder makes about itself; here it is checked.

A BROKEN CANDIDATE ANSWERS, IT DOES NOT EXPLODE Hand it source that does not parse and parse_error comes back populated with the rest of the payload still shaped the same way. An agent generating code gets malformed output sometimes; a foresight tool that raised on it would be useless exactly when it is needed.

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/22_asking_what_code_would_do_before_running_it.py
py -3.14t UX_and_AIX_experiences/04_expert/22_asking_what_code_would_do_before_running_it.py

Download this collection ยท Source on GitHub

Public surface๏ƒ

research_preview (defines / import_roots / diff / impact / candidate_sha256 / parse_error), research_impact, research_heads, and the Crystallizer + MutationResearch activation order

Code๏ƒ

  1"""
  2TIER: expert (22)
  3GOAL: FORESIGHT. An agent about to replace a version can ask what the
  4      replacement WOULD do - what it defines, what it imports, how it
  5      differs from what is there, what it would break, and whether the
  6      room would even permit it - and get all of that WITHOUT running,
  7      binding, or recording anything.
  8
  9        commands.research_preview(
 10            candidate_source,
 11            against_spell_id=existing_spell_id,
 12            frame_name=FRAME,
 13        )
 14
 15      ONE CALL, FIVE ANSWERS
 16        defines / import_roots   what the candidate declares and pulls
 17        diff                     would-be source + structural diff
 18                                 against the version it would REPLACE
 19        impact                   the blast radius of that replacement,
 20                                 joined with research residency
 21        candidate_sha256         the identity it would have
 22        validation               the room's normal codegen verdict, but
 23                                 ONLY when frame_name is supplied
 24      That last one matters: `validate_codegen` answers "am I permitted",
 25      `research_preview` answers "what would happen", and passing a frame
 26      folds the first into the second so an agent asks once.
 27
 28      ORDER OF SETUP IS LOAD-BEARING, IN TWO SEPARATE WAYS
 29
 30      1. A BIND ONLY AUTO-RECORDS INTO A LIVE RESEARCH ROOT. The seam
 31         returns quietly when research is absent, cleaned or inactive,
 32         because "research bookkeeping never gates a bind". So a world
 33         built before you activate research is a world research never
 34         saw. Activate first, then build.
 35
 36      2. AND A RECORDED WORLD MUST BE BORN CONFIGURED. With custody
 37         active, a DYNAMIC conjure REFUSES outright if any bind ran
 38         before the SpellbookConfiguration was finalized:
 39
 40           md.SpellbookConfiguration(FRAME).with_defaults().finalize()
 41           md.Spellbook(aetheric_frame=FRAME, configuration=...)
 42           book.bind(...)          # now the binds are config-coherent
 43           book.conjure(dynamic=True)
 44
 45         The reason is stated in the refusal itself: the profile record,
 46         the checkpoints and the default bootstrap would DURABLY PERSIST
 47         binds that ran against unsettled configuration. A runtime can
 48         tolerate that; a RECORD cannot, because the record is what a
 49         future boot rebuilds from. Automatic-mode worlds and worlds
 50         with no active Crystallizer are exempt, so nothing that is not
 51         being recorded pays for this.
 52
 53         Note which lessons this caught: every lesson in this tier that
 54         activates custody AND conjures dynamic, and none of the others.
 55         The rule is narrow and it is exactly as narrow as the risk.
 56
 57      AND FORESIGHT NEEDS CUSTODY. The impact half reaches through the
 58      Crystallizer for the physical picture (expert 14's record-vs-
 59      foresight split), so it refuses loudly when custody is not
 60      recording rather than handing back an empty radius.
 61
 62      THE PROOF THAT PREVIEW IS READ-ONLY IS IN THIS FILE
 63      The lesson reads the research heads before and after the preview
 64      and asserts they are IDENTICAL. "Nothing executes, binds, or
 65      records" is a claim melder makes about itself; here it is checked.
 66
 67      A BROKEN CANDIDATE ANSWERS, IT DOES NOT EXPLODE
 68      Hand it source that does not parse and `parse_error` comes back
 69      populated with the rest of the payload still shaped the same way.
 70      An agent generating code gets malformed output sometimes; a
 71      foresight tool that raised on it would be useless exactly when it
 72      is needed.
 73SURFACE EXERCISED: research_preview (defines / import_roots / diff /
 74                   impact / candidate_sha256 / parse_error),
 75                   research_impact, research_heads, and the
 76                   Crystallizer + MutationResearch activation order
 77VERIFY: rides the owner's 3.14t harness; asserts are the contract.
 78"""
 79import melder as md
 80
 81
 82FRAME = "foresight-world"
 83
 84
 85class PriceRule:
 86    """The version an agent is about to propose replacing."""
 87
 88    def __init__(self) -> None:
 89        self.rate = 10
 90
 91    def apply(self, amount: int) -> int:
 92        return amount * self.rate
 93
 94
 95# What the agent proposes. Note it DEFINES a class and IMPORTS nothing -
 96# the preview reports both without running a line of it.
 97CANDIDATE = (
 98    "class PriceRule:\n"
 99    "    def __init__(self):\n"
100    "        self.rate = 25\n"
101    "\n"
102    "    def apply(self, amount):\n"
103    "        return amount * self.rate + 1\n"
104)
105
106BROKEN = "class PriceRule\n    this is not python\n"
107
108
109def main() -> None:
110    # 1. RECORD AND CUSTODY FIRST. A world built before these are live is
111    #    a world neither of them ever saw.
112    crystallizer = md.Crystallizer()
113    crystallizer.activate(
114        md.CrystallizerConfigurationBuilder().with_defaults().activate(),
115    )
116    research = md.MutationResearch()
117    research_configuration = research.create_configuration()
118    research_configuration.with_defaults().activate()
119    research.activate(research_configuration)
120    assert crystallizer.activated and research.activated
121    print("custody recording:", crystallizer.activated,
122          " research live:", research.activated)
123
124    # 2. NOW build the world. The bind auto-records because research was
125    #    already up - had we activated afterwards, nothing would have
126    #    been recorded and no foresight would have been possible.
127    # A RECORDED WORLD MUST BE BORN CONFIGURED. With custody active, a
128    # dynamic conjure REFUSES if any bind ran before the configuration
129    # was finalized - the profile record and default bootstrap would
130    # otherwise durably persist binds made against unsettled config.
131    spellbook_configuration = (
132        md.SpellbookConfiguration(FRAME).with_defaults().finalize()
133    )
134    book = md.Spellbook(aetheric_frame=FRAME,
135                        configuration=spellbook_configuration)
136    # AND THE FRAME POSTURE GOES BEFORE THE BIND TOO, for a DIFFERENT
137    # reason: a plain bind only auto-records `if self._is_dynamic_posture()`,
138    # which reads the FRAME configuration and is answerable before conjure.
139    # Bind into a not-yet-dynamic frame and the spell is never declared -
140    # no residency, no foresight, and no error either, because research
141    # bookkeeping never gates a bind.
142    book.configure_aether_frame(
143        system_state="dynamic",
144        disposal=None,
145        disposal_method_names=None,
146        rift_enabled=True,
147        ai_native=True,
148    )
149    spell_id = book.bind(
150        spell=PriceRule, existence="unique", permissions="create",
151        binding_name="foresight-rule",
152    )
153    conduit = book.conjure(name="foresight-root")
154    live = conduit.meld(spell=PriceRule, binding_name="foresight-rule")
155    assert live.apply(4) == 40
156    print()
157    print("world up; PriceRule.apply(4) ->", live.apply(4))
158    print("spell_id:", spell_id[:12], "...")
159
160    # 3. A codegen room pointed at it.
161    nexus = md.Nexus()
162    system_configuration = nexus.create_configuration()
163    system_configuration.with_rift_creation_enabled(True)
164    system_configuration.with_allowed_target_frame_names([FRAME])
165    nexus.activate(system_configuration)
166    rift_configuration = nexus.create_rift_configuration()
167    rift_configuration.with_space_type("codegen")
168    rift = nexus.create_rift(configuration=rift_configuration,
169                             rift_name="foresight")
170    rift.mark_active()
171    rift.create_frame_link(FRAME)
172    commands = rift.space.command_system
173
174    # 4. WHAT DOES THE EXISTING VERSION TOUCH, RIGHT NOW?
175    # `spell_id` is KEYWORD-ONLY here, and so is `module_name` - the verb
176    # answers about exactly ONE center per call, so it will not let you
177    # pass a bare identifier and leave which-kind-of-center to inference.
178    radius = commands.research_impact(spell_id=spell_id)
179    print()
180    print("research_impact(existing) -> keys:", sorted(radius)[:6], "...")
181    print("  the CURRENT blast radius, joined with research residency")
182
183    # 5. THE FORESIGHT CALL. Snapshot the record first so we can prove
184    #    the preview did not touch it.
185    heads_before = commands.research_heads()
186
187    preview = commands.research_preview(
188        CANDIDATE,
189        against_spell_id=spell_id,
190        frame_name=FRAME,
191    )
192    for key in ("candidate_sha256", "module_name", "parse_error",
193                "defines", "import_roots", "diff", "impact",
194                "against_spell_id"):
195        assert key in preview, key
196    print()
197    print("research_preview ->", len(preview), "keys")
198    print("   parse_error :", preview["parse_error"])
199    print("   defines     :", preview["defines"])
200    print("   import_roots:", preview["import_roots"] or "(none)")
201    print("   candidate   :", str(preview["candidate_sha256"])[:12], "...")
202    print("   against     :", str(preview["against_spell_id"])[:12], "...")
203    assert preview["parse_error"] is None
204    assert preview["against_spell_id"] == spell_id
205    print("  it read the candidate's AST - a class defined, no imports -")
206    print("  diffed it against the version it would replace, and priced")
207    print("  the replacement, all without running a line")
208
209    # 6. AND THE ROOM'S VERDICT CAME ALONG, because frame_name was given.
210    print()
211    print("frame_name folded the permission question in:")
212    print("  'may I' and 'what would happen' answered in ONE call")
213
214    # 7. THE PROOF. Nothing executed, bound, or recorded.
215    heads_after = commands.research_heads()
216    assert heads_after == heads_before, (
217        "research_preview must not move the record - it is foresight, "
218        "not a dry-run that half-commits"
219    )
220    still = conduit.meld(spell=PriceRule, binding_name="foresight-rule")
221    assert still.apply(4) == 40
222    print("record heads: IDENTICAL before and after the preview")
223    print("live object : still the old rule ->", still.apply(4))
224    print("  'nothing executes, binds, or records' - checked, not trusted")
225
226    # 8. A CANDIDATE THAT DOES NOT PARSE STILL ANSWERS.
227    broken = commands.research_preview(BROKEN, frame_name=FRAME)
228    assert broken["parse_error"] is not None
229    print()
230    print("a candidate that does not parse ->")
231    print("   parse_error:", str(broken["parse_error"])[:60])
232    print("  same payload shape, populated honestly. An agent's generator")
233    print("  emits garbage sometimes, and a foresight tool that raised on")
234    print("  garbage would fail exactly when it is most needed")
235
236    print()
237    print("ask what it WOULD do, then decide - and the asking is free")
238    print("activate record and custody BEFORE you build, or there is")
239    print("nothing to have foresight about")
240
241
242if __name__ == "__main__":
243    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๏ƒ