agora.plan.structure
Structural models of plan artifacts + comparators for cross-layer drift.
Three layers of “what the system believes a module looks like”:
- L1 — Contract model (
ContractModel): derived from
plan/api_spec.md. Ground truth — what the plan commits to.- L2 — Usage-implied traces (
UsageTrace): derived from testbodies. What the tester ASSUMES each method’s return looks like based on how they access it.
- L3 — Implementation-actual model (
ImplClassModel):derived from
src/*.pyAST after the implementer writes. What the code actually exposes.
Comparators diff these pairwise. Every comparator returns a list of
Violation objects with severity ∈ {"certain", "unresolved"}.
certain: an obvious contradiction (e.g.list[str][0]['key']when key-subscript on a string is invalid).
unresolved: the comparator couldn’t figure something out because a type wasUnknown, a variable was aliased through multiple assignments, etc.
Callers can filter: permissive mode reports only certain;
strict mode reports both. Default is permissive so false positives
don’t wreck productive runs; strict is an opt-in stress-test surface.
Functions
|
Return a violation for every attribute the class READS without ever SETTING. |
|
Return all drift violations between test-body usage and the spec. |
|
Parse |
|
Parse impl source; return an |
|
Walk a test file's AST; collect usage traces for every call whose receiver resolves to a spec-declared class. |
|
Filter a violation list by report |
Classes
One step in a value-access chain. |
|
A class as its name + method signatures, for structural comparison (implementation vs. plan/spec). |
|
L1: everything api_spec declares. |
|
What a class in |
|
One function/method signature as a comparable value (name, typed params excluding |
|
Drift-report strictness. |
|
A module's structural surface — its classes and top-level functions — as extracted from one layer (source AST, plan, or api_spec). |
|
What category of type a |
|
A parsed representation of a type annotation. |
|
A method call captured from a test body, plus the chain of indexing/attribute accesses applied to its return value. |
|
A cross-layer drift the comparator detected. |
- class agora.plan.structure.AccessStep[source]
Bases:
objectOne step in a value-access chain.
- Kinds:
subscript_index—x[42]orx[-1](numeric key)subscript_str—x['key'](string key)subscript_var—x[name_or_expr](can’t statically tell)attribute—x.attrcall—x(...)(rare but possible via callables)
- __init__(kind, value='')
- class agora.plan.structure.ClassModel[source]
Bases:
objectA class as its name + method signatures, for structural comparison (implementation vs. plan/spec).
find_method()resolves by name.- methods: tuple[MethodSignature, ...] = ()
- __init__(name, methods=())
- class agora.plan.structure.ContractModel[source]
Bases:
objectL1: everything api_spec declares. Frozen — deterministic from text.
- modules: tuple[ModuleModel, ...] = ()
- __init__(modules=())
- class agora.plan.structure.ImplClassModel[source]
Bases:
objectWhat a class in
src/*.pyactually exposes, derived from AST.Used by
check_impl_self_consistent()to detect bugs like “__init__setsself.url_mappingbutadd_urlreadsself.url_hash_map” — a typo that pytest only catches at runtime on first method call.- __init__(name, method_names=(), attrs_set=(), attrs_read=())
- class agora.plan.structure.MethodSignature[source]
Bases:
objectOne function/method signature as a comparable value (name, typed params excluding
self, return type). Equality drives cross-layer drift detection, so params carryTypeRefrather than raw strings — an unresolved type compares as unknown instead of falsely differing.- __init__(name, params=(), return_type=<factory>, has_self=True)
- class agora.plan.structure.Mode[source]
-
Drift-report strictness.
PERMISSIVEreports onlycertainviolations (both sides resolved to concrete, differing types);STRICTalso reportsunresolvedones (a type that could not be resolved, so the mismatch is suspected not proven). Lets a caller choose false-positive vs. false-negative risk without re-running the comparison.- PERMISSIVE = 'permissive'
- STRICT = 'strict'
- __new__(value)
- class agora.plan.structure.ModuleModel[source]
Bases:
objectA module’s structural surface — its classes and top-level functions — as extracted from one layer (source AST, plan, or api_spec). Comparing two ModuleModels is how the framework catches a tester and implementer drifting onto different APIs.
find_class()resolves by name.- classes: tuple[ClassModel, ...] = ()
- functions: tuple[MethodSignature, ...] = ()
- __init__(path, classes=(), functions=())
- class agora.plan.structure.TypeKind[source]
-
What category of type a
TypeRefrepresents.Kept deliberately coarse — this module is not mypy. Anything the parser can’t categorise becomes
UNKNOWNand comparators treat it as unresolved (permissive by default).- PRIMITIVE = 'primitive'
- NONE = 'none'
- LIST = 'list'
- TUPLE = 'tuple'
- DICT = 'dict'
- CLASS = 'class'
- OPTIONAL = 'optional'
- UNION = 'union'
- ANY = 'any'
- UNKNOWN = 'unknown'
- __new__(value)
- class agora.plan.structure.TypeRef[source]
Bases:
objectA parsed representation of a type annotation.
Only the fields relevant to
kindare populated:PRIMITIVE:name("str","int","bool","float")LIST:params=(element_type,)TUPLE:params=(t0, t1, ...)with optional trailing Ellipsis marker viatuple_variadicDICT:params=(key_type, value_type)CLASS:name= declared class nameOPTIONAL/UNION:params=(t0, t1, ...)NONE/ANY/UNKNOWN: no additional info
- __init__(kind, name='', params=(), tuple_variadic=False)
- class agora.plan.structure.UsageTrace[source]
Bases:
objectA method call captured from a test body, plus the chain of indexing/attribute accesses applied to its return value.
- Example:
shortener.list_mappings()[0]['hash']→ - ``class_name=”URLShortener”, method_name=”list_mappings”,
steps=[subscript_index(0), subscript_str(“hash”)]``
test_nameandbody_linehelp error messages point at the offending test function + line within the body.consumed_call_idsholds theid(ast.Call)values of inner Call nodes that contributed to this trace’s step chain (viaobj.method1().method2()). The extractor uses it to avoid emitting duplicate standalone traces for the inner calls.- steps: tuple[AccessStep, ...] = ()
- __init__(test_name, class_name, method_name, steps=(), body_line=0, consumed_call_ids=<factory>)
- Example:
- class agora.plan.structure.Violation[source]
Bases:
objectA cross-layer drift the comparator detected.
severitycontrols whether permissive mode surfaces this.pathis a human-oriented breadcrumb (e.g."test_foo → URLShortener.bar() → [0] → ['key']") so the error message points precisely at the offending chain.- __init__(path, message, severity='certain')
- agora.plan.structure.check_impl_self_consistent(impl_classes)[source]
Return a violation for every attribute the class READS without ever SETTING.
Note: methods declared on the class (
method_names) are excluded fromattrs_readevaluation — callingself.method()doesn’t count as reading an attribute that needs to be assigned. Private helpers (self._foo) are treated the same as public ones.Does NOT flag reads of methods, @property-style computed attributes we can’t statically detect, or attributes set via
setattr. Permissive-leaning on purpose — the false-positive floor is higher than the return-type checker.
- agora.plan.structure.check_usage_matches_contract(traces, contract)[source]
Return all drift violations between test-body usage and the spec.
Permissive/strict filtering is the CALLER’s job — we return every finding, tagged with severity. Callers apply
filter_by_mode().
- agora.plan.structure.extract_contract(spec_text)[source]
Parse
agora.plan.api_specoutput into a structured model.Uses
agora.plan.api_spec.parse_api_spec()as the source of module boundaries + method bodies, then walks each method’s source to extract aMethodSignaturewith typed params + return.
- agora.plan.structure.extract_impl_classes(source)[source]
Parse impl source; return an
ImplClassModelper class.- For each class:
method_names= everydef fooat class body levelattrs_set= everyself.X = ...(or aug-assignment) across all methodsattrs_read= everyself.Xread outside assignment target context
- agora.plan.structure.extract_usage_traces(test_source, contract)[source]
Walk a test file’s AST; collect usage traces for every call whose receiver resolves to a spec-declared class.
Only catches the patterns that actually appear in LLM-authored tests: direct constructor chain (
URLShortener().method()), simple same-scope aliases (x = URLShortener(); x.method()), and class- method-style calls (URLShortener.method(...)). Anything more indirect (variable passed through functions, conditional assignment, list comprehensions over instances) is intentionally skipped — unresolved ≠ violation, per permissive-by-default.