Skip to content

cogant.reverse

The cogant.reverse package is the inverse of the forward translate pipeline: it parses GNN markdown, plans a synthesis target, and either emits a runnable Python package (synthesize_package) or binds runtime-callable closures (MatrixFunctions) directly.

Package

cogant.reverse

COGANT reverse synthesis engine — GNN markdown → Python package.

The :mod:cogant.reverse package implements the reverse direction of the COGANT pipeline. Where the forward direction consumes a source tree and emits a Generalized Notation for Networks (GNN) Active Inference model, the reverse direction consumes a GNN markdown file and synthesizes a runnable Python package whose structure mirrors the GNN topology.

Roundtrip contract

The round-trip cannot reproduce the original source code verbatim — GNN is a lossy semantic projection that discards implementation details, argument names, control-flow, docstrings, and anything that is not a hidden-state, observation, action, policy, or constraint role.

The public verifier reports a roundtrip_status enum plus an invariant ledger. ROLE_PRESERVED means the semantic role multiset survived above the configured role_preservation_score threshold. The stricter STRUCTURALLY_ISOMORPHIC status is reserved for runs that also preserve graph counts, edge kinds, state-space shapes, matrix shapes/values, GNN sections, generated-code compile status, and the second forward pass.

Concrete node IDs and edge weights are not expected to survive unless the strict invariant tier says they did.

Public API

  • :class:ReverseGNNModel — parsed representation of a GNN markdown file.
  • :func:parse_gnn — parse a GNN markdown file into a ReverseGNNModel.
  • :class:PackagePlan — mapping plan from GNN roles to Python package files.
  • :func:plan_package — construct a PackagePlan from a ReverseGNNModel.
  • :func:synthesize_package — emit Python source files from a PackagePlan.
  • :func:verify_roundtrip — round-trip idempotency verifier.

ROLE_PRESERVATION_THRESHOLD = 0.5 module-attribute

Default minimum role-preservation score for the weaker success tier.

DEFAULT_ISOMORPHISM_THRESHOLD = 0.7 module-attribute

Default cutoff for :attr:IsomorphismReport.structurally_isomorphic.

MatrixFunctions

Copied source matrices with categorical filtering and policy operations.

Source code in py/cogant/reverse/callable.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class MatrixFunctions:
    """Copied source matrices with categorical filtering and policy operations."""

    def __init__(self, model: ReverseGNNModel) -> None:
        _validate_matrix_semantics(model)
        n_states = model.n_states
        n_obs = model.n_obs
        n_actions = model.n_actions

        A = [list(row) for row in model.A]
        B = [[list(cell) for cell in row] for row in model.B]
        C = list(model.C)
        D = list(model.D)

        self._A = A
        self._B = B
        self._C = C
        self._D = D
        self._n_states = n_states
        self._n_obs = n_obs
        self._n_actions = n_actions

        self.A = A
        self.B = B
        self.C = C
        self.D = D

    def _categorical(self) -> CategoricalModel:
        return CategoricalModel(self.A, self.B, self.C, self.D)

    def likelihood(self, state_dist: list[float]) -> list[float]:
        return self._categorical().observe(state_dist)

    def transition(self, state_dist: list[float], action: int = 0) -> list[float]:
        return self._categorical().predict(state_dist, action)

    def preference_score(self, obs_dist: list[float]) -> float:
        return self._categorical().preference_score(obs_dist)

    def prior(self) -> list[float]:
        """Return D vector (initial state prior)."""
        return list(self._D)

    def expected_free_energy(self, state_dist: list[float], action: int) -> float:
        """Evaluate one-step outcome risk plus expected likelihood ambiguity."""
        return self._categorical().score(state_dist, [action])

    def score_preference_gradient(self, state_dist: list[float], policy: list[int]) -> list[float]:
        """Return fixed-policy score sensitivity along the C observation axis."""
        return self._categorical().score_preference_gradient(state_dist, policy)

    def best_action(self, state_dist: list[float]) -> int:
        """Return argmin EFE over the declared action axis."""
        if self._n_actions == 0:
            raise ValueError("policy selection requires at least one action")
        best_a = 0
        best_efe = float("inf")
        for a in range(self._n_actions):
            efe = self.expected_free_energy(state_dist, a)
            if efe < best_efe:
                best_efe = efe
                best_a = a
        return best_a

    @classmethod
    def from_gnn_text(cls, gnn_text: str) -> MatrixFunctions:
        model = parse_gnn(gnn_text)
        return cls(model)

prior()

Return D vector (initial state prior).

Source code in py/cogant/reverse/callable.py
49
50
51
def prior(self) -> list[float]:
    """Return D vector (initial state prior)."""
    return list(self._D)

expected_free_energy(state_dist, action)

Evaluate one-step outcome risk plus expected likelihood ambiguity.

Source code in py/cogant/reverse/callable.py
53
54
55
def expected_free_energy(self, state_dist: list[float], action: int) -> float:
    """Evaluate one-step outcome risk plus expected likelihood ambiguity."""
    return self._categorical().score(state_dist, [action])

score_preference_gradient(state_dist, policy)

Return fixed-policy score sensitivity along the C observation axis.

Source code in py/cogant/reverse/callable.py
57
58
59
def score_preference_gradient(self, state_dist: list[float], policy: list[int]) -> list[float]:
    """Return fixed-policy score sensitivity along the C observation axis."""
    return self._categorical().score_preference_gradient(state_dist, policy)

best_action(state_dist)

Return argmin EFE over the declared action axis.

Source code in py/cogant/reverse/callable.py
61
62
63
64
65
66
67
68
69
70
71
72
def best_action(self, state_dist: list[float]) -> int:
    """Return argmin EFE over the declared action axis."""
    if self._n_actions == 0:
        raise ValueError("policy selection requires at least one action")
    best_a = 0
    best_efe = float("inf")
    for a in range(self._n_actions):
        efe = self.expected_free_energy(state_dist, a)
        if efe < best_efe:
            best_efe = efe
            best_a = a
    return best_a

RoundtripResult dataclass

Outcome of a single round-trip verification run.

Attributes:

Name Type Description
roundtrip_status str

One of ROUNDTRIP_STATUSES.

role_preservation_score float

Per-role mean of min(original_count, synthesized_count) / max(original_count, synthesized_count) over the union of original and synthesized role multisets. Range [0.0, 1.0].

role_preserved bool

True when role_preservation_score meets the configured threshold.

structurally_isomorphic bool

True only when the full strict invariant ledger passes.

matrix_preserved bool

True when observed A/B/C/D shapes and values are preserved within tolerance.

gnn_sections_preserved bool

True when Markdown section membership survives the round-trip exactly.

generated_code_ok bool

True when synthesized Python files import through py_compile.

vacuous_roundtrip bool

True when both role multisets are empty and the role-preservation score's 1.0 value is vacuous.

matrix_score float

Frobenius-based similarity of the A/B/C/D matrix stacks produced by the two sides of the round-trip. Range [0.0, 1.0]. Defaults to 0.0 when matrices were not available on either side of the comparison.

structural_score float

Graph-structure similarity (node/edge role multiset symmetric difference, normalized and inverted). Range [0.0, 1.0]. Defaults to 0.0 when the round-trip did not expose a node/edge view.

original_roles dict[str, int]

Role multiset derived from the source GNN ({role_name: count}).

synthesized_roles dict[str, int]

Role multiset from the forward pipeline's semantic mappings after reverse-synthesis, restricted to the role-bearing definitions named in the package's semantic-target manifest (generated runtime support code is not scored).

shape_match dict[str, bool]

Dict describing whether n_states, n_obs, and n_actions dimensions survived the round-trip.

package_path: Absolute path to the synthesized package (kept on disk if the caller passed a persistent tmp_dir). original_graph_summary: Node/edge/kind summary for the first graph view in the comparison. synthesized_graph_summary: Node/edge/kind summary for the graph produced by the forward re-run. graph_delta: Count and kind deltas between the graph summaries. gnn_diff: Section-level diff between original and regenerated GNN Markdown when both sides are available. matrix_delta: Shape/value deltas for A/B/C/D matrices when parseable GNN matrix blocks are available. invariants: Explicit pass/fail invariants for the code → graph → GNN → code → graph cycle. rule_evidence_trace: Rule/mapping evidence artifact from the synthesized forward pass, suitable for dashboard review. warnings: Non-fatal diagnostic warnings collected during the round-trip that do not affect status. errors: Non-fatal errors collected during the round-trip.

Source code in py/cogant/reverse/idempotency.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
@dataclass(init=False)
class RoundtripResult:
    """Outcome of a single round-trip verification run.

    Attributes:
        roundtrip_status: One of ``ROUNDTRIP_STATUSES``.
        role_preservation_score: Per-role mean of
            ``min(original_count, synthesized_count) /
            max(original_count, synthesized_count)`` over the union of
            original and synthesized role multisets. Range ``[0.0, 1.0]``.
        role_preserved: True when ``role_preservation_score`` meets
            the configured threshold.
        structurally_isomorphic: True only when the full strict
            invariant ledger passes.
        matrix_preserved: True when observed A/B/C/D shapes and values
            are preserved within tolerance.
        gnn_sections_preserved: True when Markdown section membership
            survives the round-trip exactly.
        generated_code_ok: True when synthesized Python files import
            through ``py_compile``.
        vacuous_roundtrip: True when both role multisets are empty and
            the role-preservation score's 1.0 value is vacuous.
        matrix_score: Frobenius-based similarity of the A/B/C/D
            matrix stacks produced by the two sides of the round-trip.
            Range ``[0.0, 1.0]``. Defaults to ``0.0`` when matrices
            were not available on either side of the comparison.
        structural_score: Graph-structure similarity (node/edge role
            multiset symmetric difference, normalized and inverted).
            Range ``[0.0, 1.0]``. Defaults to ``0.0`` when the
            round-trip did not expose a node/edge view.
        original_roles: Role multiset derived from the source GNN
            (``{role_name: count}``).
        synthesized_roles: Role multiset from the forward pipeline's
            semantic mappings after reverse-synthesis, restricted to the
            role-bearing definitions named in the package's semantic-target
            manifest (generated runtime support code is not scored).
        shape_match: Dict describing whether n_states, n_obs, and
            n_actions dimensions survived the round-trip.
    package_path: Absolute path to the synthesized package (kept
            on disk if the caller passed a persistent ``tmp_dir``).
        original_graph_summary: Node/edge/kind summary for the first
            graph view in the comparison.
        synthesized_graph_summary: Node/edge/kind summary for the
            graph produced by the forward re-run.
        graph_delta: Count and kind deltas between the graph summaries.
        gnn_diff: Section-level diff between original and regenerated
            GNN Markdown when both sides are available.
        matrix_delta: Shape/value deltas for A/B/C/D matrices when
            parseable GNN matrix blocks are available.
        invariants: Explicit pass/fail invariants for the
            code → graph → GNN → code → graph cycle.
        rule_evidence_trace: Rule/mapping evidence artifact from the
            synthesized forward pass, suitable for dashboard review.
        warnings: Non-fatal diagnostic warnings collected during the
            round-trip that do not affect status.
        errors: Non-fatal errors collected during the round-trip.
    """

    roundtrip_status: str
    role_preservation_score: float
    role_preserved: bool
    structurally_isomorphic: bool
    matrix_preserved: bool
    gnn_sections_preserved: bool
    generated_code_ok: bool
    vacuous_roundtrip: bool
    matrix_score: float = 0.0
    structural_score: float = 0.0
    original_roles: dict[str, int]
    synthesized_roles: dict[str, int]
    shape_match: dict[str, bool]
    package_path: Path | None = None
    original_graph_summary: dict[str, Any]
    synthesized_graph_summary: dict[str, Any]
    graph_delta: dict[str, Any]
    gnn_diff: dict[str, Any]
    matrix_delta: dict[str, Any]
    invariants: dict[str, Any]
    rule_evidence_trace: dict[str, Any]
    warnings: list[str]
    errors: list[str]

    def __init__(
        self,
        *,
        roundtrip_status: str | None = None,
        role_preservation_score: float = 0.0,
        role_preserved: bool | None = None,
        structurally_isomorphic: bool | None = None,
        matrix_preserved: bool | None = None,
        gnn_sections_preserved: bool | None = None,
        generated_code_ok: bool | None = None,
        vacuous_roundtrip: bool | None = None,
        matrix_score: float = 0.0,
        structural_score: float = 0.0,
        original_roles: dict[str, int] | None = None,
        synthesized_roles: dict[str, int] | None = None,
        shape_match: dict[str, bool] | None = None,
        package_path: Path | None = None,
        original_graph_summary: dict[str, Any] | None = None,
        synthesized_graph_summary: dict[str, Any] | None = None,
        graph_delta: dict[str, Any] | None = None,
        gnn_diff: dict[str, Any] | None = None,
        matrix_delta: dict[str, Any] | None = None,
        invariants: dict[str, Any] | None = None,
        rule_evidence_trace: dict[str, Any] | None = None,
        warnings: list[str] | None = None,
        errors: list[str] | None = None,
    ) -> None:
        self.role_preservation_score = float(role_preservation_score)
        if role_preserved is None:
            role_preserved = self.role_preservation_score >= ROLE_PRESERVATION_THRESHOLD
        self.role_preserved = bool(role_preserved)

        self.invariants = dict(invariants or {})
        if matrix_preserved is None:
            matrix_preserved = bool(self.invariants.get("matrix_preserved", False))
        if gnn_sections_preserved is None:
            gnn_sections_preserved = bool(self.invariants.get("gnn_sections_preserved", False))
        if generated_code_ok is None:
            generated_code_ok = bool(self.invariants.get("generated_code_ok", False))
        if structurally_isomorphic is None:
            structurally_isomorphic = _strict_invariants_preserved(
                role_preserved=self.role_preserved,
                matrix_preserved=bool(matrix_preserved),
                gnn_sections_preserved=bool(gnn_sections_preserved),
                generated_code_ok=bool(generated_code_ok),
                invariants=self.invariants,
            )

        self.matrix_preserved = bool(matrix_preserved)
        self.gnn_sections_preserved = bool(gnn_sections_preserved)
        self.generated_code_ok = bool(generated_code_ok)
        self.vacuous_roundtrip = bool(vacuous_roundtrip)
        self.structurally_isomorphic = bool(structurally_isomorphic)
        self.roundtrip_status = roundtrip_status or _roundtrip_status_from_invariants(
            role_preserved=self.role_preserved,
            structurally_isomorphic=self.structurally_isomorphic,
            errors=errors or [],
        )
        if self.roundtrip_status not in ROUNDTRIP_STATUSES:
            self.roundtrip_status = ROUNDTRIP_STATUS_FAILED

        self.matrix_score = float(matrix_score)
        self.structural_score = float(structural_score)
        self.original_roles = dict(original_roles or {})
        self.synthesized_roles = dict(synthesized_roles or {})
        self.shape_match = dict(shape_match or {})
        self.package_path = package_path
        self.original_graph_summary = dict(original_graph_summary or {})
        self.synthesized_graph_summary = dict(synthesized_graph_summary or {})
        self.graph_delta = dict(graph_delta or {})
        self.gnn_diff = dict(gnn_diff or {})
        self.matrix_delta = dict(matrix_delta or {})
        self.rule_evidence_trace = dict(rule_evidence_trace or {})
        self.warnings = list(warnings or [])
        self.errors = list(errors or [])

    def summary(self) -> str:
        """Return a human-readable single-line summary of the result."""
        return (
            f"[{self.roundtrip_status}] role_preservation={self.role_preservation_score:.2%} "
            f"matrix={self.matrix_score:.2f} "
            f"struct={self.structural_score:.2f} "
            f"orig={dict(self.original_roles)} "
            f"synth={dict(self.synthesized_roles)}"
        )

summary()

Return a human-readable single-line summary of the result.

Source code in py/cogant/reverse/idempotency.py
273
274
275
276
277
278
279
280
281
def summary(self) -> str:
    """Return a human-readable single-line summary of the result."""
    return (
        f"[{self.roundtrip_status}] role_preservation={self.role_preservation_score:.2%} "
        f"matrix={self.matrix_score:.2f} "
        f"struct={self.structural_score:.2f} "
        f"orig={dict(self.original_roles)} "
        f"synth={dict(self.synthesized_roles)}"
    )

IsomorphismReport dataclass

Aggregate GNN-to-GNN distance report.

All *_score fields are in [0.0, 1.0] where 1.0 means "identical" and 0.0 means "maximally different under this metric". The total_score is the weighted mean of the three component scores and is itself in [0.0, 1.0]. structurally_isomorphic is simply total_score >= threshold.

Attributes:

Name Type Description
structural_score float

Graph-structure similarity in [0, 1].

role_score float

Role distribution similarity (inverted JS divergence) in [0, 1].

matrix_score float

Frobenius-based matrix similarity in [0, 1].

total_score float

Weighted mean 0.4 * role + 0.4 * matrix + 0.2 * structural.

structurally_isomorphic bool

True when total_score >= threshold.

breakdown dict[str, Any]

Per-metric diagnostic detail. Keys include the three component scores, the threshold, the weighting, and (when available) per-matrix Frobenius distances.

Source code in py/cogant/reverse/metrics.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
@dataclass
class IsomorphismReport:
    """Aggregate GNN-to-GNN distance report.

    All ``*_score`` fields are in ``[0.0, 1.0]`` where ``1.0`` means
    "identical" and ``0.0`` means "maximally different under this
    metric". The ``total_score`` is the weighted mean of the three
    component scores and is itself in ``[0.0, 1.0]``. ``structurally_isomorphic``
    is simply ``total_score >= threshold``.

    Attributes:
        structural_score: Graph-structure similarity in ``[0, 1]``.
        role_score: Role distribution similarity (inverted JS
            divergence) in ``[0, 1]``.
        matrix_score: Frobenius-based matrix similarity in ``[0, 1]``.
        total_score: Weighted mean
            ``0.4 * role + 0.4 * matrix + 0.2 * structural``.
        structurally_isomorphic: True when ``total_score >= threshold``.
        breakdown: Per-metric diagnostic detail. Keys include the
            three component scores, the threshold, the weighting, and
            (when available) per-matrix Frobenius distances.
    """

    structural_score: float = 0.0
    role_score: float = 0.0
    matrix_score: float = 0.0
    total_score: float = 0.0
    structurally_isomorphic: bool = False
    breakdown: dict[str, Any] = field(default_factory=dict)

    def summary(self) -> str:
        """Return a compact, human-readable one-line summary.

        The format is::

            [ISO] total=0.82 role=0.90 matrix=0.85 struct=0.60

        with ``ISO`` swapped for ``DRIFT`` when
        ``structurally_isomorphic`` is False.
        """
        status = "ISO" if self.structurally_isomorphic else "DRIFT"
        return (
            f"[{status}] total={self.total_score:.2f} "
            f"role={self.role_score:.2f} "
            f"matrix={self.matrix_score:.2f} "
            f"struct={self.structural_score:.2f}"
        )

summary()

Return a compact, human-readable one-line summary.

The format is::

[ISO] total=0.82 role=0.90 matrix=0.85 struct=0.60

with ISO swapped for DRIFT when structurally_isomorphic is False.

Source code in py/cogant/reverse/metrics.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def summary(self) -> str:
    """Return a compact, human-readable one-line summary.

    The format is::

        [ISO] total=0.82 role=0.90 matrix=0.85 struct=0.60

    with ``ISO`` swapped for ``DRIFT`` when
    ``structurally_isomorphic`` is False.
    """
    status = "ISO" if self.structurally_isomorphic else "DRIFT"
    return (
        f"[{status}] total={self.total_score:.2f} "
        f"role={self.role_score:.2f} "
        f"matrix={self.matrix_score:.2f} "
        f"struct={self.structural_score:.2f}"
    )

ReverseGNNModel dataclass

Parsed GNN model ready for planning and synthesis.

Attributes:

Name Type Description
model_name str

The ## ModelName value (sanitized upstream identifier, safe for use as a Python package name).

raw_model_name str

The unsanitized ## ModelName value as it appears in the markdown (may contain non-identifier chars).

hidden_states list[str]

Names of hidden-state factors (s_f0, s_f1, ... in COGANT bundles; s or any HiddenState-annotated name upstream). Each entry is the source variable name.

observations list[str]

Names of observation modalities (o_m0, o_m1, ... / o).

actions list[str]

Names of action/control factors (u_c0, u_c1, ... / u).

policies list[str]

Names of policy variables (rare; usually empty).

constraints list[str]

Names of constraint/preference variables.

annotations dict[str, str]

Map from variable name → ontology concept ("s_f0" -> "HiddenState", "A_m0" -> "LikelihoodMatrix", etc). Populated from ## ActInfOntologyAnnotation and the extended ## State Space section.

cardinalities dict[str, int]

