On this page

Review agent bindings๏ƒ

๐Ÿ”ต Expert ยท Lesson 37

Gate agent-supplied existing objects with ordered pre-bind checks, verify agent metadata and annotate the new Spell during activation, then update and audit the published Spell in post-bind. Demonstrate rejection phases and why a post-bind failure does not undo registration.

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

Download this collection ยท Source on GitHub

Public surface๏ƒ

md.Spellbook / find_spell_by_spell_id / describe_spells_in_spellbook, md.Conduit.add_bind_hooks / clear_bind_hooks / bind / meld, md.Spell.metadata / tags, md.HookExecutionError

Code๏ƒ

  1"""
  2TIER: expert (37)
  3GOAL: Gate agent-supplied existing objects with ordered pre-bind checks,
  4      verify agent metadata and annotate the new Spell during activation,
  5      then update and audit the published Spell in post-bind. Demonstrate
  6      rejection phases and why a post-bind failure does not undo registration.
  7SURFACE EXERCISED: md.Spellbook / find_spell_by_spell_id / describe_spells_in_spellbook,
  8                  md.Conduit.add_bind_hooks / clear_bind_hooks / bind / meld,
  9                  md.Spell.metadata / tags, md.HookExecutionError
 10"""
 11import melder as md
 12
 13
 14class ReportTool:
 15    """Application-created tool that an agent proposes for registration.
 16
 17    Contract:
 18        Carries its schema version as ordinary instance state. It owns no
 19        external resources; Melder must resolve the exact supplied reference.
 20    """
 21
 22    def __init__(self, schema_version: int = 1) -> None:
 23        """Retain the supplied application schema version without registration work."""
 24        self.schema_version = schema_version
 25
 26    def render(self, subject: str) -> str:
 27        """Render a deterministic result using the already-existing object."""
 28        return f"report:{subject}"
 29
 30
 31class BackupReport(ReportTool):
 32    """Distinct registration used to demonstrate failure after publication."""
 33
 34
 35class BindingReview:
 36    """Application policy and local audit for one Book's agent submissions.
 37
 38    Contract:
 39        Borrows the Book and owns a list of published IDs. Pre checks run in
 40        declared order. Metadata updates annotate a Spell; they do not change
 41        its ID, replace its implementation or automatically refresh persistence.
 42        This small audit is used sequentially in the example.
 43    """
 44
 45    def __init__(self, book: md.Spellbook) -> None:
 46        """Borrow the target Book and initialize this review's independent audit."""
 47        self.book = book
 48        self.published_ids: list[str] = []
 49
 50    def require_report_tool(self, reference: object) -> None:
 51        """Reject references outside this application's supported existing-object type."""
 52        if not isinstance(reference, ReportTool):
 53            raise TypeError("Agent submissions must be existing ReportTool objects.")
 54
 55    def require_supported_schema(self, reference: ReportTool) -> None:
 56        """Check instance state after the preceding callback has validated its type."""
 57        if reference.schema_version != 1:
 58            raise ValueError("ReportTool schema_version must be 1.")
 59
 60    def configure_spell(self, spell: md.Spell) -> None:
 61        """Check bind metadata and decorate the actual unpublished Spell.
 62
 63        Contract:
 64            Pre-bind receives only the reference. The submitted_by bind keyword
 65            is available here, on the newly constructed Spell's metadata.
 66        """
 67        if spell.metadata.get("submitted_by") != "report-agent":
 68            raise PermissionError("This Book accepts submissions from report-agent only.")
 69        assert self.book.find_spell_by_spell_id(spell.spell_id) is None
 70        spell.metadata["review_policy"] = "report-schema-v1"
 71        spell.tags.append("agent-reviewed")
 72
 73    def record_registration(self, spell: md.Spell) -> None:
 74        """Update and audit the same Spell after it becomes publicly discoverable.
 75
 76        Contract:
 77            The post_checked annotation is live metadata. Post is not a
 78            transaction-commit or durable-record refresh callback.
 79        """
 80        assert self.book.find_spell_by_spell_id(spell.spell_id) is spell
 81        assert spell.metadata["review_policy"] == "report-schema-v1"
 82        spell.metadata["post_checked"] = True
 83        self.published_ids.append(spell.spell_id)
 84
 85
 86def unavailable_audit_sink(spell: md.Spell) -> None:
 87    """Simulate an application notification failure after the earlier post callback."""
 88    raise RuntimeError(f"Audit sink unavailable for {spell.spell_name}.")
 89
 90
 91def main() -> None:
 92    """Bind accepted agent proposals and assert the precise refusal boundaries.
 93
 94    Contract:
 95        Uses ordinary public binding against a live normal Conduit. The
 96        proposal references stand for objects supplied by an agent workflow;
 97        acquiring or generating those references is a separate concern.
 98    """
 99    book = md.Spellbook(configuration=md.SpellbookConfiguration().with_defaults())
