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 test

bodies. What the tester ASSUMES each method’s return looks like based on how they access it.

L3 — Implementation-actual model (ImplClassModel):

derived from src/*.py AST 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 was Unknown, 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

check_impl_self_consistent(impl_classes)

Return a violation for every attribute the class READS without ever SETTING.

check_usage_matches_contract(traces, contract)

Return all drift violations between test-body usage and the spec.

extract_contract(spec_text)

Parse agora.plan.api_spec output into a structured model.

extract_impl_classes(source)

Parse impl source; return an ImplClassModel per class.

extract_usage_traces(test_source, contract)

Walk a test file's AST; collect usage traces for every call whose receiver resolves to a spec-declared class.

filter_by_mode(violations, mode)

Filter a violation list by report Mode: STRICT returns all, PERMISSIVE keeps only certain ones.

Classes

AccessStep

One step in a value-access chain.

ClassModel

A class as its name + method signatures, for structural comparison (implementation vs. plan/spec).

ContractModel

L1: everything api_spec declares.

ImplClassModel

What a class in src/*.py actually exposes, derived from AST.

MethodSignature

One function/method signature as a comparable value (name, typed params excluding self, return type).

Mode

Drift-report strictness.

ModuleModel

A module's structural surface — its classes and top-level functions — as extracted from one layer (source AST, plan, or api_spec).

TypeKind

What category of type a TypeRef represents.

TypeRef

A parsed representation of a type annotation.

UsageTrace

A method call captured from a test body, plus the chain of indexing/attribute accesses applied to its return value.

Violation

A cross-layer drift the comparator detected.

class agora.plan.structure.AccessStep[source]

Bases: object

One step in a value-access chain.

Kinds:
  • subscript_index — x[42] or x[-1] (numeric key)

  • subscript_str — x['key'] (string key)

  • subscript_var — x[name_or_expr] (can’t statically tell)

  • attribute — x.attr

  • call — x(...) (rare but possible via callables)

kind: str
value: str = ''
__init__(kind, value='')
class agora.plan.structure.ClassModel[source]

Bases: object

A class as its name + method signatures, for structural comparison (implementation vs. plan/spec). find_method() resolves by name.

name: str
methods: tuple[MethodSignature, ...] = ()
find_method(method_name)[source]
__init__(name, methods=())
class agora.plan.structure.ContractModel[source]

Bases: object

L1: everything api_spec declares. Frozen — deterministic from text.

modules: tuple[ModuleModel, ...] = ()
all_class_names()[source]
find_class(class_name)[source]
__init__(modules=())
class agora.plan.structure.ImplClassModel[source]

Bases: object

What a class in src/*.py actually exposes, derived from AST.

Used by check_impl_self_consistent() to detect bugs like “__init__ sets self.url_mapping but add_url reads self.url_hash_map” — a typo that pytest only catches at runtime on first method call.

name: str
method_names: tuple[str, ...] = ()
attrs_set: tuple[str, ...] = ()
attrs_read: tuple[str, ...] = ()
__init__(name, method_names=(), attrs_set=(), attrs_read=())
class agora.plan.structure.MethodSignature[source]

Bases: object

One function/method signature as a comparable value (name, typed params excluding self, return type). Equality drives cross-layer drift detection, so params carry TypeRef rather than raw strings — an unresolved type compares as unknown instead of falsely differing.

name: str
params: tuple[tuple[str, TypeRef], ...] = ()
return_type: TypeRef
has_self: bool = True
__init__(name, params=(), return_type=<factory>, has_self=True)
class agora.plan.structure.Mode[source]

Bases: str, Enum

Drift-report strictness. PERMISSIVE reports only certain violations (both sides resolved to concrete, differing types); STRICT also reports unresolved ones (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: object

A 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.

path: str
classes: tuple[ClassModel, ...] = ()
functions: tuple[MethodSignature, ...] = ()
find_class(class_name)[source]
__init__(path, classes=(), functions=())
class agora.plan.structure.TypeKind[source]

Bases: str, Enum

What category of type a TypeRef represents.

Kept deliberately coarse — this module is not mypy. Anything the parser can’t categorise becomes UNKNOWN and 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: object

A parsed representation of a type annotation.

Only the fields relevant to kind are populated:

  • PRIMITIVE: name ("str", "int", "bool", "float")

  • LIST: params=(element_type,)

  • TUPLE: params=(t0, t1, ...) with optional trailing Ellipsis marker via tuple_variadic

  • DICT: params=(key_type, value_type)

  • CLASS: name = declared class name

  • OPTIONAL / UNION: params=(t0, t1, ...)

  • NONE / ANY / UNKNOWN: no additional info

kind: TypeKind
name: str = ''
params: tuple[TypeRef, ...] = ()
tuple_variadic: bool = False
classmethod primitive(name)[source]
classmethod cls_ref(name)[source]
classmethod none()[source]
classmethod unknown(hint='')[source]
classmethod any_()[source]
describe()[source]

Short human-readable form for error messages.

__init__(kind, name='', params=(), tuple_variadic=False)
class agora.plan.structure.UsageTrace[source]

Bases: object

A 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_name and body_line help error messages point at the offending test function + line within the body.

consumed_call_ids holds the id(ast.Call) values of inner Call nodes that contributed to this trace’s step chain (via obj.method1().method2()). The extractor uses it to avoid emitting duplicate standalone traces for the inner calls.

test_name: str
class_name: str
method_name: str
steps: tuple[AccessStep, ...] = ()
body_line: int = 0
consumed_call_ids: frozenset[int]
__init__(test_name, class_name, method_name, steps=(), body_line=0, consumed_call_ids=<factory>)
class agora.plan.structure.Violation[source]

Bases: object

A cross-layer drift the comparator detected.

severity controls whether permissive mode surfaces this. path is a human-oriented breadcrumb (e.g. "test_foo → URLShortener.bar() → [0] → ['key']") so the error message points precisely at the offending chain.

path: str
message: str
severity: Literal['certain', 'unresolved'] = 'certain'
__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 from attrs_read evaluation — calling self.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_spec output 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 a MethodSignature with typed params + return.

agora.plan.structure.extract_impl_classes(source)[source]

Parse impl source; return an ImplClassModel per class.

For each class:
  • method_names = every def foo at class body level

  • attrs_set = every self.X = ... (or aug-assignment) across all methods

  • attrs_read = every self.X read 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.

agora.plan.structure.filter_by_mode(violations, mode)[source]

Filter a violation list by report Mode: STRICT returns all, PERMISSIVE keeps only certain ones. Pure; does not reorder.