Map from variable name → categorical dimension (from ## StateSpaceBlock like s_f0[10,1,type=int]).

types dict[str, str]

Map from variable name → upstream type string (int, float, bool).

A list[list[float]]

Likelihood matrix P(o | s) of shape [n_obs x n_states]. Populated from ## InitialParameterization or from the bracket-style A matrix header in the GNN file if present. May be empty when the model has no observations.

B list[list[list[float]]]

Transition tensor P(s' | s, a) of shape [n_states x n_states x n_actions]. May be empty.

C list[float]

Log-preference vector over observations of shape [n_obs].

D list[float]

Prior distribution over hidden states of shape [n_states].

connections list[str]

Raw list of arrow-syntax connection strings from ## Connections (used for debugging and topology checks).

human_names dict[str, str]

Map from s_f0-style slot to the human-readable name pulled from ## State Space → ### State Variables. Used by the planner to produce meaningful Python identifiers.

Source code in py/cogant/reverse/parser.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
@dataclass
class ReverseGNNModel:
    """Parsed GNN model ready for planning and synthesis.

    Attributes:
        model_name: The ``## ModelName`` value (sanitized upstream
            identifier, safe for use as a Python package name).
        raw_model_name: The unsanitized ``## ModelName`` value as it
            appears in the markdown (may contain non-identifier chars).
        hidden_states: Names of hidden-state factors (``s_f0``, ``s_f1``,
            ... in COGANT bundles; ``s`` or any ``HiddenState``-annotated
            name upstream). Each entry is the source variable name.
        observations: Names of observation modalities
            (``o_m0``, ``o_m1``, ... / ``o``).
        actions: Names of action/control factors (``u_c0``, ``u_c1``, ... /
            ``u``).
        policies: Names of policy variables (rare; usually empty).
        constraints: Names of constraint/preference variables.
        annotations: Map from variable name → ontology concept
            (``"s_f0" -> "HiddenState"``, ``"A_m0" -> "LikelihoodMatrix"``,
            etc). Populated from ``## ActInfOntologyAnnotation`` and the
            extended ``## State Space`` section.
        cardinalities: Map from variable name → categorical dimension
            (from ``## StateSpaceBlock`` like ``s_f0[10,1,type=int]``).
        types: Map from variable name → upstream type string
            (``int``, ``float``, ``bool``).
        A: Likelihood matrix ``P(o | s)`` of shape ``[n_obs x n_states]``.
            Populated from ``## InitialParameterization`` or from the
            bracket-style ``A`` matrix header in the GNN file if present.
            May be empty when the model has no observations.
        B: Transition tensor ``P(s' | s, a)`` of shape
            ``[n_states x n_states x n_actions]``. May be empty.
        C: Log-preference vector over observations of shape ``[n_obs]``.
        D: Prior distribution over hidden states of shape ``[n_states]``.
        connections: Raw list of arrow-syntax connection strings from
            ``## Connections`` (used for debugging and topology checks).
        human_names: Map from ``s_f0``-style slot to the human-readable
            name pulled from ``## State Space`` → ``### State Variables``.
            Used by the planner to produce meaningful Python identifiers.
    """

    model_name: str = "cogant_model"
    raw_model_name: str = "cogant_model"
    hidden_states: list[str] = field(default_factory=list)
    observations: list[str] = field(default_factory=list)
    actions: list[str] = field(default_factory=list)
    policies: list[str] = field(default_factory=list)
    constraints: list[str] = field(default_factory=list)
    annotations: dict[str, str] = field(default_factory=dict)
    cardinalities: dict[str, int] = field(default_factory=dict)
    types: dict[str, str] = field(default_factory=dict)
    A: list[list[float]] = field(default_factory=list)
    B: list[list[list[float]]] = field(default_factory=list)
    C: list[float] = field(default_factory=list)
    D: list[float] = field(default_factory=list)
    connections: list[str] = field(default_factory=list)
    human_names: dict[str, str] = field(default_factory=dict)
    degraded: bool = False
    diagnostics: list[str] = field(default_factory=list)
    matrix_source: Literal["parameterization", "fenced"] = "parameterization"

    @property
    def n_hidden_factors(self) -> int:
        """Number of named hidden-state factors in the source ontology."""
        return len(self.hidden_states)

    @property
    def n_states(self) -> int:
        """Number of hidden dimensions represented by this model.

        Matrix dimensions are authoritative when present.  Before matrices
        are parsed, retain the declared factor count so callers can inspect
        a syntactically valid but not-yet-executable model.
        """
        if self.matrix_source == "fenced":
            return len(self.D)
        if self.D:
            return len(self.D)
        if self.B:
            return len(self.B)
        return len(self.hidden_states)

    @property
    def n_obs(self) -> int:
        """Number of observation dimensions represented by this model."""
        if self.matrix_source == "fenced":
            return len(self.C)
        if self.C:
            return len(self.C)
        if self.A:
            return len(self.A)
        return len(self.observations)

    @property
    def n_actions(self) -> int:
        """Number of action dimensions represented by this model."""
        if self.B and self.B[0] and self.B[0][0]:
            return len(self.B[0][0])
        return len(self.actions)

    def validate(self) -> list[str]:
        """Return evidence and dimension errors without inventing values."""
        errors: list[str] = []
        if self.hidden_states and not self.D:
            errors.append("D is required when hidden-state variables are declared")
        if self.observations and not self.C:
            errors.append("C is required when observation variables are declared")
        # B is indexed by hidden state, so it only exists when both hidden
        # states and actions are declared.  A stateless model whose callables
        # are ACTION roles has no transition tensor (the GNN validator
        # requires B to be empty when there are no hidden states).
        if self.hidden_states and self.actions and not self.B:
            errors.append("B is required when hidden-state and action variables are declared")
        if self.D and any(value < 0 for value in self.D):
            errors.append("D contains a negative probability")
        return errors

n_hidden_factors property

Number of named hidden-state factors in the source ontology.

n_states property

Number of hidden dimensions represented by this model.

Matrix dimensions are authoritative when present. Before matrices are parsed, retain the declared factor count so callers can inspect a syntactically valid but not-yet-executable model.

n_obs property

Number of observation dimensions represented by this model.

n_actions property

Number of action dimensions represented by this model.

validate()

Return evidence and dimension errors without inventing values.

Source code in py/cogant/reverse/parser.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def validate(self) -> list[str]:
    """Return evidence and dimension errors without inventing values."""
    errors: list[str] = []
    if self.hidden_states and not self.D:
        errors.append("D is required when hidden-state variables are declared")
    if self.observations and not self.C:
        errors.append("C is required when observation variables are declared")
    # B is indexed by hidden state, so it only exists when both hidden
    # states and actions are declared.  A stateless model whose callables
    # are ACTION roles has no transition tensor (the GNN validator
    # requires B to be empty when there are no hidden states).
    if self.hidden_states and self.actions and not self.B:
        errors.append("B is required when hidden-state and action variables are declared")
    if self.D and any(value < 0 for value in self.D):
        errors.append("D contains a negative probability")
    return errors

NodePlan dataclass

Plan for a single GNN node → Python construct.

Attributes:

Name Type Description
slot str

The GNN slot identifier (s_f0, o_m1, u_c2).

name str

The Python identifier to emit (derived from the human name when available, else the slot name).

role str

The MappingKind label (e.g. HIDDEN_STATE, OBSERVATION, ACTION, POLICY, CONSTRAINT).

python_type str

The Python type annotation string (float, int, bool, etc.).

module str

The module file this node is emitted into (state.py, observe.py, act.py, ...).

cardinality int

Categorical cardinality from the GNN declaration, or 0 if unknown. Used for default values and type hints.

initial_value str

Source-level literal for the initial value ("0.0", "False", "0").

Source code in py/cogant/reverse/planner.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
@dataclass
class NodePlan:
    """Plan for a single GNN node → Python construct.

    Attributes:
        slot: The GNN slot identifier (``s_f0``, ``o_m1``, ``u_c2``).
        name: The Python identifier to emit (derived from the human
            name when available, else the slot name).
        role: The MappingKind label (e.g. ``HIDDEN_STATE``, ``OBSERVATION``,
            ``ACTION``, ``POLICY``, ``CONSTRAINT``).
        python_type: The Python type annotation string (``float``,
            ``int``, ``bool``, etc.).
        module: The module file this node is emitted into
            (``state.py``, ``observe.py``, ``act.py``, ...).
        cardinality: Categorical cardinality from the GNN declaration,
            or 0 if unknown. Used for default values and type hints.
        initial_value: Source-level literal for the initial value
            (``"0.0"``, ``"False"``, ``"0"``).
    """

    slot: str = ""
    name: str = ""
    role: str = ""
    python_type: str = "float"
    module: str = ""
    cardinality: int = 0
    initial_value: str = "0.0"

PackagePlan dataclass

Full synthesis plan for a GNN → Python package.

Attributes:

Name Type Description
package_name str

Sanitized Python package name (derived from the GNN ## ModelName value).

raw_model_name str

Original unsanitized model name for docstrings.

nodes list[NodePlan]

All node plans in declaration order.

state_vars list[NodePlan]

Subset of nodes with role HIDDEN_STATE. Emitted as attributes on the State dataclass.

obs_functions list[NodePlan]

Subset with role OBSERVATION.

action_methods list[NodePlan]

Subset with role ACTION.

policy_functions list[NodePlan]

Subset with role POLICY (authoritative policies declared in the GNN). These are rare — most GNNs have no explicit pi_c* declarations — and the reverse pipeline additionally synthesizes scaffolding policies (see scaffold_policy_functions).

constraint_checks list[NodePlan]

Subset with role CONSTRAINT / PREFERENCE (authoritative constraints declared in the GNN, typically one per C_m*=PreferenceVector annotation).

context_functions list[NodePlan]

Subset with role CONTEXT derived from the parsed GNN (rare; populated when the ontology block annotates a variable as Context or Time).

target_role_counts dict[str, int]

Expected semantic role multiset for the synthesized package. Round-trip verification passes the source roles here so generated scaffolds are deficit-based rather than fixed boilerplate.

scaffold_constraint_checks list[NodePlan]

Additional check_* functions emitted only when target_role_counts requires more CONSTRAINT roles than the parsed GNN declares.

scaffold_policy_functions list[NodePlan]

Additional top-level POLICY scaffolds emitted only when target POLICY roles remain after authoritative policy functions and the optional policy selector helper.

scaffold_context_classes list[NodePlan]

Additional top-level CONTEXT classes emitted only when source roles include CONTEXT deficits.

has_A_matrix bool

True if the parsed A matrix has non-zero rows.

has_B_tensor bool

True if the parsed B tensor is non-trivial.

has_C_vector bool

True if the parsed C vector is non-empty.

has_D_vector bool

True if the parsed D vector is non-empty.

Source code in py/cogant/reverse/planner.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
@dataclass
class PackagePlan:
    """Full synthesis plan for a GNN → Python package.

    Attributes:
        package_name: Sanitized Python package name (derived from the
            GNN ``## ModelName`` value).
        raw_model_name: Original unsanitized model name for docstrings.
        nodes: All node plans in declaration order.
        state_vars: Subset of ``nodes`` with role ``HIDDEN_STATE``.
            Emitted as attributes on the ``State`` dataclass.
        obs_functions: Subset with role ``OBSERVATION``.
        action_methods: Subset with role ``ACTION``.
        policy_functions: Subset with role ``POLICY`` (authoritative
            policies declared in the GNN). These are rare — most GNNs
            have no explicit ``pi_c*`` declarations — and the reverse
            pipeline additionally synthesizes scaffolding policies (see
            ``scaffold_policy_functions``).
        constraint_checks: Subset with role ``CONSTRAINT`` / ``PREFERENCE``
            (authoritative constraints declared in the GNN, typically
            one per ``C_m*=PreferenceVector`` annotation).
        context_functions: Subset with role ``CONTEXT`` derived from
            the parsed GNN (rare; populated when the ontology block
            annotates a variable as ``Context`` or ``Time``).
        target_role_counts: Expected semantic role multiset for the
            synthesized package. Round-trip verification passes the
            source roles here so generated scaffolds are deficit-based
            rather than fixed boilerplate.
        scaffold_constraint_checks: Additional ``check_*`` functions
            emitted only when ``target_role_counts`` requires more
            CONSTRAINT roles than the parsed GNN declares.
        scaffold_policy_functions: Additional top-level POLICY scaffolds
            emitted only when target POLICY roles remain after
            authoritative policy functions and the optional policy
            selector helper.
        scaffold_context_classes: Additional top-level CONTEXT classes
            emitted only when source roles include CONTEXT deficits.
        has_A_matrix: True if the parsed A matrix has non-zero rows.
        has_B_tensor: True if the parsed B tensor is non-trivial.
        has_C_vector: True if the parsed C vector is non-empty.
        has_D_vector: True if the parsed D vector is non-empty.
    """

    package_name: str = "cogant_model"
    raw_model_name: str = "cogant_model"
    nodes: list[NodePlan] = field(default_factory=list)
    state_vars: list[NodePlan] = field(default_factory=list)
    obs_functions: list[NodePlan] = field(default_factory=list)
    action_methods: list[NodePlan] = field(default_factory=list)
    policy_functions: list[NodePlan] = field(default_factory=list)
    constraint_checks: list[NodePlan] = field(default_factory=list)
    context_functions: list[NodePlan] = field(default_factory=list)
    target_role_counts: dict[str, int] = field(default_factory=dict)
    scaffold_constraint_checks: list[NodePlan] = field(default_factory=list)
    scaffold_policy_functions: list[NodePlan] = field(default_factory=list)
    scaffold_context_classes: list[NodePlan] = field(default_factory=list)
    has_A_matrix: bool = False
    has_B_tensor: bool = False
    has_C_vector: bool = False
    has_D_vector: bool = False
    state_dimension: int = 0
    observation_dimension: int = 0
    action_dimension: int = 0

    def validate(self) -> list[str]:
        """Validate the package plan for structural consistency.

        Checks that the plan is internally coherent and can be synthesized.
        Does not validate the plan against external sources (e.g., the
        original GNN).

        Returns:
            A list of validation issues. Empty list means the plan is valid.
            Issues describe problems but do not necessarily prevent synthesis
            from succeeding.
        """
        issues: list[str] = []

        # Check: no duplicate names across all roles
        all_names = [n.name for n in self.nodes]
        seen: dict[str, int] = {}
        for name in all_names:
            seen[name] = seen.get(name, 0) + 1
        duplicates = [name for name, count in seen.items() if count > 1]
        if duplicates:
            issues.append(f"Duplicate node names found: {duplicates}")

        # Check: each node's role is recognized
        valid_roles = {
            "HIDDEN_STATE",
            "OBSERVATION",
            "ACTION",
            "POLICY",
            "CONSTRAINT",
            "CONTEXT",
        }
        for node in self.nodes:
            if node.role not in valid_roles:
                issues.append(f"Node {node.name!r} has unrecognized role {node.role!r}")

        # Check: nodes in subsets appear in main nodes list
        all_subsets = (
            self.state_vars
            + self.obs_functions
            + self.action_methods
            + self.policy_functions
            + self.constraint_checks
            + self.context_functions
            + self.scaffold_constraint_checks
            + self.scaffold_policy_functions
            + self.scaffold_context_classes
        )
        nodes_set = {id(n) for n in self.nodes}
        for node in all_subsets:
            if id(node) not in nodes_set:
                issues.append(f"Node {node.name!r} in a role subset but not in main nodes list")

        # Check: consistent role classification in subsets
        for node in self.state_vars:
            if node.role != "HIDDEN_STATE":
                issues.append(
                    f"state_vars node {node.name!r} has role {node.role!r}, expected HIDDEN_STATE"
                )
        for node in self.obs_functions:
            if node.role != "OBSERVATION":
                issues.append(
                    f"obs_functions node {node.name!r} has role {node.role!r}, expected OBSERVATION"
                )
        for node in self.action_methods:
            if node.role != "ACTION":
                issues.append(
                    f"action_methods node {node.name!r} has role {node.role!r}, expected ACTION"
                )

        # Check: package_name is a valid Python identifier
        import keyword

        if not self.package_name.isidentifier() or keyword.iskeyword(self.package_name):
            issues.append(f"package_name {self.package_name!r} is not a valid Python identifier")

        return issues

    def diff(self, other: PackagePlan) -> str:
        """Return a human-readable diff between this plan and another.

        Compares the role distributions, node counts, and key attributes.

        Args:
            other: Another PackagePlan to compare against.

        Returns:
            A human-readable diff string. Empty string if the plans are
            identical.
        """
        diffs: list[str] = []

        if self.package_name != other.package_name:
            diffs.append(f"  package_name: {self.package_name!r} vs {other.package_name!r}")

        # Compare role populations
        roles_self = {
            "HIDDEN_STATE": len(self.state_vars),
            "OBSERVATION": len(self.obs_functions),
            "ACTION": len(self.action_methods),
            "POLICY": len(self.policy_functions),
            "CONSTRAINT": len(self.constraint_checks),
            "CONTEXT": len(self.context_functions),
        }
        roles_other = {
            "HIDDEN_STATE": len(other.state_vars),
            "OBSERVATION": len(other.obs_functions),
            "ACTION": len(other.action_methods),
            "POLICY": len(other.policy_functions),
            "CONSTRAINT": len(other.constraint_checks),
            "CONTEXT": len(other.context_functions),
        }

        for role in roles_self:
            if roles_self[role] != roles_other[role]:
                diffs.append(f"  {role}: {roles_self[role]} vs {roles_other[role]}")

        # Compare scaffold populations
        if len(self.scaffold_constraint_checks) != len(other.scaffold_constraint_checks):
            diffs.append(
                f"  scaffold_constraint_checks: "
                f"{len(self.scaffold_constraint_checks)} vs "
                f"{len(other.scaffold_constraint_checks)}"
            )

        if len(self.scaffold_policy_functions) != len(other.scaffold_policy_functions):
            diffs.append(
                f"  scaffold_policy_functions: "
                f"{len(self.scaffold_policy_functions)} vs "
                f"{len(other.scaffold_policy_functions)}"
            )

        if self.target_role_counts != other.target_role_counts:
            diffs.append(
                f"  target_role_counts: {self.target_role_counts!r} vs {other.target_role_counts!r}"
            )

        # Compare matrix presence flags
        matrix_flags = ["has_A_matrix", "has_B_tensor", "has_C_vector", "has_D_vector"]
        for flag in matrix_flags:
            self_val = getattr(self, flag)
            other_val = getattr(other, flag)
            if self_val != other_val:
                diffs.append(f"  {flag}: {self_val} vs {other_val}")

        if not diffs:
            return ""

        return "PackagePlan differences:\n" + "\n".join(diffs)

    def to_json(self) -> str:
        """Serialize the PackagePlan to JSON.

        Returns:
            A JSON string representation of the plan suitable for
            serialization and round-trip recovery.
        """
        data = {
            "package_name": self.package_name,
            "raw_model_name": self.raw_model_name,
            "nodes": [self._node_to_dict(n) for n in self.nodes],
            "state_vars": [n.name for n in self.state_vars],
            "obs_functions": [n.name for n in self.obs_functions],
            "action_methods": [n.name for n in self.action_methods],
            "policy_functions": [n.name for n in self.policy_functions],
            "constraint_checks": [n.name for n in self.constraint_checks],
            "context_functions": [n.name for n in self.context_functions],
            "target_role_counts": dict(self.target_role_counts),
            "scaffold_constraint_checks": [n.name for n in self.scaffold_constraint_checks],
            "scaffold_policy_functions": [n.name for n in self.scaffold_policy_functions],
            "scaffold_context_classes": [n.name for n in self.scaffold_context_classes],
            "has_A_matrix": self.has_A_matrix,
            "has_B_tensor": self.has_B_tensor,
            "has_C_vector": self.has_C_vector,
            "has_D_vector": self.has_D_vector,
            "state_dimension": self.state_dimension,
            "observation_dimension": self.observation_dimension,
            "action_dimension": self.action_dimension,
        }
        return json.dumps(data, indent=2)

    @classmethod
    def from_json(cls, data: str) -> PackagePlan:
        """Deserialize a PackagePlan from JSON.

        Args:
            data: A JSON string representation of a PackagePlan.

        Returns:
            A reconstructed PackagePlan instance.

        Raises:
            json.JSONDecodeError: If the JSON is malformed.
            KeyError: If required fields are missing.
        """
        parsed = json.loads(data)
        nodes_data = parsed.get("nodes", [])

        # Reconstruct all nodes
        all_nodes: dict[str, NodePlan] = {}
        for node_dict in nodes_data:
            node = cls._dict_to_node(node_dict)
            all_nodes[node.name] = node

        # Retrieve nodes by name for each subset
        def get_nodes(names: list[str]) -> list[NodePlan]:
            return [all_nodes[name] for name in names if name in all_nodes]

        plan = cls(
            package_name=parsed.get("package_name", "cogant_model"),
            raw_model_name=parsed.get("raw_model_name", "cogant_model"),
            nodes=list(all_nodes.values()),
            state_vars=get_nodes(parsed.get("state_vars", [])),
            obs_functions=get_nodes(parsed.get("obs_functions", [])),
            action_methods=get_nodes(parsed.get("action_methods", [])),
            policy_functions=get_nodes(parsed.get("policy_functions", [])),
            constraint_checks=get_nodes(parsed.get("constraint_checks", [])),
            context_functions=get_nodes(parsed.get("context_functions", [])),
            target_role_counts=_normalise_role_counts(parsed.get("target_role_counts", {})),
            scaffold_constraint_checks=get_nodes(parsed.get("scaffold_constraint_checks", [])),
            scaffold_policy_functions=get_nodes(parsed.get("scaffold_policy_functions", [])),
            scaffold_context_classes=get_nodes(parsed.get("scaffold_context_classes", [])),
            has_A_matrix=parsed.get("has_A_matrix", False),
            has_B_tensor=parsed.get("has_B_tensor", False),
            has_C_vector=parsed.get("has_C_vector", False),
            has_D_vector=parsed.get("has_D_vector", False),
            state_dimension=int(parsed.get("state_dimension", 0)),
            observation_dimension=int(parsed.get("observation_dimension", 0)),
            action_dimension=int(parsed.get("action_dimension", 0)),
        )
        return plan

    @staticmethod
    def _node_to_dict(node: NodePlan) -> dict:
        """Convert a NodePlan to a dict for JSON serialization."""
        return {
            "slot": node.slot,
            "name": node.name,
            "role": node.role,
            "python_type": node.python_type,
            "module": node.module,
            "cardinality": node.cardinality,
            "initial_value": node.initial_value,
        }

    @staticmethod
    def _dict_to_node(data: dict) -> NodePlan:
        """Convert a dict from JSON deserialization to a NodePlan."""
        return NodePlan(
            slot=data.get("slot", ""),
            name=data.get("name", ""),
            role=data.get("role", ""),
            python_type=data.get("python_type", "float"),
            module=data.get("module", ""),
            cardinality=data.get("cardinality", 0),
            initial_value=data.get("initial_value", "0.0"),
        )

validate()

Validate the package plan for structural consistency.

Checks that the plan is internally coherent and can be synthesized. Does not validate the plan against external sources (e.g., the original GNN).

Returns:

Type Description
list[str]

A list of validation issues. Empty list means the plan is valid.

list[str]

Issues describe problems but do not necessarily prevent synthesis

list[str]

from succeeding.

Source code in py/cogant/reverse/planner.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def validate(self) -> list[str]:
    """Validate the package plan for structural consistency.

    Checks that the plan is internally coherent and can be synthesized.
    Does not validate the plan against external sources (e.g., the
    original GNN).

    Returns:
        A list of validation issues. Empty list means the plan is valid.
        Issues describe problems but do not necessarily prevent synthesis
        from succeeding.
    """
    issues: list[str] = []

    # Check: no duplicate names across all roles
    all_names = [n.name for n in self.nodes]
    seen: dict[str, int] = {}
    for name in all_names:
        seen[name] = seen.get(name, 0) + 1
    duplicates = [name for name, count in seen.items() if count > 1]
    if duplicates:
        issues.append(f"Duplicate node names found: {duplicates}")

    # Check: each node's role is recognized
    valid_roles = {
        "HIDDEN_STATE",
        "OBSERVATION",
        "ACTION",
        "POLICY",
        "CONSTRAINT",
        "CONTEXT",
    }
    for node in self.nodes:
        if node.role not in valid_roles:
            issues.append(f"Node {node.name!r} has unrecognized role {node.role!r}")

    # Check: nodes in subsets appear in main nodes list
    all_subsets = (
        self.state_vars
        + self.obs_functions
        + self.action_methods
        + self.policy_functions
        + self.constraint_checks
        + self.context_functions
        + self.scaffold_constraint_checks
        + self.scaffold_policy_functions
        + self.scaffold_context_classes
    )
    nodes_set = {id(n) for n in self.nodes}
    for node in all_subsets:
        if id(node) not in nodes_set:
            issues.append(f"Node {node.name!r} in a role subset but not in main nodes list")

    # Check: consistent role classification in subsets
    for node in self.state_vars:
        if node.role != "HIDDEN_STATE":
            issues.append(
                f"state_vars node {node.name!r} has role {node.role!r}, expected HIDDEN_STATE"
            )
    for node in self.obs_functions:
        if node.role != "OBSERVATION":
            issues.append(
                f"obs_functions node {node.name!r} has role {node.role!r}, expected OBSERVATION"
            )
    for node in self.action_methods:
        if node.role != "ACTION":
            issues.append(
                f"action_methods node {node.name!r} has role {node.role!r}, expected ACTION"
            )

    # Check: package_name is a valid Python identifier
    import keyword

    if not self.package_name.isidentifier() or keyword.iskeyword(self.package_name):
        issues.append(f"package_name {self.package_name!r} is not a valid Python identifier")

    return issues

diff(other)

Return a human-readable diff between this plan and another.

Compares the role distributions, node counts, and key attributes.

Parameters:

Name Type Description Default
other PackagePlan

Another PackagePlan to compare against.

required

Returns:

Type Description
str

A human-readable diff string. Empty string if the plans are

str

identical.

Source code in py/cogant/reverse/planner.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def diff(self, other: PackagePlan) -> str:
    """Return a human-readable diff between this plan and another.

    Compares the role distributions, node counts, and key attributes.

    Args:
        other: Another PackagePlan to compare against.

    Returns:
        A human-readable diff string. Empty string if the plans are
        identical.
    """
    diffs: list[str] = []

    if self.package_name != other.package_name:
        diffs.append(f"  package_name: {self.package_name!r} vs {other.package_name!r}")

    # Compare role populations
    roles_self = {
        "HIDDEN_STATE": len(self.state_vars),
        "OBSERVATION": len(self.obs_functions),
        "ACTION": len(self.action_methods),
        "POLICY": len(self.policy_functions),
        "CONSTRAINT": len(self.constraint_checks),
        "CONTEXT": len(self.context_functions),
    }
    roles_other = {
        "HIDDEN_STATE": len(other.state_vars),
        "OBSERVATION": len(other.obs_functions),
        "ACTION": len(other.action_methods),
        "POLICY": len(other.policy_functions),
        "CONSTRAINT": len(other.constraint_checks),
        "CONTEXT": len(other.context_functions),
    }

    for role in roles_self:
        if roles_self[role] != roles_other[role]:
            diffs.append(f"  {role}: {roles_self[role]} vs {roles_other[role]}")

    # Compare scaffold populations
    if len(self.scaffold_constraint_checks) != len(other.scaffold_constraint_checks):
        diffs.append(
            f"  scaffold_constraint_checks: "
            f"{len(self.scaffold_constraint_checks)} vs "
            f"{len(other.scaffold_constraint_checks)}"
        )

    if len(self.scaffold_policy_functions) != len(other.scaffold_policy_functions):
        diffs.append(
            f"  scaffold_policy_functions: "
            f"{len(self.scaffold_policy_functions)} vs "
            f"{len(other.scaffold_policy_functions)}"
        )

    if self.target_role_counts != other.target_role_counts:
        diffs.append(
            f"  target_role_counts: {self.target_role_counts!r} vs {other.target_role_counts!r}"
        )

    # Compare matrix presence flags
    matrix_flags = ["has_A_matrix", "has_B_tensor", "has_C_vector", "has_D_vector"]
    for flag in matrix_flags:
        self_val = getattr(self, flag)
        other_val = getattr(other, flag)
        if self_val != other_val:
            diffs.append(f"  {flag}: {self_val} vs {other_val}")

    if not diffs:
        return ""

    return "PackagePlan differences:\n" + "\n".join(diffs)

to_json()

Serialize the PackagePlan to JSON.

Returns:

Type Description
str

A JSON string representation of the plan suitable for

str

serialization and round-trip recovery.

Source code in py/cogant/reverse/planner.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def to_json(self) -> str:
    """Serialize the PackagePlan to JSON.

    Returns:
        A JSON string representation of the plan suitable for
        serialization and round-trip recovery.
    """
    data = {
        "package_name": self.package_name,
        "raw_model_name": self.raw_model_name,
        "nodes": [self._node_to_dict(n) for n in self.nodes],
        "state_vars": [n.name for n in self.state_vars],
        "obs_functions": [n.name for n in self.obs_functions],
        "action_methods": [n.name for n in self.action_methods],
        "policy_functions": [n.name for n in self.policy_functions],
        "constraint_checks": [n.name for n in self.constraint_checks],
        "context_functions": [n.name for n in self.context_functions],
        "target_role_counts": dict(self.target_role_counts),
        "scaffold_constraint_checks": [n.name for n in self.scaffold_constraint_checks],
        "scaffold_policy_functions": [n.name for n in self.scaffold_policy_functions],
        "scaffold_context_classes": [n.name for n in self.scaffold_context_classes],
        "has_A_matrix": self.has_A_matrix,
        "has_B_tensor": self.has_B_tensor,
        "has_C_vector": self.has_C_vector,
        "has_D_vector": self.has_D_vector,
        "state_dimension": self.state_dimension,
        "observation_dimension": self.observation_dimension,
        "action_dimension": self.action_dimension,
    }
    return json.dumps(data, indent=2)

from_json(data) classmethod

Deserialize a PackagePlan from JSON.

Parameters:

Name Type Description Default
data str

A JSON string representation of a PackagePlan.

required

Returns:

Type Description
PackagePlan

A reconstructed PackagePlan instance.

Raises:

Type Description
JSONDecodeError

If the JSON is malformed.

KeyError

If required fields are missing.

Source code in py/cogant/reverse/planner.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
@classmethod
def from_json(cls, data: str) -> PackagePlan:
    """Deserialize a PackagePlan from JSON.

    Args:
        data: A JSON string representation of a PackagePlan.

    Returns:
        A reconstructed PackagePlan instance.

    Raises:
        json.JSONDecodeError: If the JSON is malformed.
        KeyError: If required fields are missing.
    """
    parsed = json.loads(data)
    nodes_data = parsed.get("nodes", [])

    # Reconstruct all nodes
    all_nodes: dict[str, NodePlan] = {}
    for node_dict in nodes_data:
        node = cls._dict_to_node(node_dict)
        all_nodes[node.name] = node

    # Retrieve nodes by name for each subset
    def get_nodes(names: list[str]) -> list[NodePlan]:
        return [all_nodes[name] for name in names if name in all_nodes]

    plan = cls(
        package_name=parsed.get("package_name", "cogant_model"),
        raw_model_name=parsed.get("raw_model_name", "cogant_model"),
        nodes=list(all_nodes.values()),
        state_vars=get_nodes(parsed.get("state_vars", [])),
        obs_functions=get_nodes(parsed.get("obs_functions", [])),
        action_methods=get_nodes(parsed.get("action_methods", [])),
        policy_functions=get_nodes(parsed.get("policy_functions", [])),
        constraint_checks=get_nodes(parsed.get("constraint_checks", [])),
        context_functions=get_nodes(parsed.get("context_functions", [])),
        target_role_counts=_normalise_role_counts(parsed.get("target_role_counts", {})),
        scaffold_constraint_checks=get_nodes(parsed.get("scaffold_constraint_checks", [])),
        scaffold_policy_functions=get_nodes(parsed.get("scaffold_policy_functions", [])),
        scaffold_context_classes=get_nodes(parsed.get("scaffold_context_classes", [])),
        has_A_matrix=parsed.get("has_A_matrix", False),
        has_B_tensor=parsed.get("has_B_tensor", False),
        has_C_vector=parsed.get("has_C_vector", False),
        has_D_vector=parsed.get("has_D_vector", False),
        state_dimension=int(parsed.get("state_dimension", 0)),
        observation_dimension=int(parsed.get("observation_dimension", 0)),
        action_dimension=int(parsed.get("action_dimension", 0)),
    )
    return plan

verify_repo_roundtrip(repo_path, output_dir=None, *, role_threshold=ROLE_PRESERVATION_THRESHOLD)

Run forward → reverse → forward on an existing repository.

This is the entry point used by the cogant roundtrip CLI subcommand. It:

  1. Runs the forward pipeline on repo_path and emits a GNN plus a first semantic-mappings multiset R1.
  2. Parses the emitted GNN back into a ReverseGNNModel.
  3. Synthesizes a Python package from the plan.
  4. Runs the forward pipeline again on the synthesized package and collects a second semantic-mappings multiset R2.
  5. Compares R1 and R2 directly; the role-preservation score is the mean per-role min(count1, count2) / max(count1, count2) multiset similarity.

This comparison style (forward-vs-forward) is the strictest role preservation measurement for an existing repository: it asks whether the same pipeline sees the same roles in the synthesized package that it saw in the original. The alternative (parse the GNN, compare to forward-on-synth) is weaker because it mixes two different rule systems — the parser's role derivation and the forward pipeline's semantic rules — on the two sides of the comparison.

Parameters:

Name Type Description Default
repo_path str | Path

Repository to round-trip.

required
output_dir str | Path | None

Directory to write intermediate artifacts into. If None, a temporary directory is used and cleaned up.

None
role_threshold float

Minimum role match score to accept.

ROLE_PRESERVATION_THRESHOLD

Returns:

Type Description
RoundtripResult

class:RoundtripResult with original_roles drawn from the

RoundtripResult

first forward pass and synthesized_roles drawn from the

RoundtripResult

second. When the reverse parser, planning, or synthesis rejects the

RoundtripResult

emitted model, the result has roundtrip_status=FAILED and the

RoundtripResult

reason in errors.

Source code in py/cogant/reverse/idempotency.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
def verify_repo_roundtrip(
    repo_path: str | Path,
    output_dir: str | Path | None = None,
    *,
    role_threshold: float = ROLE_PRESERVATION_THRESHOLD,
) -> RoundtripResult:
    """Run forward → reverse → forward on an existing repository.

    This is the entry point used by the ``cogant roundtrip`` CLI
    subcommand. It:

    1. Runs the forward pipeline on ``repo_path`` and emits a GNN plus
       a **first** semantic-mappings multiset ``R1``.
    2. Parses the emitted GNN back into a ReverseGNNModel.
    3. Synthesizes a Python package from the plan.
    4. Runs the forward pipeline again on the synthesized package and
       collects a **second** semantic-mappings multiset ``R2``.
    5. Compares ``R1`` and ``R2`` directly; the role-preservation score is
       the mean per-role ``min(count1, count2) / max(count1, count2)``
       multiset similarity.

    This comparison style (forward-vs-forward) is the strictest role
    preservation measurement for an existing repository:
    it asks whether the *same* pipeline sees the *same* roles in the
    synthesized package that it saw in the original. The alternative
    (parse the GNN, compare to forward-on-synth) is weaker because it
    mixes two different rule systems — the parser's role derivation
    and the forward pipeline's semantic rules — on the two sides of
    the comparison.

    Args:
        repo_path: Repository to round-trip.
        output_dir: Directory to write intermediate artifacts into.
            If None, a temporary directory is used and cleaned up.
        role_threshold: Minimum role match score to accept.

    Returns:
        :class:`RoundtripResult` with ``original_roles`` drawn from the
        first forward pass and ``synthesized_roles`` drawn from the
        second. When the reverse parser, planning, or synthesis rejects the
        emitted model, the result has ``roundtrip_status=FAILED`` and the
        reason in ``errors``.
    """
    from cogant.api.session import Session

    repo_path = Path(repo_path).expanduser().resolve()
    using_tmp = output_dir is None
    work_dir = Path(output_dir or tempfile.mkdtemp(prefix="cogant-roundtrip-")).resolve()
    work_dir.mkdir(parents=True, exist_ok=True)

    gnn_dir = work_dir / "forward"
    gnn_dir.mkdir(parents=True, exist_ok=True)
    reverse_dir = work_dir / "reverse"
    reverse_dir.mkdir(parents=True, exist_ok=True)

    try:
        # Stage 1: forward on the original repo → GNN markdown + mappings.
        session = Session(target=str(repo_path))
        session.extract_static()
        session.build_graph()
        session.translate_to_gnn()
        session.compile_state_space()
        bundle = session._bundle_internal()

        original_mappings = bundle.artifacts.get("_semantic_mappings", {}) or {}
        original_roles = _role_multiset_from_mappings(original_mappings)
        original_state_space = bundle.artifacts.get("_state_space_model")
        original_graph = bundle.artifacts.get("_program_graph")
        original_trace = bundle.artifacts.get("_rule_evidence_trace") or {}

        from cogant.gnn.formatter import GNNMarkdownFormatter

        formatter = GNNMarkdownFormatter(
            program_graph=bundle.artifacts["_program_graph"],
            state_space_model=bundle.artifacts["_state_space_model"],
            process_model=bundle.artifacts["_process_model"],
            semantic_mappings=original_mappings,
        )
        gnn_md = formatter.format()
        gnn_path = gnn_dir / "model.gnn.md"
        gnn_path.write_text(gnn_md, encoding="utf-8")
        logger.info("Wrote forward GNN to %s", gnn_path)

        # Stage 2+3: parse → plan → synthesize.  A model that the reverse
        # parser, planning, or synthesis rejects is a FAILED round-trip, not a
        # crash.
        try:
            model = parse_gnn(gnn_path)
            plan = plan_package(model, expected_roles=original_roles)
            if supports_stable_minimal_profile(plan, model):
                package_path = synthesize_stable_minimal_package(plan, model, reverse_dir)
            else:
                package_path = synthesize_package(plan, model, reverse_dir)
        except ValueError as exc:
            logger.warning("Reverse synthesis failed for %s: %s", repo_path, exc)
            return _synthesis_failed_result(original_roles, exc, role_threshold=role_threshold)

        # Stage 4: forward on the synthesized package.
        forward = _run_forward(package_path)
        synthesized_roles = _role_multiset_from_mappings(
            forward.get("mappings"),
            semantic_targets=forward.get("semantic_targets"),
        )
        roundtrip_warnings: list[str] = []
        synthesized_gnn_md = str(forward.get("gnn_markdown") or "")
        synthesized_gnn_path = work_dir / "regenerated" / "model.gnn.md"
        synth_model = _parse_regenerated_gnn(
            synthesized_gnn_md,
            synthesized_gnn_path,
            roundtrip_warnings,
        )

        # role_preservation_score = mean over every role present on either
        # side of min(orig,synth)/max(orig,synth) — the formula documented
        # in manuscript appendix S01. A role introduced OR dropped scores
        # 0.0 for that role; both-zero scores 1.0 (vacuous). (Prior code:
        # recall-only Sum(min)/Sum(orig), saturated at 1.0 for ANY superset
        # synthesis — keystone defect, review 2026-05-19.)
        score, vacuous_roundtrip = _role_preservation_score(original_roles, synthesized_roles)

        # Shape match: compare the two state-space models directly.
        shape_match: dict[str, bool] = {}
        orig_ss = original_state_space
        new_ss = forward.get("state_space")
        orig_n_states = len(getattr(orig_ss, "variables", {}) or {}) if orig_ss else 0
        orig_n_obs = len(getattr(orig_ss, "observations", {}) or {}) if orig_ss else 0
        orig_n_actions = len(getattr(orig_ss, "actions", {}) or {}) if orig_ss else 0
        new_n_states = len(getattr(new_ss, "variables", {}) or {}) if new_ss else 0
        new_n_obs = len(getattr(new_ss, "observations", {}) or {}) if new_ss else 0
        new_n_actions = len(getattr(new_ss, "actions", {}) or {}) if new_ss else 0
        if orig_n_states > 0:
            shape_match["n_states"] = new_n_states >= 1
        if orig_n_obs > 0:
            shape_match["n_obs"] = new_n_obs >= 1
        if orig_n_actions > 0:
            shape_match["n_actions"] = new_n_actions >= 1

        # Auxiliary distance metrics. The repo round-trip has access
        # to two compiled state-space models, so we can compare their
        # matrix slots directly when available.
        matrix_score = compare_matrices(
            _model_matrices(model),
            _model_matrices(synth_model)
            if synth_model is not None
            else _state_space_matrices(new_ss),
        )
        orig_nodes, orig_edges = _nodes_edges_from_mappings(original_mappings)
        synth_nodes, synth_edges = _nodes_edges_from_mappings(forward.get("mappings"))
        structural_score = compare_graph_structure(orig_nodes, orig_edges, synth_nodes, synth_edges)
        original_graph_summary = _graph_summary(original_graph)
        synthesized_graph_summary = _graph_summary(forward.get("program_graph"))
        graph_delta = _graph_delta(original_graph_summary, synthesized_graph_summary)
        matrix_delta = _matrix_delta(
            _model_matrices(model),
            _model_matrices(synth_model)
            if synth_model is not None
            else _state_space_matrices(new_ss),
        )
        gnn_diff = _gnn_diff(gnn_md, synthesized_gnn_md) if synthesized_gnn_md else {}
        generated_code_ok, generated_code_errors = _generated_code_status(package_path)
        errors = list(generated_code_errors)
        if forward.get("error"):
            errors.append(str(forward["error"]))
        invariants = _invariants(
            role_preservation_score=score,
            role_threshold=role_threshold,
            shape_match=shape_match,
            graph_delta=graph_delta,
            matrix_delta=matrix_delta,
            gnn_diff=gnn_diff,
            generated_code_ok=generated_code_ok,
            forward_error=forward.get("error"),
        )
        role_preserved = bool(invariants["role_preserved"])
        matrix_preserved = bool(invariants["matrix_preserved"])
        gnn_sections_preserved = bool(invariants["gnn_sections_preserved"])
        structurally_isomorphic = _strict_invariants_preserved(
            role_preserved=role_preserved,
            matrix_preserved=matrix_preserved,
            gnn_sections_preserved=gnn_sections_preserved,
            generated_code_ok=generated_code_ok,
            invariants=invariants,
        )

        result = RoundtripResult(
            roundtrip_status=_roundtrip_status_from_invariants(
                role_preserved=role_preserved,
                structurally_isomorphic=structurally_isomorphic,
                errors=errors,
            ),
            role_preservation_score=score,
            role_preserved=role_preserved,
            structurally_isomorphic=structurally_isomorphic,
            matrix_preserved=matrix_preserved,
            gnn_sections_preserved=gnn_sections_preserved,
            generated_code_ok=generated_code_ok,
            matrix_score=matrix_score,
            structural_score=structural_score,
            original_roles=dict(original_roles),
            synthesized_roles=dict(synthesized_roles),
            shape_match=shape_match,
            package_path=package_path,
            original_graph_summary=original_graph_summary,
            synthesized_graph_summary=synthesized_graph_summary,
            graph_delta=graph_delta,
            gnn_diff=gnn_diff,
            matrix_delta=matrix_delta,
            invariants=invariants,
            rule_evidence_trace={
                "original": original_trace,
                "synthesized": forward.get("rule_evidence_trace") or {},
            },
            warnings=roundtrip_warnings,
            errors=errors,
            vacuous_roundtrip=vacuous_roundtrip,
        )
        logger.info("Repo round-trip result: %s", result.summary())
        return result
    finally:
        if using_tmp:
            shutil.rmtree(work_dir, ignore_errors=True)

verify_roundtrip(gnn_path, tmp_dir=None, *, role_threshold=ROLE_PRESERVATION_THRESHOLD, keep_tmp=False)

Run a full round-trip on a GNN markdown file and score the result.

Parameters:

Name Type Description Default
gnn_path str | Path

Path to a GNN markdown file produced by COGANT (or any conforming emitter).

required
tmp_dir str | Path | None

Optional directory where the synthesized package should be written. If None, a temporary directory is created and removed after the run (unless keep_tmp is True).

None
role_threshold float

Minimum role_preservation_score for the weaker role-preserved success tier. Defaults to :data:ROLE_PRESERVATION_THRESHOLD.

ROLE_PRESERVATION_THRESHOLD
keep_tmp bool

When True, do not delete the temporary directory after the run. Useful for debugging.

False

Returns:

Name Type Description
A RoundtripResult

class:RoundtripResult summarising the run. Once the source GNN

RoundtripResult

has been parsed, the result is always returned — a model that

RoundtripResult

planning or synthesis rejects yields roundtrip_status=FAILED,

RoundtripResult

and exceptions inside the forward pipeline are captured as

RoundtripResult

errors rather than raised. A temporary directory created here

RoundtripResult

is removed even when the run fails.

Source code in py/cogant/reverse/idempotency.py
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
def verify_roundtrip(
    gnn_path: str | Path,
    tmp_dir: str | Path | None = None,
    *,
    role_threshold: float = ROLE_PRESERVATION_THRESHOLD,
    keep_tmp: bool = False,
) -> RoundtripResult:
    """Run a full round-trip on a GNN markdown file and score the result.

    Args:
        gnn_path: Path to a GNN markdown file produced by COGANT (or
            any conforming emitter).
        tmp_dir: Optional directory where the synthesized package
            should be written. If None, a temporary directory is
            created and removed after the run (unless ``keep_tmp``
            is True).
        role_threshold: Minimum ``role_preservation_score`` for the
            weaker role-preserved success tier. Defaults to
            :data:`ROLE_PRESERVATION_THRESHOLD`.
        keep_tmp: When True, do not delete the temporary directory
            after the run. Useful for debugging.

    Returns:
        A :class:`RoundtripResult` summarising the run. Once the source GNN
        has been parsed, the result is always returned — a model that
        planning or synthesis rejects yields ``roundtrip_status=FAILED``,
        and exceptions inside the forward pipeline are captured as
        ``errors`` rather than raised. A temporary directory created here
        is removed even when the run fails.
    """
    gnn_path = Path(gnn_path).expanduser().resolve()

    # 1. Parse the source GNN.
    model = parse_gnn(gnn_path)
    original_roles = _role_multiset_from_model(model)

    # 2. Plan and synthesize into a temporary directory.
    cleanup_dir: Path | None = None
    if tmp_dir is None:
        tmp_dir_obj = Path(tempfile.mkdtemp(prefix="cogant-roundtrip-"))
        if not keep_tmp:
            cleanup_dir = tmp_dir_obj
    else:
        tmp_dir_obj = Path(tmp_dir).expanduser().resolve()
        tmp_dir_obj.mkdir(parents=True, exist_ok=True)

    try:
        result = _verify_gnn_roundtrip_in(
            gnn_path,
            model,
            original_roles,
            tmp_dir_obj,
            role_threshold=role_threshold,
        )
    finally:
        # 6. Cleanup, also when synthesis or scoring raised.
        if cleanup_dir is not None:
            shutil.rmtree(cleanup_dir, ignore_errors=True)
    if cleanup_dir is not None:
        # The package_path points to deleted files; clear it so callers don't
        # try to read deleted files.
        result.package_path = None

    logger.info("Round-trip result: %s", result.summary())
    return result

compare_graph_structure(nodes_a, edges_a, nodes_b, edges_b)

Return a graph-structure similarity score in [0, 1].

We build two multisets for each graph:

  1. role(nodes) — one bucket per node role label.
  2. (source_role, target_role) — one bucket per edge.

We then compute the normalized symmetric difference of each multiset separately and return 1 - mean(d_nodes, d_edges). Nodes-only graphs (no edges on either side) skip the edge term.

Edge cases:

  • Both graphs empty → return 1.0 (vacuously identical).
  • One graph empty, other non-empty → return 0.0.

Parameters:

Name Type Description Default
nodes_a Sequence[Any]

Iterable of node-like objects for graph A.

required
edges_a Sequence[Any]

Iterable of edge-like objects for graph A.

required
nodes_b Sequence[Any]

Iterable of node-like objects for graph B.

required
edges_b Sequence[Any]

Iterable of edge-like objects for graph B.

required

Returns:

Type Description
float

Similarity score in [0.0, 1.0].

Source code in py/cogant/reverse/metrics.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def compare_graph_structure(
    nodes_a: Sequence[Any],
    edges_a: Sequence[Any],
    nodes_b: Sequence[Any],
    edges_b: Sequence[Any],
) -> float:
    """Return a graph-structure similarity score in ``[0, 1]``.

    We build two multisets for each graph:

    1. ``role(nodes)`` — one bucket per node role label.
    2. ``(source_role, target_role)`` — one bucket per edge.

    We then compute the normalized symmetric difference of each
    multiset separately and return ``1 - mean(d_nodes, d_edges)``.
    Nodes-only graphs (no edges on either side) skip the edge term.

    Edge cases:

    * Both graphs empty → return ``1.0`` (vacuously identical).
    * One graph empty, other non-empty → return ``0.0``.

    Args:
        nodes_a: Iterable of node-like objects for graph A.
        edges_a: Iterable of edge-like objects for graph A.
        nodes_b: Iterable of node-like objects for graph B.
        edges_b: Iterable of edge-like objects for graph B.

    Returns:
        Similarity score in ``[0.0, 1.0]``.
    """
    n_a = list(nodes_a or [])
    n_b = list(nodes_b or [])
    e_a = list(edges_a or [])
    e_b = list(edges_b or [])

    if not n_a and not n_b and not e_a and not e_b:
        return 1.0
    if (not n_a and n_b) or (n_a and not n_b):
        # One side has zero nodes, the other has some — maximally
        # different at the structural level.
        if not e_a and not e_b:
            return 0.0

    node_labels_a = _multiset(_node_role_label(n) for n in n_a)
    node_labels_b = _multiset(_node_role_label(n) for n in n_b)
    node_total = sum(node_labels_a.values()) + sum(node_labels_b.values())
    node_symdiff = _multiset_symmetric_difference(node_labels_a, node_labels_b)
    node_distance = (node_symdiff / node_total) if node_total > 0 else 0.0

    edge_labels_a = _multiset(_edge_role_pair(e) for e in e_a)
    edge_labels_b = _multiset(_edge_role_pair(e) for e in e_b)
    edge_total = sum(edge_labels_a.values()) + sum(edge_labels_b.values())
    if edge_total > 0:
        edge_symdiff = _multiset_symmetric_difference(edge_labels_a, edge_labels_b)
        edge_distance = edge_symdiff / edge_total
        distance = 0.5 * (node_distance + edge_distance)
    else:
        distance = node_distance

    distance = max(0.0, min(1.0, distance))
    return 1.0 - distance

compare_matrices(matrices_a, matrices_b)

Return an averaged Frobenius-similarity score in [0, 1].

For each canonical Active Inference matrix slot (A, B, C, D) present in both input dicts and non-empty on both sides, we compute::

1 - ||m1 - m2||_F / (||m1||_F + ||m2||_F + eps)

after zero-padding the two matrices to their common bounding shape. The returned score is the unweighted mean of these per-matrix similarities.

Edge cases:

  • If neither side has any recognisable numeric matrix entry, return 0.5 (neutral — the metric is undefined, not zero).
  • If a key is present on only one side it is ignored (the structural-graph score is the axis that penalises missing slots).
  • Extra keys beyond {A, B, C, D} are tolerated and included.

The metric is symmetric: compare_matrices(a, b) == compare_matrices(b, a) up to floating point round-off.

Parameters:

Name Type Description Default
matrices_a Mapping[str, Any]

Dict mapping matrix name to a 2D array-like.

required
matrices_b Mapping[str, Any]

Dict mapping matrix name to a 2D array-like.

required

Returns:

Type Description
float

Mean similarity score in [0, 1], or 0.5 when no

float

comparable matrices exist.

Source code in py/cogant/reverse/metrics.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def compare_matrices(
    matrices_a: Mapping[str, Any],
    matrices_b: Mapping[str, Any],
) -> float:
    """Return an averaged Frobenius-similarity score in ``[0, 1]``.

    For each canonical Active Inference matrix slot
    (``A``, ``B``, ``C``, ``D``) present in **both** input dicts and
    non-empty on both sides, we compute::

        1 - ||m1 - m2||_F / (||m1||_F + ||m2||_F + eps)

    after zero-padding the two matrices to their common bounding
    shape. The returned score is the unweighted mean of these
    per-matrix similarities.

    Edge cases:

    * If neither side has any recognisable numeric matrix entry,
      return ``0.5`` (neutral — the metric is undefined, not zero).
    * If a key is present on only one side it is ignored (the
      structural-graph score is the axis that penalises missing
      slots).
    * Extra keys beyond ``{A, B, C, D}`` are tolerated and included.

    The metric is symmetric: ``compare_matrices(a, b) ==
    compare_matrices(b, a)`` up to floating point round-off.

    Args:
        matrices_a: Dict mapping matrix name to a 2D array-like.
        matrices_b: Dict mapping matrix name to a 2D array-like.

    Returns:
        Mean similarity score in ``[0, 1]``, or ``0.5`` when no
        comparable matrices exist.
    """
    # Stable key ordering: canonical A/B/C/D first, then any extras
    # sorted alphabetically.
    shared_keys: list[str] = []
    for key in MATRIX_KEYS:
        if key in matrices_a and key in matrices_b:
            shared_keys.append(key)
    extras = sorted((set(matrices_a.keys()) & set(matrices_b.keys())) - set(MATRIX_KEYS))
    shared_keys.extend(extras)

    if not shared_keys:
        return 0.5

    scores: list[float] = []
    for key in shared_keys:
        arr_a = _coerce_matrix(matrices_a.get(key))
        arr_b = _coerce_matrix(matrices_b.get(key))
        if arr_a is None or arr_b is None:
            continue
        score, _ = _matrix_pair_score(arr_a, arr_b)
        scores.append(score)

    if not scores:
        return 0.5
    return float(sum(scores) / len(scores))

compare_role_distributions(roles_a, roles_b)

Return a similarity score in [0, 1] for two role multisets.

The underlying distance is the Jensen-Shannon divergence in base 2, which for two probability vectors p and q is::

JS(p, q) = 0.5 * KL(p || M) + 0.5 * KL(q || M),  M = 0.5*(p+q)

and is bounded in [0, 1]. We return 1 - JS so that higher is better.

Edge cases:

  • If both distributions are empty, we return 0.0 (there is no distribution to compare, and the spec asks for a neutral-low value here so that the overall isomorphism score does not spuriously inflate on degenerate inputs).
  • If exactly one distribution is empty, we also return 0.0 (maximally different — one side has no roles at all).

Parameters:

Name Type Description Default
roles_a Mapping[str, float]

Mapping from role name to count (or weight).

required
roles_b Mapping[str, float]

Mapping from role name to count (or weight).

required

Returns:

Type Description
float

Similarity score in [0.0, 1.0]. 1.0 means the two role

float

distributions are identical; 0.0 means their supports are

float

disjoint or one side is empty.

Source code in py/cogant/reverse/metrics.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def compare_role_distributions(
    roles_a: Mapping[str, float],
    roles_b: Mapping[str, float],
) -> float:
    """Return a similarity score in ``[0, 1]`` for two role multisets.

    The underlying distance is the Jensen-Shannon divergence in base 2,
    which for two probability vectors ``p`` and ``q`` is::

        JS(p, q) = 0.5 * KL(p || M) + 0.5 * KL(q || M),  M = 0.5*(p+q)

    and is bounded in ``[0, 1]``. We return ``1 - JS`` so that higher
    is better.

    Edge cases:

    * If both distributions are empty, we return ``0.0`` (there is no
      distribution to compare, and the spec asks for a neutral-low
      value here so that the overall isomorphism score does not
      spuriously inflate on degenerate inputs).
    * If exactly one distribution is empty, we also return ``0.0``
      (maximally different — one side has no roles at all).

    Args:
        roles_a: Mapping from role name to count (or weight).
        roles_b: Mapping from role name to count (or weight).

    Returns:
        Similarity score in ``[0.0, 1.0]``. ``1.0`` means the two role
        distributions are identical; ``0.0`` means their supports are
        disjoint or one side is empty.
    """
    total_a = sum(float(v) for v in roles_a.values())
    total_b = sum(float(v) for v in roles_b.values())

    if total_a <= 0.0 and total_b <= 0.0:
        return 0.0
    if total_a <= 0.0 or total_b <= 0.0:
        return 0.0

    support: list[str] = sorted(set(roles_a.keys()) | set(roles_b.keys()))
    p = _to_probability(roles_a, support)
    q = _to_probability(roles_b, support)

    m = 0.5 * (p + q)
    js = 0.5 * _kl_divergence(p, m) + 0.5 * _kl_divergence(q, m)
    # Numerical clamp: floating point can produce tiny negatives or
    # values a hair above 1.0.
    js = max(0.0, min(1.0, js))
    return 1.0 - js

compute_isomorphism_report(gnn_a, gnn_b, threshold=DEFAULT_ISOMORPHISM_THRESHOLD)

Compute a full :class:IsomorphismReport for two GNN packages.

gnn_a and gnn_b are expected to be dict-like bundles with the following optional keys:

  • roles — {role_name: count} multiset.
  • matrices — {"A"|"B"|"C"|"D": array_like} dict.
  • nodes — iterable of node objects or dicts.
  • edges — iterable of edge objects or dicts.

Missing keys are tolerated: the corresponding component score falls back to its documented neutral value (0.0 for roles, 0.5 for matrices, 1.0 for an empty graph).

The three component scores are combined with fixed weights::

total = 0.4 * role + 0.4 * matrix + 0.2 * structural

and structurally_isomorphic is total >= threshold.

Parameters:

Name Type Description Default
gnn_a Mapping[str, Any]

First GNN package dict.

required
gnn_b Mapping[str, Any]

Second GNN package dict.

required
threshold float

Cutoff for :attr:IsomorphismReport.structurally_isomorphic. Defaults to :data:DEFAULT_ISOMORPHISM_THRESHOLD (0.7).

DEFAULT_ISOMORPHISM_THRESHOLD

Returns:

Type Description
IsomorphismReport

A fully populated :class:IsomorphismReport.

Source code in py/cogant/reverse/metrics.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
def compute_isomorphism_report(
    gnn_a: Mapping[str, Any],
    gnn_b: Mapping[str, Any],
    threshold: float = DEFAULT_ISOMORPHISM_THRESHOLD,
) -> IsomorphismReport:
    """Compute a full :class:`IsomorphismReport` for two GNN packages.

    ``gnn_a`` and ``gnn_b`` are expected to be dict-like bundles with
    the following optional keys:

    * ``roles`` — ``{role_name: count}`` multiset.
    * ``matrices`` — ``{"A"|"B"|"C"|"D": array_like}`` dict.
    * ``nodes`` — iterable of node objects or dicts.
    * ``edges`` — iterable of edge objects or dicts.

    Missing keys are tolerated: the corresponding component score
    falls back to its documented neutral value (``0.0`` for roles,
    ``0.5`` for matrices, ``1.0`` for an empty graph).

    The three component scores are combined with fixed weights::

        total = 0.4 * role + 0.4 * matrix + 0.2 * structural

    and ``structurally_isomorphic`` is ``total >= threshold``.

    Args:
        gnn_a: First GNN package dict.
        gnn_b: Second GNN package dict.
        threshold: Cutoff for :attr:`IsomorphismReport.structurally_isomorphic`.
            Defaults to :data:`DEFAULT_ISOMORPHISM_THRESHOLD` (0.7).

    Returns:
        A fully populated :class:`IsomorphismReport`.
    """
    roles_a: Mapping[str, float] = gnn_a.get("roles", {}) or {}
    roles_b: Mapping[str, float] = gnn_b.get("roles", {}) or {}
    matrices_a: Mapping[str, Any] = gnn_a.get("matrices", {}) or {}
    matrices_b: Mapping[str, Any] = gnn_b.get("matrices", {}) or {}
    nodes_a: Sequence[Any] = gnn_a.get("nodes", []) or []
    nodes_b: Sequence[Any] = gnn_b.get("nodes", []) or []
    edges_a: Sequence[Any] = gnn_a.get("edges", []) or []
    edges_b: Sequence[Any] = gnn_b.get("edges", []) or []

    role_score = compare_role_distributions(roles_a, roles_b)
    matrix_score = compare_matrices(matrices_a, matrices_b)
    structural_score = compare_graph_structure(nodes_a, edges_a, nodes_b, edges_b)

    total_score = (
        _ROLE_WEIGHT * role_score
        + _MATRIX_WEIGHT * matrix_score
        + _STRUCTURAL_WEIGHT * structural_score
    )
    # Clamp for floating-point safety.
    total_score = max(0.0, min(1.0, total_score))

    breakdown: dict[str, Any] = {
        "role_score": role_score,
        "matrix_score": matrix_score,
        "structural_score": structural_score,
        "weights": {
            "role": _ROLE_WEIGHT,
            "matrix": _MATRIX_WEIGHT,
            "structural": _STRUCTURAL_WEIGHT,
        },
        "threshold": threshold,
        "roles_a_total": sum(float(v) for v in roles_a.values()),
        "roles_b_total": sum(float(v) for v in roles_b.values()),
        "matrix_keys_a": sorted(matrices_a.keys()),
        "matrix_keys_b": sorted(matrices_b.keys()),
        "n_nodes_a": len(list(nodes_a)),
        "n_nodes_b": len(list(nodes_b)),
        "n_edges_a": len(list(edges_a)),
        "n_edges_b": len(list(edges_b)),
    }

    # Per-matrix raw Frobenius detail, if we can compute it cheaply.
    per_matrix: dict[str, float] = {}
    for key in MATRIX_KEYS:
        if key in matrices_a and key in matrices_b:
            arr_a = _coerce_matrix(matrices_a.get(key))
            arr_b = _coerce_matrix(matrices_b.get(key))
            if arr_a is not None and arr_b is not None:
                _, raw = _matrix_pair_score(arr_a, arr_b)
                per_matrix[key] = raw
    if per_matrix:
        breakdown["per_matrix_frobenius"] = per_matrix

    return IsomorphismReport(
        structural_score=float(structural_score),
        role_score=float(role_score),
        matrix_score=float(matrix_score),
        total_score=float(total_score),
        structurally_isomorphic=bool(total_score >= threshold),
        breakdown=breakdown,
    )

parse_gnn(gnn)

Parse a GNN markdown file or string into a :class:ReverseGNNModel.

Parameters:

Name Type Description Default
gnn str | Path

Either a path to a .gnn.md file or a raw markdown string. If the argument is a string that does not point to an existing file, it is treated as the raw markdown text.

required

Returns:

Type Description
ReverseGNNModel

A populated :class:ReverseGNNModel. Fields that cannot be parsed

ReverseGNNModel

from the source remain empty. Consumers must treat an incomplete

ReverseGNNModel

model as invalid evidence rather than filling missing semantics.

Example

from cogant.reverse.parser import parse_gnn gnn = '''## ModelName ... Demo ... ... ## StateSpaceBlock ... s_f0[2,1,type=int] ... o_m0[2,1,type=int] ... ''' model = parse_gnn(gnn) model.raw_model_name 'Demo'

Source code in py/cogant/reverse/parser.py
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
def parse_gnn(gnn: str | Path) -> ReverseGNNModel:
    """Parse a GNN markdown file or string into a :class:`ReverseGNNModel`.

    Args:
        gnn: Either a path to a ``.gnn.md`` file or a raw markdown
            string. If the argument is a string that does not point to
            an existing file, it is treated as the raw markdown text.

    Returns:
        A populated :class:`ReverseGNNModel`. Fields that cannot be parsed
        from the source remain empty. Consumers must treat an incomplete
        model as invalid evidence rather than filling missing semantics.

    Example:
        >>> from cogant.reverse.parser import parse_gnn
        >>> gnn = '''## ModelName
        ... Demo
        ...
        ... ## StateSpaceBlock
        ... s_f0[2,1,type=int]
        ... o_m0[2,1,type=int]
        ... '''
        >>> model = parse_gnn(gnn)
        >>> model.raw_model_name
        'Demo'
    """
    if isinstance(gnn, Path):
        text = gnn.read_text(encoding="utf-8")
    elif isinstance(gnn, str):
        # Guard against long markdown strings being mistaken for paths
        # (``Path(long_str).is_file()`` raises OSError: file name too
        # long on macOS and Linux). Only probe the filesystem when the
        # argument is short and lacks newlines.
        looks_like_path = "\n" not in gnn and len(gnn) < 4096 and (Path(gnn).suffix or "/" in gnn)
        if looks_like_path and Path(gnn).is_file():
            text = Path(gnn).read_text(encoding="utf-8")
        else:
            text = gnn  # Raw markdown string.
    else:
        raise TypeError(f"parse_gnn: expected str or Path, got {type(gnn).__name__}")

    model = ReverseGNNModel()
    sections = _split_sections(text)

    def first(name: str) -> str | None:
        """Return the first body under section ``name``, or ``None`` if absent."""
        bodies = sections.get(name)
        return bodies[0] if bodies else None

    def last(name: str) -> str | None:
        """Return the last body under section ``name``, or ``None`` if absent."""
        bodies = sections.get(name)
        return bodies[-1] if bodies else None

    # Model name: prefer the upstream ``## ModelName`` section.
    body = first("ModelName") or first("GNNSection")
    if body:
        raw = body.strip().splitlines()
        if raw:
            model.raw_model_name = raw[0].strip()
            model.model_name = _sanitize_identifier(raw[0].strip())

    declarations = [body for body in map(first, _DECLARATION_SECTIONS) if body]
    if declarations:
        _parse_state_space_block("\n".join(declarations), model)

    body = first("ActInfOntologyAnnotation")
    if body:
        _parse_ontology_annotation(body, model)

    # The authoritative gnn-matrices fence overrides the parameterization;
    # read it first so the projection skips the matrices it supplies.
    fenced = _read_matrices_fenced_block(text)

    if set(fenced) == {"A", "B", "C", "D"}:
        model.matrix_source = "fenced"
    body = first("InitialParameterization")
    if body and model.matrix_source != "fenced":
        _parse_initial_parameterization(body, model, fenced=frozenset(fenced))

    # COGANT extended section with the human-readable state variable
    # table (header is ``## State Space``). This gives the planner
    # meaningful Python identifier roots. Use first() — the last
    # ``## State Space`` occurrence may be the matrices section.
    body = first("State Space")
    if body:
        _parse_state_variables_extended(body, model)

    # For connections, the upstream ``## Connections`` is authoritative.
    # The COGANT extended ``## Connections`` subsection (Contains /
    # Reads / Writes tables) comes later and has the same header; we
    # only want the first (upstream) occurrence for arrow-syntax edges.
    body = first("Connections")
    if body:
        _parse_connections(body, model)

    # Apply the authoritative A/B/C/D from the fenced gnn-matrices block
    # if present — it overrides the aggregate forms derived above.
    for key, value in fenced.items():
        setattr(model, key, value)
    _normalize_reverse_dimensions(model)

    logger.info(
        "Parsed GNN model %r: n_states=%d n_obs=%d n_actions=%d",
        model.model_name,
        model.n_states,
        model.n_obs,
        model.n_actions,
    )
    return model

plan_package(model, *, expected_roles=None)

Build a :class:PackagePlan from a :class:ReverseGNNModel.

Each hidden-state slot becomes a State dataclass attribute; each observation slot becomes an observe_* function; each action slot becomes an act_* function; etc. Naming prefers the human-readable labels from the extended state-variable table when available, else falls back to the slot name.

Parameters:

Name Type Description Default
model ReverseGNNModel

Parsed GNN model.

required
expected_roles Mapping[str, int] | None

Optional source semantic role multiset. When provided, POLICY / CONSTRAINT / CONTEXT scaffolds are added only for deficits relative to that target. When omitted, the target is derived from the parsed GNN itself.

None
Source code in py/cogant/reverse/planner.py
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
def plan_package(
    model: ReverseGNNModel,
    *,
    expected_roles: Mapping[str, int] | None = None,
) -> PackagePlan:
    """Build a :class:`PackagePlan` from a :class:`ReverseGNNModel`.

    Each hidden-state slot becomes a State dataclass attribute; each
    observation slot becomes an ``observe_*`` function; each action
    slot becomes an ``act_*`` function; etc. Naming prefers the
    human-readable labels from the extended state-variable table when
    available, else falls back to the slot name.

    Args:
        model: Parsed GNN model.
        expected_roles: Optional source semantic role multiset. When
            provided, POLICY / CONSTRAINT / CONTEXT scaffolds are added
            only for deficits relative to that target. When omitted,
            the target is derived from the parsed GNN itself.
    """
    plan = PackagePlan(
        package_name=model.model_name or "cogant_model",
        raw_model_name=model.raw_model_name or model.model_name or "cogant_model",
    )
    used_names: dict[str, int] = {}

    # Hidden states → State attributes in state.py
    for i, slot in enumerate(model.hidden_states):
        human = model.human_names.get(slot, "")
        ident = _to_identifier(human, slot)
        ident = _reserved_avoid(ident, used_names)
        gnn_type = model.types.get(slot, "int")
        py_type = _python_type_for(gnn_type)
        card = model.cardinalities.get(slot, 0)
        d_mass = model.D[i] if i < len(model.D) else 0.0
        init = _default_value_for(py_type, card, d_mass)
        node = NodePlan(
            slot=slot,
            name=ident,
            role="HIDDEN_STATE",
            python_type=py_type,
            module="state.py",
            cardinality=card,
            initial_value=init,
        )
        plan.state_vars.append(node)
        plan.nodes.append(node)

    # Observations → get_<name> functions in observe.py.
    #
    # Naming rationale: the forward ObservationRule keyword match fires
    # on ``get/read/fetch/query/display/show/status/info/list``. Prefix
    # every synthesized observation with ``get_`` so the keyword hit is
    # deterministic regardless of whether the edge extractor later
    # records a READS edge for the function body. This gives the
    # reverse → forward round-trip a strong, first-class lexical signal
    # that cannot be lost to edge-extraction noise.
    for _i, slot in enumerate(model.observations):
        human = model.human_names.get(slot, "")
        ident = _to_identifier(human, slot)
        ident = _reserved_avoid(f"get_{ident}" if ident == slot else f"get_{ident}", used_names)
        gnn_type = model.types.get(slot, "int")
        py_type = _python_type_for(gnn_type)
        card = model.cardinalities.get(slot, 0)
        node = NodePlan(
            slot=slot,
            name=ident,
            role="OBSERVATION",
            python_type=py_type,
            module="observe.py",
            cardinality=card,
            initial_value="0.0",
        )
        plan.obs_functions.append(node)
        plan.nodes.append(node)

    # Actions → update_<name> functions in act.py.
    #
    # Naming rationale: the forward ActionRule keyword match fires on
    # ``set/update/create/delete/send/push/execute/run/process/handle/
    # dispatch/encode/decode/dump/load``. Prefix every synthesized action
    # with ``update_`` so the keyword hit is deterministic regardless of
    # whether the edge extractor records a WRITES edge for the function
    # body. This matches the symmetry with ``get_`` on the observation
    # side and guarantees the forward pass will classify the right
    # number of actions on the synthesized package.
    for _i, slot in enumerate(model.actions):
        human = model.human_names.get(slot, "")
        ident = _to_identifier(human, slot)
        ident = _reserved_avoid(
            f"update_{ident}" if ident == slot else f"update_{ident}", used_names
        )
        gnn_type = model.types.get(slot, "int")
        py_type = _python_type_for(gnn_type)
        card = model.cardinalities.get(slot, 0)
        node = NodePlan(
            slot=slot,
            name=ident,
            role="ACTION",
            python_type=py_type,
            module="act.py",
            cardinality=card,
            initial_value="0",
        )
        plan.action_methods.append(node)
        plan.nodes.append(node)

    # Policies → policy_<name> functions in policy.py
    for slot in model.policies:
        human = model.human_names.get(slot, "")
        ident = _to_identifier(human, slot)
        ident = _reserved_avoid(f"pi_{ident}" if ident == slot else ident, used_names)
        node = NodePlan(
            slot=slot,
            name=ident,
            role="POLICY",
            python_type="str",
            module="policy.py",
            cardinality=0,
            initial_value='""',
        )
        plan.policy_functions.append(node)
        plan.nodes.append(node)

    # Constraints → check_<name> functions in constraints.py
    for slot in model.constraints:
        human = model.human_names.get(slot, "")
        ident = _to_identifier(human, slot)
        ident = _reserved_avoid(f"cnst_{ident}" if ident == slot else ident, used_names)
        node = NodePlan(
            slot=slot,
            name=ident,
            role="CONSTRAINT",
            python_type="bool",
            module="constraints.py",
            cardinality=0,
            initial_value="True",
        )
        plan.constraint_checks.append(node)
        plan.nodes.append(node)

    # Context functions — derived from ontology annotations that name
    # a variable as ``Context`` or ``Time``. These are separate from
    # the scaffold context classes emitted below; the two populations
    # are combined by the synthesizer when rendering ``context.py``.
    for var, concept in model.annotations.items():
        if var in (
            model.hidden_states
            + model.observations
            + model.actions
            + model.policies
            + model.constraints
        ):
            continue
        lc = concept.lower()
        if "context" in lc or lc == "time":
            ident = _to_identifier(var, var)
            ident = _reserved_avoid(f"context_{ident}", used_names)
            node = NodePlan(
                slot=var,
                name=ident,
                role="CONTEXT",
                python_type="dict",
                module="context.py",
                cardinality=0,
                initial_value="{}",
            )
            plan.context_functions.append(node)
            plan.nodes.append(node)

    plan.target_role_counts = (
        _normalise_role_counts(expected_roles)
        if expected_roles is not None
        else _role_counts_from_model(model)
    )

    # Fill only declared role deficits.  These are explicit compatibility
    # scaffolds, not unlabelled runtime helpers: the generated manifest names
    # them and the forward role audit can distinguish them from source-backed
    # definitions.  In particular, an ExpectedFreeEnergy annotation needs a
    # policy-shaped selector to survive a reverse/forward round trip.
    plan.scaffold_constraint_checks = _build_scaffold_constraints(plan, used_names)
    plan.scaffold_policy_functions = _build_scaffold_policies(plan, used_names)
    plan.scaffold_context_classes = _build_scaffold_contexts(plan, used_names)

    plan.has_A_matrix = bool(model.A) and any(any(row) for row in model.A)
    plan.has_B_tensor = bool(model.B)
    plan.has_C_vector = bool(model.C)
    plan.has_D_vector = bool(model.D)
    plan.state_dimension = model.n_states
    plan.observation_dimension = model.n_obs
    plan.action_dimension = model.n_actions

    logger.info(
        "Planned package %r: %d state vars, %d obs, %d actions, %d policies, "
        "%d constraints, %d contexts, scaffold(constraints=%d, policies=%d, "
        "contexts=%d)",
        plan.package_name,
        len(plan.state_vars),
        len(plan.obs_functions),
        len(plan.action_methods),
        len(plan.policy_functions),
        len(plan.constraint_checks),
        len(plan.context_functions),
        len(plan.scaffold_constraint_checks),
        len(plan.scaffold_policy_functions),
        len(plan.scaffold_context_classes),
    )
    return plan

synthesize_package(plan, model, output_dir)

Emit a full Python package to output_dir from plan.

The function creates a package directory named plan.package_name inside output_dir so that the parent directory can contain multiple synthesized models side by side. Inside the package it writes state.py, observe.py, act.py, policy.py, constraints.py, matrices.py, main.py, and a smoke test under tests/.

Parameters:

Name Type Description Default
plan PackagePlan

Package plan produced by :func:plan_package.

required
model ReverseGNNModel

Parsed GNN model (provides matrix values).

required
output_dir str | Path

Directory where the package is created. The directory is created if it does not exist.

required

Returns:

Type Description
Path

The path to the created package directory (``output_dir /

Path

package_name``).

Source code in py/cogant/reverse/synthesizer.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
def synthesize_package(
    plan: PackagePlan,
    model: ReverseGNNModel,
    output_dir: str | Path,
) -> Path:
    """Emit a full Python package to ``output_dir`` from ``plan``.

    The function creates a package directory named ``plan.package_name``
    **inside** ``output_dir`` so that the parent directory can contain
    multiple synthesized models side by side. Inside the package it
    writes ``state.py``, ``observe.py``, ``act.py``, ``policy.py``,
    ``constraints.py``, ``matrices.py``, ``main.py``, and a smoke
    test under ``tests/``.

    Args:
        plan: Package plan produced by :func:`plan_package`.
        model: Parsed GNN model (provides matrix values).
        output_dir: Directory where the package is created. The
            directory is created if it does not exist.

    Returns:
        The path to the created package directory (``output_dir /
        package_name``).
    """
    output_path = Path(output_dir).expanduser().resolve()
    package_path = output_path / plan.package_name
    package_path.mkdir(parents=True, exist_ok=True)
    tests_path = package_path / "tests"
    tests_path.mkdir(parents=True, exist_ok=True)

    semantic_targets = _semantic_role_targets(plan)
    manifest = {
        "schema": "cogant.reverse.semantic_targets.v1",
        "target_role_counts": dict(plan.target_role_counts),
        "semantic_targets": semantic_targets,
    }
    files = {
        package_path / ".gitignore": "tests\n.pytest_cache\n__pycache__\n*.pyc\n",
        package_path / SEMANTIC_TARGETS_MANIFEST: json.dumps(manifest, indent=2, sort_keys=True)
        + "\n",
        package_path / "__init__.py": _render_package_init(plan),
        package_path / "state.py": _render_state_module(plan),
        package_path / "observe.py": _render_observe_module(plan),
        package_path / "act.py": _render_act_module(plan),
        package_path / "policy.py": _render_policy_module(plan),
        package_path / "constraints.py": _render_constraints_module(plan),
        package_path / "context.py": _render_context_module(plan),
        package_path / "matrices.py": render_matrices_module(model),
        package_path / "main.py": _render_main_module(plan),
        tests_path / "__init__.py": '"""Test package for the synthesized model."""\n',
        tests_path / "test_smoke.py": _render_test_smoke(
            plan,
            has_actions=model.n_actions > 0,
            executable=bool(model.A and model.B and model.C and model.D),
        ),
    }

    for path, content in files.items():
        path.write_text(content, encoding="utf-8")
        logger.debug("Wrote %s (%d bytes)", path, len(content))

    logger.info(
        "Synthesized package %r at %s (%d files, %d state vars, %d obs, %d actions)",
        plan.package_name,
        package_path,
        len(files),
        len(plan.state_vars),
        len(plan.obs_functions),
        len(plan.action_methods),
    )
    return package_path

Parser

GNN markdown → ReverseGNNModel. Tolerates both the upstream canonical syntax and the COGANT extended sections.

cogant.reverse.parser

GNN markdown → :class:ReverseGNNModel parser.

This module is the inverse of :mod:cogant.gnn.formatter. It reads a GNN markdown file (COGANT schema GNN v2.0.0, including the bundle emitted by current COGANT) and extracts the structured content required to synthesize a Python package: the state space, observation modalities, actions, policies, constraints, ontology annotations, and A/B/C/D matrices.

Connection and section parsing accepts bare upstream connection syntax (D_f0>s_f0), grouped multi-source edges ((A_m0, s_f0)>o_m0), bare comma sources (A_m0,s_f0>o_m0), and parenthesised examples ((D_f0) > (s_f0)), both bracketed matrix blocks (A[[rows=3][cols=2]]) and InitialParameterization tuple blocks (D_f0={ (0.3, 0.3, 0.4) }), and any mix of COGANT's extended sections alongside the upstream header. Upstream files keep their own variable names (s, o, u, s_beliefs), trailing # comments, multi-line A={ ... } parameter literals, and action-major B slices. Sections the parser does not recognise are ignored rather than causing an error, so the parser tolerates future COGANT extensions.

Matrices the source does not provide are projected from its factorized declarations and the model is marked degraded with diagnostics; every allocation sized by source integers is bounded by :data:MAX_REVERSE_MATRIX_ELEMENTS.

The parser does not consult the ProgramGraph; it relies entirely on the markdown text. This keeps the reverse pipeline standalone — a GNN file alone is sufficient to produce a ReverseGNNModel.

MAX_REVERSE_MATRIX_ELEMENTS = 2000000 module-attribute

Largest number of cells a single A/B/C/D tensor may allocate while parsing.

Every dimension the parser allocates from — identity(r,c,d) shorthands, fenced B[[rows=..][cols=..][depth=..]] headers, and the Cartesian product of declared factor cardinalities — is an integer taken from the GNN text, which the /reverse endpoint accepts from untrusted clients. A ~100-byte document could otherwise request billions of cells. The budget is checked before the nested lists are built; exceeding it raises :class:ReverseModelError. Callers that knowingly reverse larger models may raise this module attribute.

ReverseGNNModel dataclass

Parsed GNN model ready for planning and synthesis.

Attributes:

Name Type Description
model_name str

The ## ModelName value (sanitized upstream identifier, safe for use as a Python package name).

raw_model_name str

The unsanitized ## ModelName value as it appears in the markdown (may contain non-identifier chars).

hidden_states list[str]

Names of hidden-state factors (s_f0, s_f1, ... in COGANT bundles; s or any HiddenState-annotated name upstream). Each entry is the source variable name.

observations list[str]

Names of observation modalities (o_m0, o_m1, ... / o).

actions list[str]

Names of action/control factors (u_c0, u_c1, ... / u).

policies list[str]

Names of policy variables (rare; usually empty).

constraints list[str]

Names of constraint/preference variables.

annotations dict[str, str]

Map from variable name → ontology concept ("s_f0" -> "HiddenState", "A_m0" -> "LikelihoodMatrix", etc). Populated from ## ActInfOntologyAnnotation and the extended ## State Space section.

cardinalities dict[str, int]

Map from variable name → categorical dimension (from ## StateSpaceBlock like s_f0[10,1,type=int]).

types dict[str, str]

Map from variable name → upstream type string (int, float, bool).

A list[list[float]]

Likelihood matrix P(o | s) of shape [n_obs x n_states]. Populated from ## InitialParameterization or from the bracket-style A matrix header in the GNN file if present. May be empty when the model has no observations.

B list[list[list[float]]]

Transition tensor P(s' | s, a) of shape [n_states x n_states x n_actions]. May be empty.

C list[float]

Log-preference vector over observations of shape [n_obs].

D list[float]

Prior distribution over hidden states of shape [n_states].

connections list[str]

Raw list of arrow-syntax connection strings from ## Connections (used for debugging and topology checks).

human_names dict[str, str]

Map from s_f0-style slot to the human-readable name pulled from ## State Space → ### State Variables. Used by the planner to produce meaningful Python identifiers.

Source code in py/cogant/reverse/parser.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
@dataclass
class ReverseGNNModel:
    """Parsed GNN model ready for planning and synthesis.

    Attributes:
        model_name: The ``## ModelName`` value (sanitized upstream
            identifier, safe for use as a Python package name).
        raw_model_name: The unsanitized ``## ModelName`` value as it
            appears in the markdown (may contain non-identifier chars).
        hidden_states: Names of hidden-state factors (``s_f0``, ``s_f1``,
            ... in COGANT bundles; ``s`` or any ``HiddenState``-annotated
            name upstream). Each entry is the source variable name.
        observations: Names of observation modalities
            (``o_m0``, ``o_m1``, ... / ``o``).
        actions: Names of action/control factors (``u_c0``, ``u_c1``, ... /
            ``u``).
        policies: Names of policy variables (rare; usually empty).
        constraints: Names of constraint/preference variables.
        annotations: Map from variable name → ontology concept
            (``"s_f0" -> "HiddenState"``, ``"A_m0" -> "LikelihoodMatrix"``,
            etc). Populated from ``## ActInfOntologyAnnotation`` and the
            extended ``## State Space`` section.
        cardinalities: Map from variable name → categorical dimension
            (from ``## StateSpaceBlock`` like ``s_f0[10,1,type=int]``).
        types: Map from variable name → upstream type string
            (``int``, ``float``, ``bool``).
        A: Likelihood matrix ``P(o | s)`` of shape ``[n_obs x n_states]``.
            Populated from ``## InitialParameterization`` or from the
            bracket-style ``A`` matrix header in the GNN file if present.
            May be empty when the model has no observations.
        B: Transition tensor ``P(s' | s, a)`` of shape
            ``[n_states x n_states x n_actions]``. May be empty.
        C: Log-preference vector over observations of shape ``[n_obs]``.
        D: Prior distribution over hidden states of shape ``[n_states]``.
        connections: Raw list of arrow-syntax connection strings from
            ``## Connections`` (used for debugging and topology checks).
        human_names: Map from ``s_f0``-style slot to the human-readable
            name pulled from ``## State Space`` → ``### State Variables``.
            Used by the planner to produce meaningful Python identifiers.
    """

    model_name: str = "cogant_model"
    raw_model_name: str = "cogant_model"
    hidden_states: list[str] = field(default_factory=list)
    observations: list[str] = field(default_factory=list)
    actions: list[str] = field(default_factory=list)
    policies: list[str] = field(default_factory=list)
    constraints: list[str] = field(default_factory=list)
    annotations: dict[str, str] = field(default_factory=dict)
    cardinalities: dict[str, int] = field(default_factory=dict)
    types: dict[str, str] = field(default_factory=dict)
    A: list[list[float]] = field(default_factory=list)
    B: list[list[list[float]]] = field(default_factory=list)
    C: list[float] = field(default_factory=list)
    D: list[float] = field(default_factory=list)
    connections: list[str] = field(default_factory=list)
    human_names: dict[str, str] = field(default_factory=dict)
    degraded: bool = False
    diagnostics: list[str] = field(default_factory=list)
    matrix_source: Literal["parameterization", "fenced"] = "parameterization"

    @property
    def n_hidden_factors(self) -> int:
        """Number of named hidden-state factors in the source ontology."""
        return len(self.hidden_states)

    @property
    def n_states(self) -> int:
        """Number of hidden dimensions represented by this model.

        Matrix dimensions are authoritative when present.  Before matrices
        are parsed, retain the declared factor count so callers can inspect
        a syntactically valid but not-yet-executable model.
        """
        if self.matrix_source == "fenced":
            return len(self.D)
        if self.D:
            return len(self.D)
        if self.B:
            return len(self.B)
        return len(self.hidden_states)

    @property
    def n_obs(self) -> int:
        """Number of observation dimensions represented by this model."""
        if self.matrix_source == "fenced":
            return len(self.C)
        if self.C:
            return len(self.C)
        if self.A:
            return len(self.A)
        return len(self.observations)

    @property
    def n_actions(self) -> int:
        """Number of action dimensions represented by this model."""
        if self.B and self.B[0] and self.B[0][0]:
            return len(self.B[0][0])
        return len(self.actions)

    def validate(self) -> list[str]:
        """Return evidence and dimension errors without inventing values."""
        errors: list[str] = []
        if self.hidden_states and not self.D:
            errors.append("D is required when hidden-state variables are declared")
        if self.observations and not self.C:
            errors.append("C is required when observation variables are declared")
        # B is indexed by hidden state, so it only exists when both hidden
        # states and actions are declared.  A stateless model whose callables
        # are ACTION roles has no transition tensor (the GNN validator
        # requires B to be empty when there are no hidden states).
        if self.hidden_states and self.actions and not self.B:
            errors.append("B is required when hidden-state and action variables are declared")
        if self.D and any(value < 0 for value in self.D):
            errors.append("D contains a negative probability")
        return errors

n_actions property

Number of action dimensions represented by this model.

n_hidden_factors property

Number of named hidden-state factors in the source ontology.

n_obs property

Number of observation dimensions represented by this model.

n_states property

Number of hidden dimensions represented by this model.

Matrix dimensions are authoritative when present. Before matrices are parsed, retain the declared factor count so callers can inspect a syntactically valid but not-yet-executable model.

validate()

Return evidence and dimension errors without inventing values.

Source code in py/cogant/reverse/parser.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def validate(self) -> list[str]:
    """Return evidence and dimension errors without inventing values."""
    errors: list[str] = []
    if self.hidden_states and not self.D:
        errors.append("D is required when hidden-state variables are declared")
    if self.observations and not self.C:
        errors.append("C is required when observation variables are declared")
    # B is indexed by hidden state, so it only exists when both hidden
    # states and actions are declared.  A stateless model whose callables
    # are ACTION roles has no transition tensor (the GNN validator
    # requires B to be empty when there are no hidden states).
    if self.hidden_states and self.actions and not self.B:
        errors.append("B is required when hidden-state and action variables are declared")
    if self.D and any(value < 0 for value in self.D):
        errors.append("D contains a negative probability")
    return errors

ReverseModelError

Bases: ValueError

Raised when a parsed model cannot provide executable semantics.

Source code in py/cogant/reverse/parser.py
46
47
48
49
class ReverseModelError(ValueError):
    """Raised when a parsed model cannot provide executable semantics."""

    code = "INVALID_REVERSE_MODEL"

parse_gnn(gnn)

Parse a GNN markdown file or string into a :class:ReverseGNNModel.

Parameters:

Name Type Description Default
gnn str | Path

Either a path to a .gnn.md file or a raw markdown string. If the argument is a string that does not point to an existing file, it is treated as the raw markdown text.

required

Returns:

Type Description
ReverseGNNModel

A populated :class:ReverseGNNModel. Fields that cannot be parsed

ReverseGNNModel

from the source remain empty. Consumers must treat an incomplete

ReverseGNNModel

model as invalid evidence rather than filling missing semantics.

Example

from cogant.reverse.parser import parse_gnn gnn = '''## ModelName ... Demo ... ... ## StateSpaceBlock ... s_f0[2,1,type=int] ... o_m0[2,1,type=int] ... ''' model = parse_gnn(gnn) model.raw_model_name 'Demo'

Source code in py/cogant/reverse/parser.py
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
def parse_gnn(gnn: str | Path) -> ReverseGNNModel:
    """Parse a GNN markdown file or string into a :class:`ReverseGNNModel`.

    Args:
        gnn: Either a path to a ``.gnn.md`` file or a raw markdown
            string. If the argument is a string that does not point to
            an existing file, it is treated as the raw markdown text.

    Returns:
        A populated :class:`ReverseGNNModel`. Fields that cannot be parsed
        from the source remain empty. Consumers must treat an incomplete
        model as invalid evidence rather than filling missing semantics.

    Example:
        >>> from cogant.reverse.parser import parse_gnn
        >>> gnn = '''## ModelName
        ... Demo
        ...
        ... ## StateSpaceBlock
        ... s_f0[2,1,type=int]
        ... o_m0[2,1,type=int]
        ... '''
        >>> model = parse_gnn(gnn)
        >>> model.raw_model_name
        'Demo'
    """
    if isinstance(gnn, Path):
        text = gnn.read_text(encoding="utf-8")
    elif isinstance(gnn, str):
        # Guard against long markdown strings being mistaken for paths
        # (``Path(long_str).is_file()`` raises OSError: file name too
        # long on macOS and Linux). Only probe the filesystem when the
        # argument is short and lacks newlines.
        looks_like_path = "\n" not in gnn and len(gnn) < 4096 and (Path(gnn).suffix or "/" in gnn)
        if looks_like_path and Path(gnn).is_file():
            text = Path(gnn).read_text(encoding="utf-8")
        else:
            text = gnn  # Raw markdown string.
    else:
        raise TypeError(f"parse_gnn: expected str or Path, got {type(gnn).__name__}")

    model = ReverseGNNModel()
    sections = _split_sections(text)

    def first(name: str) -> str | None:
        """Return the first body under section ``name``, or ``None`` if absent."""
        bodies = sections.get(name)
        return bodies[0] if bodies else None

    def last(name: str) -> str | None:
        """Return the last body under section ``name``, or ``None`` if absent."""
        bodies = sections.get(name)
        return bodies[-1] if bodies else None

    # Model name: prefer the upstream ``## ModelName`` section.
    body = first("ModelName") or first("GNNSection")
    if body:
        raw = body.strip().splitlines()
        if raw:
            model.raw_model_name = raw[0].strip()
            model.model_name = _sanitize_identifier(raw[0].strip())

    declarations = [body for body in map(first, _DECLARATION_SECTIONS) if body]
    if declarations:
        _parse_state_space_block("\n".join(declarations), model)

    body = first("ActInfOntologyAnnotation")
    if body:
        _parse_ontology_annotation(body, model)

    # The authoritative gnn-matrices fence overrides the parameterization;
    # read it first so the projection skips the matrices it supplies.
    fenced = _read_matrices_fenced_block(text)

    if set(fenced) == {"A", "B", "C", "D"}:
        model.matrix_source = "fenced"
    body = first("InitialParameterization")
    if body and model.matrix_source != "fenced":
        _parse_initial_parameterization(body, model, fenced=frozenset(fenced))

    # COGANT extended section with the human-readable state variable
    # table (header is ``## State Space``). This gives the planner
    # meaningful Python identifier roots. Use first() — the last
    # ``## State Space`` occurrence may be the matrices section.
    body = first("State Space")
    if body:
        _parse_state_variables_extended(body, model)

    # For connections, the upstream ``## Connections`` is authoritative.
    # The COGANT extended ``## Connections`` subsection (Contains /
    # Reads / Writes tables) comes later and has the same header; we
    # only want the first (upstream) occurrence for arrow-syntax edges.
    body = first("Connections")
    if body:
        _parse_connections(body, model)

    # Apply the authoritative A/B/C/D from the fenced gnn-matrices block
    # if present — it overrides the aggregate forms derived above.
    for key, value in fenced.items():
        setattr(model, key, value)
    _normalize_reverse_dimensions(model)

    logger.info(
        "Parsed GNN model %r: n_states=%d n_obs=%d n_actions=%d",
        model.model_name,
        model.n_states,
        model.n_obs,
        model.n_actions,
    )
    return model

Callable

Runtime-callable closures built directly from a ReverseGNNModel. No code generation, no exec() — plain Python function calls.

cogant.reverse.callable

Parsed GNN matrix operations using the shared categorical numerical kernel.

MatrixFunctions

Copied source matrices with categorical filtering and policy operations.

Source code in py/cogant/reverse/callable.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class MatrixFunctions:
    """Copied source matrices with categorical filtering and policy operations."""

    def __init__(self, model: ReverseGNNModel) -> None:
        _validate_matrix_semantics(model)
        n_states = model.n_states
        n_obs = model.n_obs
        n_actions = model.n_actions

        A = [list(row) for row in model.A]
        B = [[list(cell) for cell in row] for row in model.B]
        C = list(model.C)
        D = list(model.D)

        self._A = A
        self._B = B
        self._C = C
        self._D = D
        self._n_states = n_states
        self._n_obs = n_obs
        self._n_actions = n_actions

        self.A = A
        self.B = B
        self.C = C
        self.D = D

    def _categorical(self) -> CategoricalModel:
        return CategoricalModel(self.A, self.B, self.C, self.D)

    def likelihood(self, state_dist: list[float]) -> list[float]:
        return self._categorical().observe(state_dist)

    def transition(self, state_dist: list[float], action: int = 0) -> list[float]:
        return self._categorical().predict(state_dist, action)

    def preference_score(self, obs_dist: list[float]) -> float:
        return self._categorical().preference_score(obs_dist)

    def prior(self) -> list[float]:
        """Return D vector (initial state prior)."""
        return list(self._D)

    def expected_free_energy(self, state_dist: list[float], action: int) -> float:
        """Evaluate one-step outcome risk plus expected likelihood ambiguity."""
        return self._categorical().score(state_dist, [action])

    def score_preference_gradient(self, state_dist: list[float], policy: list[int]) -> list[float]:
        """Return fixed-policy score sensitivity along the C observation axis."""
        return self._categorical().score_preference_gradient(state_dist, policy)

    def best_action(self, state_dist: list[float]) -> int:
        """Return argmin EFE over the declared action axis."""
        if self._n_actions == 0:
            raise ValueError("policy selection requires at least one action")
        best_a = 0
        best_efe = float("inf")
        for a in range(self._n_actions):
            efe = self.expected_free_energy(state_dist, a)
            if efe < best_efe:
                best_efe = efe
                best_a = a
        return best_a

    @classmethod
    def from_gnn_text(cls, gnn_text: str) -> MatrixFunctions:
        model = parse_gnn(gnn_text)
        return cls(model)

best_action(state_dist)

Return argmin EFE over the declared action axis.

Source code in py/cogant/reverse/callable.py
61
62
63
64
65
66
67
68
69
70
71
72
def best_action(self, state_dist: list[float]) -> int:
    """Return argmin EFE over the declared action axis."""
    if self._n_actions == 0:
        raise ValueError("policy selection requires at least one action")
    best_a = 0
    best_efe = float("inf")
    for a in range(self._n_actions):
        efe = self.expected_free_energy(state_dist, a)
        if efe < best_efe:
            best_efe = efe
            best_a = a
    return best_a

expected_free_energy(state_dist, action)

Evaluate one-step outcome risk plus expected likelihood ambiguity.

Source code in py/cogant/reverse/callable.py
53
54
55
def expected_free_energy(self, state_dist: list[float], action: int) -> float:
    """Evaluate one-step outcome risk plus expected likelihood ambiguity."""
    return self._categorical().score(state_dist, [action])

prior()

Return D vector (initial state prior).

Source code in py/cogant/reverse/callable.py
49
50
51
def prior(self) -> list[float]:
    """Return D vector (initial state prior)."""
    return list(self._D)

score_preference_gradient(state_dist, policy)

Return fixed-policy score sensitivity along the C observation axis.

Source code in py/cogant/reverse/callable.py
57
58
59
def score_preference_gradient(self, state_dist: list[float], policy: list[int]) -> list[float]:
    """Return fixed-policy score sensitivity along the C observation axis."""
    return self._categorical().score_preference_gradient(state_dist, policy)

Planner

Planning step that turns a parsed model into a synthesis plan (names, dimensions, helper signatures).

cogant.reverse.planner

Package planner: :class:ReverseGNNModel → :class:PackagePlan.

This module decides how each semantic role in a GNN model becomes a Python construct. The mapping is intentionally simple and mechanical so the forward COGANT pipeline can recognise the resulting code:

=============== ======================================================== GNN role Python target =============== ======================================================== HIDDEN_STATE @dataclass field on State in state.py OBSERVATION def observe_<name>(state) in observe.py ACTION def act_<name>(state) in act.py POLICY def policy_<name>(state, obs) in policy.py CONSTRAINT def check_<name>(state) in constraints.py PREFERENCE def prefer_<name>(obs) in constraints.py =============== ========================================================

This mapping is designed so that when COGANT's forward pipeline parses the synthesized package, it naturally classifies the dataclass fields as hidden-state variables (mutated inside class methods), the observe_* functions as observation modalities (pure reads over state), the act_* functions as actions (WRITES edges to state), and the policy_* / check_* functions as POLICY/CONSTRAINT mappings. This gives the round-trip the best chance of role multiset equality.

Human naming

Wherever possible the planner prefers human-readable identifiers extracted from the GNN's COGANT-extended state-variable table rather than the opaque upstream slot names (s_f0, o_m1). When no human name is available, the slot name is used verbatim. All final identifiers are sanitized to valid Python identifiers.

NodePlan dataclass

Plan for a single GNN node → Python construct.

Attributes:

Name Type Description
slot str

The GNN slot identifier (s_f0, o_m1, u_c2).

name str

The Python identifier to emit (derived from the human name when available, else the slot name).

role str

The MappingKind label (e.g. HIDDEN_STATE, OBSERVATION, ACTION, POLICY, CONSTRAINT).

python_type str

The Python type annotation string (float, int, bool, etc.).

module str

The module file this node is emitted into (state.py, observe.py, act.py, ...).

cardinality int

Categorical cardinality from the GNN declaration, or 0 if unknown. Used for default values and type hints.

initial_value str

Source-level literal for the initial value ("0.0", "False", "0").

Source code in py/cogant/reverse/planner.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
@dataclass
class NodePlan:
    """Plan for a single GNN node → Python construct.

    Attributes:
        slot: The GNN slot identifier (``s_f0``, ``o_m1``, ``u_c2``).
        name: The Python identifier to emit (derived from the human
            name when available, else the slot name).
        role: The MappingKind label (e.g. ``HIDDEN_STATE``, ``OBSERVATION``,
            ``ACTION``, ``POLICY``, ``CONSTRAINT``).
        python_type: The Python type annotation string (``float``,
            ``int``, ``bool``, etc.).
        module: The module file this node is emitted into
            (``state.py``, ``observe.py``, ``act.py``, ...).
        cardinality: Categorical cardinality from the GNN declaration,
            or 0 if unknown. Used for default values and type hints.
        initial_value: Source-level literal for the initial value
            (``"0.0"``, ``"False"``, ``"0"``).
    """

    slot: str = ""
    name: str = ""
    role: str = ""
    python_type: str = "float"
    module: str = ""
    cardinality: int = 0
    initial_value: str = "0.0"

PackagePlan dataclass

Full synthesis plan for a GNN → Python package.

Attributes:

Name Type Description
package_name str

Sanitized Python package name (derived from the GNN ## ModelName value).

raw_model_name str

Original unsanitized model name for docstrings.

nodes list[NodePlan]

All node plans in declaration order.

state_vars list[NodePlan]

Subset of nodes with role HIDDEN_STATE. Emitted as attributes on the State dataclass.

obs_functions list[NodePlan]

Subset with role OBSERVATION.

action_methods list[NodePlan]

Subset with role ACTION.

policy_functions list[NodePlan]

Subset with role POLICY (authoritative policies declared in the GNN). These are rare — most GNNs have no explicit pi_c* declarations — and the reverse pipeline additionally synthesizes scaffolding policies (see scaffold_policy_functions).

constraint_checks list[NodePlan]

Subset with role CONSTRAINT / PREFERENCE (authoritative constraints declared in the GNN, typically one per C_m*=PreferenceVector annotation).

context_functions list[NodePlan]

Subset with role CONTEXT derived from the parsed GNN (rare; populated when the ontology block annotates a variable as Context or Time).

target_role_counts dict[str, int]

Expected semantic role multiset for the synthesized package. Round-trip verification passes the source roles here so generated scaffolds are deficit-based rather than fixed boilerplate.

scaffold_constraint_checks list[NodePlan]

Additional check_* functions emitted only when target_role_counts requires more CONSTRAINT roles than the parsed GNN declares.

scaffold_policy_functions list[NodePlan]

Additional top-level POLICY scaffolds emitted only when target POLICY roles remain after authoritative policy functions and the optional policy selector helper.

scaffold_context_classes list[NodePlan]

Additional top-level CONTEXT classes emitted only when source roles include CONTEXT deficits.

has_A_matrix bool

True if the parsed A matrix has non-zero rows.

has_B_tensor bool

True if the parsed B tensor is non-trivial.

has_C_vector bool

True if the parsed C vector is non-empty.

has_D_vector bool

True if the parsed D vector is non-empty.

Source code in py/cogant/reverse/planner.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
@dataclass
class PackagePlan:
    """Full synthesis plan for a GNN → Python package.

    Attributes:
        package_name: Sanitized Python package name (derived from the
            GNN ``## ModelName`` value).
        raw_model_name: Original unsanitized model name for docstrings.
        nodes: All node plans in declaration order.
        state_vars: Subset of ``nodes`` with role ``HIDDEN_STATE``.
            Emitted as attributes on the ``State`` dataclass.
        obs_functions: Subset with role ``OBSERVATION``.
        action_methods: Subset with role ``ACTION``.
        policy_functions: Subset with role ``POLICY`` (authoritative
            policies declared in the GNN). These are rare — most GNNs
            have no explicit ``pi_c*`` declarations — and the reverse
            pipeline additionally synthesizes scaffolding policies (see
            ``scaffold_policy_functions``).
        constraint_checks: Subset with role ``CONSTRAINT`` / ``PREFERENCE``
            (authoritative constraints declared in the GNN, typically
            one per ``C_m*=PreferenceVector`` annotation).
        context_functions: Subset with role ``CONTEXT`` derived from
            the parsed GNN (rare; populated when the ontology block
            annotates a variable as ``Context`` or ``Time``).
        target_role_counts: Expected semantic role multiset for the
            synthesized package. Round-trip verification passes the
            source roles here so generated scaffolds are deficit-based
            rather than fixed boilerplate.
        scaffold_constraint_checks: Additional ``check_*`` functions
            emitted only when ``target_role_counts`` requires more
            CONSTRAINT roles than the parsed GNN declares.
        scaffold_policy_functions: Additional top-level POLICY scaffolds
            emitted only when target POLICY roles remain after
            authoritative policy functions and the optional policy
            selector helper.
        scaffold_context_classes: Additional top-level CONTEXT classes
            emitted only when source roles include CONTEXT deficits.
        has_A_matrix: True if the parsed A matrix has non-zero rows.
        has_B_tensor: True if the parsed B tensor is non-trivial.
        has_C_vector: True if the parsed C vector is non-empty.
        has_D_vector: True if the parsed D vector is non-empty.
    """

    package_name: str = "cogant_model"
    raw_model_name: str = "cogant_model"
    nodes: list[NodePlan] = field(default_factory=list)
    state_vars: list[NodePlan] = field(default_factory=list)
    obs_functions: list[NodePlan] = field(default_factory=list)
    action_methods: list[NodePlan] = field(default_factory=list)
    policy_functions: list[NodePlan] = field(default_factory=list)
    constraint_checks: list[NodePlan] = field(default_factory=list)
    context_functions: list[NodePlan] = field(default_factory=list)
    target_role_counts: dict[str, int] = field(default_factory=dict)
    scaffold_constraint_checks: list[NodePlan] = field(default_factory=list)
    scaffold_policy_functions: list[NodePlan] = field(default_factory=list)
    scaffold_context_classes: list[NodePlan] = field(default_factory=list)
    has_A_matrix: bool = False
    has_B_tensor: bool = False
    has_C_vector: bool = False
    has_D_vector: bool = False
    state_dimension: int = 0
    observation_dimension: int = 0
    action_dimension: int = 0

    def validate(self) -> list[str]:
        """Validate the package plan for structural consistency.

        Checks that the plan is internally coherent and can be synthesized.
        Does not validate the plan against external sources (e.g., the
        original GNN).

        Returns:
            A list of validation issues. Empty list means the plan is valid.
            Issues describe problems but do not necessarily prevent synthesis
            from succeeding.
        """
        issues: list[str] = []

        # Check: no duplicate names across all roles
        all_names = [n.name for n in self.nodes]
        seen: dict[str, int] = {}
        for name in all_names:
            seen[name] = seen.get(name, 0) + 1
        duplicates = [name for name, count in seen.items() if count > 1]
        if duplicates:
            issues.append(f"Duplicate node names found: {duplicates}")

        # Check: each node's role is recognized
        valid_roles = {
            "HIDDEN_STATE",
            "OBSERVATION",
            "ACTION",
            "POLICY",
            "CONSTRAINT",
            "CONTEXT",
        }
        for node in self.nodes:
            if node.role not in valid_roles:
                issues.append(f"Node {node.name!r} has unrecognized role {node.role!r}")

        # Check: nodes in subsets appear in main nodes list
        all_subsets = (
            self.state_vars
            + self.obs_functions
            + self.action_methods
            + self.policy_functions
            + self.constraint_checks
            + self.context_functions
            + self.scaffold_constraint_checks
            + self.scaffold_policy_functions
            + self.scaffold_context_classes
        )
        nodes_set = {id(n) for n in self.nodes}
        for node in all_subsets:
            if id(node) not in nodes_set:
                issues.append(f"Node {node.name!r} in a role subset but not in main nodes list")

        # Check: consistent role classification in subsets
        for node in self.state_vars:
            if node.role != "HIDDEN_STATE":
                issues.append(
                    f"state_vars node {node.name!r} has role {node.role!r}, expected HIDDEN_STATE"
                )
        for node in self.obs_functions:
            if node.role != "OBSERVATION":
                issues.append(
                    f"obs_functions node {node.name!r} has role {node.role!r}, expected OBSERVATION"
                )
        for node in self.action_methods:
            if node.role != "ACTION":
                issues.append(
                    f"action_methods node {node.name!r} has role {node.role!r}, expected ACTION"
                )

        # Check: package_name is a valid Python identifier
        import keyword

        if not self.package_name.isidentifier() or keyword.iskeyword(self.package_name):
            issues.append(f"package_name {self.package_name!r} is not a valid Python identifier")

        return issues

    def diff(self, other: PackagePlan) -> str:
        """Return a human-readable diff between this plan and another.

        Compares the role distributions, node counts, and key attributes.

        Args:
            other: Another PackagePlan to compare against.

        Returns:
            A human-readable diff string. Empty string if the plans are
            identical.
        """
        diffs: list[str] = []

        if self.package_name != other.package_name:
            diffs.append(f"  package_name: {self.package_name!r} vs {other.package_name!r}")

        # Compare role populations
        roles_self = {
            "HIDDEN_STATE": len(self.state_vars),
            "OBSERVATION": len(self.obs_functions),
            "ACTION": len(self.action_methods),
            "POLICY": len(self.policy_functions),
            "CONSTRAINT": len(self.constraint_checks),
            "CONTEXT": len(self.context_functions),
        }
        roles_other = {
            "HIDDEN_STATE": len(other.state_vars),
            "OBSERVATION": len(other.obs_functions),
            "ACTION": len(other.action_methods),
            "POLICY": len(other.policy_functions),
            "CONSTRAINT": len(other.constraint_checks),
            "CONTEXT": len(other.context_functions),
        }

        for role in roles_self:
            if roles_self[role] != roles_other[role]:
                diffs.append(f"  {role}: {roles_self[role]} vs {roles_other[role]}")

        # Compare scaffold populations
        if len(self.scaffold_constraint_checks) != len(other.scaffold_constraint_checks):
            diffs.append(
                f"  scaffold_constraint_checks: "
                f"{len(self.scaffold_constraint_checks)} vs "
                f"{len(other.scaffold_constraint_checks)}"
            )

        if len(self.scaffold_policy_functions) != len(other.scaffold_policy_functions):
            diffs.append(
                f"  scaffold_policy_functions: "
                f"{len(self.scaffold_policy_functions)} vs "
                f"{len(other.scaffold_policy_functions)}"
            )

        if self.target_role_counts != other.target_role_counts:
            diffs.append(
                f"  target_role_counts: {self.target_role_counts!r} vs {other.target_role_counts!r}"
            )

        # Compare matrix presence flags
        matrix_flags = ["has_A_matrix", "has_B_tensor", "has_C_vector", "has_D_vector"]
        for flag in matrix_flags:
            self_val = getattr(self, flag)
            other_val = getattr(other, flag)
            if self_val != other_val:
                diffs.append(f"  {flag}: {self_val} vs {other_val}")

        if not diffs:
            return ""

        return "PackagePlan differences:\n" + "\n".join(diffs)

    def to_json(self) -> str:
        """Serialize the PackagePlan to JSON.

        Returns:
            A JSON string representation of the plan suitable for
            serialization and round-trip recovery.
        """
        data = {
            "package_name": self.package_name,
            "raw_model_name": self.raw_model_name,
            "nodes": [self._node_to_dict(n) for n in self.nodes],
            "state_vars": [n.name for n in self.state_vars],
            "obs_functions": [n.name for n in self.obs_functions],
            "action_methods": [n.name for n in self.action_methods],
            "policy_functions": [n.name for n in self.policy_functions],
            "constraint_checks": [n.name for n in self.constraint_checks],
            "context_functions": [n.name for n in self.context_functions],
            "target_role_counts": dict(self.target_role_counts),
            "scaffold_constraint_checks": [n.name for n in self.scaffold_constraint_checks],
            "scaffold_policy_functions": [n.name for n in self.scaffold_policy_functions],
            "scaffold_context_classes": [n.name for n in self.scaffold_context_classes],
            "has_A_matrix": self.has_A_matrix,
            "has_B_tensor": self.has_B_tensor,
            "has_C_vector": self.has_C_vector,
            "has_D_vector": self.has_D_vector,
            "state_dimension": self.state_dimension,
            "observation_dimension": self.observation_dimension,
            "action_dimension": self.action_dimension,
        }
        return json.dumps(data, indent=2)

    @classmethod
    def from_json(cls, data: str) -> PackagePlan:
        """Deserialize a PackagePlan from JSON.

        Args:
            data: A JSON string representation of a PackagePlan.

        Returns:
            A reconstructed PackagePlan instance.

        Raises:
            json.JSONDecodeError: If the JSON is malformed.
            KeyError: If required fields are missing.
        """
        parsed = json.loads(data)
        nodes_data = parsed.get("nodes", [])

        # Reconstruct all nodes
        all_nodes: dict[str, NodePlan] = {}
        for node_dict in nodes_data:
            node = cls._dict_to_node(node_dict)
            all_nodes[node.name] = node

        # Retrieve nodes by name for each subset
        def get_nodes(names: list[str]) -> list[NodePlan]:
            return [all_nodes[name] for name in names if name in all_nodes]

        plan = cls(
            package_name=parsed.get("package_name", "cogant_model"),
            raw_model_name=parsed.get("raw_model_name", "cogant_model"),
            nodes=list(all_nodes.values()),
            state_vars=get_nodes(parsed.get("state_vars", [])),
            obs_functions=get_nodes(parsed.get("obs_functions", [])),
            action_methods=get_nodes(parsed.get("action_methods", [])),
            policy_functions=get_nodes(parsed.get("policy_functions", [])),
            constraint_checks=get_nodes(parsed.get("constraint_checks", [])),
            context_functions=get_nodes(parsed.get("context_functions", [])),
            target_role_counts=_normalise_role_counts(parsed.get("target_role_counts", {})),
            scaffold_constraint_checks=get_nodes(parsed.get("scaffold_constraint_checks", [])),
            scaffold_policy_functions=get_nodes(parsed.get("scaffold_policy_functions", [])),
            scaffold_context_classes=get_nodes(parsed.get("scaffold_context_classes", [])),
            has_A_matrix=parsed.get("has_A_matrix", False),
            has_B_tensor=parsed.get("has_B_tensor", False),
            has_C_vector=parsed.get("has_C_vector", False),
            has_D_vector=parsed.get("has_D_vector", False),
            state_dimension=int(parsed.get("state_dimension", 0)),
            observation_dimension=int(parsed.get("observation_dimension", 0)),
            action_dimension=int(parsed.get("action_dimension", 0)),
        )
        return plan

    @staticmethod
    def _node_to_dict(node: NodePlan) -> dict:
        """Convert a NodePlan to a dict for JSON serialization."""
        return {
            "slot": node.slot,
            "name": node.name,
            "role": node.role,
            "python_type": node.python_type,
            "module": node.module,
            "cardinality": node.cardinality,
            "initial_value": node.initial_value,
        }

    @staticmethod
    def _dict_to_node(data: dict) -> NodePlan:
        """Convert a dict from JSON deserialization to a NodePlan."""
        return NodePlan(
            slot=data.get("slot", ""),
            name=data.get("name", ""),
            role=data.get("role", ""),
            python_type=data.get("python_type", "float"),
            module=data.get("module", ""),
            cardinality=data.get("cardinality", 0),
            initial_value=data.get("initial_value", "0.0"),
        )

diff(other)

Return a human-readable diff between this plan and another.

Compares the role distributions, node counts, and key attributes.

Parameters:

Name Type Description Default
other PackagePlan

Another PackagePlan to compare against.

required

Returns:

Type Description
str

A human-readable diff string. Empty string if the plans are

str

identical.

Source code in py/cogant/reverse/planner.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def diff(self, other: PackagePlan) -> str:
    """Return a human-readable diff between this plan and another.

    Compares the role distributions, node counts, and key attributes.

    Args:
        other: Another PackagePlan to compare against.

    Returns:
        A human-readable diff string. Empty string if the plans are
        identical.
    """
    diffs: list[str] = []

    if self.package_name != other.package_name:
        diffs.append(f"  package_name: {self.package_name!r} vs {other.package_name!r}")

    # Compare role populations
    roles_self = {
        "HIDDEN_STATE": len(self.state_vars),
        "OBSERVATION": len(self.obs_functions),
        "ACTION": len(self.action_methods),
        "POLICY": len(self.policy_functions),
        "CONSTRAINT": len(self.constraint_checks),
        "CONTEXT": len(self.context_functions),
    }
    roles_other = {
        "HIDDEN_STATE": len(other.state_vars),
        "OBSERVATION": len(other.obs_functions),
        "ACTION": len(other.action_methods),
        "POLICY": len(other.policy_functions),
        "CONSTRAINT": len(other.constraint_checks),
        "CONTEXT": len(other.context_functions),
    }

    for role in roles_self:
        if roles_self[role] != roles_other[role]:
            diffs.append(f"  {role}: {roles_self[role]} vs {roles_other[role]}")

    # Compare scaffold populations
    if len(self.scaffold_constraint_checks) != len(other.scaffold_constraint_checks):
        diffs.append(
            f"  scaffold_constraint_checks: "
            f"{len(self.scaffold_constraint_checks)} vs "
            f"{len(other.scaffold_constraint_checks)}"
        )

    if len(self.scaffold_policy_functions) != len(other.scaffold_policy_functions):
        diffs.append(
            f"  scaffold_policy_functions: "
            f"{len(self.scaffold_policy_functions)} vs "
            f"{len(other.scaffold_policy_functions)}"
        )

    if self.target_role_counts != other.target_role_counts:
        diffs.append(
            f"  target_role_counts: {self.target_role_counts!r} vs {other.target_role_counts!r}"
        )

    # Compare matrix presence flags
    matrix_flags = ["has_A_matrix", "has_B_tensor", "has_C_vector", "has_D_vector"]
    for flag in matrix_flags:
        self_val = getattr(self, flag)
        other_val = getattr(other, flag)
        if self_val != other_val:
            diffs.append(f"  {flag}: {self_val} vs {other_val}")

    if not diffs:
        return ""

    return "PackagePlan differences:\n" + "\n".join(diffs)

from_json(data) classmethod

Deserialize a PackagePlan from JSON.

Parameters:

Name Type Description Default
data str

A JSON string representation of a PackagePlan.

required

Returns:

Type Description
PackagePlan

A reconstructed PackagePlan instance.

Raises:

Type Description
JSONDecodeError

If the JSON is malformed.

KeyError

If required fields are missing.

Source code in py/cogant/reverse/planner.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
@classmethod
def from_json(cls, data: str) -> PackagePlan:
    """Deserialize a PackagePlan from JSON.

    Args:
        data: A JSON string representation of a PackagePlan.

    Returns:
        A reconstructed PackagePlan instance.

    Raises:
        json.JSONDecodeError: If the JSON is malformed.
        KeyError: If required fields are missing.
    """
    parsed = json.loads(data)
    nodes_data = parsed.get("nodes", [])

    # Reconstruct all nodes
    all_nodes: dict[str, NodePlan] = {}
    for node_dict in nodes_data:
        node = cls._dict_to_node(node_dict)
        all_nodes[node.name] = node

    # Retrieve nodes by name for each subset
    def get_nodes(names: list[str]) -> list[NodePlan]:
        return [all_nodes[name] for name in names if name in all_nodes]

    plan = cls(
        package_name=parsed.get("package_name", "cogant_model"),
        raw_model_name=parsed.get("raw_model_name", "cogant_model"),
        nodes=list(all_nodes.values()),
        state_vars=get_nodes(parsed.get("state_vars", [])),
        obs_functions=get_nodes(parsed.get("obs_functions", [])),
        action_methods=get_nodes(parsed.get("action_methods", [])),
        policy_functions=get_nodes(parsed.get("policy_functions", [])),
        constraint_checks=get_nodes(parsed.get("constraint_checks", [])),
        context_functions=get_nodes(parsed.get("context_functions", [])),
        target_role_counts=_normalise_role_counts(parsed.get("target_role_counts", {})),
        scaffold_constraint_checks=get_nodes(parsed.get("scaffold_constraint_checks", [])),
        scaffold_policy_functions=get_nodes(parsed.get("scaffold_policy_functions", [])),
        scaffold_context_classes=get_nodes(parsed.get("scaffold_context_classes", [])),
        has_A_matrix=parsed.get("has_A_matrix", False),
        has_B_tensor=parsed.get("has_B_tensor", False),
        has_C_vector=parsed.get("has_C_vector", False),
        has_D_vector=parsed.get("has_D_vector", False),
        state_dimension=int(parsed.get("state_dimension", 0)),
        observation_dimension=int(parsed.get("observation_dimension", 0)),
        action_dimension=int(parsed.get("action_dimension", 0)),
    )
    return plan

to_json()

Serialize the PackagePlan to JSON.

Returns:

Type Description
str

A JSON string representation of the plan suitable for

str

serialization and round-trip recovery.

Source code in py/cogant/reverse/planner.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def to_json(self) -> str:
    """Serialize the PackagePlan to JSON.

    Returns:
        A JSON string representation of the plan suitable for
        serialization and round-trip recovery.
    """
    data = {
        "package_name": self.package_name,
        "raw_model_name": self.raw_model_name,
        "nodes": [self._node_to_dict(n) for n in self.nodes],
        "state_vars": [n.name for n in self.state_vars],
        "obs_functions": [n.name for n in self.obs_functions],
        "action_methods": [n.name for n in self.action_methods],
        "policy_functions": [n.name for n in self.policy_functions],
        "constraint_checks": [n.name for n in self.constraint_checks],
        "context_functions": [n.name for n in self.context_functions],
        "target_role_counts": dict(self.target_role_counts),
        "scaffold_constraint_checks": [n.name for n in self.scaffold_constraint_checks],
        "scaffold_policy_functions": [n.name for n in self.scaffold_policy_functions],
        "scaffold_context_classes": [n.name for n in self.scaffold_context_classes],
        "has_A_matrix": self.has_A_matrix,
        "has_B_tensor": self.has_B_tensor,
        "has_C_vector": self.has_C_vector,
        "has_D_vector": self.has_D_vector,
        "state_dimension": self.state_dimension,
        "observation_dimension": self.observation_dimension,
        "action_dimension": self.action_dimension,
    }
    return json.dumps(data, indent=2)

validate()

Validate the package plan for structural consistency.

Checks that the plan is internally coherent and can be synthesized. Does not validate the plan against external sources (e.g., the original GNN).

Returns:

Type Description
list[str]

A list of validation issues. Empty list means the plan is valid.

list[str]

Issues describe problems but do not necessarily prevent synthesis

list[str]

from succeeding.

Source code in py/cogant/reverse/planner.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def validate(self) -> list[str]:
    """Validate the package plan for structural consistency.

    Checks that the plan is internally coherent and can be synthesized.
    Does not validate the plan against external sources (e.g., the
    original GNN).

    Returns:
        A list of validation issues. Empty list means the plan is valid.
        Issues describe problems but do not necessarily prevent synthesis
        from succeeding.
    """
    issues: list[str] = []

    # Check: no duplicate names across all roles
    all_names = [n.name for n in self.nodes]
    seen: dict[str, int] = {}
    for name in all_names:
        seen[name] = seen.get(name, 0) + 1
    duplicates = [name for name, count in seen.items() if count > 1]
    if duplicates:
        issues.append(f"Duplicate node names found: {duplicates}")

    # Check: each node's role is recognized
    valid_roles = {
        "HIDDEN_STATE",
        "OBSERVATION",
        "ACTION",
        "POLICY",
        "CONSTRAINT",
        "CONTEXT",
    }
    for node in self.nodes:
        if node.role not in valid_roles:
            issues.append(f"Node {node.name!r} has unrecognized role {node.role!r}")

    # Check: nodes in subsets appear in main nodes list
    all_subsets = (
        self.state_vars
        + self.obs_functions
        + self.action_methods
        + self.policy_functions
        + self.constraint_checks
        + self.context_functions
        + self.scaffold_constraint_checks
        + self.scaffold_policy_functions
        + self.scaffold_context_classes
    )
    nodes_set = {id(n) for n in self.nodes}
    for node in all_subsets:
        if id(node) not in nodes_set:
            issues.append(f"Node {node.name!r} in a role subset but not in main nodes list")

    # Check: consistent role classification in subsets
    for node in self.state_vars:
        if node.role != "HIDDEN_STATE":
            issues.append(
                f"state_vars node {node.name!r} has role {node.role!r}, expected HIDDEN_STATE"
            )
    for node in self.obs_functions:
        if node.role != "OBSERVATION":
            issues.append(
                f"obs_functions node {node.name!r} has role {node.role!r}, expected OBSERVATION"
            )
    for node in self.action_methods:
        if node.role != "ACTION":
            issues.append(
                f"action_methods node {node.name!r} has role {node.role!r}, expected ACTION"
            )

    # Check: package_name is a valid Python identifier
    import keyword

    if not self.package_name.isidentifier() or keyword.iskeyword(self.package_name):
        issues.append(f"package_name {self.package_name!r} is not a valid Python identifier")

    return issues

plan_package(model, *, expected_roles=None)

Build a :class:PackagePlan from a :class:ReverseGNNModel.

Each hidden-state slot becomes a State dataclass attribute; each observation slot becomes an observe_* function; each action slot becomes an act_* function; etc. Naming prefers the human-readable labels from the extended state-variable table when available, else falls back to the slot name.

Parameters:

Name Type Description Default
model ReverseGNNModel

Parsed GNN model.

required
expected_roles Mapping[str, int] | None

Optional source semantic role multiset. When provided, POLICY / CONSTRAINT / CONTEXT scaffolds are added only for deficits relative to that target. When omitted, the target is derived from the parsed GNN itself.

None
Source code in py/cogant/reverse/planner.py
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
def plan_package(
    model: ReverseGNNModel,
    *,
    expected_roles: Mapping[str, int] | None = None,
) -> PackagePlan:
    """Build a :class:`PackagePlan` from a :class:`ReverseGNNModel`.

    Each hidden-state slot becomes a State dataclass attribute; each
    observation slot becomes an ``observe_*`` function; each action
    slot becomes an ``act_*`` function; etc. Naming prefers the
    human-readable labels from the extended state-variable table when
    available, else falls back to the slot name.

    Args:
        model: Parsed GNN model.
        expected_roles: Optional source semantic role multiset. When
            provided, POLICY / CONSTRAINT / CONTEXT scaffolds are added
            only for deficits relative to that target. When omitted,
            the target is derived from the parsed GNN itself.
    """
    plan = PackagePlan(
        package_name=model.model_name or "cogant_model",
        raw_model_name=model.raw_model_name or model.model_name or "cogant_model",
    )
    used_names: dict[str, int] = {}

    # Hidden states → State attributes in state.py
    for i, slot in enumerate(model.hidden_states):
        human = model.human_names.get(slot, "")
        ident = _to_identifier(human, slot)
        ident = _reserved_avoid(ident, used_names)
        gnn_type = model.types.get(slot, "int")
        py_type = _python_type_for(gnn_type)
        card = model.cardinalities.get(slot, 0)
        d_mass = model.D[i] if i < len(model.D) else 0.0
        init = _default_value_for(py_type, card, d_mass)
        node = NodePlan(
            slot=slot,
            name=ident,
            role="HIDDEN_STATE",
            python_type=py_type,
            module="state.py",
            cardinality=card,
            initial_value=init,
        )
        plan.state_vars.append(node)
        plan.nodes.append(node)

    # Observations → get_<name> functions in observe.py.
    #
    # Naming rationale: the forward ObservationRule keyword match fires
    # on ``get/read/fetch/query/display/show/status/info/list``. Prefix
    # every synthesized observation with ``get_`` so the keyword hit is
    # deterministic regardless of whether the edge extractor later
    # records a READS edge for the function body. This gives the
    # reverse → forward round-trip a strong, first-class lexical signal
    # that cannot be lost to edge-extraction noise.
    for _i, slot in enumerate(model.observations):
        human = model.human_names.get(slot, "")
        ident = _to_identifier(human, slot)
        ident = _reserved_avoid(f"get_{ident}" if ident == slot else f"get_{ident}", used_names)
        gnn_type = model.types.get(slot, "int")
        py_type = _python_type_for(gnn_type)
        card = model.cardinalities.get(slot, 0)
        node = NodePlan(
            slot=slot,
            name=ident,
            role="OBSERVATION",
            python_type=py_type,
            module="observe.py",
            cardinality=card,
            initial_value="0.0",
        )
        plan.obs_functions.append(node)
        plan.nodes.append(node)

    # Actions → update_<name> functions in act.py.
    #
    # Naming rationale: the forward ActionRule keyword match fires on
    # ``set/update/create/delete/send/push/execute/run/process/handle/
    # dispatch/encode/decode/dump/load``. Prefix every synthesized action
    # with ``update_`` so the keyword hit is deterministic regardless of
    # whether the edge extractor records a WRITES edge for the function
    # body. This matches the symmetry with ``get_`` on the observation
    # side and guarantees the forward pass will classify the right
    # number of actions on the synthesized package.
    for _i, slot in enumerate(model.actions):
        human = model.human_names.get(slot, "")
        ident = _to_identifier(human, slot)
        ident = _reserved_avoid(
            f"update_{ident}" if ident == slot else f"update_{ident}", used_names
        )
        gnn_type = model.types.get(slot, "int")
        py_type = _python_type_for(gnn_type)
        card = model.cardinalities.get(slot, 0)
        node = NodePlan(
            slot=slot,
            name=ident,
            role="ACTION",
            python_type=py_type,
            module="act.py",
            cardinality=card,
            initial_value="0",
        )
        plan.action_methods.append(node)
        plan.nodes.append(node)

    # Policies → policy_<name> functions in policy.py
    for slot in model.policies:
        human = model.human_names.get(slot, "")
        ident = _to_identifier(human, slot)
        ident = _reserved_avoid(f"pi_{ident}" if ident == slot else ident, used_names)
        node = NodePlan(
            slot=slot,
            name=ident,
            role="POLICY",
            python_type="str",
            module="policy.py",
            cardinality=0,
            initial_value='""',
        )
        plan.policy_functions.append(node)
        plan.nodes.append(node)

    # Constraints → check_<name> functions in constraints.py
    for slot in model.constraints:
        human = model.human_names.get(slot, "")
        ident = _to_identifier(human, slot)
        ident = _reserved_avoid(f"cnst_{ident}" if ident == slot else ident, used_names)
        node = NodePlan(
            slot=slot,
            name=ident,
            role="CONSTRAINT",
            python_type="bool",
            module="constraints.py",
            cardinality=0,
            initial_value="True",
        )
        plan.constraint_checks.append(node)
        plan.nodes.append(node)

    # Context functions — derived from ontology annotations that name
    # a variable as ``Context`` or ``Time``. These are separate from
    # the scaffold context classes emitted below; the two populations
    # are combined by the synthesizer when rendering ``context.py``.
    for var, concept in model.annotations.items():
        if var in (
            model.hidden_states
            + model.observations
            + model.actions
            + model.policies
            + model.constraints
        ):
            continue
        lc = concept.lower()
        if "context" in lc or lc == "time":
            ident = _to_identifier(var, var)
            ident = _reserved_avoid(f"context_{ident}", used_names)
            node = NodePlan(
                slot=var,
                name=ident,
                role="CONTEXT",
                python_type="dict",
                module="context.py",
                cardinality=0,
                initial_value="{}",
            )
            plan.context_functions.append(node)
            plan.nodes.append(node)

    plan.target_role_counts = (
        _normalise_role_counts(expected_roles)
        if expected_roles is not None
        else _role_counts_from_model(model)
    )

    # Fill only declared role deficits.  These are explicit compatibility
    # scaffolds, not unlabelled runtime helpers: the generated manifest names
    # them and the forward role audit can distinguish them from source-backed
    # definitions.  In particular, an ExpectedFreeEnergy annotation needs a
    # policy-shaped selector to survive a reverse/forward round trip.
    plan.scaffold_constraint_checks = _build_scaffold_constraints(plan, used_names)
    plan.scaffold_policy_functions = _build_scaffold_policies(plan, used_names)
    plan.scaffold_context_classes = _build_scaffold_contexts(plan, used_names)

    plan.has_A_matrix = bool(model.A) and any(any(row) for row in model.A)
    plan.has_B_tensor = bool(model.B)
    plan.has_C_vector = bool(model.C)
    plan.has_D_vector = bool(model.D)
    plan.state_dimension = model.n_states
    plan.observation_dimension = model.n_obs
    plan.action_dimension = model.n_actions

    logger.info(
        "Planned package %r: %d state vars, %d obs, %d actions, %d policies, "
        "%d constraints, %d contexts, scaffold(constraints=%d, policies=%d, "
        "contexts=%d)",
        plan.package_name,
        len(plan.state_vars),
        len(plan.obs_functions),
        len(plan.action_methods),
        len(plan.policy_functions),
        len(plan.constraint_checks),
        len(plan.context_functions),
        len(plan.scaffold_constraint_checks),
        len(plan.scaffold_policy_functions),
        len(plan.scaffold_context_classes),
    )
    return plan

Synthesizer

End-to-end package synthesis. synthesize_package writes a runnable Python package to disk from a parsed model.

cogant.reverse.synthesizer

Package synthesizer: :class:PackagePlan → Python source files.

This is the core of the reverse pipeline. Given a planned mapping of GNN roles to Python constructs, it emits a runnable Python package with the following layout::

<output_dir>/
+-- __init__.py
+-- state.py         # State dataclass (HIDDEN_STATE fields)
+-- observe.py       # get_<name> functions (OBSERVATION)
+-- act.py           # update_<name> functions (ACTION)
+-- policy.py        # selector + policy/scaffold functions
+-- constraints.py   # check_<name> functions (CONSTRAINT)
+-- matrices.py      # A/B/C/D runtime matrices
+-- main.py          # Driver that runs a few inference steps
+-- tests/
|   +-- __init__.py
|   +-- test_smoke.py

The synthesizer uses string templates rather than an AST builder. Building ASTs via ast.unparse would work for Python 3.9+ but string templates are simpler, debuggable by eye, produce cleaner formatting, and avoid the libCST/ast-unparse dependency question entirely.

Determinism

The emitter is deterministic: given the same PackagePlan it produces identical source files on every run. This is essential for the round-trip verifier, which caches synthesized packages by GNN hash.

SynthesisResult dataclass

Result of synthesizing code from a PackagePlan.

Attributes:

Name Type Description
code str

The synthesized Python code as a string.

parse_ok bool

True if the code parses successfully with ast.parse().

issues list[str]

List of validation issues encountered (empty = valid).

role_counts dict[str, int]

Dict mapping role names to counts of synthesized functions/classes for that role (e.g., {"HIDDEN_STATE": 5, "ACTION": 3}). Useful for debugging role distribution.

filename str

Optional filename for error reporting.

Source code in py/cogant/reverse/synthesizer.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
@dataclass
class SynthesisResult:
    """Result of synthesizing code from a PackagePlan.

    Attributes:
        code: The synthesized Python code as a string.
        parse_ok: True if the code parses successfully with ast.parse().
        issues: List of validation issues encountered (empty = valid).
        role_counts: Dict mapping role names to counts of synthesized
            functions/classes for that role (e.g., {"HIDDEN_STATE": 5,
            "ACTION": 3}). Useful for debugging role distribution.
        filename: Optional filename for error reporting.
    """

    code: str = ""
    parse_ok: bool = False
    issues: list[str] = field(default_factory=list)
    role_counts: dict[str, int] = field(default_factory=dict)
    filename: str = ""

supports_stable_minimal_profile(plan, model)

Return whether a model belongs to the strict reversible subset.

The profile is intentionally narrow. It is not a shortcut around the strict verifier; it only avoids emitting the full demo/runtime scaffold when the source model is already the one-class/one-observer/one-mutator shape that COGANT can re-ingest without graph or matrix growth.

Source code in py/cogant/reverse/synthesizer.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def supports_stable_minimal_profile(plan: PackagePlan, model: ReverseGNNModel) -> bool:
    """Return whether a model belongs to the strict reversible subset.

    The profile is intentionally narrow. It is not a shortcut around the
    strict verifier; it only avoids emitting the full demo/runtime scaffold
    when the source model is already the one-class/one-observer/one-mutator
    shape that COGANT can re-ingest without graph or matrix growth.
    """

    target = {str(k).upper(): int(v) for k, v in plan.target_role_counts.items()}
    allowed = {"HIDDEN_STATE", "OBSERVATION", "ACTION"}
    return (
        set(target).issubset(allowed)
        and target.get("HIDDEN_STATE") == 1
        and target.get("OBSERVATION") == 1
        and target.get("ACTION") == 2
        and len(plan.state_vars) == 1
        and len(plan.obs_functions) == 1
        and len(plan.action_methods) >= 1
        and not plan.policy_functions
        and not plan.constraint_checks
        and not plan.scaffold_policy_functions
        and not plan.scaffold_constraint_checks
        and not plan.scaffold_context_classes
        and model.n_states == 1
        and model.n_obs == 1
        and model.n_actions == 2
        and bool(model.A)
        and bool(model.B)
        and bool(model.C)
        and bool(model.D)
    )

synthesize_package(plan, model, output_dir)

Emit a full Python package to output_dir from plan.

The function creates a package directory named plan.package_name inside output_dir so that the parent directory can contain multiple synthesized models side by side. Inside the package it writes state.py, observe.py, act.py, policy.py, constraints.py, matrices.py, main.py, and a smoke test under tests/.

Parameters:

Name Type Description Default
plan PackagePlan

Package plan produced by :func:plan_package.

required
model ReverseGNNModel

Parsed GNN model (provides matrix values).

required
output_dir str | Path

Directory where the package is created. The directory is created if it does not exist.

required

Returns:

Type Description
Path

The path to the created package directory (``output_dir /

Path

package_name``).

Source code in py/cogant/reverse/synthesizer.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
def synthesize_package(
    plan: PackagePlan,
    model: ReverseGNNModel,
    output_dir: str | Path,
) -> Path:
    """Emit a full Python package to ``output_dir`` from ``plan``.

    The function creates a package directory named ``plan.package_name``
    **inside** ``output_dir`` so that the parent directory can contain
    multiple synthesized models side by side. Inside the package it
    writes ``state.py``, ``observe.py``, ``act.py``, ``policy.py``,
    ``constraints.py``, ``matrices.py``, ``main.py``, and a smoke
    test under ``tests/``.

    Args:
        plan: Package plan produced by :func:`plan_package`.
        model: Parsed GNN model (provides matrix values).
        output_dir: Directory where the package is created. The
            directory is created if it does not exist.

    Returns:
        The path to the created package directory (``output_dir /
        package_name``).
    """
    output_path = Path(output_dir).expanduser().resolve()
    package_path = output_path / plan.package_name
    package_path.mkdir(parents=True, exist_ok=True)
    tests_path = package_path / "tests"
    tests_path.mkdir(parents=True, exist_ok=True)

    semantic_targets = _semantic_role_targets(plan)
    manifest = {
        "schema": "cogant.reverse.semantic_targets.v1",
        "target_role_counts": dict(plan.target_role_counts),
        "semantic_targets": semantic_targets,
    }
    files = {
        package_path / ".gitignore": "tests\n.pytest_cache\n__pycache__\n*.pyc\n",
        package_path / SEMANTIC_TARGETS_MANIFEST: json.dumps(manifest, indent=2, sort_keys=True)
        + "\n",
        package_path / "__init__.py": _render_package_init(plan),
        package_path / "state.py": _render_state_module(plan),
        package_path / "observe.py": _render_observe_module(plan),
        package_path / "act.py": _render_act_module(plan),
        package_path / "policy.py": _render_policy_module(plan),
        package_path / "constraints.py": _render_constraints_module(plan),
        package_path / "context.py": _render_context_module(plan),
        package_path / "matrices.py": render_matrices_module(model),
        package_path / "main.py": _render_main_module(plan),
        tests_path / "__init__.py": '"""Test package for the synthesized model."""\n',
        tests_path / "test_smoke.py": _render_test_smoke(
            plan,
            has_actions=model.n_actions > 0,
            executable=bool(model.A and model.B and model.C and model.D),
        ),
    }

    for path, content in files.items():
        path.write_text(content, encoding="utf-8")
        logger.debug("Wrote %s (%d bytes)", path, len(content))

    logger.info(
        "Synthesized package %r at %s (%d files, %d state vars, %d obs, %d actions)",
        plan.package_name,
        package_path,
        len(files),
        len(plan.state_vars),
        len(plan.obs_functions),
        len(plan.action_methods),
    )
    return package_path

synthesize_stable_minimal_package(plan, model, output_dir)

Emit the strict reversible subset package.

The emitted source is deliberately small: one module, one hidden-state class, one read-only observation function, and one top-level action mutator. The class __init__ provides the second ACTION role that the forward parser records for this subset. No helper modules, tests, imports, or runtime scaffolds are emitted, because each of those is observable to the graph verifier and would correctly fail strict isomorphism.

Source code in py/cogant/reverse/synthesizer.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def synthesize_stable_minimal_package(
    plan: PackagePlan,
    model: ReverseGNNModel,
    output_dir: str | Path,
) -> Path:
    """Emit the strict reversible subset package.

    The emitted source is deliberately small: one module, one hidden-state
    class, one read-only observation function, and one top-level action
    mutator. The class ``__init__`` provides the second ACTION role that the
    forward parser records for this subset. No helper modules, tests, imports,
    or runtime scaffolds are emitted, because each of those is observable to
    the graph verifier and would correctly fail strict isomorphism.
    """

    if not supports_stable_minimal_profile(plan, model):
        raise ValueError("stable minimal profile requested for a non-minimal plan")

    return synthesize_package(plan, model, output_dir)

synthesize_with_validation(plan, model, output_dir)

Synthesize code and validate that it parses as valid Python.

Parameters:

Name Type Description Default
plan PackagePlan

Package plan produced by :func:plan_package.

required
model ReverseGNNModel

Parsed GNN model (provides matrix values).

required
output_dir str | Path

Directory where the package is created.

required

Returns:

Type Description
str

A tuple of (package_path_str, issues_list). The path is the string

list[str]

representation of the synthesized package directory. issues_list

tuple[str, list[str]]

contains zero or more validation warnings/errors. An empty list

tuple[str, list[str]]

means all files synthesized and parsed successfully.

Source code in py/cogant/reverse/synthesizer.py
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
def synthesize_with_validation(
    plan: PackagePlan,
    model: ReverseGNNModel,
    output_dir: str | Path,
) -> tuple[str, list[str]]:
    """Synthesize code and validate that it parses as valid Python.

    Args:
        plan: Package plan produced by :func:`plan_package`.
        model: Parsed GNN model (provides matrix values).
        output_dir: Directory where the package is created.

    Returns:
        A tuple of (package_path_str, issues_list). The path is the string
        representation of the synthesized package directory. issues_list
        contains zero or more validation warnings/errors. An empty list
        means all files synthesized and parsed successfully.
    """
    pkg_path = synthesize_package(plan, model, output_dir)
    issues: list[str] = []

    # Check that all generated Python files parse
    py_files = [
        pkg_path / "__init__.py",
        pkg_path / "state.py",
        pkg_path / "observe.py",
        pkg_path / "act.py",
        pkg_path / "policy.py",
        pkg_path / "constraints.py",
        pkg_path / "context.py",
        pkg_path / "matrices.py",
        pkg_path / "main.py",
        pkg_path / "tests" / "test_smoke.py",
    ]

    for py_file in py_files:
        if py_file.exists():
            try:
                content = py_file.read_text(encoding="utf-8")
                ast.parse(content)
            except SyntaxError as e:
                issues.append(f"Syntax error in {py_file.name}: line {e.lineno}: {e.msg}")
            except (OSError, UnicodeDecodeError, ValueError) as e:
                issues.append(f"Error parsing {py_file.name}: {type(e).__name__}: {e}")

    if issues:
        logger.warning("Validation found %d issue(s) in synthesized package", len(issues))
    else:
        logger.info("All synthesized files validated successfully")

    return str(pkg_path), issues

Matrices

Code-generation helpers used by the synthesizer to render the A/B/C/D matrices module.

cogant.reverse.matrices

Standalone matrix modules embedding the shared categorical numerical kernel.

render_matrices_module(model)

Embed the shared stdlib categorical kernel with the exact source matrices.

Source code in py/cogant/reverse/matrices.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def render_matrices_module(model: ReverseGNNModel) -> str:
    """Embed the shared stdlib categorical kernel with the exact source matrices."""
    _validate_matrix_semantics(model)
    kernel = inspect.getsource(categorical).replace("from __future__ import annotations\n", "")
    constants = [
        f"N_HIDDEN_STATES: int = {model.n_states}",
        f"N_OBSERVATIONS: int = {model.n_obs}",
        f"N_ACTIONS: int = {model.n_actions}",
        f"DEGRADED_SOURCE_PROJECTION = {model.degraded!r}",
        f"SOURCE_DIAGNOSTICS = {model.diagnostics!r}",
        f"A = {_format_matrix_2d(model.A)}",
        f"B = {_format_tensor_3d(model.B)}",
        f"C = {_format_vector(model.C)}",
        f"D = {_format_vector(model.D)}",
        "INITIAL_STATE_PRIOR = list(D)",
    ]
    helpers = """
def likelihood(state_dist: list[float]) -> list[float]:
    return CategoricalModel(A, B, C, D).observe(state_dist)


def transition(state_dist: list[float], action: int = 0) -> list[float]:
    return CategoricalModel(A, B, C, D).predict(state_dist, action)


def preference_score(obs_dist: list[float]) -> float:
    return CategoricalModel(A, B, C, D).preference_score(obs_dist)


def expected_free_energy(state_dist: list[float], action: int) -> float:
    return CategoricalModel(A, B, C, D).score(state_dist, [action])


def score_preference_gradient(state_dist: list[float], policy: list[int]) -> list[float]:
    '''Return fixed-policy score sensitivity along the C observation axis.'''
    return CategoricalModel(A, B, C, D).score_preference_gradient(state_dist, policy)


def best_action(state_dist: list[float]) -> int:
    scores = CategoricalModel(A, B, C, D).action_scores(state_dist)
    return min(range(N_ACTIONS), key=scores.__getitem__)


def inference_step(state_dist: list[float], observation: int | None = None) -> CategoricalStep:
    return CategoricalModel(A, B, C, D).step(state_dist, observation)
"""
    return kernel + "\n" + "\n".join(constants) + "\n" + helpers

Metrics

Roundtrip error (ε) and isomorphism metrics — the empirical bar the forward-reverse cycle is held against.

cogant.reverse.metrics

GNN-to-GNN distance and isomorphism metrics.

This module supplies the real, principled distance functions used by :mod:cogant.reverse.idempotency when it asks the question "is the round-tripped GNN isomorphic to the source GNN?".

Three orthogonal views of "close" are measured and then fused into a single :class:IsomorphismReport:

  • Role distribution — a Jensen-Shannon divergence between the two role multisets (HIDDEN_STATE, OBSERVATION, ACTION, ...). JS-divergence is bounded in [0, log 2] for base-e and in [0, 1] for base-2. We use base-2 and invert so that identical distributions score 1.0 and disjoint supports score 0.0.
  • Matrix Frobenius distance — for each Active Inference matrix A (likelihood), B (transition), C (preferences), D (prior) present in both packages, we compute the normalized Frobenius distance ||M1 - M2|| / (||M1|| + ||M2|| + eps) and convert it to a score 1 - d. Matrices of mismatched shape are zero-padded to a common envelope before subtraction so the metric is defined for round-trips that change factor cardinality. We average over matrix types present in both dicts; if no shared matrix types exist the score is the neutral value 0.5.
  • Graph structure — a normalized symmetric-difference distance between the multisets of node roles and between the multisets of edge-role-pairs. This is intentionally weaker than exact graph edit distance (which is NP-hard and overkill here) but captures the right intuition: "did the synthesized package grow or drop nodes and edges relative to the source?". The returned score is 1 - normalized_symdiff.

The three scores are combined with the weights 0.4 * role + 0.4 * matrix + 0.2 * structural — role and matrix carry equal top billing because they are the scientifically meaningful axes for an Active Inference model, while structural drift is treated as a tie-breaker. The cutoff for structurally_isomorphic defaults to 0.7 and can be tightened by the caller.

All functions in this module are pure and free of side effects. The only external dependency is NumPy, which the cogant test environment provides (numpy>=2.0). Inputs may be NumPy arrays or plain Python lists; they are coerced to float64 on entry.

DEFAULT_ISOMORPHISM_THRESHOLD = 0.7 module-attribute

Default cutoff for :attr:IsomorphismReport.structurally_isomorphic.

MATRIX_KEYS = ('A', 'B', 'C', 'D') module-attribute

Canonical Active Inference matrix slot names used by COGANT.

IsomorphismReport dataclass

Aggregate GNN-to-GNN distance report.

All *_score fields are in [0.0, 1.0] where 1.0 means "identical" and 0.0 means "maximally different under this metric". The total_score is the weighted mean of the three component scores and is itself in [0.0, 1.0]. structurally_isomorphic is simply total_score >= threshold.

Attributes:

Name Type Description
structural_score float

Graph-structure similarity in [0, 1].

role_score float

Role distribution similarity (inverted JS divergence) in [0, 1].

matrix_score float

Frobenius-based matrix similarity in [0, 1].

total_score float

Weighted mean 0.4 * role + 0.4 * matrix + 0.2 * structural.

structurally_isomorphic bool

True when total_score >= threshold.

breakdown dict[str, Any]

Per-metric diagnostic detail. Keys include the three component scores, the threshold, the weighting, and (when available) per-matrix Frobenius distances.

Source code in py/cogant/reverse/metrics.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
@dataclass
class IsomorphismReport:
    """Aggregate GNN-to-GNN distance report.

    All ``*_score`` fields are in ``[0.0, 1.0]`` where ``1.0`` means
    "identical" and ``0.0`` means "maximally different under this
    metric". The ``total_score`` is the weighted mean of the three
    component scores and is itself in ``[0.0, 1.0]``. ``structurally_isomorphic``
    is simply ``total_score >= threshold``.

    Attributes:
        structural_score: Graph-structure similarity in ``[0, 1]``.
        role_score: Role distribution similarity (inverted JS
            divergence) in ``[0, 1]``.
        matrix_score: Frobenius-based matrix similarity in ``[0, 1]``.
        total_score: Weighted mean
            ``0.4 * role + 0.4 * matrix + 0.2 * structural``.
        structurally_isomorphic: True when ``total_score >= threshold``.
        breakdown: Per-metric diagnostic detail. Keys include the
            three component scores, the threshold, the weighting, and
            (when available) per-matrix Frobenius distances.
    """

    structural_score: float = 0.0
    role_score: float = 0.0
    matrix_score: float = 0.0
    total_score: float = 0.0
    structurally_isomorphic: bool = False
    breakdown: dict[str, Any] = field(default_factory=dict)

    def summary(self) -> str:
        """Return a compact, human-readable one-line summary.

        The format is::

            [ISO] total=0.82 role=0.90 matrix=0.85 struct=0.60

        with ``ISO`` swapped for ``DRIFT`` when
        ``structurally_isomorphic`` is False.
        """
        status = "ISO" if self.structurally_isomorphic else "DRIFT"
        return (
            f"[{status}] total={self.total_score:.2f} "
            f"role={self.role_score:.2f} "
            f"matrix={self.matrix_score:.2f} "
            f"struct={self.structural_score:.2f}"
        )

summary()

Return a compact, human-readable one-line summary.

The format is::

[ISO] total=0.82 role=0.90 matrix=0.85 struct=0.60

with ISO swapped for DRIFT when structurally_isomorphic is False.

Source code in py/cogant/reverse/metrics.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def summary(self) -> str:
    """Return a compact, human-readable one-line summary.

    The format is::

        [ISO] total=0.82 role=0.90 matrix=0.85 struct=0.60

    with ``ISO`` swapped for ``DRIFT`` when
    ``structurally_isomorphic`` is False.
    """
    status = "ISO" if self.structurally_isomorphic else "DRIFT"
    return (
        f"[{status}] total={self.total_score:.2f} "
        f"role={self.role_score:.2f} "
        f"matrix={self.matrix_score:.2f} "
        f"struct={self.structural_score:.2f}"
    )

compare_graph_structure(nodes_a, edges_a, nodes_b, edges_b)

Return a graph-structure similarity score in [0, 1].

We build two multisets for each graph:

  1. role(nodes) — one bucket per node role label.
  2. (source_role, target_role) — one bucket per edge.

We then compute the normalized symmetric difference of each multiset separately and return 1 - mean(d_nodes, d_edges). Nodes-only graphs (no edges on either side) skip the edge term.

Edge cases:

  • Both graphs empty → return 1.0 (vacuously identical).
  • One graph empty, other non-empty → return 0.0.

Parameters:

Name Type Description Default
nodes_a Sequence[Any]

Iterable of node-like objects for graph A.

required
edges_a Sequence[Any]

Iterable of edge-like objects for graph A.

required
nodes_b Sequence[Any]

Iterable of node-like objects for graph B.

required
edges_b Sequence[Any]

Iterable of edge-like objects for graph B.

required

Returns:

Type Description
float

Similarity score in [0.0, 1.0].

Source code in py/cogant/reverse/metrics.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def compare_graph_structure(
    nodes_a: Sequence[Any],
    edges_a: Sequence[Any],
    nodes_b: Sequence[Any],
    edges_b: Sequence[Any],
) -> float:
    """Return a graph-structure similarity score in ``[0, 1]``.

    We build two multisets for each graph:

    1. ``role(nodes)`` — one bucket per node role label.
    2. ``(source_role, target_role)`` — one bucket per edge.

    We then compute the normalized symmetric difference of each
    multiset separately and return ``1 - mean(d_nodes, d_edges)``.
    Nodes-only graphs (no edges on either side) skip the edge term.

    Edge cases:

    * Both graphs empty → return ``1.0`` (vacuously identical).
    * One graph empty, other non-empty → return ``0.0``.

    Args:
        nodes_a: Iterable of node-like objects for graph A.
        edges_a: Iterable of edge-like objects for graph A.
        nodes_b: Iterable of node-like objects for graph B.
        edges_b: Iterable of edge-like objects for graph B.

    Returns:
        Similarity score in ``[0.0, 1.0]``.
    """
    n_a = list(nodes_a or [])
    n_b = list(nodes_b or [])
    e_a = list(edges_a or [])
    e_b = list(edges_b or [])

    if not n_a and not n_b and not e_a and not e_b:
        return 1.0
    if (not n_a and n_b) or (n_a and not n_b):
        # One side has zero nodes, the other has some — maximally
        # different at the structural level.
        if not e_a and not e_b:
            return 0.0

    node_labels_a = _multiset(_node_role_label(n) for n in n_a)
    node_labels_b = _multiset(_node_role_label(n) for n in n_b)
    node_total = sum(node_labels_a.values()) + sum(node_labels_b.values())
    node_symdiff = _multiset_symmetric_difference(node_labels_a, node_labels_b)
    node_distance = (node_symdiff / node_total) if node_total > 0 else 0.0

    edge_labels_a = _multiset(_edge_role_pair(e) for e in e_a)
    edge_labels_b = _multiset(_edge_role_pair(e) for e in e_b)
    edge_total = sum(edge_labels_a.values()) + sum(edge_labels_b.values())
    if edge_total > 0:
        edge_symdiff = _multiset_symmetric_difference(edge_labels_a, edge_labels_b)
        edge_distance = edge_symdiff / edge_total
        distance = 0.5 * (node_distance + edge_distance)
    else:
        distance = node_distance

    distance = max(0.0, min(1.0, distance))
    return 1.0 - distance

compare_matrices(matrices_a, matrices_b)

Return an averaged Frobenius-similarity score in [0, 1].

For each canonical Active Inference matrix slot (A, B, C, D) present in both input dicts and non-empty on both sides, we compute::

1 - ||m1 - m2||_F / (||m1||_F + ||m2||_F + eps)

after zero-padding the two matrices to their common bounding shape. The returned score is the unweighted mean of these per-matrix similarities.

Edge cases:

  • If neither side has any recognisable numeric matrix entry, return 0.5 (neutral — the metric is undefined, not zero).
  • If a key is present on only one side it is ignored (the structural-graph score is the axis that penalises missing slots).
  • Extra keys beyond {A, B, C, D} are tolerated and included.

The metric is symmetric: compare_matrices(a, b) == compare_matrices(b, a) up to floating point round-off.

Parameters:

Name Type Description Default
matrices_a Mapping[str, Any]

Dict mapping matrix name to a 2D array-like.

required
matrices_b Mapping[str, Any]

Dict mapping matrix name to a 2D array-like.

required

Returns:

Type Description
float

Mean similarity score in [0, 1], or 0.5 when no

float

comparable matrices exist.

Source code in py/cogant/reverse/metrics.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def compare_matrices(
    matrices_a: Mapping[str, Any],
    matrices_b: Mapping[str, Any],
) -> float:
    """Return an averaged Frobenius-similarity score in ``[0, 1]``.

    For each canonical Active Inference matrix slot
    (``A``, ``B``, ``C``, ``D``) present in **both** input dicts and
    non-empty on both sides, we compute::

        1 - ||m1 - m2||_F / (||m1||_F + ||m2||_F + eps)

    after zero-padding the two matrices to their common bounding
    shape. The returned score is the unweighted mean of these
    per-matrix similarities.

    Edge cases:

    * If neither side has any recognisable numeric matrix entry,
      return ``0.5`` (neutral — the metric is undefined, not zero).
    * If a key is present on only one side it is ignored (the
      structural-graph score is the axis that penalises missing
      slots).
    * Extra keys beyond ``{A, B, C, D}`` are tolerated and included.

    The metric is symmetric: ``compare_matrices(a, b) ==
    compare_matrices(b, a)`` up to floating point round-off.

    Args:
        matrices_a: Dict mapping matrix name to a 2D array-like.
        matrices_b: Dict mapping matrix name to a 2D array-like.

    Returns:
        Mean similarity score in ``[0, 1]``, or ``0.5`` when no
        comparable matrices exist.
    """
    # Stable key ordering: canonical A/B/C/D first, then any extras
    # sorted alphabetically.
    shared_keys: list[str] = []
    for key in MATRIX_KEYS:
        if key in matrices_a and key in matrices_b:
            shared_keys.append(key)
    extras = sorted((set(matrices_a.keys()) & set(matrices_b.keys())) - set(MATRIX_KEYS))
    shared_keys.extend(extras)

    if not shared_keys:
        return 0.5

    scores: list[float] = []
    for key in shared_keys:
        arr_a = _coerce_matrix(matrices_a.get(key))
        arr_b = _coerce_matrix(matrices_b.get(key))
        if arr_a is None or arr_b is None:
            continue
        score, _ = _matrix_pair_score(arr_a, arr_b)
        scores.append(score)

    if not scores:
        return 0.5
    return float(sum(scores) / len(scores))

compare_role_distributions(roles_a, roles_b)

Return a similarity score in [0, 1] for two role multisets.

The underlying distance is the Jensen-Shannon divergence in base 2, which for two probability vectors p and q is::

JS(p, q) = 0.5 * KL(p || M) + 0.5 * KL(q || M),  M = 0.5*(p+q)

and is bounded in [0, 1]. We return 1 - JS so that higher is better.

Edge cases:

  • If both distributions are empty, we return 0.0 (there is no distribution to compare, and the spec asks for a neutral-low value here so that the overall isomorphism score does not spuriously inflate on degenerate inputs).
  • If exactly one distribution is empty, we also return 0.0 (maximally different — one side has no roles at all).

Parameters:

Name Type Description Default
roles_a Mapping[str, float]

Mapping from role name to count (or weight).

required
roles_b Mapping[str, float]

Mapping from role name to count (or weight).

required

Returns:

Type Description
float

Similarity score in [0.0, 1.0]. 1.0 means the two role

float

distributions are identical; 0.0 means their supports are

float

disjoint or one side is empty.

Source code in py/cogant/reverse/metrics.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def compare_role_distributions(
    roles_a: Mapping[str, float],
    roles_b: Mapping[str, float],
) -> float:
    """Return a similarity score in ``[0, 1]`` for two role multisets.

    The underlying distance is the Jensen-Shannon divergence in base 2,
    which for two probability vectors ``p`` and ``q`` is::

        JS(p, q) = 0.5 * KL(p || M) + 0.5 * KL(q || M),  M = 0.5*(p+q)

    and is bounded in ``[0, 1]``. We return ``1 - JS`` so that higher
    is better.

    Edge cases:

    * If both distributions are empty, we return ``0.0`` (there is no
      distribution to compare, and the spec asks for a neutral-low
      value here so that the overall isomorphism score does not
      spuriously inflate on degenerate inputs).
    * If exactly one distribution is empty, we also return ``0.0``
      (maximally different — one side has no roles at all).

    Args:
        roles_a: Mapping from role name to count (or weight).
        roles_b: Mapping from role name to count (or weight).

    Returns:
        Similarity score in ``[0.0, 1.0]``. ``1.0`` means the two role
        distributions are identical; ``0.0`` means their supports are
        disjoint or one side is empty.
    """
    total_a = sum(float(v) for v in roles_a.values())
    total_b = sum(float(v) for v in roles_b.values())

    if total_a <= 0.0 and total_b <= 0.0:
        return 0.0
    if total_a <= 0.0 or total_b <= 0.0:
        return 0.0

    support: list[str] = sorted(set(roles_a.keys()) | set(roles_b.keys()))
    p = _to_probability(roles_a, support)
    q = _to_probability(roles_b, support)

    m = 0.5 * (p + q)
    js = 0.5 * _kl_divergence(p, m) + 0.5 * _kl_divergence(q, m)
    # Numerical clamp: floating point can produce tiny negatives or
    # values a hair above 1.0.
    js = max(0.0, min(1.0, js))
    return 1.0 - js

compute_isomorphism_report(gnn_a, gnn_b, threshold=DEFAULT_ISOMORPHISM_THRESHOLD)

Compute a full :class:IsomorphismReport for two GNN packages.

gnn_a and gnn_b are expected to be dict-like bundles with the following optional keys:

  • roles — {role_name: count} multiset.
  • matrices — {"A"|"B"|"C"|"D": array_like} dict.
  • nodes — iterable of node objects or dicts.
  • edges — iterable of edge objects or dicts.

Missing keys are tolerated: the corresponding component score falls back to its documented neutral value (0.0 for roles, 0.5 for matrices, 1.0 for an empty graph).

The three component scores are combined with fixed weights::

total = 0.4 * role + 0.4 * matrix + 0.2 * structural

and structurally_isomorphic is total >= threshold.

Parameters:

Name Type Description Default
gnn_a Mapping[str, Any]

First GNN package dict.

required
gnn_b Mapping[str, Any]

Second GNN package dict.

required
threshold float

Cutoff for :attr:IsomorphismReport.structurally_isomorphic. Defaults to :data:DEFAULT_ISOMORPHISM_THRESHOLD (0.7).

DEFAULT_ISOMORPHISM_THRESHOLD

Returns:

Type Description
IsomorphismReport

A fully populated :class:IsomorphismReport.

Source code in py/cogant/reverse/metrics.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
def compute_isomorphism_report(
    gnn_a: Mapping[str, Any],
    gnn_b: Mapping[str, Any],
    threshold: float = DEFAULT_ISOMORPHISM_THRESHOLD,
) -> IsomorphismReport:
    """Compute a full :class:`IsomorphismReport` for two GNN packages.

    ``gnn_a`` and ``gnn_b`` are expected to be dict-like bundles with
    the following optional keys:

    * ``roles`` — ``{role_name: count}`` multiset.
    * ``matrices`` — ``{"A"|"B"|"C"|"D": array_like}`` dict.
    * ``nodes`` — iterable of node objects or dicts.
    * ``edges`` — iterable of edge objects or dicts.

    Missing keys are tolerated: the corresponding component score
    falls back to its documented neutral value (``0.0`` for roles,
    ``0.5`` for matrices, ``1.0`` for an empty graph).

    The three component scores are combined with fixed weights::

        total = 0.4 * role + 0.4 * matrix + 0.2 * structural

    and ``structurally_isomorphic`` is ``total >= threshold``.

    Args:
        gnn_a: First GNN package dict.
        gnn_b: Second GNN package dict.
        threshold: Cutoff for :attr:`IsomorphismReport.structurally_isomorphic`.
            Defaults to :data:`DEFAULT_ISOMORPHISM_THRESHOLD` (0.7).

    Returns:
        A fully populated :class:`IsomorphismReport`.
    """
    roles_a: Mapping[str, float] = gnn_a.get("roles", {}) or {}
    roles_b: Mapping[str, float] = gnn_b.get("roles", {}) or {}
    matrices_a: Mapping[str, Any] = gnn_a.get("matrices", {}) or {}
    matrices_b: Mapping[str, Any] = gnn_b.get("matrices", {}) or {}
    nodes_a: Sequence[Any] = gnn_a.get("nodes", []) or []
    nodes_b: Sequence[Any] = gnn_b.get("nodes", []) or []
    edges_a: Sequence[Any] = gnn_a.get("edges", []) or []
    edges_b: Sequence[Any] = gnn_b.get("edges", []) or []

    role_score = compare_role_distributions(roles_a, roles_b)
    matrix_score = compare_matrices(matrices_a, matrices_b)
    structural_score = compare_graph_structure(nodes_a, edges_a, nodes_b, edges_b)

    total_score = (
        _ROLE_WEIGHT * role_score
        + _MATRIX_WEIGHT * matrix_score
        + _STRUCTURAL_WEIGHT * structural_score
    )
    # Clamp for floating-point safety.
    total_score = max(0.0, min(1.0, total_score))

    breakdown: dict[str, Any] = {
        "role_score": role_score,
        "matrix_score": matrix_score,
        "structural_score": structural_score,
        "weights": {
            "role": _ROLE_WEIGHT,
            "matrix": _MATRIX_WEIGHT,
            "structural": _STRUCTURAL_WEIGHT,
        },
        "threshold": threshold,
        "roles_a_total": sum(float(v) for v in roles_a.values()),
        "roles_b_total": sum(float(v) for v in roles_b.values()),
        "matrix_keys_a": sorted(matrices_a.keys()),
        "matrix_keys_b": sorted(matrices_b.keys()),
        "n_nodes_a": len(list(nodes_a)),
        "n_nodes_b": len(list(nodes_b)),
        "n_edges_a": len(list(edges_a)),
        "n_edges_b": len(list(edges_b)),
    }

    # Per-matrix raw Frobenius detail, if we can compute it cheaply.
    per_matrix: dict[str, float] = {}
    for key in MATRIX_KEYS:
        if key in matrices_a and key in matrices_b:
            arr_a = _coerce_matrix(matrices_a.get(key))
            arr_b = _coerce_matrix(matrices_b.get(key))
            if arr_a is not None and arr_b is not None:
                _, raw = _matrix_pair_score(arr_a, arr_b)
                per_matrix[key] = raw
    if per_matrix:
        breakdown["per_matrix_frobenius"] = per_matrix

    return IsomorphismReport(
        structural_score=float(structural_score),
        role_score=float(role_score),
        matrix_score=float(matrix_score),
        total_score=float(total_score),
        structurally_isomorphic=bool(total_score >= threshold),
        breakdown=breakdown,
    )

Idempotency

Helpers for the idempotency checks that drive the roundtrip ε metric.

cogant.reverse.idempotency

Round-trip idempotency verifier.

This module answers the question: "If we synthesize a Python package from a GNN markdown file and then re-run COGANT forward on the resulting package, what survived the round-trip?"

Earlier versions used one role-overlap score and called the result "isomorphic". That was too strong: COGANT can preserve the semantic roles that matter for active-inference interpretation while still changing graph counts, section text, matrix values, or generated-code behavior. The public contract is now an invariant ledger plus a roundtrip_status taxonomy:

STRUCTURALLY_ISOMORPHIC The strict tier: role preservation passes, graph node/edge counts and edge kinds match, state-space and matrix invariants hold, GNN sections are preserved, generated code imports/compiles, and the second forward pass succeeded.

ROLE_PRESERVED The useful weaker tier: the source and regenerated artifacts preserve the semantic role multiset above the configured threshold, but at least one strict structural invariant drifted or was not observable.

DRIFT The round-trip completed but role preservation did not meet the configured threshold.

FAILED Synthesis or the second forward pass failed.

The role metric is intentionally soft. The forward pipeline emits semantic mappings for any pattern it recognises, including patterns the synthesizer did not explicitly model. The verifier rewards overlap but reports extra/missing roles, graph deltas, matrix deltas, and GNN section deltas instead of collapsing distinct evidence into one label.

MATRIX_VALUE_TOLERANCE = 1e-09 module-attribute

Maximum absolute A/B/C/D value delta allowed for strict preservation.

ROLE_PRESERVATION_THRESHOLD = 0.5 module-attribute

Default minimum role-preservation score for the weaker success tier.

IdempotencyReport dataclass

Detailed structural and semantic idempotency analysis.

Attributes:

Name Type Description
is_idempotent bool

True if the round-trip preserved structural and semantic properties above their respective thresholds.

forward_roles dict[str, int]

Role multiset from the original forward pipeline run on the source code (before synthesis).

reverse_roles dict[str, int]

Role multiset from the re-run of forward on the synthesized code.

differences list[str]

List of human-readable differences found between forward_roles and reverse_roles.

score float

A composite score in [0.0, 1.0] combining role match, structural match, and semantic match. Higher is better.

Source code in py/cogant/reverse/idempotency.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
@dataclass
class IdempotencyReport:
    """Detailed structural and semantic idempotency analysis.

    Attributes:
        is_idempotent: True if the round-trip preserved structural and
            semantic properties above their respective thresholds.
        forward_roles: Role multiset from the original forward pipeline
            run on the source code (before synthesis).
        reverse_roles: Role multiset from the re-run of forward on
            the synthesized code.
        differences: List of human-readable differences found between
            forward_roles and reverse_roles.
        score: A composite score in [0.0, 1.0] combining role match,
            structural match, and semantic match. Higher is better.
    """

    is_idempotent: bool = False
    forward_roles: dict[str, int] = field(default_factory=dict)
    reverse_roles: dict[str, int] = field(default_factory=dict)
    differences: list[str] = field(default_factory=list)
    score: float = 0.0

RoundtripResult dataclass

Outcome of a single round-trip verification run.

Attributes:

Name Type Description
roundtrip_status str

One of ROUNDTRIP_STATUSES.

role_preservation_score float

Per-role mean of min(original_count, synthesized_count) / max(original_count, synthesized_count) over the union of original and synthesized role multisets. Range [0.0, 1.0].

role_preserved bool

True when role_preservation_score meets the configured threshold.

structurally_isomorphic bool

True only when the full strict invariant ledger passes.

matrix_preserved bool

True when observed A/B/C/D shapes and values are preserved within tolerance.

gnn_sections_preserved bool

True when Markdown section membership survives the round-trip exactly.

generated_code_ok bool

True when synthesized Python files import through py_compile.

vacuous_roundtrip bool

True when both role multisets are empty and the role-preservation score's 1.0 value is vacuous.

matrix_score float

Frobenius-based similarity of the A/B/C/D matrix stacks produced by the two sides of the round-trip. Range [0.0, 1.0]. Defaults to 0.0 when matrices were not available on either side of the comparison.

structural_score float

Graph-structure similarity (node/edge role multiset symmetric difference, normalized and inverted). Range [0.0, 1.0]. Defaults to 0.0 when the round-trip did not expose a node/edge view.

original_roles dict[str, int]

Role multiset derived from the source GNN ({role_name: count}).

synthesized_roles dict[str, int]

Role multiset from the forward pipeline's semantic mappings after reverse-synthesis, restricted to the role-bearing definitions named in the package's semantic-target manifest (generated runtime support code is not scored).

shape_match dict[str, bool]

Dict describing whether n_states, n_obs, and n_actions dimensions survived the round-trip.

package_path: Absolute path to the synthesized package (kept on disk if the caller passed a persistent tmp_dir). original_graph_summary: Node/edge/kind summary for the first graph view in the comparison. synthesized_graph_summary: Node/edge/kind summary for the graph produced by the forward re-run. graph_delta: Count and kind deltas between the graph summaries. gnn_diff: Section-level diff between original and regenerated GNN Markdown when both sides are available. matrix_delta: Shape/value deltas for A/B/C/D matrices when parseable GNN matrix blocks are available. invariants: Explicit pass/fail invariants for the code → graph → GNN → code → graph cycle. rule_evidence_trace: Rule/mapping evidence artifact from the synthesized forward pass, suitable for dashboard review. warnings: Non-fatal diagnostic warnings collected during the round-trip that do not affect status. errors: Non-fatal errors collected during the round-trip.

Source code in py/cogant/reverse/idempotency.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
@dataclass(init=False)
class RoundtripResult:
    """Outcome of a single round-trip verification run.

    Attributes:
        roundtrip_status: One of ``ROUNDTRIP_STATUSES``.
        role_preservation_score: Per-role mean of
            ``min(original_count, synthesized_count) /
            max(original_count, synthesized_count)`` over the union of
            original and synthesized role multisets. Range ``[0.0, 1.0]``.
        role_preserved: True when ``role_preservation_score`` meets
            the configured threshold.
        structurally_isomorphic: True only when the full strict
            invariant ledger passes.
        matrix_preserved: True when observed A/B/C/D shapes and values
            are preserved within tolerance.
        gnn_sections_preserved: True when Markdown section membership
            survives the round-trip exactly.
        generated_code_ok: True when synthesized Python files import
            through ``py_compile``.
        vacuous_roundtrip: True when both role multisets are empty and
            the role-preservation score's 1.0 value is vacuous.
        matrix_score: Frobenius-based similarity of the A/B/C/D
            matrix stacks produced by the two sides of the round-trip.
            Range ``[0.0, 1.0]``. Defaults to ``0.0`` when matrices
            were not available on either side of the comparison.
        structural_score: Graph-structure similarity (node/edge role
            multiset symmetric difference, normalized and inverted).
            Range ``[0.0, 1.0]``. Defaults to ``0.0`` when the
            round-trip did not expose a node/edge view.
        original_roles: Role multiset derived from the source GNN
            (``{role_name: count}``).
        synthesized_roles: Role multiset from the forward pipeline's
            semantic mappings after reverse-synthesis, restricted to the
            role-bearing definitions named in the package's semantic-target
            manifest (generated runtime support code is not scored).
        shape_match: Dict describing whether n_states, n_obs, and
            n_actions dimensions survived the round-trip.
    package_path: Absolute path to the synthesized package (kept
            on disk if the caller passed a persistent ``tmp_dir``).
        original_graph_summary: Node/edge/kind summary for the first
            graph view in the comparison.
        synthesized_graph_summary: Node/edge/kind summary for the
            graph produced by the forward re-run.
        graph_delta: Count and kind deltas between the graph summaries.
        gnn_diff: Section-level diff between original and regenerated
            GNN Markdown when both sides are available.
        matrix_delta: Shape/value deltas for A/B/C/D matrices when
            parseable GNN matrix blocks are available.
        invariants: Explicit pass/fail invariants for the
            code → graph → GNN → code → graph cycle.
        rule_evidence_trace: Rule/mapping evidence artifact from the
            synthesized forward pass, suitable for dashboard review.
        warnings: Non-fatal diagnostic warnings collected during the
            round-trip that do not affect status.
        errors: Non-fatal errors collected during the round-trip.
    """

    roundtrip_status: str
    role_preservation_score: float
    role_preserved: bool
    structurally_isomorphic: bool
    matrix_preserved: bool
    gnn_sections_preserved: bool
    generated_code_ok: bool
    vacuous_roundtrip: bool
    matrix_score: float = 0.0
    structural_score: float = 0.0
    original_roles: dict[str, int]
    synthesized_roles: dict[str, int]
    shape_match: dict[str, bool]
    package_path: Path | None = None
    original_graph_summary: dict[str, Any]
    synthesized_graph_summary: dict[str, Any]
    graph_delta: dict[str, Any]
    gnn_diff: dict[str, Any]
    matrix_delta: dict[str, Any]
    invariants: dict[str, Any]
    rule_evidence_trace: dict[str, Any]
    warnings: list[str]
    errors: list[str]

    def __init__(
        self,
        *,
        roundtrip_status: str | None = None,
        role_preservation_score: float = 0.0,
        role_preserved: bool | None = None,
        structurally_isomorphic: bool | None = None,
        matrix_preserved: bool | None = None,
        gnn_sections_preserved: bool | None = None,
        generated_code_ok: bool | None = None,
        vacuous_roundtrip: bool | None = None,
        matrix_score: float = 0.0,
        structural_score: float = 0.0,
        original_roles: dict[str, int] | None = None,
        synthesized_roles: dict[str, int] | None = None,
        shape_match: dict[str, bool] | None = None,
        package_path: Path | None = None,
        original_graph_summary: dict[str, Any] | None = None,
        synthesized_graph_summary: dict[str, Any] | None = None,
        graph_delta: dict[str, Any] | None = None,
        gnn_diff: dict[str, Any] | None = None,
        matrix_delta: dict[str, Any] | None = None,
        invariants: dict[str, Any] | None = None,
        rule_evidence_trace: dict[str, Any] | None = None,
        warnings: list[str] | None = None,
        errors: list[str] | None = None,
    ) -> None:
        self.role_preservation_score = float(role_preservation_score)
        if role_preserved is None:
            role_preserved = self.role_preservation_score >= ROLE_PRESERVATION_THRESHOLD
        self.role_preserved = bool(role_preserved)

        self.invariants = dict(invariants or {})
        if matrix_preserved is None:
            matrix_preserved = bool(self.invariants.get("matrix_preserved", False))
        if gnn_sections_preserved is None:
            gnn_sections_preserved = bool(self.invariants.get("gnn_sections_preserved", False))
        if generated_code_ok is None:
            generated_code_ok = bool(self.invariants.get("generated_code_ok", False))
        if structurally_isomorphic is None:
            structurally_isomorphic = _strict_invariants_preserved(
                role_preserved=self.role_preserved,
                matrix_preserved=bool(matrix_preserved),
                gnn_sections_preserved=bool(gnn_sections_preserved),
                generated_code_ok=bool(generated_code_ok),
                invariants=self.invariants,
            )

        self.matrix_preserved = bool(matrix_preserved)
        self.gnn_sections_preserved = bool(gnn_sections_preserved)
        self.generated_code_ok = bool(generated_code_ok)
        self.vacuous_roundtrip = bool(vacuous_roundtrip)
        self.structurally_isomorphic = bool(structurally_isomorphic)
        self.roundtrip_status = roundtrip_status or _roundtrip_status_from_invariants(
            role_preserved=self.role_preserved,
            structurally_isomorphic=self.structurally_isomorphic,
            errors=errors or [],
        )
        if self.roundtrip_status not in ROUNDTRIP_STATUSES:
            self.roundtrip_status = ROUNDTRIP_STATUS_FAILED

        self.matrix_score = float(matrix_score)
        self.structural_score = float(structural_score)
        self.original_roles = dict(original_roles or {})
        self.synthesized_roles = dict(synthesized_roles or {})
        self.shape_match = dict(shape_match or {})
        self.package_path = package_path
        self.original_graph_summary = dict(original_graph_summary or {})
        self.synthesized_graph_summary = dict(synthesized_graph_summary or {})
        self.graph_delta = dict(graph_delta or {})
        self.gnn_diff = dict(gnn_diff or {})
        self.matrix_delta = dict(matrix_delta or {})
        self.rule_evidence_trace = dict(rule_evidence_trace or {})
        self.warnings = list(warnings or [])
        self.errors = list(errors or [])

    def summary(self) -> str:
        """Return a human-readable single-line summary of the result."""
        return (
            f"[{self.roundtrip_status}] role_preservation={self.role_preservation_score:.2%} "
            f"matrix={self.matrix_score:.2f} "
            f"struct={self.structural_score:.2f} "
            f"orig={dict(self.original_roles)} "
            f"synth={dict(self.synthesized_roles)}"
        )

summary()

Return a human-readable single-line summary of the result.

Source code in py/cogant/reverse/idempotency.py
273
274
275
276
277
278
279
280
281
def summary(self) -> str:
    """Return a human-readable single-line summary of the result."""
    return (
        f"[{self.roundtrip_status}] role_preservation={self.role_preservation_score:.2%} "
        f"matrix={self.matrix_score:.2f} "
        f"struct={self.structural_score:.2f} "
        f"orig={dict(self.original_roles)} "
        f"synth={dict(self.synthesized_roles)}"
    )

check_semantic_idempotency(original_mappings, roundtrip_mappings)

Check semantic idempotency of two semantic-mapping dicts.

Compares the role populations and distributions of two sets of semantic mappings.

Parameters:

Name Type Description Default
original_mappings dict[str, Any]

Semantic mappings from the original forward run.

required
roundtrip_mappings dict[str, Any]

Semantic mappings from the re-run.

required

Returns:

Type Description
IdempotencyReport

An IdempotencyReport describing semantic similarities and

IdempotencyReport

differences.

Source code in py/cogant/reverse/idempotency.py
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
def check_semantic_idempotency(
    original_mappings: dict[str, Any], roundtrip_mappings: dict[str, Any]
) -> IdempotencyReport:
    """Check semantic idempotency of two semantic-mapping dicts.

    Compares the role populations and distributions of two sets of
    semantic mappings.

    Args:
        original_mappings: Semantic mappings from the original forward run.
        roundtrip_mappings: Semantic mappings from the re-run.

    Returns:
        An IdempotencyReport describing semantic similarities and
        differences.
    """
    report = IdempotencyReport()

    orig_roles = _role_multiset_from_mappings(original_mappings)
    rt_roles = _role_multiset_from_mappings(roundtrip_mappings)

    report.forward_roles = dict(orig_roles)
    report.reverse_roles = dict(rt_roles)

    # Find differences
    all_roles = set(orig_roles.keys()) | set(rt_roles.keys())
    for role in sorted(all_roles):
        orig_count = orig_roles.get(role, 0)
        rt_count = rt_roles.get(role, 0)
        if orig_count != rt_count:
            report.differences.append(f"Role {role}: {orig_count} → {rt_count}")

    # Compute Jensen-Shannon-like score
    if orig_roles and rt_roles:
        intersection = sum(min(orig_roles.get(r, 0), rt_roles.get(r, 0)) for r in all_roles)
        union = sum(max(orig_roles.get(r, 0), rt_roles.get(r, 0)) for r in all_roles)
        report.score = intersection / union if union > 0 else 0.0
    else:
        report.score = 0.0

    report.is_idempotent = len(report.differences) == 0

    return report

check_structural_idempotency(original_graph, roundtrip_graph)

Check structural idempotency of two program graphs.

Compares the node and edge populations of two graphs to determine if they have the same structural shape.

Parameters:

Name Type Description Default
original_graph Any

The original ProgramGraph or compatible structure.

required
roundtrip_graph Any

The ProgramGraph from the re-run.

required

Returns:

Type Description
IdempotencyReport

An IdempotencyReport describing structural similarities and

IdempotencyReport

differences.

Source code in py/cogant/reverse/idempotency.py
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
def check_structural_idempotency(original_graph: Any, roundtrip_graph: Any) -> IdempotencyReport:
    """Check structural idempotency of two program graphs.

    Compares the node and edge populations of two graphs to determine
    if they have the same structural shape.

    Args:
        original_graph: The original ProgramGraph or compatible structure.
        roundtrip_graph: The ProgramGraph from the re-run.

    Returns:
        An IdempotencyReport describing structural similarities and
        differences.
    """
    report = IdempotencyReport()

    # Extract node/edge information from both graphs
    orig_nodes, orig_edges = _nodes_edges_from_mappings(original_graph)
    rt_nodes, rt_edges = _nodes_edges_from_mappings(roundtrip_graph)

    # Compare node role multisets
    orig_role_counts = Counter(node.get("role", "UNKNOWN") for node in orig_nodes)
    rt_role_counts = Counter(node.get("role", "UNKNOWN") for node in rt_nodes)

    report.forward_roles = dict(orig_role_counts)
    report.reverse_roles = dict(rt_role_counts)

    # Find differences
    all_roles = set(orig_role_counts.keys()) | set(rt_role_counts.keys())
    for role in sorted(all_roles):
        orig_count = orig_role_counts.get(role, 0)
        rt_count = rt_role_counts.get(role, 0)
        if orig_count != rt_count:
            report.differences.append(f"Role {role}: {orig_count} → {rt_count}")

    # Compute a simple structural score
    if orig_role_counts and rt_role_counts:
        intersection = sum(
            min(orig_role_counts.get(r, 0), rt_role_counts.get(r, 0)) for r in all_roles
        )
        union = sum(max(orig_role_counts.get(r, 0), rt_role_counts.get(r, 0)) for r in all_roles)
        report.score = intersection / union if union > 0 else 0.0
    else:
        report.score = 0.0

    report.is_idempotent = len(report.differences) == 0

    return report

verify_repo_roundtrip(repo_path, output_dir=None, *, role_threshold=ROLE_PRESERVATION_THRESHOLD)

Run forward → reverse → forward on an existing repository.

This is the entry point used by the cogant roundtrip CLI subcommand. It:

  1. Runs the forward pipeline on repo_path and emits a GNN plus a first semantic-mappings multiset R1.
  2. Parses the emitted GNN back into a ReverseGNNModel.
  3. Synthesizes a Python package from the plan.
  4. Runs the forward pipeline again on the synthesized package and collects a second semantic-mappings multiset R2.
  5. Compares R1 and R2 directly; the role-preservation score is the mean per-role min(count1, count2) / max(count1, count2) multiset similarity.

This comparison style (forward-vs-forward) is the strictest role preservation measurement for an existing repository: it asks whether the same pipeline sees the same roles in the synthesized package that it saw in the original. The alternative (parse the GNN, compare to forward-on-synth) is weaker because it mixes two different rule systems — the parser's role derivation and the forward pipeline's semantic rules — on the two sides of the comparison.

Parameters:

Name Type Description Default
repo_path str | Path

Repository to round-trip.

required
output_dir str | Path | None

Directory to write intermediate artifacts into. If None, a temporary directory is used and cleaned up.

None
role_threshold float

Minimum role match score to accept.

ROLE_PRESERVATION_THRESHOLD

Returns:

Type Description
RoundtripResult

class:RoundtripResult with original_roles drawn from the

RoundtripResult

first forward pass and synthesized_roles drawn from the

RoundtripResult

second. When the reverse parser, planning, or synthesis rejects the

RoundtripResult

emitted model, the result has roundtrip_status=FAILED and the

RoundtripResult

reason in errors.

Source code in py/cogant/reverse/idempotency.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
def verify_repo_roundtrip(
    repo_path: str | Path,
    output_dir: str | Path | None = None,
    *,
    role_threshold: float = ROLE_PRESERVATION_THRESHOLD,
) -> RoundtripResult:
    """Run forward → reverse → forward on an existing repository.

    This is the entry point used by the ``cogant roundtrip`` CLI
    subcommand. It:

    1. Runs the forward pipeline on ``repo_path`` and emits a GNN plus
       a **first** semantic-mappings multiset ``R1``.
    2. Parses the emitted GNN back into a ReverseGNNModel.
    3. Synthesizes a Python package from the plan.
    4. Runs the forward pipeline again on the synthesized package and
       collects a **second** semantic-mappings multiset ``R2``.
    5. Compares ``R1`` and ``R2`` directly; the role-preservation score is
       the mean per-role ``min(count1, count2) / max(count1, count2)``
       multiset similarity.

    This comparison style (forward-vs-forward) is the strictest role
    preservation measurement for an existing repository:
    it asks whether the *same* pipeline sees the *same* roles in the
    synthesized package that it saw in the original. The alternative
    (parse the GNN, compare to forward-on-synth) is weaker because it
    mixes two different rule systems — the parser's role derivation
    and the forward pipeline's semantic rules — on the two sides of
    the comparison.

    Args:
        repo_path: Repository to round-trip.
        output_dir: Directory to write intermediate artifacts into.
            If None, a temporary directory is used and cleaned up.
        role_threshold: Minimum role match score to accept.

    Returns:
        :class:`RoundtripResult` with ``original_roles`` drawn from the
        first forward pass and ``synthesized_roles`` drawn from the
        second. When the reverse parser, planning, or synthesis rejects the
        emitted model, the result has ``roundtrip_status=FAILED`` and the
        reason in ``errors``.
    """
    from cogant.api.session import Session

    repo_path = Path(repo_path).expanduser().resolve()
    using_tmp = output_dir is None
    work_dir = Path(output_dir or tempfile.mkdtemp(prefix="cogant-roundtrip-")).resolve()
    work_dir.mkdir(parents=True, exist_ok=True)

    gnn_dir = work_dir / "forward"
    gnn_dir.mkdir(parents=True, exist_ok=True)
    reverse_dir = work_dir / "reverse"
    reverse_dir.mkdir(parents=True, exist_ok=True)

    try:
        # Stage 1: forward on the original repo → GNN markdown + mappings.
        session = Session(target=str(repo_path))
        session.extract_static()
        session.build_graph()
        session.translate_to_gnn()
        session.compile_state_space()
        bundle = session._bundle_internal()

        original_mappings = bundle.artifacts.get("_semantic_mappings", {}) or {}
        original_roles = _role_multiset_from_mappings(original_mappings)
        original_state_space = bundle.artifacts.get("_state_space_model")
        original_graph = bundle.artifacts.get("_program_graph")
        original_trace = bundle.artifacts.get("_rule_evidence_trace") or {}

        from cogant.gnn.formatter import GNNMarkdownFormatter

        formatter = GNNMarkdownFormatter(
            program_graph=bundle.artifacts["_program_graph"],
            state_space_model=bundle.artifacts["_state_space_model"],
            process_model=bundle.artifacts["_process_model"],
            semantic_mappings=original_mappings,
        )
        gnn_md = formatter.format()
        gnn_path = gnn_dir / "model.gnn.md"
        gnn_path.write_text(gnn_md, encoding="utf-8")
        logger.info("Wrote forward GNN to %s", gnn_path)

        # Stage 2+3: parse → plan → synthesize.  A model that the reverse
        # parser, planning, or synthesis rejects is a FAILED round-trip, not a
        # crash.
        try:
            model = parse_gnn(gnn_path)
            plan = plan_package(model, expected_roles=original_roles)
            if supports_stable_minimal_profile(plan, model):
                package_path = synthesize_stable_minimal_package(plan, model, reverse_dir)
            else:
                package_path = synthesize_package(plan, model, reverse_dir)
        except ValueError as exc:
            logger.warning("Reverse synthesis failed for %s: %s", repo_path, exc)
            return _synthesis_failed_result(original_roles, exc, role_threshold=role_threshold)

        # Stage 4: forward on the synthesized package.
        forward = _run_forward(package_path)
        synthesized_roles = _role_multiset_from_mappings(
            forward.get("mappings"),
            semantic_targets=forward.get("semantic_targets"),
        )
        roundtrip_warnings: list[str] = []
        synthesized_gnn_md = str(forward.get("gnn_markdown") or "")
        synthesized_gnn_path = work_dir / "regenerated" / "model.gnn.md"
        synth_model = _parse_regenerated_gnn(
            synthesized_gnn_md,
            synthesized_gnn_path,
            roundtrip_warnings,
        )

        # role_preservation_score = mean over every role present on either
        # side of min(orig,synth)/max(orig,synth) — the formula documented
        # in manuscript appendix S01. A role introduced OR dropped scores
        # 0.0 for that role; both-zero scores 1.0 (vacuous). (Prior code:
        # recall-only Sum(min)/Sum(orig), saturated at 1.0 for ANY superset
        # synthesis — keystone defect, review 2026-05-19.)
        score, vacuous_roundtrip = _role_preservation_score(original_roles, synthesized_roles)

        # Shape match: compare the two state-space models directly.
        shape_match: dict[str, bool] = {}
        orig_ss = original_state_space
        new_ss = forward.get("state_space")
        orig_n_states = len(getattr(orig_ss, "variables", {}) or {}) if orig_ss else 0
        orig_n_obs = len(getattr(orig_ss, "observations", {}) or {}) if orig_ss else 0
        orig_n_actions = len(getattr(orig_ss, "actions", {}) or {}) if orig_ss else 0
        new_n_states = len(getattr(new_ss, "variables", {}) or {}) if new_ss else 0
        new_n_obs = len(getattr(new_ss, "observations", {}) or {}) if new_ss else 0
        new_n_actions = len(getattr(new_ss, "actions", {}) or {}) if new_ss else 0
        if orig_n_states > 0:
            shape_match["n_states"] = new_n_states >= 1
        if orig_n_obs > 0:
            shape_match["n_obs"] = new_n_obs >= 1
        if orig_n_actions > 0:
            shape_match["n_actions"] = new_n_actions >= 1

        # Auxiliary distance metrics. The repo round-trip has access
        # to two compiled state-space models, so we can compare their
        # matrix slots directly when available.
        matrix_score = compare_matrices(
            _model_matrices(model),
            _model_matrices(synth_model)
            if synth_model is not None
            else _state_space_matrices(new_ss),
        )
        orig_nodes, orig_edges = _nodes_edges_from_mappings(original_mappings)
        synth_nodes, synth_edges = _nodes_edges_from_mappings(forward.get("mappings"))
        structural_score = compare_graph_structure(orig_nodes, orig_edges, synth_nodes, synth_edges)
        original_graph_summary = _graph_summary(original_graph)
        synthesized_graph_summary = _graph_summary(forward.get("program_graph"))
        graph_delta = _graph_delta(original_graph_summary, synthesized_graph_summary)
        matrix_delta = _matrix_delta(
            _model_matrices(model),
            _model_matrices(synth_model)
            if synth_model is not None
            else _state_space_matrices(new_ss),
        )
        gnn_diff = _gnn_diff(gnn_md, synthesized_gnn_md) if synthesized_gnn_md else {}
        generated_code_ok, generated_code_errors = _generated_code_status(package_path)
        errors = list(generated_code_errors)
        if forward.get("error"):
            errors.append(str(forward["error"]))
        invariants = _invariants(
            role_preservation_score=score,
            role_threshold=role_threshold,
            shape_match=shape_match,
            graph_delta=graph_delta,
            matrix_delta=matrix_delta,
            gnn_diff=gnn_diff,
            generated_code_ok=generated_code_ok,
            forward_error=forward.get("error"),
        )
        role_preserved = bool(invariants["role_preserved"])
        matrix_preserved = bool(invariants["matrix_preserved"])
        gnn_sections_preserved = bool(invariants["gnn_sections_preserved"])
        structurally_isomorphic = _strict_invariants_preserved(
            role_preserved=role_preserved,
            matrix_preserved=matrix_preserved,
            gnn_sections_preserved=gnn_sections_preserved,
            generated_code_ok=generated_code_ok,
            invariants=invariants,
        )

        result = RoundtripResult(
            roundtrip_status=_roundtrip_status_from_invariants(
                role_preserved=role_preserved,
                structurally_isomorphic=structurally_isomorphic,
                errors=errors,
            ),
            role_preservation_score=score,
            role_preserved=role_preserved,
            structurally_isomorphic=structurally_isomorphic,
            matrix_preserved=matrix_preserved,
            gnn_sections_preserved=gnn_sections_preserved,
            generated_code_ok=generated_code_ok,
            matrix_score=matrix_score,
            structural_score=structural_score,
            original_roles=dict(original_roles),
            synthesized_roles=dict(synthesized_roles),
            shape_match=shape_match,
            package_path=package_path,
            original_graph_summary=original_graph_summary,
            synthesized_graph_summary=synthesized_graph_summary,
            graph_delta=graph_delta,
            gnn_diff=gnn_diff,
            matrix_delta=matrix_delta,
            invariants=invariants,
            rule_evidence_trace={
                "original": original_trace,
                "synthesized": forward.get("rule_evidence_trace") or {},
            },
            warnings=roundtrip_warnings,
            errors=errors,
            vacuous_roundtrip=vacuous_roundtrip,
        )
        logger.info("Repo round-trip result: %s", result.summary())
        return result
    finally:
        if using_tmp:
            shutil.rmtree(work_dir, ignore_errors=True)

verify_roundtrip(gnn_path, tmp_dir=None, *, role_threshold=ROLE_PRESERVATION_THRESHOLD, keep_tmp=False)

Run a full round-trip on a GNN markdown file and score the result.

Parameters:

Name Type Description Default
gnn_path str | Path

Path to a GNN markdown file produced by COGANT (or any conforming emitter).

required
tmp_dir str | Path | None

Optional directory where the synthesized package should be written. If None, a temporary directory is created and removed after the run (unless keep_tmp is True).

None
role_threshold float

Minimum role_preservation_score for the weaker role-preserved success tier. Defaults to :data:ROLE_PRESERVATION_THRESHOLD.

ROLE_PRESERVATION_THRESHOLD
keep_tmp bool

When True, do not delete the temporary directory after the run. Useful for debugging.

False

Returns:

Name Type Description
A RoundtripResult

class:RoundtripResult summarising the run. Once the source GNN

RoundtripResult

has been parsed, the result is always returned — a model that

RoundtripResult

planning or synthesis rejects yields roundtrip_status=FAILED,

RoundtripResult

and exceptions inside the forward pipeline are captured as

RoundtripResult

errors rather than raised. A temporary directory created here

RoundtripResult

is removed even when the run fails.

Source code in py/cogant/reverse/idempotency.py
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
def verify_roundtrip(
    gnn_path: str | Path,
    tmp_dir: str | Path | None = None,
    *,
    role_threshold: float = ROLE_PRESERVATION_THRESHOLD,
    keep_tmp: bool = False,
) -> RoundtripResult:
    """Run a full round-trip on a GNN markdown file and score the result.

    Args:
        gnn_path: Path to a GNN markdown file produced by COGANT (or
            any conforming emitter).
        tmp_dir: Optional directory where the synthesized package
            should be written. If None, a temporary directory is
            created and removed after the run (unless ``keep_tmp``
            is True).
        role_threshold: Minimum ``role_preservation_score`` for the
            weaker role-preserved success tier. Defaults to
            :data:`ROLE_PRESERVATION_THRESHOLD`.
        keep_tmp: When True, do not delete the temporary directory
            after the run. Useful for debugging.

    Returns:
        A :class:`RoundtripResult` summarising the run. Once the source GNN
        has been parsed, the result is always returned — a model that
        planning or synthesis rejects yields ``roundtrip_status=FAILED``,
        and exceptions inside the forward pipeline are captured as
        ``errors`` rather than raised. A temporary directory created here
        is removed even when the run fails.
    """
    gnn_path = Path(gnn_path).expanduser().resolve()

    # 1. Parse the source GNN.
    model = parse_gnn(gnn_path)
    original_roles = _role_multiset_from_model(model)

    # 2. Plan and synthesize into a temporary directory.
    cleanup_dir: Path | None = None
    if tmp_dir is None:
        tmp_dir_obj = Path(tempfile.mkdtemp(prefix="cogant-roundtrip-"))
        if not keep_tmp:
            cleanup_dir = tmp_dir_obj
    else:
        tmp_dir_obj = Path(tmp_dir).expanduser().resolve()
        tmp_dir_obj.mkdir(parents=True, exist_ok=True)

    try:
        result = _verify_gnn_roundtrip_in(
            gnn_path,
            model,
            original_roles,
            tmp_dir_obj,
            role_threshold=role_threshold,
        )
    finally:
        # 6. Cleanup, also when synthesis or scoring raised.
        if cleanup_dir is not None:
            shutil.rmtree(cleanup_dir, ignore_errors=True)
    if cleanup_dir is not None:
        # The package_path points to deleted files; clear it so callers don't
        # try to read deleted files.
        result.package_path = None

    logger.info("Round-trip result: %s", result.summary())
    return result

Examples

The full reverse surface (parser, callable, planner, synthesizer, matrices, metrics, idempotency) is exercised by: