agora.plan.module_editor

AST-aware upsert helpers for Python source files.

Sprint 7.4 — the implementer equivalent of Sprint 7.3’s fill_test_body. Observed failure: 7B can reliably author an INITIAL Python module but can’t combine multiple edit_file_replace / edit_file_append calls into a coherent file when adding more code. The file accumulates half-finished class definitions stacked on top of each other (see live run logs: add_core_domain_module produced 5 duplicate class definitions over 49 iterations before giving up).

These helpers decompose that work: the model emits the new top-level function, class, or class-method source, and the framework owns the positional surgery — append if new, replace if a definition with the same name already exists. The model never has to match whitespace against the existing file or keep track of where anything goes.

All three functions are pure string transformations; they parse the source with ast and manipulate the line list in place. Callers catch ValueError for “target not found” and SyntaxError for “your code doesn’t parse” — both are recoverable by the model on the next turn.

Functions

upsert_class(source, code)

Add a top-level class to source or replace an existing one.

upsert_class_method(source, class_name, code)

Add a method inside class_name or replace an existing method.

upsert_function(source, code)

Add a top-level function to source or replace an existing one.

agora.plan.module_editor.upsert_function(source, code)[source]

Add a top-level function to source or replace an existing one.

code must be the complete Python source for ONE function (including the def line, body, and optionally decorators). If a top-level function with the same name already exists, it’s replaced in place; otherwise the new function is appended at the end of the module.

Returns the new module source. Raises ValueError if code doesn’t define exactly one function. Raises SyntaxError if code or the resulting module won’t parse.

agora.plan.module_editor.upsert_class(source, code)[source]

Add a top-level class to source or replace an existing one.

Same semantics as upsert_function() but for classes.

agora.plan.module_editor.upsert_class_method(source, class_name, code)[source]

Add a method inside class_name or replace an existing method.

code must be the source for ONE def or async def (the method, without the enclosing class — framework re-indents). If a method with the same name exists on the class, it’s replaced at the same position; otherwise the method is appended to the end of the class body.

Raises ValueError if the class doesn’t exist in source, or if code doesn’t define exactly one function.