100    conduit = None
101    try:
102        conduit = book.conjure(dynamic=True, name="agent-bind-review")
103        review = BindingReview(book)
104        conduit.add_bind_hooks(
105            pre=[review.require_report_tool, review.require_supported_schema],
106            activation=[review.configure_spell],
107            post=[review.record_registration],
108        )
109
110        # A reference check rejects by raising, not by returning False.
111        for proposal, cause in ((object(), TypeError), (ReportTool(2), ValueError)):
112            try:
113                conduit.bind(spell=proposal, existence="unique", submitted_by="report-agent")
114            except md.HookExecutionError as error:
115                assert error.phase == "pre_bind"
116                assert isinstance(error.original_exception, cause)
117                print("reference refused:", error.phase, str(error.original_exception))
118            else:
119                raise AssertionError("The unsuitable proposal was registered.")
120        assert book.describe_spells_in_spellbook() == []
121        assert review.published_ids == []
122
123        supplied = ReportTool()
124        try:
125            conduit.bind(spell=supplied, existence="unique", submitted_by="unknown-agent")
126        except md.HookExecutionError as error:
127            assert error.phase == "bind_activation"
128            assert isinstance(error.original_exception, PermissionError)
129            print("agent metadata refused:", error.phase)
130        else:
131            raise AssertionError("The unapproved agent was admitted.")
132        assert book.describe_spells_in_spellbook() == []
133        assert supplied.render("still-owned-by-caller") == "report:still-owned-by-caller"
134
135        spell_id = conduit.bind(
136            spell=supplied, existence="unique", submitted_by="report-agent",
137        )
138        registered = book.find_spell_by_spell_id(spell_id)
139        assert registered is not None
140        assert registered.metadata == {
141            "submitted_by": "report-agent",
142            "review_policy": "report-schema-v1",
143            "post_checked": True,
144        }
145        assert "agent-reviewed" in registered.tags
146        assert conduit.meld("ReportTool") is supplied
147        assert supplied.render("weekly") == "report:weekly"
148        assert review.published_ids == [spell_id]
149        print("accepted existing object:", registered.metadata)
150
151        # add appends: record_registration runs before the later failing callback.
152        conduit.add_bind_hooks(post=[unavailable_audit_sink])
153        backup = BackupReport()
154        try:
155            conduit.bind(spell=backup, existence="unique", submitted_by="report-agent")
156        except md.HookExecutionError as error:
157            assert error.phase == "post_bind"
158            assert isinstance(error.original_exception, RuntimeError)
159            print("post notification failed; inspect the published binding before retrying")
160        else:
161            raise AssertionError("The audit failure was not propagated.")
162        assert len(review.published_ids) == 2
163        published_backup = book.find_spell_by_spell_id(review.published_ids[-1])
164        assert published_backup is not None
165        assert published_backup.spell_name == "BackupReport"
166        assert published_backup.metadata["post_checked"] is True
167        assert conduit.meld("BackupReport") is backup
168        print("binding survived post failure:", published_backup.spell_name)
169
170        conduit.clear_bind_hooks()
171        assert conduit.meld("ReportTool") is supplied
172        assert registered.metadata["post_checked"] is True
173    finally:
174        if conduit is not None:
175            conduit.cleanup()
176        book.cleanup()
177
178
179if __name__ == "__main__":
180    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๏ƒ