Skip to content

cogant.gnn

The cogant.gnn package builds, formats, and validates Generalized Notation Notation packages. The on-disk artifact is produced by GNNPackageBuilder; GNNValidator produces a 0–100 score and an error/warning table.

Package

cogant.gnn

GNN formatting, export, package building, validation, and execution modules.

Emits GNN markdown and JSON representations with all sections in canonical order. Builds complete GNN packages, validates them, and executes the generative model.

ExecutionTrace dataclass

Posterior beliefs and the subsequent action-conditioned prediction.

Source code in py/cogant/gnn/execution.py
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
@dataclass(frozen=True, slots=True)
class ExecutionTrace:
    """Posterior beliefs and the subsequent action-conditioned prediction."""

    step: int
    state: dict[str, float]
    action: str
    observation: str
    beliefs: dict[str, float]
    beliefs_prior: dict[str, float]
    free_energy_after: float
    policy_scores: list[tuple[str, float]]
    predicted_state: dict[str, float]

    @classmethod
    def from_record(cls, record: InferenceRecord, labels: AxisLabels) -> ExecutionTrace:
        """Attach axis labels without inferring semantics from their spelling."""
        prior = dict(zip(labels.states, record.prior, strict=True))
        return cls(
            step=record.t,
            state=prior.copy(),
            action=labels.actions[record.action],
            observation=labels.observations[record.observation],
            beliefs=dict(zip(labels.states, record.posterior, strict=True)),
            beliefs_prior=prior,
            free_energy_after=record.free_energy,
            policy_scores=list(zip(labels.actions, record.policy_scores, strict=True)),
            predicted_state=dict(zip(labels.states, record.predicted_belief, strict=True)),
        )

    def to_dict(self) -> dict[str, JsonValue]:
        """Return JSON-ready copies so consumers cannot mutate the trace."""
        return {
            "step": self.step,
            "state": dict(self.state),
            "action": self.action,
            "observation": self.observation,
            "beliefs": dict(self.beliefs),
            "beliefs_prior": dict(self.beliefs_prior),
            "free_energy_after": self.free_energy_after,
            "policy_scores": [[action, score] for action, score in self.policy_scores],
            "predicted_state": dict(self.predicted_state),
        }

from_record(record, labels) classmethod

Attach axis labels without inferring semantics from their spelling.

Source code in py/cogant/gnn/execution.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@classmethod
def from_record(cls, record: InferenceRecord, labels: AxisLabels) -> ExecutionTrace:
    """Attach axis labels without inferring semantics from their spelling."""
    prior = dict(zip(labels.states, record.prior, strict=True))
    return cls(
        step=record.t,
        state=prior.copy(),
        action=labels.actions[record.action],
        observation=labels.observations[record.observation],
        beliefs=dict(zip(labels.states, record.posterior, strict=True)),
        beliefs_prior=prior,
        free_energy_after=record.free_energy,
        policy_scores=list(zip(labels.actions, record.policy_scores, strict=True)),
        predicted_state=dict(zip(labels.states, record.predicted_belief, strict=True)),
    )

to_dict()

Return JSON-ready copies so consumers cannot mutate the trace.

Source code in py/cogant/gnn/execution.py
43
44
45
46
47
48
49
50
51
52
53
54
55
def to_dict(self) -> dict[str, JsonValue]:
    """Return JSON-ready copies so consumers cannot mutate the trace."""
    return {
        "step": self.step,
        "state": dict(self.state),
        "action": self.action,
        "observation": self.observation,
        "beliefs": dict(self.beliefs),
        "beliefs_prior": dict(self.beliefs_prior),
        "free_energy_after": self.free_energy_after,
        "policy_scores": [[action, score] for action, score in self.policy_scores],
        "predicted_state": dict(self.predicted_state),
    }

GNNJSONExporter

Exports GNN models to machine-readable JSON format with stable IDs.

Source code in py/cogant/gnn/json_export.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 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
403
404
405
406
407
408
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
471
472
473
474
475
476
477
478
479
480
481
482
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
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
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
class GNNJSONExporter:
    """
    Exports GNN models to machine-readable JSON format with stable IDs.
    """

    def __init__(
        self,
        program_graph: ProgramGraph,
        state_space_model: StateSpaceModel,
        process_model: ProcessModel,
        semantic_mappings: dict[str, Any],
    ):
        """
        Initialize the exporter.

        Args:
            program_graph: The program graph.
            state_space_model: The state space model.
            process_model: The process model.
            semantic_mappings: Semantic mappings dictionary.
        """
        self.graph = program_graph
        self.state_space = state_space_model
        self.process = process_model
        self.mappings = semantic_mappings

    def export(self) -> dict[str, Any]:
        """
        Export the complete GNN model as a JSON-serializable dictionary.

        Returns:
            Dictionary ready for JSON serialization.
        """
        logger.info(
            "Exporting GNN model to JSON: %d nodes, %d edges, %d vars, %d obs, %d actions",
            len(self.graph.nodes),
            len(self.graph.edges),
            len(self.state_space.variables),
            len(self.state_space.observations),
            len(self.state_space.actions),
        )

        # Debug: check mappings type - ensure it's always a dict
        if not isinstance(self.mappings, dict):
            logger.warning(f"WARNING: mappings is {type(self.mappings)}, not dict. Converting...")
            if isinstance(self.mappings, list):
                self.mappings = {m.id: m for m in self.mappings}
            else:
                self.mappings = {}

        # Build all 19 canonical sections
        output = {
            # Core identifiers and metadata
            "model_id": self.state_space.id,
            "schema_name": self.state_space.schema_name,
            # Canonical sections (19 total)
            "model_metadata": self._export_metadata(),
            "repository_metadata": self._export_repository_metadata(),
            "source_coverage": self._export_source_coverage(),
            "state_space": self._export_state_space(),
            "observation_modalities": self._export_observation_modalities(),
            "actions_policies": self._export_actions_policies(),
            "connections": self._export_connections(),
            "factors": self._export_factors_section(),
            "transition_structure": self._export_transition_structure(),
            "likelihood_structure": self._export_likelihood_structure(),
            "preferences_constraints": self._export_preferences_constraints(),
            "time_settings": self._export_time_settings(),
            "parameterization": self._export_parameterization(),
            "ontology_mapping": self._export_ontology_mapping(),
            "markov_blanket": self._export_markov_blanket(),
            "provenance": self._export_provenance_section(),
            "confidence": self._export_confidence(),
            "rendering_hints": self._export_rendering_hints(),
            "validation_notes": self._export_validation_notes(),
            # AII Active Inference matrices (A, B, C, D)
            "matrices": self._export_matrices(),
            # Additional cross-reference sections
            "program_graph": self._export_program_graph(),
            "process_model": self._export_process_model(),
            "mappings": self._export_mappings(),
        }

        # Log matrix shapes and section summary at INFO level
        matrices_raw = output.get("matrices", {})
        matrices = matrices_raw if isinstance(matrices_raw, dict) else {}
        shapes_raw = matrices.get("shapes", {})
        shapes = shapes_raw if isinstance(shapes_raw, dict) else {}
        n_sections = len(output)
        logger.info(
            "GNN JSON export complete: %d sections + matrices (A=%s, B=%s, C=%s, D=%s)",
            n_sections,
            shapes.get("A", [0, 0]),
            shapes.get("B", [0, 0, 0]),
            shapes.get("C", [0]),
            shapes.get("D", [0]),
        )

        return output

    def _export_matrices(self) -> dict[str, Any]:
        """Export the AII Active Inference A/B/C/D matrices.

        Delegates to :class:`cogant.gnn.matrices.GNNMatrices`. On failure
        (e.g. empty state space) a safe empty structure is returned so
        the downstream validator can cleanly skip the check.
        """
        try:
            matrices = GNNMatrices(
                graph=self.graph,
                mappings=self.mappings,
                state_space=self.state_space,
            )
            return matrices.to_dict()
        except (ValueError, KeyError, AttributeError) as exc:
            logger.warning(
                "Failed to derive GNN matrices for export: %s: %s",
                type(exc).__name__,
                exc,
            )
            logger.info("Matrix export failed; returning empty A/B/C/D structures")
            return {
                "A": [],
                "B": [],
                "C": [],
                "D": [],
                "shapes": {"A": [0, 0], "B": [0, 0, 0], "C": [0], "D": [0]},
                "dimensions": {"n_states": 0, "n_obs": 0, "n_actions": 0},
            }

    def export_to_string(self, indent: int | None = 2) -> str:
        """
        Export the model to a JSON string.

        Args:
            indent: Number of spaces for indentation, or None for compact.

        Returns:
            JSON string.
        """
        data = self.export()
        return json.dumps(data, indent=indent, default=str)

    def _export_metadata(self) -> dict[str, Any]:
        """Build the ``metadata`` block.

        Always populates ``generated_at``, ``schema_version``,
        ``cogant_version``, ``model_id``, and ``schema_name``. When the
        program graph carries ``RepositoryMetadata``, also adds a
        ``repository`` sub-object (uri, languages, version, timestamps,
        evidence sources, optional ``custom`` field) and the state-space
        derived metrics block.
        """
        metadata: dict[str, Any] = {
            "generated_at": datetime.now().isoformat(),
            "schema_version": "1.0",
            "cogant_version": _cogant_version(),
            "model_id": self.state_space.id,
            "schema_name": self.state_space.schema_name,
        }

        # Add graph metadata
        if self.graph.metadata:
            meta = self.graph.metadata
            metadata["repository"] = {
                "uri": meta.repo_uri,
                "languages": list(meta.languages),
                "version": meta.version,
                "created_at": meta.created_at.isoformat(),
                "updated_at": meta.updated_at.isoformat(),
                "evidence_sources": meta.evidence_sources,
            }
            if meta.custom_metadata:
                metadata["repository"]["custom"] = meta.custom_metadata

        # Add state space metrics
        metadata["metrics"] = {
            "node_count": len(self.graph.nodes),
            "edge_count": len(self.graph.edges),
            "state_variables": len(self.state_space.variables),
            "observations": len(self.state_space.observations),
            "actions": len(self.state_space.actions),
            "transitions": len(self.state_space.transitions),
            "processes": len(self.process.stages),
            "mappings": len(self.mappings),
        }

        # Pipeline and extraction info
        if self.state_space.metadata:
            if "pipeline_stages" in self.state_space.metadata:
                metadata["pipeline_stages"] = self.state_space.metadata["pipeline_stages"]
            if "extraction_time_ms" in self.state_space.metadata:
                metadata["extraction_time_ms"] = self.state_space.metadata["extraction_time_ms"]

        return metadata

    def _export_repository_metadata(self) -> dict[str, Any]:
        """Export repository metadata section."""
        if self.graph.metadata:
            meta = self.graph.metadata
            return {
                "uri": meta.repo_uri,
                "languages": list(meta.languages),
                "version": meta.version,
                "created_at": meta.created_at.isoformat(),
                "updated_at": meta.updated_at.isoformat(),
                "evidence_sources": meta.evidence_sources,
                "custom": meta.custom_metadata or {},
            }
        return {}

    def _export_source_coverage(self) -> dict[str, Any]:
        """Export source coverage information."""
        return {
            "nodes": len(self.graph.nodes),
            "edges": len(self.graph.edges),
            "evidence_sources": self.graph.metadata.evidence_sources if self.graph.metadata else [],
            "coverage_percentage": self._compute_coverage(),
        }

    def _compute_coverage(self) -> float:
        """Compute coverage percentage."""
        if not self.graph.nodes:
            return 0.0
        # Coverage is based on all nodes being covered
        return 100.0

    def _export_observation_modalities(self) -> dict[str, Any]:
        """Export observation modalities section."""
        return {
            "modalities": self._extract_modality_list(),
            "count": len(self.state_space.observations),
            "observations": self._export_observation_details(),
        }

    def _extract_modality_list(self) -> list[str]:
        """Extract list of observation modalities."""
        modalities = set()
        for obs in self.state_space.observations.values():
            if hasattr(obs, "modality_type") and obs.modality_type:
                modalities.add(obs.modality_type)
        return sorted(modalities) if modalities else ["symbolic"]

    def _export_observation_details(self) -> dict[str, Any]:
        """Export observation details for canonical section."""
        observations: dict[str, dict[str, Any]] = {}
        for obs_id, obs in self.state_space.observations.items():
            observations[obs_id] = {
                "id": obs.id,
                "name": obs.name,
                "source_node_id": obs.source_node_id,
                "modality_type": obs.modality_type,
                "cardinality": obs.cardinality or [],
                "description": obs.description,
                "confidence": obs.confidence.value
                if hasattr(obs.confidence, "value")
                else str(obs.confidence),
            }
        return observations

    def _export_actions_policies(self) -> dict[str, Any]:
        """Export actions and policies as canonical section."""
        actions = {}
        for action_id, action in self.state_space.actions.items():
            actions[action_id] = {
                "id": action.id,
                "name": action.name,
                "controller_id": action.controller_id,
                "parameters": action.parameters or {},
                "effects": action.effects or {},
                "preconditions": action.preconditions or {},
                "description": action.description,
            }
        return {
            "actions": actions,
            "policies": self._extract_policy_details(),
            "count": len(actions),
        }

    def _extract_policy_details(self) -> list[dict[str, Any]]:
        """Extract policy details."""
        return [
            {"type": "deterministic", "coverage": 1.0, "actions": len(self.state_space.actions)}
        ]

    def _export_connections(self) -> dict[str, Any]:
        """Export connections (edges) as canonical section."""
        edges: dict[str, dict[str, Any]] = {}
        edge_kinds: dict[str, int] = defaultdict(int)
        for edge_id, edge in self.graph.edges.items():
            edge_kinds[edge.kind.value] += 1
            edges[edge_id] = {
                "id": edge.id,
                "source_id": edge.source_id,
                "target_id": edge.target_id,
                "kind": edge.kind.value,
                "weight": edge.weight,
                "evidence_sources": edge.evidence_sources or [],
                "metadata": edge.metadata or {},
            }
        return {
            "edges": edges,
            "count": len(edges),
            "by_kind": dict(edge_kinds),
        }

    def _export_factors_section(self) -> dict[str, Any]:
        """Export factorization as canonical section."""
        var_by_factor = defaultdict(list)
        for var_id, var in self.state_space.variables.items():
            if var.factors:
                for factor in var.factors:
                    var_by_factor[factor].append(var_id)
        return {
            "factorization": dict(var_by_factor.items()),
            "factors": list(var_by_factor.keys()),
            "count": len(var_by_factor),
        }

    def _export_transition_structure(self) -> dict[str, Any]:
        """Export transition structure as canonical section."""
        transitions = {}
        for trans_id, trans in self.state_space.transitions.items():
            transitions[trans_id] = {
                "id": trans.id,
                "source_state": trans.source_state,
                "target_state": trans.target_state,
                "action_id": trans.action_id,
                "triggered_by": trans.triggered_by,
                "probability": trans.probability or 0.0,
                "confidence": trans.confidence.value
                if hasattr(trans.confidence, "value")
                else str(trans.confidence),
            }
        return {
            "transitions": transitions,
            "deterministic": self._is_deterministic(),
            "markovian": self._is_markovian(),
            "count": len(transitions),
        }

    def _is_deterministic(self) -> bool:
        """Check if model is deterministic."""
        return all(t.probability in [None, 1.0] for t in self.state_space.transitions.values())

    def _is_markovian(self) -> bool:
        """Check if model is Markovian."""
        return True  # Default assumption

    def _export_likelihood_structure(self) -> dict[str, Any]:
        """Export likelihood structure as canonical section."""
        likelihoods = {}
        for like_id, like in self.state_space.likelihoods.items():
            likelihoods[like_id] = {
                "id": like.id,
                "variable_id": like.variable_id,
                "distribution_type": like.distribution_type,
                "parameters": like.parameters or {},
                "confidence": like.confidence.value
                if hasattr(like.confidence, "value")
                else str(like.confidence),
            }
        return {
            "likelihoods": likelihoods,
            "count": len(likelihoods),
        }

    def _export_preferences_constraints(self) -> dict[str, Any]:
        """Export preferences and constraints as canonical section."""
        preferences = {}
        for pref_id, pref in self.state_space.preferences.items():
            preferences[pref_id] = {
                "id": pref.id,
                "name": pref.name,
                "description": pref.description,
                "scope": pref.scope,
                "expression": pref.expression,
                "weight": pref.weight,
                "source": pref.source,
                "confidence": pref.confidence.value
                if hasattr(pref.confidence, "value")
                else str(pref.confidence),
            }
        return {
            "preferences": preferences,
            "constraints": [],
            "count": len(preferences),
        }

    def _export_time_settings(self) -> dict[str, Any]:
        """Export time regime and settings."""
        return {
            "time_regime": self.state_space.time_regime.value
            if hasattr(self.state_space.time_regime, "value")
            else str(self.state_space.time_regime),
            "time_scale": "discrete",
            "synchronous": True,
        }

    def _export_parameterization(self) -> dict[str, Any]:
        """Export parameterization details."""
        return {
            "parameters": {},
            "hyperparameters": {},
            "configuration": self.state_space.metadata.copy() if self.state_space.metadata else {},
        }

    def _export_ontology_mapping(self) -> dict[str, Any]:
        """Export ontology mapping as canonical section."""
        mappings_data = {}
        for mapping_id, mapping in self.mappings.items():
            mappings_data[mapping_id] = {
                "id": mapping_id,
                "semantic_label": mapping.semantic_label
                if hasattr(mapping, "semantic_label")
                else "",
                "graph_nodes": mapping.graph_fragment_node_ids
                if hasattr(mapping, "graph_fragment_node_ids")
                else [],
                "graph_edges": mapping.graph_fragment_edge_ids
                if hasattr(mapping, "graph_fragment_edge_ids")
                else [],
            }
        return {
            "mappings": mappings_data,
            "count": len(mappings_data),
        }

    def _export_markov_blanket(self) -> dict[str, Any]:
        """Export Markov blanket partition as canonical section.

        Extracts a real Markov blanket from the program graph using
        :class:`cogant.markov.extractor.MarkovBlanketExtractor` with the
        ``"auto"`` strategy, then serializes it via
        :func:`cogant.markov.blanket.serialize_blanket`.  If extraction
        fails (e.g. empty graph), a safe empty structure is returned so
        the downstream validator can cleanly skip the check.
        """
        try:
            extractor = MarkovBlanketExtractor(self.graph)
            blanket = extractor.extract(strategy="auto")
            serialized = serialize_blanket(
                blanket,
                self.graph,
                include_rationale=False,
            )
            # Merge the serialized blanket with partition-level
            # summary fields expected by the GNN validator.
            stats = dict(blanket.stats)
            return {
                "partition": serialized["roles"],
                "seed_strategy": blanket.metadata.get("strategy", "auto"),
                "boundary_ratio": stats.get("boundary_ratio", 0.0),
                "stats": stats,
                "metadata": serialized.get("metadata", {}),
            }
        except (ValueError, KeyError, AttributeError) as exc:
            logger.warning(
                "Failed to extract Markov blanket for export: %s: %s",
                type(exc).__name__,
                exc,
            )
            return {
                "partition": {
                    "internal": [],
                    "sensory": [],
                    "active": [],
                    "external": [],
                },
                "seed_strategy": "auto",
                "boundary_ratio": 0.0,
            }

    def _export_provenance_section(self) -> dict[str, Any]:
        """Export provenance as canonical section."""
        return {
            "timestamp": datetime.now().isoformat(),
            "graph_nodes": len(self.graph.nodes),
            "graph_edges": len(self.graph.edges),
            "state_space_elements": {
                "variables": len(self.state_space.variables),
                "observations": len(self.state_space.observations),
                "actions": len(self.state_space.actions),
            },
            "sources": self.graph.metadata.evidence_sources if self.graph.metadata else [],
        }

    def _export_confidence(self) -> dict[str, Any]:
        """Export confidence metrics as canonical section."""
        return {
            "overall_confidence": self._compute_average_confidence(),
            "by_component": {
                "variables": self._compute_component_confidence("variables"),
                "observations": self._compute_component_confidence("observations"),
                "actions": self._compute_component_confidence("actions"),
                "transitions": self._compute_component_confidence("transitions"),
                "semantic_mappings": self._compute_component_confidence("semantic_mappings"),
            },
        }

    def _compute_average_confidence(self) -> float:
        """Compute average confidence across all components."""
        confidences: list[float] = []
        for component in ("variables", "observations", "actions", "transitions"):
            confidences.extend(self._component_confidences(component))
        confidences.extend(self._mapping_confidences())
        return sum(confidences) / len(confidences) if confidences else 0.5

    def _component_confidences(self, component: str) -> list[float]:
        components: Any
        if component == "variables":
            components = self.state_space.variables.values()
        elif component == "observations":
            components = self.state_space.observations.values()
        elif component == "actions":
            components = self.state_space.actions.values()
        elif component == "transitions":
            components = self.state_space.transitions.values()
        else:
            return []

        confidences: list[float] = []
        for comp in components:
            if not hasattr(comp, "confidence"):
                continue
            val = _confidence_to_float(comp.confidence)
            if val is not None:
                confidences.append(val)
            elif comp.confidence:
                logger.debug(
                    "Skipping uncoercible confidence value in component %r: %r",
                    component,
                    comp,
                )
        return confidences

    def _mapping_confidences(self) -> list[float]:
        if not isinstance(self.mappings, dict):
            return []
        confidences: list[float] = []
        for mapping in self.mappings.values():
            val = _confidence_to_float(getattr(mapping, "confidence_score", None))
            if val is not None:
                confidences.append(val)
        return confidences

    def _compute_component_confidence(self, component: str) -> float:
        """Compute confidence for a specific component."""
        if component == "semantic_mappings":
            confidences = self._mapping_confidences()
            return sum(confidences) / len(confidences) if confidences else 0.5
        if component not in {"variables", "observations", "actions", "transitions"}:
            return 0.5
        confidences = self._component_confidences(component)
        return sum(confidences) / len(confidences) if confidences else 0.5

    def _export_rendering_hints(self) -> dict[str, Any]:
        """Export rendering hints for visualization."""
        return {
            "layout": "force-directed",
            "colors": {
                "nodes": "by_kind",
                "edges": "by_kind",
            },
            "features": ["interactive", "zoomable", "searchable"],
        }

    def _export_validation_notes(self) -> dict[str, Any]:
        """Export validation notes and metadata."""
        return {
            "schema_version": "1.0",
            "cogant_version": _cogant_version(),
            "last_validated": datetime.now().isoformat(),
            "validation_status": "valid",
        }

    def _export_program_graph(self) -> dict[str, Any]:
        """Export program graph with rich metadata."""
        nodes: dict[str, dict[str, Any]] = {}
        node_kinds: dict[str, int] = defaultdict(int)

        for node_id, node in self.graph.nodes.items():
            node_kinds[node.kind.value] += 1
            nodes[node_id] = {
                "id": node.id,
                "name": node.name,
                "kind": node.kind.value,
                "qualified_name": node.qualified_name,
                "path": node.path,
                "language": node.language,
                "source_range": node.source_range,
                "metadata": node.metadata,
                "created_at": node.created_at.isoformat(),
            }

        edges: dict[str, dict[str, Any]] = {}
        edge_kinds: dict[str, int] = defaultdict(int)

        for edge_id, edge in self.graph.edges.items():
            edge_kinds[edge.kind.value] += 1
            edges[edge_id] = {
                "id": edge.id,
                "source_id": edge.source_id,
                "target_id": edge.target_id,
                "kind": edge.kind.value,
                "weight": edge.weight,
                "evidence_sources": edge.evidence_sources,
                "metadata": edge.metadata,
                "created_at": edge.created_at.isoformat(),
            }

        return {
            "summary": {
                "node_count": len(nodes),
                "edge_count": len(edges),
                "node_kinds": dict(node_kinds),
                "edge_kinds": dict(edge_kinds),
            },
            "nodes": nodes,
            "edges": edges,
        }

    def _export_state_space(self) -> dict[str, Any]:
        """Build the ``state_space`` block.

        Serialises every variable, observation, action, transition,
        likelihood, and preference to plain dicts and returns them
        alongside a ``summary`` carrying the time regime, the per-class
        counts, and the ``factorization`` map (factor → variable ids).
        """
        variables = {}
        var_by_factor = defaultdict(list)

        for var_id, var in self.state_space.variables.items():
            variables[var_id] = {
                "id": var.id,
                "name": var.name,
                "type": var.var_type.value if hasattr(var.var_type, "value") else str(var.var_type),
                "node_id": var.node_id,
                "cardinality": var.cardinality or [],
                "domain": var.domain or [],
                "factors": var.factors or [],
                "is_discrete": var.is_discrete,
                "confidence": var.confidence.value
                if hasattr(var.confidence, "value")
                else str(var.confidence),
                "description": var.description,
            }
            if var.factors:
                for factor in var.factors:
                    var_by_factor[factor].append(var_id)

        observations: dict[str, dict[str, Any]] = {}
        for obs_id, obs in self.state_space.observations.items():
            observations[obs_id] = {
                "id": obs.id,
                "name": obs.name,
                "source_node_id": obs.source_node_id,
                "modality_type": obs.modality_type,
                "cardinality": obs.cardinality or [],
                "description": obs.description,
                "confidence": obs.confidence.value
                if hasattr(obs.confidence, "value")
                else str(obs.confidence),
            }

        actions: dict[str, dict[str, Any]] = {}
        for action_id, action in self.state_space.actions.items():
            actions[action_id] = {
                "id": action.id,
                "name": action.name,
                "controller_id": action.controller_id,
                "parameters": action.parameters or {},
                "effects": action.effects or {},
                "preconditions": action.preconditions or {},
                "description": action.description,
                "confidence": action.confidence.value
                if hasattr(action.confidence, "value")
                else str(action.confidence),
            }

        transitions = {}
        for trans_id, trans in self.state_space.transitions.items():
            transitions[trans_id] = {
                "id": trans.id,
                "source_state": trans.source_state,
                "target_state": trans.target_state,
                "action_id": trans.action_id,
                "triggered_by": trans.triggered_by,
                "probability": trans.probability or 0.0,
                "confidence": trans.confidence.value
                if hasattr(trans.confidence, "value")
                else str(trans.confidence),
            }

        likelihoods = {}
        for like_id, like in self.state_space.likelihoods.items():
            likelihoods[like_id] = {
                "id": like.id,
                "variable_id": like.variable_id,
                "distribution_type": like.distribution_type,
                "parameters": like.parameters or {},
                "confidence": like.confidence.value
                if hasattr(like.confidence, "value")
                else str(like.confidence),
            }

        preferences = {}
        for pref_id, pref in self.state_space.preferences.items():
            preferences[pref_id] = {
                "id": pref.id,
                "name": pref.name,
                "description": pref.description,
                "scope": pref.scope,
                "expression": pref.expression,
                "weight": pref.weight,
                "source": pref.source,
                "confidence": pref.confidence.value
                if hasattr(pref.confidence, "value")
                else str(pref.confidence),
            }

        return {
            "summary": {
                "time_regime": self.state_space.time_regime.value
                if hasattr(self.state_space.time_regime, "value")
                else str(self.state_space.time_regime),
                "variable_count": len(variables),
                "observation_count": len(observations),
                "action_count": len(actions),
                "transition_count": len(transitions),
                "likelihood_count": len(likelihoods),
                "preference_count": len(preferences),
                "factorization": {factor: len(vars) for factor, vars in var_by_factor.items()},
            },
            "variables": variables,
            "observations": observations,
            "actions": actions,
            "transitions": transitions,
            "likelihoods": likelihoods,
            "preferences": preferences,
        }

    def _export_process_model(self) -> dict[str, Any]:
        """Build the ``process_model`` block.

        Emits each ``Stage`` (id, name, description, contained
        ``node_ids``, entry/exit points, side effects, expected
        duration, confidence) and each ``Connection`` (source/target
        stages, trigger, condition, success rate) plus a ``summary``
        with stage and connection counts and the entry/exit ids.
        """
        stages = {}
        if self.process.stages:
            for stage_id, stage in self.process.stages.items():
                stages[stage_id] = {
                    "id": stage.id,
                    "name": stage.name,
                    "description": stage.description,
                    "node_ids": stage.node_ids,
                    "entry_points": stage.entry_points,
                    "exit_points": stage.exit_points,
                    "side_effects": stage.side_effects,
                    "expected_duration": stage.expected_duration,
                    "confidence": stage.confidence,
                }

        connections = {}
        if self.process.connections:
            for conn_id, conn in self.process.connections.items():
                connections[conn_id] = {
                    "id": conn.id,
                    "source_stage_id": conn.source_stage_id,
                    "target_stage_id": conn.target_stage_id,
                    "trigger": conn.trigger,
                    "condition": conn.condition,
                    "success_rate": conn.success_rate,
                }

        return {
            "summary": {
                "stage_count": len(stages),
                "connection_count": len(connections),
                "entry_stage_id": self.process.entry_stage_id
                if hasattr(self.process, "entry_stage_id")
                else None,
                "exit_stage_ids": self.process.exit_stage_ids
                if hasattr(self.process, "exit_stage_ids")
                else [],
            },
            "stages": stages,
            "connections": connections,
        }

    def _export_mappings(self) -> dict[str, Any]:
        """Build the ``mappings`` block.

        Walks every ``SemanticMapping``, serialising the source
        ``node_id``, ``kind``, ``tier``, ``status``, confidence, and any
        evidence. Returns the per-mapping dicts alongside a ``summary``
        with tally counts grouped by ``kind``, ``tier``, and ``status``.
        """
        mappings: dict[str, dict[str, Any]] = {}
        kind_counts: dict[str, int] = defaultdict(int)
        tier_counts: dict[str, int] = defaultdict(int)
        status_counts: dict[str, int] = defaultdict(int)

        for mapping_id, mapping in self.mappings.items():
            kind = mapping.kind.value if hasattr(mapping, "kind") else "unknown"
            kind_counts[kind] += 1

            if hasattr(mapping, "confidence_tier"):
                tier_counts[mapping.confidence_tier.value] += 1
            if hasattr(mapping, "status"):
                status_counts[mapping.status] += 1

            mappings[mapping_id] = {
                "id": mapping_id,
                "kind": kind,
                "semantic_label": mapping.semantic_label
                if hasattr(mapping, "semantic_label")
                else "",
                "description": mapping.description if hasattr(mapping, "description") else "",
                "graph_fragment_node_ids": mapping.graph_fragment_node_ids
                if hasattr(mapping, "graph_fragment_node_ids")
                else [],
                "graph_fragment_edge_ids": mapping.graph_fragment_edge_ids
                if hasattr(mapping, "graph_fragment_edge_ids")
                else [],
                "confidence_score": mapping.confidence_score
                if hasattr(mapping, "confidence_score")
                else 0.0,
                "confidence_tier": mapping.confidence_tier.value
                if hasattr(mapping, "confidence_tier")
                else "unknown",
                "evidence_count": mapping.evidence_count
                if hasattr(mapping, "evidence_count")
                else 0,
                "evidence_diversity": mapping.evidence_diversity
                if hasattr(mapping, "evidence_diversity")
                else 0.0,
                "parser_certainty": mapping.parser_certainty
                if hasattr(mapping, "parser_certainty")
                else 0.0,
                "status": mapping.status if hasattr(mapping, "status") else "unknown",
                "reviewed_by": mapping.reviewed_by if hasattr(mapping, "reviewed_by") else None,
                "reviewed_at": mapping.reviewed_at.isoformat()
                if hasattr(mapping, "reviewed_at") and mapping.reviewed_at
                else None,
                "created_at": mapping.created_at.isoformat()
                if hasattr(mapping, "created_at")
                else None,
            }

            # Include provenance if available
            if hasattr(mapping, "provenance") and mapping.provenance:
                mappings[mapping_id]["provenance"] = [
                    {
                        "source": p.source,
                        "timestamp": p.timestamp.isoformat() if p.timestamp else None,
                        "confidence": p.confidence,
                    }
                    for p in mapping.provenance
                ]

        return {
            "summary": {
                "total_mappings": len(mappings),
                "mapping_kinds": dict(kind_counts),
                "confidence_tiers": dict(tier_counts),
                "status_distribution": dict(status_counts),
            },
            "mappings": mappings,
        }

__init__(program_graph, state_space_model, process_model, semantic_mappings)

Initialize the exporter.

Parameters:

Name Type Description Default
program_graph ProgramGraph

The program graph.

required
state_space_model StateSpaceModel

The state space model.

required
process_model ProcessModel

The process model.

required
semantic_mappings dict[str, Any]

Semantic mappings dictionary.

required
Source code in py/cogant/gnn/json_export.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def __init__(
    self,
    program_graph: ProgramGraph,
    state_space_model: StateSpaceModel,
    process_model: ProcessModel,
    semantic_mappings: dict[str, Any],
):
    """
    Initialize the exporter.

    Args:
        program_graph: The program graph.
        state_space_model: The state space model.
        process_model: The process model.
        semantic_mappings: Semantic mappings dictionary.
    """
    self.graph = program_graph
    self.state_space = state_space_model
    self.process = process_model
    self.mappings = semantic_mappings

export()

Export the complete GNN model as a JSON-serializable dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary ready for JSON serialization.

Source code in py/cogant/gnn/json_export.py
 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
def export(self) -> dict[str, Any]:
    """
    Export the complete GNN model as a JSON-serializable dictionary.

    Returns:
        Dictionary ready for JSON serialization.
    """
    logger.info(
        "Exporting GNN model to JSON: %d nodes, %d edges, %d vars, %d obs, %d actions",
        len(self.graph.nodes),
        len(self.graph.edges),
        len(self.state_space.variables),
        len(self.state_space.observations),
        len(self.state_space.actions),
    )

    # Debug: check mappings type - ensure it's always a dict
    if not isinstance(self.mappings, dict):
        logger.warning(f"WARNING: mappings is {type(self.mappings)}, not dict. Converting...")
        if isinstance(self.mappings, list):
            self.mappings = {m.id: m for m in self.mappings}
        else:
            self.mappings = {}

    # Build all 19 canonical sections
    output = {
        # Core identifiers and metadata
        "model_id": self.state_space.id,
        "schema_name": self.state_space.schema_name,
        # Canonical sections (19 total)
        "model_metadata": self._export_metadata(),
        "repository_metadata": self._export_repository_metadata(),
        "source_coverage": self._export_source_coverage(),
        "state_space": self._export_state_space(),
        "observation_modalities": self._export_observation_modalities(),
        "actions_policies": self._export_actions_policies(),
        "connections": self._export_connections(),
        "factors": self._export_factors_section(),
        "transition_structure": self._export_transition_structure(),
        "likelihood_structure": self._export_likelihood_structure(),
        "preferences_constraints": self._export_preferences_constraints(),
        "time_settings": self._export_time_settings(),
        "parameterization": self._export_parameterization(),
        "ontology_mapping": self._export_ontology_mapping(),
        "markov_blanket": self._export_markov_blanket(),
        "provenance": self._export_provenance_section(),
        "confidence": self._export_confidence(),
        "rendering_hints": self._export_rendering_hints(),
        "validation_notes": self._export_validation_notes(),
        # AII Active Inference matrices (A, B, C, D)
        "matrices": self._export_matrices(),
        # Additional cross-reference sections
        "program_graph": self._export_program_graph(),
        "process_model": self._export_process_model(),
        "mappings": self._export_mappings(),
    }

    # Log matrix shapes and section summary at INFO level
    matrices_raw = output.get("matrices", {})
    matrices = matrices_raw if isinstance(matrices_raw, dict) else {}
    shapes_raw = matrices.get("shapes", {})
    shapes = shapes_raw if isinstance(shapes_raw, dict) else {}
    n_sections = len(output)
    logger.info(
        "GNN JSON export complete: %d sections + matrices (A=%s, B=%s, C=%s, D=%s)",
        n_sections,
        shapes.get("A", [0, 0]),
        shapes.get("B", [0, 0, 0]),
        shapes.get("C", [0]),
        shapes.get("D", [0]),
    )

    return output

export_to_string(indent=2)

Export the model to a JSON string.

Parameters:

Name Type Description Default
indent int | None

Number of spaces for indentation, or None for compact.

2

Returns:

Type Description
str

JSON string.

Source code in py/cogant/gnn/json_export.py
192
193
194
195
196
197
198
199
200
201
202
203
def export_to_string(self, indent: int | None = 2) -> str:
    """
    Export the model to a JSON string.

    Args:
        indent: Number of spaces for indentation, or None for compact.

    Returns:
        JSON string.
    """
    data = self.export()
    return json.dumps(data, indent=indent, default=str)

GNNMarkdownFormatter

Bases: _UpstreamSectionsMixin, _MetadataSectionsMixin, _StructuralSectionsMixin, _DynamicsSectionsMixin, _SemanticSectionsMixin

Formats complete GNN models to canonical markdown with all sections.

The emitted markdown is simultaneously an upstream-valid GNN model (accepted by the generalized-notation-notation 4.x validator) (containing ## GNNSection, ## GNNVersionAndFlags, ## ModelName, ## StateSpaceBlock, ## Connections, ## InitialParameterization, ## Equations, ## Time, ## ActInfOntologyAnnotation, ## ModelParameters, ## Footer, and ## Signature) and a COGANT-extended bundle with richer metadata, provenance, Markov blanket, and validation sections appended below the upstream header.

Source code in py/cogant/gnn/formatter/base.py
 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
 78
 79
 80
 81
 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
class GNNMarkdownFormatter(
    _UpstreamSectionsMixin,
    _MetadataSectionsMixin,
    _StructuralSectionsMixin,
    _DynamicsSectionsMixin,
    _SemanticSectionsMixin,
):
    """
    Formats complete GNN models to canonical markdown with all sections.

    The emitted markdown is simultaneously an upstream-valid GNN model
    (accepted by the ``generalized-notation-notation`` 4.x validator)
    (containing ``## GNNSection``, ``## GNNVersionAndFlags``,
    ``## ModelName``, ``## StateSpaceBlock``, ``## Connections``,
    ``## InitialParameterization``, ``## Equations``, ``## Time``,
    ``## ActInfOntologyAnnotation``, ``## ModelParameters``, ``## Footer``,
    and ``## Signature``) and a COGANT-extended bundle with
    richer metadata, provenance, Markov blanket, and validation
    sections appended below the upstream header.
    """

    # Canonical section order. The upstream GNN header comes FIRST
    # so the file parses cleanly in the upstream type-checker
    # (``gnn/5_type_checker.py``). COGANT's extended sections follow and
    # are treated as ignored extras by upstream tooling.
    SECTION_ORDER = [
        "upstream_header",
        "model_metadata",
        "repository_metadata",
        "source_coverage",
        "state_space",
        "observation_modalities",
        "actions_policies",
        "program_graph_connections",
        "factors",
        "transition_structure",
        "likelihood_structure",
        "preferences_constraints",
        "time_settings",
        "parameterization",
        "ontology_mapping",
        "markov_blanket",
        "provenance",
        "confidence",
        "rendering_hints",
        "validation_notes",
    ]

    def __init__(
        self,
        program_graph: ProgramGraph,
        state_space_model: StateSpaceModel,
        process_model: ProcessModel,
        semantic_mappings: dict[str, Any],
    ):
        """
        Initialize the formatter.

        Args:
            program_graph: The program graph.
            state_space_model: The state space model.
            process_model: The process model.
            semantic_mappings: Semantic mappings dictionary.
        """
        self.graph = program_graph
        self.state_space = state_space_model
        self.process = process_model
        self.mappings = semantic_mappings

    def format(self) -> str:
        """
        Format the complete GNN model as markdown.

        Returns:
            Formatted markdown string.
        """
        logger.info("Formatting GNN model to markdown...")

        # Debug: check mappings type
        if not isinstance(self.mappings, dict):
            logger.warning(f"WARNING: mappings is {type(self.mappings)}, not dict. Converting...")
            if isinstance(self.mappings, list):
                self.mappings = {m.id: m for m in self.mappings}
            else:
                self.mappings = {}

        sections = {}
        methods = [
            ("upstream_header", self._format_upstream_header),
            ("model_metadata", self._format_model_metadata),
            ("repository_metadata", self._format_repository_metadata),
            ("source_coverage", self._format_source_coverage),
            ("state_space", self._format_state_space),
            ("observation_modalities", self._format_observation_modalities),
            ("actions_policies", self._format_actions_policies),
            ("program_graph_connections", self._format_connections),
            ("factors", self._format_factors),
            ("transition_structure", self._format_transition_structure),
            ("likelihood_structure", self._format_likelihood_structure),
            ("preferences_constraints", self._format_preferences),
            ("time_settings", self._format_time_settings),
            ("parameterization", self._format_parameterization),
            ("ontology_mapping", self._format_ontology_mapping),
            ("markov_blanket", self._format_markov_blanket),
            ("provenance", self._format_provenance),
            ("confidence", self._format_confidence),
            ("rendering_hints", self._format_rendering_hints),
            ("validation_notes", self._format_validation_notes),
        ]

        for section_name, method in methods:
            try:
                sections[section_name] = method()
            except Exception as e:
                logger.error(f"Failed to format {section_name}: {type(e).__name__}: {e}")
                traceback.print_exc()
                sections[section_name] = f"[Error formatting {section_name}: {e}]"

        # Emit in canonical order
        output = []
        for section_name in self.SECTION_ORDER:
            if section_name in sections and sections[section_name]:
                output.append(sections[section_name])

        return "\n\n".join(output)

    @staticmethod
    def _action_effects(action: Any) -> list[str]:
        """Read action effects across schema variants."""
        effects = getattr(action, "effects", None)
        if effects is None:
            effects = getattr(action, "affects_state_vars", None)
        return list(effects or [])

    def _derive_probability_from_edges(self, action_id: str | None) -> float | None:
        """
        Derive action transition probability from edge weights in the graph.

        Args:
            action_id: The action ID or name to look up in graph.

        Returns:
            Normalized probability derived from edge weights, or None if not found.
        """
        if not action_id:
            return None

        # Find action node in graph
        action_node = None
        for node in self.graph.nodes.values():
            if action_id in node.id or action_id in node.name:
                action_node = node
                break

        if not action_node:
            return None

        # Get CALLS and WRITES edges from action
        outgoing_edges = self.graph.get_edges_from(action_node.id)
        total_weight = 0.0
        edge_count = 0

        for edge in outgoing_edges:
            if edge.kind in (EdgeKind.CALLS, EdgeKind.WRITES, EdgeKind.RETURNS):
                total_weight += edge.weight
                edge_count += 1

        if edge_count > 0:
            # Normalize weight to [0, 1]
            avg_weight = total_weight / edge_count
            return min(1.0, avg_weight / 10.0) if avg_weight > 0 else 0.5

        return None

    def format_section(self, section_name: str) -> str | None:
        """
        Format a specific section.

        Args:
            section_name: Name of the section.

        Returns:
            Formatted section or None.
        """
        method_name = f"_format_{section_name}"
        if hasattr(self, method_name):
            result: str | None = getattr(self, method_name)()
            return result
        return None

__init__(program_graph, state_space_model, process_model, semantic_mappings)

Initialize the formatter.

Parameters:

Name Type Description Default
program_graph ProgramGraph

The program graph.

required
state_space_model StateSpaceModel

The state space model.

required
process_model ProcessModel

The process model.

required
semantic_mappings dict[str, Any]

Semantic mappings dictionary.

required
Source code in py/cogant/gnn/formatter/base.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def __init__(
    self,
    program_graph: ProgramGraph,
    state_space_model: StateSpaceModel,
    process_model: ProcessModel,
    semantic_mappings: dict[str, Any],
):
    """
    Initialize the formatter.

    Args:
        program_graph: The program graph.
        state_space_model: The state space model.
        process_model: The process model.
        semantic_mappings: Semantic mappings dictionary.
    """
    self.graph = program_graph
    self.state_space = state_space_model
    self.process = process_model
    self.mappings = semantic_mappings

format()

Format the complete GNN model as markdown.

Returns:

Type Description
str

Formatted markdown string.

Source code in py/cogant/gnn/formatter/base.py
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
def format(self) -> str:
    """
    Format the complete GNN model as markdown.

    Returns:
        Formatted markdown string.
    """
    logger.info("Formatting GNN model to markdown...")

    # Debug: check mappings type
    if not isinstance(self.mappings, dict):
        logger.warning(f"WARNING: mappings is {type(self.mappings)}, not dict. Converting...")
        if isinstance(self.mappings, list):
            self.mappings = {m.id: m for m in self.mappings}
        else:
            self.mappings = {}

    sections = {}
    methods = [
        ("upstream_header", self._format_upstream_header),
        ("model_metadata", self._format_model_metadata),
        ("repository_metadata", self._format_repository_metadata),
        ("source_coverage", self._format_source_coverage),
        ("state_space", self._format_state_space),
        ("observation_modalities", self._format_observation_modalities),
        ("actions_policies", self._format_actions_policies),
        ("program_graph_connections", self._format_connections),
        ("factors", self._format_factors),
        ("transition_structure", self._format_transition_structure),
        ("likelihood_structure", self._format_likelihood_structure),
        ("preferences_constraints", self._format_preferences),
        ("time_settings", self._format_time_settings),
        ("parameterization", self._format_parameterization),
        ("ontology_mapping", self._format_ontology_mapping),
        ("markov_blanket", self._format_markov_blanket),
        ("provenance", self._format_provenance),
        ("confidence", self._format_confidence),
        ("rendering_hints", self._format_rendering_hints),
        ("validation_notes", self._format_validation_notes),
    ]

    for section_name, method in methods:
        try:
            sections[section_name] = method()
        except Exception as e:
            logger.error(f"Failed to format {section_name}: {type(e).__name__}: {e}")
            traceback.print_exc()
            sections[section_name] = f"[Error formatting {section_name}: {e}]"

    # Emit in canonical order
    output = []
    for section_name in self.SECTION_ORDER:
        if section_name in sections and sections[section_name]:
            output.append(sections[section_name])

    return "\n\n".join(output)

format_section(section_name)

Format a specific section.

Parameters:

Name Type Description Default
section_name str

Name of the section.

required

Returns:

Type Description
str | None

Formatted section or None.

Source code in py/cogant/gnn/formatter/base.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def format_section(self, section_name: str) -> str | None:
    """
    Format a specific section.

    Args:
        section_name: Name of the section.

    Returns:
        Formatted section or None.
    """
    method_name = f"_format_{section_name}"
    if hasattr(self, method_name):
        result: str | None = getattr(self, method_name)()
        return result
    return None

GNNMatrices

Derives GNN A/B/C/D matrices from COGANT analysis artifacts.

The matrices are computed once on construction-time demand via the compute_* methods. Callers that need all four at once should use :meth:to_dict or :meth:to_gnn_markdown_block.

Source code in py/cogant/gnn/matrices.py
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
403
404
405
406
407
408
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
471
472
473
474
475
476
477
478
479
480
481
482
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
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
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
class GNNMatrices:
    """Derives GNN A/B/C/D matrices from COGANT analysis artifacts.

    The matrices are computed once on construction-time demand via the
    ``compute_*`` methods. Callers that need all four at once should use
    :meth:`to_dict` or :meth:`to_gnn_markdown_block`.
    """

    def __init__(
        self,
        graph: ProgramGraph,
        mappings: Any,
        state_space: StateSpaceModel,
    ) -> None:
        """Initialize the matrix deriver.

        Args:
            graph: The program graph with nodes and edges.
            mappings: Semantic mappings; accepted as either a ``dict``
                keyed by mapping ID or a list of ``SemanticMapping``.
            state_space: The compiled state space model.
        """
        self.graph = graph
        self.state_space = state_space

        # Normalize mappings to a list for convenient filtering while
        # preserving a stable ordering.
        if isinstance(mappings, dict):
            mapping_list: list[SemanticMapping] = list(mappings.values())
        elif isinstance(mappings, list):
            mapping_list = list(mappings)
        elif mappings is None:
            mapping_list = []
        else:
            mapping_list = list(mappings)
        self._mappings: list[SemanticMapping] = mapping_list

        # Enumerate spaces.
        self._hidden_states: list[SemanticMapping] = [
            m for m in self._mappings if m.kind == MappingKind.HIDDEN_STATE
        ]
        self._observations: list[SemanticMapping] = [
            m for m in self._mappings if m.kind == MappingKind.OBSERVATION
        ]
        self._actions: list[SemanticMapping] = [
            m for m in self._mappings if m.kind in (MappingKind.ACTION, MappingKind.POLICY)
        ]
        self._constraints: list[SemanticMapping] = [
            m for m in self._mappings if m.kind in (MappingKind.CONSTRAINT, MappingKind.PREFERENCE)
        ]

        # The compiled state-space variables are the authoritative hidden-state
        # axis. A single HIDDEN_STATE mapping can cover multiple graph-fragment
        # nodes, and the state-space compiler expands those into distinct
        # variables. Using the compiled variables here keeps A/B/D dimensions
        # aligned with ``state_space.json`` and avoids losing matrix-bearing
        # states when a mapping spans more than one node.
        self._state_space_vars = list(self.state_space.variables.values())
        self._use_state_space_vars = bool(self._state_space_vars)

        # Populated by compute_B() when the full B tensor would exceed
        # _MAX_B_ENTRIES.  Callers can inspect these to understand the
        # approximation that was applied.
        self._b_truncated: bool = False
        self._b_n_states_full: int = 0  # untruncated n_states
        self._b_n_states_kept: int = 0  # n_states after truncation
        # Indices (into the full A-column / D state axis) of the states
        # kept on the B axis, ascending. B index ``j`` is full state
        # ``self._b_kept_state_indices[j]``.
        self._b_kept_state_indices: list[int] = []

    # ------------------------------------------------------------------
    # Dimensions
    # ------------------------------------------------------------------
    @property
    def n_states(self) -> int:
        """Number of hidden-state dimensions."""
        if self._use_state_space_vars:
            return len(self._state_space_vars)
        return len(self._hidden_states)

    @property
    def n_obs(self) -> int:
        """Number of observation dimensions."""
        if self.state_space.observations:
            return len(self.state_space.observations)
        return len(self._observations)

    @property
    def n_actions(self) -> int:
        """Number of action dimensions.

        Zero is a valid dimension for a degenerate empty state space.  The
        matrix exporter preserves that fact instead of inventing an action
        dimension, which keeps the declared dimensions consistent with the
        compiled state-space model.
        """
        if self._actions:
            return len(self._actions)
        return len(self.state_space.actions)

    # ------------------------------------------------------------------
    # Helpers
    # ------------------------------------------------------------------
    def _state_node_ids(self) -> list[str]:
        """Return the ordered list of graph node IDs backing hidden states."""
        if self._use_state_space_vars:
            return [v.node_id for v in self._state_space_vars]
        ids: list[str] = []
        for mapping in self._hidden_states:
            if mapping.graph_fragment_node_ids:
                ids.append(mapping.graph_fragment_node_ids[0])
            else:
                ids.append("")
        return ids

    def _obs_node_ids(self) -> list[str]:
        """Return the ordered list of graph node IDs backing observations."""
        # The compiler expands multi-node mappings and deduplicates channels.
        # Use its axis for both A and C, including its declared row order.
        if self.state_space.observations:
            return [o.source_node_id for o in self.state_space.observations.values()]
        if self._observations:
            ids: list[str] = []
            for mapping in self._observations:
                if mapping.graph_fragment_node_ids:
                    ids.append(mapping.graph_fragment_node_ids[0])
                else:
                    ids.append("")
            return ids
        return []

    def _action_node_ids(self) -> list[str]:
        """Return the ordered list of graph node IDs backing actions."""
        if self._actions:
            ids: list[str] = []
            for mapping in self._actions:
                if mapping.graph_fragment_node_ids:
                    ids.append(mapping.graph_fragment_node_ids[0])
                else:
                    ids.append("")
            return ids
        return [a.controller_id for a in self.state_space.actions.values()]

    def _edges_from(self, node_id: str) -> list[Any]:
        """Return outgoing edges from ``node_id`` (or an empty list)."""
        if not node_id:
            return []
        return [e for e in self.graph.edges.values() if e.source_id == node_id]

    def _edges_to(self, node_id: str) -> list[Any]:
        """Return incoming edges to ``node_id`` (or an empty list)."""
        if not node_id:
            return []
        return [e for e in self.graph.edges.values() if e.target_id == node_id]

    def _top_k_state_indices(self, state_ids: list[str], k: int) -> list[int]:
        """Return indices of the *k* states with the highest combined degree.

        Used by :meth:`compute_B` when the full ``n_states × n_states ×
        n_actions`` tensor would exceed ``_MAX_B_ENTRIES``.  We keep the
        highest-degree nodes because they carry the most transition
        information; the approximation is a principal submatrix of the
        full B tensor restricted to the top-k row/column indices.

        Args:
            state_ids: Full ordered list of state node IDs.
            k: Number of states to keep.

        Returns:
            At most *k* indices into ``state_ids``, in ascending order so
            the kept B axis preserves the A/D state order. Ties in degree
            are broken by original position, so the selection is
            deterministic.
        """
        if k >= len(state_ids):
            return list(range(len(state_ids)))

        # Count in+out degree for each state node using a single pass
        # over the full edge list (O(|E|), not O(|V|²)).
        degree: dict[str, int] = {nid: 0 for nid in state_ids if nid}
        state_id_set = set(degree)
        for edge in self.graph.edges.values():
            if edge.source_id in state_id_set:
                degree[edge.source_id] += 1
            if edge.target_id in state_id_set:
                degree[edge.target_id] += 1

        # Sort by descending degree, preserving original order for ties
        # so the truncated matrix is deterministic.
        ranked = sorted(range(len(state_ids)), key=lambda j: -degree.get(state_ids[j], 0))
        return sorted(ranked[: max(k, 0)])

    def _top_k_state_ids(self, state_ids: list[str], k: int) -> list[str]:
        """Return the *k* state node IDs with the highest combined degree.

        Thin wrapper over :meth:`_top_k_state_indices`; the IDs are
        returned in their original (A/D axis) order.
        """
        return [state_ids[j] for j in self._top_k_state_indices(state_ids, k)]

    def _state_axis_ids(self) -> list[str]:
        """Return a stable identifier per hidden state on the A/D axis.

        Compiled state-space variable ids when available, otherwise the
        HIDDEN_STATE mapping ids.
        """
        if self._use_state_space_vars:
            return [v.id for v in self._state_space_vars]
        return [m.id for m in self._hidden_states]

    # ------------------------------------------------------------------
    # A matrix — likelihood
    # ------------------------------------------------------------------
    def compute_A(self) -> list[list[float]]:
        """Compute the likelihood matrix ``A[n_obs x n_states]``.

        ``A[i][j] = P(observation_i | hidden_state_j)``.

        Derivation:
            For each observation ``i``, find the set of hidden-state
            nodes that it directly reads (READS/OBSERVES edges from the
            observation's node). Those direct reads receive a high
            probability mass; all other states share the residual mass
            uniformly. Columns are then normalized so each hidden state
            defines a distribution over observations.
        """
        n_obs = self.n_obs
        n_states = self.n_states
        if n_obs == 0 or n_states == 0:
            return []

        state_ids = self._state_node_ids()
        obs_ids = self._obs_node_ids()
        state_index = {nid: j for j, nid in enumerate(state_ids) if nid}

        direct_kinds = {EdgeKind.READS, EdgeKind.OBSERVES, EdgeKind.DEPENDS_ON}

        A: list[list[float]] = [[0.0] * n_states for _ in range(n_obs)]
        n_uniform = 0  # count of rows with no direct evidence

        for i in range(n_obs):
            obs_node_id = obs_ids[i] if i < len(obs_ids) else ""
            direct: list[int] = []
            if obs_node_id:
                for edge in self._edges_from(obs_node_id):
                    if edge.kind in direct_kinds and edge.target_id in state_index:
                        j = state_index[edge.target_id]
                        if j not in direct:
                            direct.append(j)
                # Also look at incoming edges that go TO this observation
                # node (e.g., state->obs "OBSERVES" edges in the reverse
                # direction).
                for edge in self._edges_to(obs_node_id):
                    if edge.kind in direct_kinds and edge.source_id in state_index:
                        j = state_index[edge.source_id]
                        if j not in direct:
                            direct.append(j)

            n_direct = len(direct)
            n_indirect = n_states - n_direct
            if n_direct == 0:
                # No evidence linking this observation to any state: assign
                # equal pre-normalization mass across states. After the
                # column normalization below this row contributes uniformly
                # to every state-column (a maximally vague observation).
                A[i] = [1.0 / n_states] * n_states
                n_uniform += 1
                continue
            direct_share = _DEFAULT_DIRECT_MASS / n_direct
            indirect_share = _DEFAULT_INDIRECT_MASS / n_indirect if n_indirect > 0 else 0.0
            for j in range(n_states):
                A[i][j] = direct_share if j in direct else indirect_share

        # Column-stochastic normalization (AII/pymdp convention). ``A`` holds
        # ``A[o][s] = P(o | s)``, so for every fixed hidden state ``s`` the
        # distribution over observation outcomes must sum to 1: each *column*
        # sums to 1, not each row. (Row-normalizing would make ``sum_s
        # P(o|s) = 1``, which is not a valid likelihood and breaks the
        # predicted-observation update ``pred_obs[o] = sum_s A[o][s]·q(s)``
        # in ``simulate/free_energy.py``.)
        for j in range(n_states):
            col_total = sum(A[i][j] for i in range(n_obs))
            if col_total <= _EPSILON:
                # A state observed by nothing: uniform over observations.
                for i in range(n_obs):
                    A[i][j] = 1.0 / n_obs
            else:
                for i in range(n_obs):
                    A[i][j] = A[i][j] / col_total

        # Log A matrix computation details
        n_informed = n_obs - n_uniform
        logger.info(
            "A matrix computed: shape [%d x %d], %d/%d observations with direct evidence, "
            "%d observations uniform before column normalization (no READS/OBSERVES edges)",
            n_obs,
            n_states,
            n_informed,
            n_obs,
            n_uniform,
        )

        return A

    # ------------------------------------------------------------------
    # B matrix — transition
    # ------------------------------------------------------------------
    def compute_B(self) -> list[list[list[float]]]:
        """Compute the transition tensor ``B[n_states x n_states x n_actions]``.

        ``B[next][cur][action] = P(next_state | current_state, action)``.

        Derivation:
            For each action ``k``, find the hidden-state nodes that it
            WRITES/MUTATES. Those destinations become high-probability
            successors of every current state; otherwise the transition
            defaults to an identity (stay) move. Every column
            ``(cur, action)`` is normalized so that it sums to 1.0.

        Truncation:
            When ``n_states² × n_actions`` would exceed ``_MAX_B_ENTRIES``
            (default 5 M), the state space is reduced to the top-K
            highest-degree nodes so that the tensor fits in memory and
            serializes in reasonable time. The kept states stay in their
            original A/D order, so B index ``j`` is full state
            ``self._b_kept_state_indices[j]``. The truncation is recorded
            in ``self._b_truncated``, ``self._b_n_states_full``,
            ``self._b_n_states_kept`` and ``self._b_kept_state_indices``,
            and surfaced in :meth:`to_dict` under the ``"truncation"`` key.
            This approximation is a principal submatrix of the full B
            restricted to the most structurally important state nodes.
        """
        n_states = self.n_states
        n_actions = self.n_actions
        if n_states == 0:
            return []

        state_ids = self._state_node_ids()
        action_ids = self._action_node_ids()

        # ---- Truncation guard ----------------------------------------
        # If the full tensor would exceed _MAX_B_ENTRIES, keep only the
        # top-K state nodes ranked by in+out degree.  This turns an O(S²A)
        # explosion into O(_MAX_B_ENTRIES) work, preserving the most
        # structurally important nodes.
        full_b_entries = n_states * n_states * n_actions
        self._b_n_states_full = n_states
        self._b_truncated = False
        self._b_kept_state_indices = list(range(n_states))

        if full_b_entries > _MAX_B_ENTRIES and n_actions > 0:
            # Solve for max_k: k² × n_actions ≤ _MAX_B_ENTRIES
            import math

            max_k = max(1, int(math.isqrt(_MAX_B_ENTRIES // n_actions)))
            self._b_truncated = True
            self._b_n_states_kept = max_k
            logger.warning(
                "B tensor would be %d entries (%d states × %d states × %d actions) "
                "which exceeds _MAX_B_ENTRIES=%d. Truncating to top-%d state nodes "
                "by graph degree. Set _MAX_B_ENTRIES higher to disable truncation.",
                full_b_entries,
                n_states,
                n_states,
                n_actions,
                _MAX_B_ENTRIES,
                max_k,
            )
            logger.info(
                "B tensor truncated: %d → %d state nodes (%.1f%% reduction, %d → %d entries)",
                n_states,
                max_k,
                (1 - max_k / n_states) * 100 if n_states > 0 else 0.0,
                full_b_entries,
                max_k * max_k * n_actions,
            )
            kept = self._top_k_state_indices(state_ids, max_k)
            self._b_kept_state_indices = kept
            self._b_n_states_kept = len(kept)
            state_ids = [state_ids[j] for j in kept]
            n_states = len(state_ids)
        else:
            self._b_n_states_kept = n_states
        # ---------------------------------------------------------------

        state_index = {nid: j for j, nid in enumerate(state_ids) if nid}

        write_kinds = {EdgeKind.WRITES, EdgeKind.MUTATES}

        # Initialize to identity per action so that non-writing actions
        # leave the state unchanged (a valid default transition).
        B: list[list[list[float]]] = [
            [[0.0] * n_actions for _ in range(n_states)] for _ in range(n_states)
        ]
        for cur in range(n_states):
            for k in range(n_actions):
                B[cur][cur][k] = 1.0

        n_identity_actions = 0  # actions with no WRITES/MUTATES edges
        n_writing_actions = 0

        for k in range(n_actions):
            act_node_id = action_ids[k] if k < len(action_ids) else ""
            written: list[int] = []
            if act_node_id:
                for edge in self._edges_from(act_node_id):
                    if edge.kind in write_kinds and edge.target_id in state_index:
                        j = state_index[edge.target_id]
                        if j not in written:
                            written.append(j)

            if not written:
                # Already identity — nothing to update for this action.
                n_identity_actions += 1
                continue
            n_writing_actions += 1

            # For every current state ``cur``, redistribute mass so the
            # written destinations receive _DEFAULT_DIRECT_MASS and the
            # identity "stay" move receives _DEFAULT_INDIRECT_MASS.
            for cur in range(n_states):
                column = [0.0] * n_states
                n_w = len(written)
                direct_share = _DEFAULT_DIRECT_MASS / n_w
                for j in written:
                    column[j] = direct_share
                # Residual mass on the identity move (or uniform if the
                # current state is itself a written destination — in that
                # case ``column[cur]`` already received its share above and
                # we normalize as-is below).
                if cur not in written:
                    column[cur] += _DEFAULT_INDIRECT_MASS
                column = _normalize_row(column)
                for nxt in range(n_states):
                    B[nxt][cur][k] = column[nxt]

        # Log B tensor computation details
        logger.info(
            "B tensor computed: shape [%d x %d x %d], %d/%d writing actions "
            "(%d identity/stay), direct_mass=%.2f",
            n_states,
            n_states,
            n_actions,
            n_writing_actions,
            n_actions,
            n_identity_actions,
            _DEFAULT_DIRECT_MASS,
        )

        return B

    # ------------------------------------------------------------------
    # C vector — log preferences over observations
    # ------------------------------------------------------------------
    def compute_C(self) -> list[float]:
        """Compute the log-preference vector ``C[n_obs]``.

        Derivation:
            Each observation receives a log-preference derived from the
            confidence scores of CONSTRAINT/PREFERENCE mappings whose
            graph fragments intersect with the observation's node set.
            Preferences with CONSTRAINT kind contribute a positive
            preference (the constraint describes a desired observation);
            absent any matching constraint, C defaults to 0.0 (neutral).
        """
        n_obs = self.n_obs
        if n_obs == 0:
            return []

        obs_node_ids = self._obs_node_ids()
        C: list[float] = [0.0] * n_obs

        n_preferred = 0  # observations with nonzero preference
        n_aversive = 0  # observations with negative preference
        for i in range(n_obs):
            obs_nid = obs_node_ids[i] if i < len(obs_node_ids) else ""
            if not obs_nid:
                continue
            # Sum signed log-preference contributions from constraints
            # that touch the observation's node (or any graph neighbor).
            total = 0.0
            for mapping in self._constraints:
                if obs_nid in mapping.graph_fragment_node_ids:
                    # Constraint: higher confidence → stronger preference.
                    sign = 1.0
                    if mapping.kind == MappingKind.CONSTRAINT:
                        # Constraints are "must hold" → strongly preferred.
                        sign = 1.0
                    elif mapping.kind == MappingKind.PREFERENCE:
                        # Preferences can be soft and may be aversive if
                        # the mapping semantic label starts with "avoid"
                        # or "reject".
                        label = (mapping.semantic_label or "").lower()
                        if label.startswith(("avoid", "reject", "!")):
                            sign = -1.0
                    total += sign * float(mapping.confidence_score or 0.0)
            C[i] = total
            if total > 0:
                n_preferred += 1
            elif total < 0:
                n_aversive += 1

        # Log C vector computation details
        n_neutral = n_obs - n_preferred - n_aversive
        logger.info(
            "C vector computed: length %d, %d preferred, %d aversive, %d neutral",
            n_obs,
            n_preferred,
            n_aversive,
            n_neutral,
        )

        return C

    # ------------------------------------------------------------------
    # D vector — initial prior over hidden states
    # ------------------------------------------------------------------
    def compute_D(self) -> list[float]:
        """Compute the initial prior ``D[n_states]``.

        Derivation:
            If any hidden state has an explicit ``default_value`` or an
            attached CONFIGURATION node with a value, concentrate mass
            on that state. Otherwise return a uniform prior. The vector
            always sums to 1.0.
        """
        n_states = self.n_states
        if n_states == 0:
            return []

        # Base: uniform prior.
        D: list[float] = [1.0 / n_states] * n_states

        if self._use_state_space_vars:
            # Bias toward any variable whose StateVariable has a default
            # value or a CONFIGURATION neighbor in the graph.
            biased = [0.0] * n_states
            any_bias = False
            for j, var in enumerate(self._state_space_vars):
                bias = 1.0
                # Explicit domain/default bias.
                meta_default = getattr(var, "domain", None)
                if meta_default:
                    any_bias = True
                    bias += 1.0
                # CONFIGURATION neighbor in the graph → stronger prior.
                node_id = getattr(var, "node_id", "")
                if node_id and node_id in self.graph.nodes:
                    for edge in self._edges_to(node_id) + self._edges_from(node_id):
                        other_id = edge.source_id if edge.target_id == node_id else edge.target_id
                        other = self.graph.nodes.get(other_id)
                        if other and other.kind == NodeKind.CONFIGURATION:
                            any_bias = True
                            bias += 2.0
                            break
                biased[j] = bias
            if any_bias:
                D = _normalize_vector(biased)
            else:
                D = _normalize_vector(D)
        else:
            # Hidden-state semantic mappings: use mapping confidence as
            # a soft prior weight so that high-confidence hidden states
            # receive more prior mass.
            weights = [max(float(m.confidence_score or 0.0), _EPSILON) for m in self._hidden_states]
            D = _normalize_vector(weights)

        # Log D vector computation details
        peak_idx = max(range(len(D)), key=lambda j: D[j]) if D else -1
        peak_val = D[peak_idx] if peak_idx >= 0 else 0.0
        logger.info(
            "D vector computed: length %d, peak at index %d (%.4f), source=%s",
            len(D),
            peak_idx,
            peak_val,
            "state_space_vars" if self._use_state_space_vars else "hidden_state_mappings",
        )

        return D

    # ------------------------------------------------------------------
    # Output formatting
    # ------------------------------------------------------------------
    def to_dict(self) -> dict[str, Any]:
        """Return a JSON-serializable dict of all four matrices.

        Returns:
            ``{"A": ..., "B": ..., "C": ..., "D": ..., "shapes": ...,
            "dimensions": ..., "truncation": ...}``

            The ``"truncation"`` key is ``None`` when no truncation
            occurred; otherwise it is a dict with:

            * ``"applied"``: ``True``
            * ``"n_states_full"``: original (un-truncated) n_states
            * ``"n_states_kept"``: n_states after truncation
            * ``"max_b_entries"``: the ``_MAX_B_ENTRIES`` threshold
            * ``"kept_state_indices"``: ascending indices into the full
                A-column / D state axis; B index ``j`` is full state
                ``kept_state_indices[j]``
            * ``"kept_state_ids"``: the matching state ids
            * ``"reason"``: human-readable explanation

            ``"shapes"`` reports the emitted arrays, so a truncated B is
            declared as ``[n_states_kept, n_states_kept, n_actions]``
            while ``"dimensions"`` keeps the full ``n_states``.
        """
        A = self.compute_A()
        B = self.compute_B()
        C = self.compute_C()
        D = self.compute_D()

        truncation: dict[str, Any] | None = None
        if self._b_truncated:
            axis_ids = self._state_axis_ids()
            kept = list(self._b_kept_state_indices)
            truncation = {
                "applied": True,
                "n_states_full": self._b_n_states_full,
                "n_states_kept": self._b_n_states_kept,
                "max_b_entries": _MAX_B_ENTRIES,
                "kept_state_indices": kept,
                "kept_state_ids": [axis_ids[j] if j < len(axis_ids) else "" for j in kept],
                "reason": (
                    f"B tensor ({self._b_n_states_full}² × {self.n_actions} = "
                    f"{self._b_n_states_full**2 * self.n_actions:,} entries) "
                    f"exceeded _MAX_B_ENTRIES={_MAX_B_ENTRIES:,}; "
                    f"kept top-{self._b_n_states_kept} state nodes by degree."
                ),
            }

        # Declared shapes are the logical array shapes. An empty A (zero
        # observations or zero hidden states) or an empty B (zero hidden
        # states) is still an ``[n_obs, n_states]`` /
        # ``[n_states, n_states, n_actions]`` array with a zero axis, so
        # fall back to the dimensions instead of collapsing to ``[0, 0]``.
        return {
            "A": A,
            "B": B,
            "C": C,
            "D": D,
            "shapes": {
                "A": [len(A), len(A[0])] if A else [self.n_obs, self.n_states],
                "B": [len(B), len(B[0]), len(B[0][0]) if B[0] else 0]
                if B
                else [0, 0, self.n_actions],
                "C": [len(C)],
                "D": [len(D)],
            },
            "dimensions": {
                "n_states": self.n_states,
                "n_obs": self.n_obs,
                "n_actions": self.n_actions,
            },
            "truncation": truncation,
        }

    def to_gnn_markdown_block(self) -> str:
        """Format the matrices as a GNN-compatible markdown block.

        Emits AII-style sections with ``rows=``, ``cols=``, ``depth=``
        bracket headers. This block is additive to the existing
        ``StateSpaceBlock`` / ``InitialParameterization`` sections; it is
        meant to be embedded as a COGANT extension.
        """
        A = self.compute_A()
        B = self.compute_B()
        C = self.compute_C()
        D = self.compute_D()

        lines: list[str] = []

        n_rows = len(A)
        n_cols = len(A[0]) if A else self.n_states
        lines.append(f"A[[rows={n_rows}][cols={n_cols}]]")
        for row in A:
            lines.append("  " + " ".join(repr(float(v)) for v in row))
        lines.append("")

        # --- B tensor ---
        if B:
            n_rows = len(B)
            n_cols = len(B[0]) if B else 0
            n_depth = len(B[0][0]) if (B and B[0]) else 0
            lines.append(f"B[[rows={n_rows}][cols={n_cols}][depth={n_depth}]]")
            for k in range(n_depth):
                lines.append(f"  # action={k}")
                for r in range(n_rows):
                    row_vals = [B[r][c][k] for c in range(n_cols)]
                    lines.append("  " + " ".join(repr(float(v)) for v in row_vals))
            lines.append("")
        else:
            lines.extend(("B[[rows=0][cols=0][depth=0]]", ""))

        # --- C vector ---
        lines.append(f"C[[rows={len(C)}]]")
        for v in C:
            lines.append(f"  {float(v)!r}")
        lines.append("")

        # --- D vector ---
        lines.append(f"D[[rows={len(D)}]]")
        for v in D:
            lines.append(f"  {float(v)!r}")
        lines.append("")

        return "\n".join(lines).rstrip()

    # ------------------------------------------------------------------
    # Validation helpers
    # ------------------------------------------------------------------
    def validate_shapes(self) -> tuple[bool, list[str]]:
        """Validate that all four matrices have the expected shapes.

        Returns:
            ``(ok, errors)`` where ``ok`` is True if no shape errors
            were found.
        """
        errors: list[str] = []
        A = self.compute_A()
        B = self.compute_B()
        C = self.compute_C()
        D = self.compute_D()

        n_s = self.n_states
        n_o = self.n_obs
        n_a = self.n_actions
        # A truncated B covers only the kept states (see compute_B).
        n_b = self._b_n_states_kept if self._b_truncated else n_s

        # A: n_obs x n_states, columns sum to 1.
        # Column-sum tolerance 1e-6 — principled default, matches the
        # PyMDP validator tolerance and is ~7 orders of magnitude
        # above float64 round-off noise (~1e-16) for a typical
        # n_states <= 50. Strict enough to catch normalization bugs
        # but loose enough to tolerate accumulated rounding across
        # multiple ``_normalize_row`` passes.
        if n_o > 0 and n_s > 0:
            if len(A) != n_o:
                errors.append(f"A row count {len(A)} != n_obs {n_o}")
            elif A and any(len(row) != n_s for row in A):
                errors.append(f"A has inconsistent column count (expected {n_s})")
            else:
                # A is column-stochastic: P(o|s) sums to 1 over observation
                # outcomes for each fixed hidden state s (a column).
                for j in range(n_s):
                    col_sum = sum(A[i][j] for i in range(len(A)))
                    if abs(col_sum - 1.0) > 1e-6:  # col-norm tolerance
                        errors.append(f"A column {j} does not sum to 1 (sum={col_sum:.6f})")

        # B: n_states x n_states x n_actions (n_states_kept when truncated)
        if n_s > 0:
            if len(B) != n_b:
                errors.append(f"B first dim {len(B)} != n_states {n_b}")
            elif any(len(row) != n_b for row in B):
                errors.append(f"B second dim != n_states {n_b}")
            elif any(len(cell) != n_a for row in B for cell in row):
                errors.append(f"B third dim != n_actions {n_a}")
            else:
                if any(
                    B[i][j][k] < -1e-9 for i in range(n_b) for j in range(n_b) for k in range(n_a)
                ):
                    errors.append("B contains negative probabilities")
                for k in range(n_a):
                    for j in range(n_b):
                        col_sum = sum(B[i][j][k] for i in range(n_b))
                        if abs(col_sum - 1.0) > 1e-6:  # same tolerance as A columns
                            errors.append(
                                f"B action {k} column {j} does not sum to 1 (sum={col_sum:.6f})"
                            )

        # C: length n_obs
        if len(C) != n_o:
            errors.append(f"C length {len(C)} != n_obs {n_o}")

        # D: length n_states, sums to 1 (same 1e-6 tolerance as A/B
        # simplex-normalization check above).
        if len(D) != n_s:
            errors.append(f"D length {len(D)} != n_states {n_s}")
        elif D and abs(sum(D) - 1.0) > 1e-6:  # same tolerance as A/B columns
            errors.append(f"D does not sum to 1 (sum={sum(D):.6f})")

        return (len(errors) == 0, errors)

    def validate(self) -> list[str]:
        """Validate dimensional consistency across A/B/C/D matrices.

        Checks that all four matrices have the expected shapes and that
        stochastic constraints are satisfied (column sums for A, column
        sums for B slices, sum for D).

        Returns:
            A list of validation issues. Empty list means all matrices
            are dimensionally consistent and satisfy stochastic constraints.
        """
        _, errors = self.validate_shapes()
        return errors

    def to_plain_dict(self) -> dict[str, Any]:
        """Export matrices as plain Python lists for JSON serialization.

        Unlike :meth:`to_dict`, this method guarantees all values are plain
        Python lists/floats with no numpy arrays or other special types.

        Returns:
            A dict with keys "A", "B", "C", "D" containing the matrices
            as plain Python lists.  Additional keys include "n_states",
            "n_obs", "n_actions" for shape information, and metadata like
            "b_truncated" if the B tensor was truncated.
        """
        A = self.compute_A()
        B = self.compute_B()
        C = self.compute_C()
        D = self.compute_D()

        # A, B, C, D are always plain Python lists — explicit ``list(...)``
        # copies guarantee independence from the cached compute_* outputs
        # so callers may mutate the returned dict safely.
        result: dict[str, Any] = {
            "A": [list(row) for row in A],
            "B": [[list(cell) for cell in row] for row in B],
            "C": list(C),
            "D": list(D),
            "n_states": self.n_states,
            "n_obs": self.n_obs,
            "n_actions": self.n_actions,
        }

        # Include truncation metadata if B was truncated.
        if self._b_truncated:
            result["b_truncated"] = True
            result["b_n_states_full"] = self._b_n_states_full
            result["b_n_states_kept"] = self._b_n_states_kept
            result["b_kept_state_indices"] = list(self._b_kept_state_indices)

        return result

n_actions property

Number of action dimensions.

Zero is a valid dimension for a degenerate empty state space. The matrix exporter preserves that fact instead of inventing an action dimension, which keeps the declared dimensions consistent with the compiled state-space model.

n_obs property

Number of observation dimensions.

n_states property

Number of hidden-state dimensions.

__init__(graph, mappings, state_space)

Initialize the matrix deriver.

Parameters:

Name Type Description Default
graph ProgramGraph

The program graph with nodes and edges.

required
mappings Any

Semantic mappings; accepted as either a dict keyed by mapping ID or a list of SemanticMapping.

required
state_space StateSpaceModel

The compiled state space model.

required
Source code in py/cogant/gnn/matrices.py
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
def __init__(
    self,
    graph: ProgramGraph,
    mappings: Any,
    state_space: StateSpaceModel,
) -> None:
    """Initialize the matrix deriver.

    Args:
        graph: The program graph with nodes and edges.
        mappings: Semantic mappings; accepted as either a ``dict``
            keyed by mapping ID or a list of ``SemanticMapping``.
        state_space: The compiled state space model.
    """
    self.graph = graph
    self.state_space = state_space

    # Normalize mappings to a list for convenient filtering while
    # preserving a stable ordering.
    if isinstance(mappings, dict):
        mapping_list: list[SemanticMapping] = list(mappings.values())
    elif isinstance(mappings, list):
        mapping_list = list(mappings)
    elif mappings is None:
        mapping_list = []
    else:
        mapping_list = list(mappings)
    self._mappings: list[SemanticMapping] = mapping_list

    # Enumerate spaces.
    self._hidden_states: list[SemanticMapping] = [
        m for m in self._mappings if m.kind == MappingKind.HIDDEN_STATE
    ]
    self._observations: list[SemanticMapping] = [
        m for m in self._mappings if m.kind == MappingKind.OBSERVATION
    ]
    self._actions: list[SemanticMapping] = [
        m for m in self._mappings if m.kind in (MappingKind.ACTION, MappingKind.POLICY)
    ]
    self._constraints: list[SemanticMapping] = [
        m for m in self._mappings if m.kind in (MappingKind.CONSTRAINT, MappingKind.PREFERENCE)
    ]

    # The compiled state-space variables are the authoritative hidden-state
    # axis. A single HIDDEN_STATE mapping can cover multiple graph-fragment
    # nodes, and the state-space compiler expands those into distinct
    # variables. Using the compiled variables here keeps A/B/D dimensions
    # aligned with ``state_space.json`` and avoids losing matrix-bearing
    # states when a mapping spans more than one node.
    self._state_space_vars = list(self.state_space.variables.values())
    self._use_state_space_vars = bool(self._state_space_vars)

    # Populated by compute_B() when the full B tensor would exceed
    # _MAX_B_ENTRIES.  Callers can inspect these to understand the
    # approximation that was applied.
    self._b_truncated: bool = False
    self._b_n_states_full: int = 0  # untruncated n_states
    self._b_n_states_kept: int = 0  # n_states after truncation
    # Indices (into the full A-column / D state axis) of the states
    # kept on the B axis, ascending. B index ``j`` is full state
    # ``self._b_kept_state_indices[j]``.
    self._b_kept_state_indices: list[int] = []

compute_A()

Compute the likelihood matrix A[n_obs x n_states].

A[i][j] = P(observation_i | hidden_state_j).

Derivation

For each observation i, find the set of hidden-state nodes that it directly reads (READS/OBSERVES edges from the observation's node). Those direct reads receive a high probability mass; all other states share the residual mass uniformly. Columns are then normalized so each hidden state defines a distribution over observations.

Source code in py/cogant/gnn/matrices.py
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
403
404
405
406
def compute_A(self) -> list[list[float]]:
    """Compute the likelihood matrix ``A[n_obs x n_states]``.

    ``A[i][j] = P(observation_i | hidden_state_j)``.

    Derivation:
        For each observation ``i``, find the set of hidden-state
        nodes that it directly reads (READS/OBSERVES edges from the
        observation's node). Those direct reads receive a high
        probability mass; all other states share the residual mass
        uniformly. Columns are then normalized so each hidden state
        defines a distribution over observations.
    """
    n_obs = self.n_obs
    n_states = self.n_states
    if n_obs == 0 or n_states == 0:
        return []

    state_ids = self._state_node_ids()
    obs_ids = self._obs_node_ids()
    state_index = {nid: j for j, nid in enumerate(state_ids) if nid}

    direct_kinds = {EdgeKind.READS, EdgeKind.OBSERVES, EdgeKind.DEPENDS_ON}

    A: list[list[float]] = [[0.0] * n_states for _ in range(n_obs)]
    n_uniform = 0  # count of rows with no direct evidence

    for i in range(n_obs):
        obs_node_id = obs_ids[i] if i < len(obs_ids) else ""
        direct: list[int] = []
        if obs_node_id:
            for edge in self._edges_from(obs_node_id):
                if edge.kind in direct_kinds and edge.target_id in state_index:
                    j = state_index[edge.target_id]
                    if j not in direct:
                        direct.append(j)
            # Also look at incoming edges that go TO this observation
            # node (e.g., state->obs "OBSERVES" edges in the reverse
            # direction).
            for edge in self._edges_to(obs_node_id):
                if edge.kind in direct_kinds and edge.source_id in state_index:
                    j = state_index[edge.source_id]
                    if j not in direct:
                        direct.append(j)

        n_direct = len(direct)
        n_indirect = n_states - n_direct
        if n_direct == 0:
            # No evidence linking this observation to any state: assign
            # equal pre-normalization mass across states. After the
            # column normalization below this row contributes uniformly
            # to every state-column (a maximally vague observation).
            A[i] = [1.0 / n_states] * n_states
            n_uniform += 1
            continue
        direct_share = _DEFAULT_DIRECT_MASS / n_direct
        indirect_share = _DEFAULT_INDIRECT_MASS / n_indirect if n_indirect > 0 else 0.0
        for j in range(n_states):
            A[i][j] = direct_share if j in direct else indirect_share

    # Column-stochastic normalization (AII/pymdp convention). ``A`` holds
    # ``A[o][s] = P(o | s)``, so for every fixed hidden state ``s`` the
    # distribution over observation outcomes must sum to 1: each *column*
    # sums to 1, not each row. (Row-normalizing would make ``sum_s
    # P(o|s) = 1``, which is not a valid likelihood and breaks the
    # predicted-observation update ``pred_obs[o] = sum_s A[o][s]·q(s)``
    # in ``simulate/free_energy.py``.)
    for j in range(n_states):
        col_total = sum(A[i][j] for i in range(n_obs))
        if col_total <= _EPSILON:
            # A state observed by nothing: uniform over observations.
            for i in range(n_obs):
                A[i][j] = 1.0 / n_obs
        else:
            for i in range(n_obs):
                A[i][j] = A[i][j] / col_total

    # Log A matrix computation details
    n_informed = n_obs - n_uniform
    logger.info(
        "A matrix computed: shape [%d x %d], %d/%d observations with direct evidence, "
        "%d observations uniform before column normalization (no READS/OBSERVES edges)",
        n_obs,
        n_states,
        n_informed,
        n_obs,
        n_uniform,
    )

    return A

compute_B()

Compute the transition tensor B[n_states x n_states x n_actions].

B[next][cur][action] = P(next_state | current_state, action).

Derivation

For each action k, find the hidden-state nodes that it WRITES/MUTATES. Those destinations become high-probability successors of every current state; otherwise the transition defaults to an identity (stay) move. Every column (cur, action) is normalized so that it sums to 1.0.

Truncation

When n_states² × n_actions would exceed _MAX_B_ENTRIES (default 5 M), the state space is reduced to the top-K highest-degree nodes so that the tensor fits in memory and serializes in reasonable time. The kept states stay in their original A/D order, so B index j is full state self._b_kept_state_indices[j]. The truncation is recorded in self._b_truncated, self._b_n_states_full, self._b_n_states_kept and self._b_kept_state_indices, and surfaced in :meth:to_dict under the "truncation" key. This approximation is a principal submatrix of the full B restricted to the most structurally important state nodes.

Source code in py/cogant/gnn/matrices.py
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
471
472
473
474
475
476
477
478
479
480
481
482
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
def compute_B(self) -> list[list[list[float]]]:
    """Compute the transition tensor ``B[n_states x n_states x n_actions]``.

    ``B[next][cur][action] = P(next_state | current_state, action)``.

    Derivation:
        For each action ``k``, find the hidden-state nodes that it
        WRITES/MUTATES. Those destinations become high-probability
        successors of every current state; otherwise the transition
        defaults to an identity (stay) move. Every column
        ``(cur, action)`` is normalized so that it sums to 1.0.

    Truncation:
        When ``n_states² × n_actions`` would exceed ``_MAX_B_ENTRIES``
        (default 5 M), the state space is reduced to the top-K
        highest-degree nodes so that the tensor fits in memory and
        serializes in reasonable time. The kept states stay in their
        original A/D order, so B index ``j`` is full state
        ``self._b_kept_state_indices[j]``. The truncation is recorded
        in ``self._b_truncated``, ``self._b_n_states_full``,
        ``self._b_n_states_kept`` and ``self._b_kept_state_indices``,
        and surfaced in :meth:`to_dict` under the ``"truncation"`` key.
        This approximation is a principal submatrix of the full B
        restricted to the most structurally important state nodes.
    """
    n_states = self.n_states
    n_actions = self.n_actions
    if n_states == 0:
        return []

    state_ids = self._state_node_ids()
    action_ids = self._action_node_ids()

    # ---- Truncation guard ----------------------------------------
    # If the full tensor would exceed _MAX_B_ENTRIES, keep only the
    # top-K state nodes ranked by in+out degree.  This turns an O(S²A)
    # explosion into O(_MAX_B_ENTRIES) work, preserving the most
    # structurally important nodes.
    full_b_entries = n_states * n_states * n_actions
    self._b_n_states_full = n_states
    self._b_truncated = False
    self._b_kept_state_indices = list(range(n_states))

    if full_b_entries > _MAX_B_ENTRIES and n_actions > 0:
        # Solve for max_k: k² × n_actions ≤ _MAX_B_ENTRIES
        import math

        max_k = max(1, int(math.isqrt(_MAX_B_ENTRIES // n_actions)))
        self._b_truncated = True
        self._b_n_states_kept = max_k
        logger.warning(
            "B tensor would be %d entries (%d states × %d states × %d actions) "
            "which exceeds _MAX_B_ENTRIES=%d. Truncating to top-%d state nodes "
            "by graph degree. Set _MAX_B_ENTRIES higher to disable truncation.",
            full_b_entries,
            n_states,
            n_states,
            n_actions,
            _MAX_B_ENTRIES,
            max_k,
        )
        logger.info(
            "B tensor truncated: %d → %d state nodes (%.1f%% reduction, %d → %d entries)",
            n_states,
            max_k,
            (1 - max_k / n_states) * 100 if n_states > 0 else 0.0,
            full_b_entries,
            max_k * max_k * n_actions,
        )
        kept = self._top_k_state_indices(state_ids, max_k)
        self._b_kept_state_indices = kept
        self._b_n_states_kept = len(kept)
        state_ids = [state_ids[j] for j in kept]
        n_states = len(state_ids)
    else:
        self._b_n_states_kept = n_states
    # ---------------------------------------------------------------

    state_index = {nid: j for j, nid in enumerate(state_ids) if nid}

    write_kinds = {EdgeKind.WRITES, EdgeKind.MUTATES}

    # Initialize to identity per action so that non-writing actions
    # leave the state unchanged (a valid default transition).
    B: list[list[list[float]]] = [
        [[0.0] * n_actions for _ in range(n_states)] for _ in range(n_states)
    ]
    for cur in range(n_states):
        for k in range(n_actions):
            B[cur][cur][k] = 1.0

    n_identity_actions = 0  # actions with no WRITES/MUTATES edges
    n_writing_actions = 0

    for k in range(n_actions):
        act_node_id = action_ids[k] if k < len(action_ids) else ""
        written: list[int] = []
        if act_node_id:
            for edge in self._edges_from(act_node_id):
                if edge.kind in write_kinds and edge.target_id in state_index:
                    j = state_index[edge.target_id]
                    if j not in written:
                        written.append(j)

        if not written:
            # Already identity — nothing to update for this action.
            n_identity_actions += 1
            continue
        n_writing_actions += 1

        # For every current state ``cur``, redistribute mass so the
        # written destinations receive _DEFAULT_DIRECT_MASS and the
        # identity "stay" move receives _DEFAULT_INDIRECT_MASS.
        for cur in range(n_states):
            column = [0.0] * n_states
            n_w = len(written)
            direct_share = _DEFAULT_DIRECT_MASS / n_w
            for j in written:
                column[j] = direct_share
            # Residual mass on the identity move (or uniform if the
            # current state is itself a written destination — in that
            # case ``column[cur]`` already received its share above and
            # we normalize as-is below).
            if cur not in written:
                column[cur] += _DEFAULT_INDIRECT_MASS
            column = _normalize_row(column)
            for nxt in range(n_states):
                B[nxt][cur][k] = column[nxt]

    # Log B tensor computation details
    logger.info(
        "B tensor computed: shape [%d x %d x %d], %d/%d writing actions "
        "(%d identity/stay), direct_mass=%.2f",
        n_states,
        n_states,
        n_actions,
        n_writing_actions,
        n_actions,
        n_identity_actions,
        _DEFAULT_DIRECT_MASS,
    )

    return B

compute_C()

Compute the log-preference vector C[n_obs].

Derivation

Each observation receives a log-preference derived from the confidence scores of CONSTRAINT/PREFERENCE mappings whose graph fragments intersect with the observation's node set. Preferences with CONSTRAINT kind contribute a positive preference (the constraint describes a desired observation); absent any matching constraint, C defaults to 0.0 (neutral).

Source code in py/cogant/gnn/matrices.py
558
559
560
561
562
563
564
565
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
def compute_C(self) -> list[float]:
    """Compute the log-preference vector ``C[n_obs]``.

    Derivation:
        Each observation receives a log-preference derived from the
        confidence scores of CONSTRAINT/PREFERENCE mappings whose
        graph fragments intersect with the observation's node set.
        Preferences with CONSTRAINT kind contribute a positive
        preference (the constraint describes a desired observation);
        absent any matching constraint, C defaults to 0.0 (neutral).
    """
    n_obs = self.n_obs
    if n_obs == 0:
        return []

    obs_node_ids = self._obs_node_ids()
    C: list[float] = [0.0] * n_obs

    n_preferred = 0  # observations with nonzero preference
    n_aversive = 0  # observations with negative preference
    for i in range(n_obs):
        obs_nid = obs_node_ids[i] if i < len(obs_node_ids) else ""
        if not obs_nid:
            continue
        # Sum signed log-preference contributions from constraints
        # that touch the observation's node (or any graph neighbor).
        total = 0.0
        for mapping in self._constraints:
            if obs_nid in mapping.graph_fragment_node_ids:
                # Constraint: higher confidence → stronger preference.
                sign = 1.0
                if mapping.kind == MappingKind.CONSTRAINT:
                    # Constraints are "must hold" → strongly preferred.
                    sign = 1.0
                elif mapping.kind == MappingKind.PREFERENCE:
                    # Preferences can be soft and may be aversive if
                    # the mapping semantic label starts with "avoid"
                    # or "reject".
                    label = (mapping.semantic_label or "").lower()
                    if label.startswith(("avoid", "reject", "!")):
                        sign = -1.0
                total += sign * float(mapping.confidence_score or 0.0)
        C[i] = total
        if total > 0:
            n_preferred += 1
        elif total < 0:
            n_aversive += 1

    # Log C vector computation details
    n_neutral = n_obs - n_preferred - n_aversive
    logger.info(
        "C vector computed: length %d, %d preferred, %d aversive, %d neutral",
        n_obs,
        n_preferred,
        n_aversive,
        n_neutral,
    )

    return C

compute_D()

Compute the initial prior D[n_states].

Derivation

If any hidden state has an explicit default_value or an attached CONFIGURATION node with a value, concentrate mass on that state. Otherwise return a uniform prior. The vector always sums to 1.0.

Source code in py/cogant/gnn/matrices.py
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
def compute_D(self) -> list[float]:
    """Compute the initial prior ``D[n_states]``.

    Derivation:
        If any hidden state has an explicit ``default_value`` or an
        attached CONFIGURATION node with a value, concentrate mass
        on that state. Otherwise return a uniform prior. The vector
        always sums to 1.0.
    """
    n_states = self.n_states
    if n_states == 0:
        return []

    # Base: uniform prior.
    D: list[float] = [1.0 / n_states] * n_states

    if self._use_state_space_vars:
        # Bias toward any variable whose StateVariable has a default
        # value or a CONFIGURATION neighbor in the graph.
        biased = [0.0] * n_states
        any_bias = False
        for j, var in enumerate(self._state_space_vars):
            bias = 1.0
            # Explicit domain/default bias.
            meta_default = getattr(var, "domain", None)
            if meta_default:
                any_bias = True
                bias += 1.0
            # CONFIGURATION neighbor in the graph → stronger prior.
            node_id = getattr(var, "node_id", "")
            if node_id and node_id in self.graph.nodes:
                for edge in self._edges_to(node_id) + self._edges_from(node_id):
                    other_id = edge.source_id if edge.target_id == node_id else edge.target_id
                    other = self.graph.nodes.get(other_id)
                    if other and other.kind == NodeKind.CONFIGURATION:
                        any_bias = True
                        bias += 2.0
                        break
            biased[j] = bias
        if any_bias:
            D = _normalize_vector(biased)
        else:
            D = _normalize_vector(D)
    else:
        # Hidden-state semantic mappings: use mapping confidence as
        # a soft prior weight so that high-confidence hidden states
        # receive more prior mass.
        weights = [max(float(m.confidence_score or 0.0), _EPSILON) for m in self._hidden_states]
        D = _normalize_vector(weights)

    # Log D vector computation details
    peak_idx = max(range(len(D)), key=lambda j: D[j]) if D else -1
    peak_val = D[peak_idx] if peak_idx >= 0 else 0.0
    logger.info(
        "D vector computed: length %d, peak at index %d (%.4f), source=%s",
        len(D),
        peak_idx,
        peak_val,
        "state_space_vars" if self._use_state_space_vars else "hidden_state_mappings",
    )

    return D

to_dict()

Return a JSON-serializable dict of all four matrices.

Returns:

Type Description
dict[str, Any]

``{"A": ..., "B": ..., "C": ..., "D": ..., "shapes": ...,

dict[str, Any]

"dimensions": ..., "truncation": ...}``

dict[str, Any]

The "truncation" key is None when no truncation

dict[str, Any]

occurred; otherwise it is a dict with:

dict[str, Any]
  • "applied": True
dict[str, Any]
  • "n_states_full": original (un-truncated) n_states
dict[str, Any]
  • "n_states_kept": n_states after truncation
dict[str, Any]
  • "max_b_entries": the _MAX_B_ENTRIES threshold
dict[str, Any]
  • "kept_state_indices": ascending indices into the full A-column / D state axis; B index j is full state kept_state_indices[j]
dict[str, Any]
  • "kept_state_ids": the matching state ids
dict[str, Any]
  • "reason": human-readable explanation
dict[str, Any]

"shapes" reports the emitted arrays, so a truncated B is

dict[str, Any]

declared as [n_states_kept, n_states_kept, n_actions]

dict[str, Any]

while "dimensions" keeps the full n_states.

Source code in py/cogant/gnn/matrices.py
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
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-serializable dict of all four matrices.

    Returns:
        ``{"A": ..., "B": ..., "C": ..., "D": ..., "shapes": ...,
        "dimensions": ..., "truncation": ...}``

        The ``"truncation"`` key is ``None`` when no truncation
        occurred; otherwise it is a dict with:

        * ``"applied"``: ``True``
        * ``"n_states_full"``: original (un-truncated) n_states
        * ``"n_states_kept"``: n_states after truncation
        * ``"max_b_entries"``: the ``_MAX_B_ENTRIES`` threshold
        * ``"kept_state_indices"``: ascending indices into the full
            A-column / D state axis; B index ``j`` is full state
            ``kept_state_indices[j]``
        * ``"kept_state_ids"``: the matching state ids
        * ``"reason"``: human-readable explanation

        ``"shapes"`` reports the emitted arrays, so a truncated B is
        declared as ``[n_states_kept, n_states_kept, n_actions]``
        while ``"dimensions"`` keeps the full ``n_states``.
    """
    A = self.compute_A()
    B = self.compute_B()
    C = self.compute_C()
    D = self.compute_D()

    truncation: dict[str, Any] | None = None
    if self._b_truncated:
        axis_ids = self._state_axis_ids()
        kept = list(self._b_kept_state_indices)
        truncation = {
            "applied": True,
            "n_states_full": self._b_n_states_full,
            "n_states_kept": self._b_n_states_kept,
            "max_b_entries": _MAX_B_ENTRIES,
            "kept_state_indices": kept,
            "kept_state_ids": [axis_ids[j] if j < len(axis_ids) else "" for j in kept],
            "reason": (
                f"B tensor ({self._b_n_states_full}² × {self.n_actions} = "
                f"{self._b_n_states_full**2 * self.n_actions:,} entries) "
                f"exceeded _MAX_B_ENTRIES={_MAX_B_ENTRIES:,}; "
                f"kept top-{self._b_n_states_kept} state nodes by degree."
            ),
        }

    # Declared shapes are the logical array shapes. An empty A (zero
    # observations or zero hidden states) or an empty B (zero hidden
    # states) is still an ``[n_obs, n_states]`` /
    # ``[n_states, n_states, n_actions]`` array with a zero axis, so
    # fall back to the dimensions instead of collapsing to ``[0, 0]``.
    return {
        "A": A,
        "B": B,
        "C": C,
        "D": D,
        "shapes": {
            "A": [len(A), len(A[0])] if A else [self.n_obs, self.n_states],
            "B": [len(B), len(B[0]), len(B[0][0]) if B[0] else 0]
            if B
            else [0, 0, self.n_actions],
            "C": [len(C)],
            "D": [len(D)],
        },
        "dimensions": {
            "n_states": self.n_states,
            "n_obs": self.n_obs,
            "n_actions": self.n_actions,
        },
        "truncation": truncation,
    }

to_gnn_markdown_block()

Format the matrices as a GNN-compatible markdown block.

Emits AII-style sections with rows=, cols=, depth= bracket headers. This block is additive to the existing StateSpaceBlock / InitialParameterization sections; it is meant to be embedded as a COGANT extension.

Source code in py/cogant/gnn/matrices.py
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
def to_gnn_markdown_block(self) -> str:
    """Format the matrices as a GNN-compatible markdown block.

    Emits AII-style sections with ``rows=``, ``cols=``, ``depth=``
    bracket headers. This block is additive to the existing
    ``StateSpaceBlock`` / ``InitialParameterization`` sections; it is
    meant to be embedded as a COGANT extension.
    """
    A = self.compute_A()
    B = self.compute_B()
    C = self.compute_C()
    D = self.compute_D()

    lines: list[str] = []

    n_rows = len(A)
    n_cols = len(A[0]) if A else self.n_states
    lines.append(f"A[[rows={n_rows}][cols={n_cols}]]")
    for row in A:
        lines.append("  " + " ".join(repr(float(v)) for v in row))
    lines.append("")

    # --- B tensor ---
    if B:
        n_rows = len(B)
        n_cols = len(B[0]) if B else 0
        n_depth = len(B[0][0]) if (B and B[0]) else 0
        lines.append(f"B[[rows={n_rows}][cols={n_cols}][depth={n_depth}]]")
        for k in range(n_depth):
            lines.append(f"  # action={k}")
            for r in range(n_rows):
                row_vals = [B[r][c][k] for c in range(n_cols)]
                lines.append("  " + " ".join(repr(float(v)) for v in row_vals))
        lines.append("")
    else:
        lines.extend(("B[[rows=0][cols=0][depth=0]]", ""))

    # --- C vector ---
    lines.append(f"C[[rows={len(C)}]]")
    for v in C:
        lines.append(f"  {float(v)!r}")
    lines.append("")

    # --- D vector ---
    lines.append(f"D[[rows={len(D)}]]")
    for v in D:
        lines.append(f"  {float(v)!r}")
    lines.append("")

    return "\n".join(lines).rstrip()

to_plain_dict()

Export matrices as plain Python lists for JSON serialization.

Unlike :meth:to_dict, this method guarantees all values are plain Python lists/floats with no numpy arrays or other special types.

Returns:

Type Description
dict[str, Any]

A dict with keys "A", "B", "C", "D" containing the matrices

dict[str, Any]

as plain Python lists. Additional keys include "n_states",

dict[str, Any]

"n_obs", "n_actions" for shape information, and metadata like

dict[str, Any]

"b_truncated" if the B tensor was truncated.

Source code in py/cogant/gnn/matrices.py
902
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
def to_plain_dict(self) -> dict[str, Any]:
    """Export matrices as plain Python lists for JSON serialization.

    Unlike :meth:`to_dict`, this method guarantees all values are plain
    Python lists/floats with no numpy arrays or other special types.

    Returns:
        A dict with keys "A", "B", "C", "D" containing the matrices
        as plain Python lists.  Additional keys include "n_states",
        "n_obs", "n_actions" for shape information, and metadata like
        "b_truncated" if the B tensor was truncated.
    """
    A = self.compute_A()
    B = self.compute_B()
    C = self.compute_C()
    D = self.compute_D()

    # A, B, C, D are always plain Python lists — explicit ``list(...)``
    # copies guarantee independence from the cached compute_* outputs
    # so callers may mutate the returned dict safely.
    result: dict[str, Any] = {
        "A": [list(row) for row in A],
        "B": [[list(cell) for cell in row] for row in B],
        "C": list(C),
        "D": list(D),
        "n_states": self.n_states,
        "n_obs": self.n_obs,
        "n_actions": self.n_actions,
    }

    # Include truncation metadata if B was truncated.
    if self._b_truncated:
        result["b_truncated"] = True
        result["b_n_states_full"] = self._b_n_states_full
        result["b_n_states_kept"] = self._b_n_states_kept
        result["b_kept_state_indices"] = list(self._b_kept_state_indices)

    return result

validate()

Validate dimensional consistency across A/B/C/D matrices.

Checks that all four matrices have the expected shapes and that stochastic constraints are satisfied (column sums for A, column sums for B slices, sum for D).

Returns:

Type Description
list[str]

A list of validation issues. Empty list means all matrices

list[str]

are dimensionally consistent and satisfy stochastic constraints.

Source code in py/cogant/gnn/matrices.py
888
889
890
891
892
893
894
895
896
897
898
899
900
def validate(self) -> list[str]:
    """Validate dimensional consistency across A/B/C/D matrices.

    Checks that all four matrices have the expected shapes and that
    stochastic constraints are satisfied (column sums for A, column
    sums for B slices, sum for D).

    Returns:
        A list of validation issues. Empty list means all matrices
        are dimensionally consistent and satisfy stochastic constraints.
    """
    _, errors = self.validate_shapes()
    return errors

validate_shapes()

Validate that all four matrices have the expected shapes.

Returns:

Type Description
bool

(ok, errors) where ok is True if no shape errors

list[str]

were found.

Source code in py/cogant/gnn/matrices.py
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
def validate_shapes(self) -> tuple[bool, list[str]]:
    """Validate that all four matrices have the expected shapes.

    Returns:
        ``(ok, errors)`` where ``ok`` is True if no shape errors
        were found.
    """
    errors: list[str] = []
    A = self.compute_A()
    B = self.compute_B()
    C = self.compute_C()
    D = self.compute_D()

    n_s = self.n_states
    n_o = self.n_obs
    n_a = self.n_actions
    # A truncated B covers only the kept states (see compute_B).
    n_b = self._b_n_states_kept if self._b_truncated else n_s

    # A: n_obs x n_states, columns sum to 1.
    # Column-sum tolerance 1e-6 — principled default, matches the
    # PyMDP validator tolerance and is ~7 orders of magnitude
    # above float64 round-off noise (~1e-16) for a typical
    # n_states <= 50. Strict enough to catch normalization bugs
    # but loose enough to tolerate accumulated rounding across
    # multiple ``_normalize_row`` passes.
    if n_o > 0 and n_s > 0:
        if len(A) != n_o:
            errors.append(f"A row count {len(A)} != n_obs {n_o}")
        elif A and any(len(row) != n_s for row in A):
            errors.append(f"A has inconsistent column count (expected {n_s})")
        else:
            # A is column-stochastic: P(o|s) sums to 1 over observation
            # outcomes for each fixed hidden state s (a column).
            for j in range(n_s):
                col_sum = sum(A[i][j] for i in range(len(A)))
                if abs(col_sum - 1.0) > 1e-6:  # col-norm tolerance
                    errors.append(f"A column {j} does not sum to 1 (sum={col_sum:.6f})")

    # B: n_states x n_states x n_actions (n_states_kept when truncated)
    if n_s > 0:
        if len(B) != n_b:
            errors.append(f"B first dim {len(B)} != n_states {n_b}")
        elif any(len(row) != n_b for row in B):
            errors.append(f"B second dim != n_states {n_b}")
        elif any(len(cell) != n_a for row in B for cell in row):
            errors.append(f"B third dim != n_actions {n_a}")
        else:
            if any(
                B[i][j][k] < -1e-9 for i in range(n_b) for j in range(n_b) for k in range(n_a)
            ):
                errors.append("B contains negative probabilities")
            for k in range(n_a):
                for j in range(n_b):
                    col_sum = sum(B[i][j][k] for i in range(n_b))
                    if abs(col_sum - 1.0) > 1e-6:  # same tolerance as A columns
                        errors.append(
                            f"B action {k} column {j} does not sum to 1 (sum={col_sum:.6f})"
                        )

    # C: length n_obs
    if len(C) != n_o:
        errors.append(f"C length {len(C)} != n_obs {n_o}")

    # D: length n_states, sums to 1 (same 1e-6 tolerance as A/B
    # simplex-normalization check above).
    if len(D) != n_s:
        errors.append(f"D length {len(D)} != n_states {n_s}")
    elif D and abs(sum(D) - 1.0) > 1e-6:  # same tolerance as A/B columns
        errors.append(f"D does not sum to 1 (sum={sum(D):.6f})")

    return (len(errors) == 0, errors)

GNNModelRunner

Own a validated GNN snapshot and its most recent model rollout.

Observations are modes of A times the incoming belief, not measurements of source program execution. Actions minimize one-step risk-plus-ambiguity expected free energy.

Source code in py/cogant/gnn/runner.py
 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
 78
 79
 80
 81
 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
class GNNModelRunner:
    """Own a validated GNN snapshot and its most recent model rollout.

    Observations are modes of A times the incoming belief, not measurements
    of source program execution. Actions minimize one-step risk-plus-ambiguity
    expected free energy.
    """

    def __init__(self) -> None:
        self.package_dir = Path(".")
        self.manifest: dict[str, JsonValue] = {}
        self.traces: list[ExecutionTrace] = []
        self.beliefs_history: list[dict[str, float]] = []
        self.free_energy_trajectory: list[float] = []
        self.action_counts: dict[str, int] = {}
        self.last_error: str | None = None
        self._source: str | None = None
        self._result: RunnerResult | None = None
        self._work_per_step = 0

    def _clear_run(self) -> None:
        self.traces = []
        self.beliefs_history = []
        self.free_energy_trajectory = []
        self.action_counts = {}
        self.last_error = None
        self._result = None

    def load_package(self, package_dir: str) -> dict[str, JsonValue]:
        """Load complete model.gnn.md matrices; invalidate stale state on failure."""
        self._source = None
        self.manifest = {}
        self._clear_run()
        self.package_dir = Path(package_dir)
        manifest = TypeAdapter(dict[str, JsonValue]).validate_json(
            (self.package_dir / "manifest.json").read_bytes()
        )
        source = (self.package_dir / "model.gnn.md").read_bytes().decode("utf-8")
        model = parse_gnn(source)
        if model.degraded:
            raise ValueError("execution requires complete, non-degraded GNN matrices")
        functions = MatrixFunctions(model)
        categorical = CategoricalModel(functions.A, functions.B, functions.C, functions.D)
        states, observations = len(functions.D), len(functions.A)
        self._work_per_step = categorical.n_actions * (states * states + states * observations)
        self.manifest = manifest
        self._source = source
        return manifest

    def run(self, steps: int = 10) -> RunnerResult:
        """Execute 1 to 10,000 steps; invalid input fails without a success report."""
        self._clear_run()
        if self._source is None:
            raise RuntimeError("Package not loaded. Call load_package first.")
        try:
            inference = run_gnn_inference(self._source, InferenceOptions(steps=steps))
        except ValueError as error:
            self.last_error = str(error)
            raise
        self.traces = [
            ExecutionTrace.from_record(record, inference.labels) for record in inference.trace
        ]
        self.beliefs_history = [
            dict(zip(inference.labels.states, inference.matrices.D, strict=True))
        ]
        self.beliefs_history.extend(trace.beliefs.copy() for trace in self.traces)
        self.free_energy_trajectory = [trace.free_energy_after for trace in self.traces]
        for trace in self.traces:
            self.action_counts[trace.action] = self.action_counts.get(trace.action, 0) + 1
        self._result = execution_result(inference, self.traces, self.action_counts)
        return self._result

    def generate_execution_report(self, trace: RunnerResult | None = None) -> str:
        """Describe matrix inference without claiming program or control success."""
        result = trace if trace is not None else self._result
        if result is None:
            detail = (
                f"Execution rejected: {self.last_error}"
                if self.last_error
                else "No traces to report."
            )
            return f"# GNN Execution Report\n\n{detail}\n"
        return render_report(result)

    def run_with_profiling(
        self, num_steps: int = 10, num_trials: int = 1
    ) -> tuple[list[dict[str, JsonValue]], dict[str, float]]:
        """Measure complete inference runs; each trial restarts from exported D."""
        self._clear_run()
        InferenceOptions(steps=num_trials)
        InferenceOptions(steps=num_steps)
        if num_steps * num_trials > 10_000:
            raise ValueError("profiling exceeds the 10,000 total-step budget")
        if num_steps * num_trials * self._work_per_step > InferenceOptions().max_work_units:
            raise ValueError("profiling exceeds the combined matrix-work budget")
        traces: list[dict[str, JsonValue]] = []
        start = time.perf_counter()
        for trial in range(num_trials):
            result = self.run(num_steps)
            for item in result["traces"]:
                record = item.copy()
                record["trial"] = trial
                traces.append(record)
        return traces, {"total_ms": (time.perf_counter() - start) * 1000.0}

generate_execution_report(trace=None)

Describe matrix inference without claiming program or control success.

Source code in py/cogant/gnn/runner.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def generate_execution_report(self, trace: RunnerResult | None = None) -> str:
    """Describe matrix inference without claiming program or control success."""
    result = trace if trace is not None else self._result
    if result is None:
        detail = (
            f"Execution rejected: {self.last_error}"
            if self.last_error
            else "No traces to report."
        )
        return f"# GNN Execution Report\n\n{detail}\n"
    return render_report(result)

load_package(package_dir)

Load complete model.gnn.md matrices; invalidate stale state on failure.

Source code in py/cogant/gnn/runner.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def load_package(self, package_dir: str) -> dict[str, JsonValue]:
    """Load complete model.gnn.md matrices; invalidate stale state on failure."""
    self._source = None
    self.manifest = {}
    self._clear_run()
    self.package_dir = Path(package_dir)
    manifest = TypeAdapter(dict[str, JsonValue]).validate_json(
        (self.package_dir / "manifest.json").read_bytes()
    )
    source = (self.package_dir / "model.gnn.md").read_bytes().decode("utf-8")
    model = parse_gnn(source)
    if model.degraded:
        raise ValueError("execution requires complete, non-degraded GNN matrices")
    functions = MatrixFunctions(model)
    categorical = CategoricalModel(functions.A, functions.B, functions.C, functions.D)
    states, observations = len(functions.D), len(functions.A)
    self._work_per_step = categorical.n_actions * (states * states + states * observations)
    self.manifest = manifest
    self._source = source
    return manifest

run(steps=10)

Execute 1 to 10,000 steps; invalid input fails without a success report.

Source code in py/cogant/gnn/runner.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def run(self, steps: int = 10) -> RunnerResult:
    """Execute 1 to 10,000 steps; invalid input fails without a success report."""
    self._clear_run()
    if self._source is None:
        raise RuntimeError("Package not loaded. Call load_package first.")
    try:
        inference = run_gnn_inference(self._source, InferenceOptions(steps=steps))
    except ValueError as error:
        self.last_error = str(error)
        raise
    self.traces = [
        ExecutionTrace.from_record(record, inference.labels) for record in inference.trace
    ]
    self.beliefs_history = [
        dict(zip(inference.labels.states, inference.matrices.D, strict=True))
    ]
    self.beliefs_history.extend(trace.beliefs.copy() for trace in self.traces)
    self.free_energy_trajectory = [trace.free_energy_after for trace in self.traces]
    for trace in self.traces:
        self.action_counts[trace.action] = self.action_counts.get(trace.action, 0) + 1
    self._result = execution_result(inference, self.traces, self.action_counts)
    return self._result

run_with_profiling(num_steps=10, num_trials=1)

Measure complete inference runs; each trial restarts from exported D.

Source code in py/cogant/gnn/runner.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def run_with_profiling(
    self, num_steps: int = 10, num_trials: int = 1
) -> tuple[list[dict[str, JsonValue]], dict[str, float]]:
    """Measure complete inference runs; each trial restarts from exported D."""
    self._clear_run()
    InferenceOptions(steps=num_trials)
    InferenceOptions(steps=num_steps)
    if num_steps * num_trials > 10_000:
        raise ValueError("profiling exceeds the 10,000 total-step budget")
    if num_steps * num_trials * self._work_per_step > InferenceOptions().max_work_units:
        raise ValueError("profiling exceeds the combined matrix-work budget")
    traces: list[dict[str, JsonValue]] = []
    start = time.perf_counter()
    for trial in range(num_trials):
        result = self.run(num_steps)
        for item in result["traces"]:
            record = item.copy()
            record["trial"] = trial
            traces.append(record)
    return traces, {"total_ms": (time.perf_counter() - start) * 1000.0}

GNNPackageBuilder

Builds a complete, self-contained GNN model package.

Source code in py/cogant/gnn/package.py
  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
  78
  79
  80
  81
  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
 403
 404
 405
 406
 407
 408
 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
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 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
 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
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 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
 974
 975
 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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
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
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
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
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
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
class GNNPackageBuilder:
    """Builds a complete, self-contained GNN model package."""

    PACKAGE_VERSION = "1.0.0"
    REQUIRED_FILES = [
        "manifest.json",
        "model.gnn.md",
        "model.gnn.json",
        "state_space.json",
        "observations.json",
        "actions.json",
        "transitions.json",
        "preferences.json",
        "factors.json",
        "provenance.json",
        "ontology.json",
        "actions_policies.json",
        "connections.json",
        "preferences_constraints.json",
        "markov_blanket.json",
        "markov_network.json",
    ]

    def __init__(
        self,
        graph: ProgramGraph,
        state_space: StateSpaceModel,
        process_model: ProcessModel,
        mappings: dict[str, Any],
        config: dict[str, Any] | None = None,
    ):
        """
        Initialize the GNN package builder.

        Args:
            graph: Program graph.
            state_space: State space model.
            process_model: Process model.
            mappings: Semantic mappings.
            config: Optional configuration dictionary.
        """
        self.graph = graph
        self.state_space = state_space
        self.process_model = process_model
        self.mappings = mappings
        self.config = config or {}
        self.timestamp = datetime.now(UTC).isoformat()
        self.checksums: dict[str, str] = {}
        self.artifact_warnings: list[str] = []

    def build(self, output_dir: str) -> dict[str, Any]:
        """
        Build the complete GNN package.

        Args:
            output_dir: Directory to create the package in.

        Returns:
            Manifest dictionary with package metadata and checksums.
        """
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        logger.info(
            "Building GNN package in %s (%d nodes, %d edges, %d mappings)",
            output_path,
            len(self.graph.nodes),
            len(self.graph.edges),
            len(self.mappings) if isinstance(self.mappings, dict) else 0,
        )

        try:
            # 1. Generate core model files
            self._generate_markdown(output_path)
            self._generate_json_model(output_path)
            self._generate_state_space(output_path)
            self._generate_observations(output_path)
            self._generate_actions(output_path)
            self._generate_transitions(output_path)
            self._generate_preferences(output_path)
            self._generate_factors(output_path)
            self._generate_provenance(output_path)
            self._generate_ontology(output_path)

            # 2. Generate canonical section JSON files
            self._generate_actions_policies(output_path)
            self._generate_connections(output_path)
            self._generate_preferences_constraints(output_path)

            # 2b. Generate Markov blanket artifacts (Active Inference partition)
            self._generate_markov_blanket(output_path)

            # 2c. Dump the typed program graph as JSON so PNG rasterizers can
            # rebuild a NetworkX view without re-running the pipeline.
            self._generate_program_graph_json(output_path)

            # 2d. Dump the ProcessModel as JSON so ``render_all_pngs`` can
            # rasterize a Gantt timeline without re-running ProcessExtractor.
            self._generate_process_model_json(output_path)

            # 3. Generate diagrams
            self._generate_diagrams(output_path)

            # 4. Generate visualizations
            self._generate_visualizations(output_path)

            # 5. Create manifest
            manifest = self._create_manifest(output_path)

            # Summarize role distribution across semantic mappings
            role_dist: dict[str, int] = {}
            if isinstance(self.mappings, dict):
                for m in self.mappings.values():
                    kind = getattr(m, "kind", None)
                    label = kind.value if hasattr(kind, "value") else str(kind or "unknown")
                    role_dist[label] = role_dist.get(label, 0) + 1

            role_summary = (
                f" | roles={', '.join(f'{k}={v}' for k, v in sorted(role_dist.items()))}"
                if role_dist
                else ""
            )
            n_vars = (
                len(self.state_space.variables) if hasattr(self.state_space, "variables") else 0
            )
            n_obs = (
                len(self.state_space.observations)
                if hasattr(self.state_space, "observations")
                else 0
            )
            n_actions = len(self.state_space.actions) if hasattr(self.state_space, "actions") else 0

            logger.info(
                "GNN package built: %d files | state_space=%d vars, %d obs, %d actions%s",
                len(self.checksums),
                n_vars,
                n_obs,
                n_actions,
                role_summary,
            )
            return manifest

        except Exception as e:
            logger.error(f"Failed to build GNN package: {e}", exc_info=True)
            raise

    def _generate_markdown(self, output_path: Path) -> None:
        """Generate canonical GNN markdown."""
        try:
            formatter = GNNMarkdownFormatter(
                self.graph, self.state_space, self.process_model, self.mappings
            )
            markdown = formatter.format()
            markdown_path = output_path / "model.gnn.md"
            markdown_path.write_text(markdown, encoding="utf-8")
            self.checksums["model.gnn.md"] = self._checksum(markdown)
            logger.info(f"Generated {markdown_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate markdown: {e}", exc_info=True)
            raise

    def _generate_json_model(self, output_path: Path) -> None:
        """Generate machine-readable GNN JSON model."""
        try:
            exporter = GNNJSONExporter(
                self.graph, self.state_space, self.process_model, self.mappings
            )
            json_data = exporter.export()
            json_path = output_path / "model.gnn.json"
            json_path.write_text(json.dumps(json_data, indent=2, default=str), encoding="utf-8")
            self.checksums["model.gnn.json"] = self._checksum_dict(json_data)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate JSON model: {e}", exc_info=True)
            raise

    def _generate_state_space(self, output_path: Path) -> None:
        """Generate detailed state space JSON."""
        try:
            state_space_data = {
                "variables": self._extract_state_variables(),
                "observations": self._extract_observation_space(),
                "actions": self._extract_action_space(),
                "transitions": self._extract_transition_structure(),
                "metadata": {
                    "num_variables": len(self.state_space.variables)
                    if hasattr(self.state_space, "variables")
                    else 0,
                    "num_observations": len(self.state_space.observations)
                    if hasattr(self.state_space, "observations")
                    else 0,
                    "num_actions": len(self.state_space.actions)
                    if hasattr(self.state_space, "actions")
                    else 0,
                },
            }
            json_path = output_path / "state_space.json"
            json_path.write_text(json.dumps(state_space_data, indent=2), encoding="utf-8")
            self.checksums["state_space.json"] = self._checksum_dict(state_space_data)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate state space: {e}", exc_info=True)
            # Derived package sections are best-effort.  The manifest records
            # the files that were actually emitted, so callers can distinguish
            # an incomplete optional export from a valid complete package.
            return

    def _generate_observations(self, output_path: Path) -> None:
        """Generate observation modalities JSON."""
        try:
            observations = {
                "modalities": self._extract_observation_modalities(),
                "count": len(self.state_space.observations)
                if hasattr(self.state_space, "observations")
                else 0,
            }
            json_path = output_path / "observations.json"
            json_path.write_text(json.dumps(observations, indent=2), encoding="utf-8")
            self.checksums["observations.json"] = self._checksum_dict(observations)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate observations: {e}", exc_info=True)
            return

    def _generate_actions(self, output_path: Path) -> None:
        """Generate actions and policies JSON."""
        try:
            actions = {
                "actions": self._extract_actions(),
                "policies": self._extract_policies(),
                "count": len(self.state_space.actions)
                if hasattr(self.state_space, "actions")
                else 0,
            }
            json_path = output_path / "actions.json"
            json_path.write_text(json.dumps(actions, indent=2), encoding="utf-8")
            self.checksums["actions.json"] = self._checksum_dict(actions)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate actions: {e}", exc_info=True)
            return

    def _generate_transitions(self, output_path: Path) -> None:
        """Generate transition structure JSON."""
        try:
            transitions = {
                "structure": self._extract_transition_structure(),
                "deterministic": self._is_deterministic(),
                "markovian": self._is_markovian(),
            }
            json_path = output_path / "transitions.json"
            json_path.write_text(json.dumps(transitions, indent=2), encoding="utf-8")
            self.checksums["transitions.json"] = self._checksum_dict(transitions)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate transitions: {e}", exc_info=True)
            return

    def _generate_preferences(self, output_path: Path) -> None:
        """Generate preferences and constraints JSON."""
        try:
            preferences = {
                "preferences": self._extract_preferences(),
                "constraints": self._extract_constraints(),
                "objectives": self._extract_objectives(),
            }
            json_path = output_path / "preferences.json"
            json_path.write_text(json.dumps(preferences, indent=2), encoding="utf-8")
            self.checksums["preferences.json"] = self._checksum_dict(preferences)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate preferences: {e}", exc_info=True)
            return

    def _generate_factors(self, output_path: Path) -> None:
        """Generate factorization structure JSON."""
        try:
            factors = {
                "factorization": self._extract_factorization(),
                "factors": self._extract_factor_list(),
            }
            json_path = output_path / "factors.json"
            json_path.write_text(json.dumps(factors, indent=2), encoding="utf-8")
            self.checksums["factors.json"] = self._checksum_dict(factors)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate factors: {e}", exc_info=True)
            return

    def _generate_provenance(self, output_path: Path) -> None:
        """Generate full provenance chain JSON."""
        try:
            provenance = {
                "timestamp": self.timestamp,
                "graph_nodes": self._count_graph_nodes(),
                "graph_edges": self._count_graph_edges(),
                "state_space_elements": self._count_state_space_elements(),
                "semantic_mappings": len(self.mappings) if isinstance(self.mappings, dict) else 0,
                "sources": self._extract_source_evidence(),
            }
            json_path = output_path / "provenance.json"
            json_path.write_text(json.dumps(provenance, indent=2, default=str), encoding="utf-8")
            self.checksums["provenance.json"] = self._checksum_dict(provenance)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate provenance: {e}", exc_info=True)
            return

    def _generate_ontology(self, output_path: Path) -> None:
        """Generate ontology mappings JSON."""
        try:
            ontology = {
                "mappings": self._extract_ontology_mappings(),
                "classes": self._extract_classes(),
                "relationships": self._extract_relationships(),
            }
            json_path = output_path / "ontology.json"
            json_path.write_text(json.dumps(ontology, indent=2), encoding="utf-8")
            self.checksums["ontology.json"] = self._checksum_dict(ontology)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate ontology: {e}", exc_info=True)
            return

    def _generate_actions_policies(self, output_path: Path) -> None:
        """Generate canonical actions and policies JSON."""
        try:
            actions_policies = {
                "actions": self._extract_actions(),
                "policies": self._extract_policies(),
                "count": len(self.state_space.actions)
                if hasattr(self.state_space, "actions")
                else 0,
            }
            json_path = output_path / "actions_policies.json"
            json_path.write_text(json.dumps(actions_policies, indent=2), encoding="utf-8")
            self.checksums["actions_policies.json"] = self._checksum_dict(actions_policies)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate actions_policies: {e}", exc_info=True)
            return

    def _generate_connections(self, output_path: Path) -> None:
        """Generate connections (graph edges) JSON."""
        try:
            connections = {
                "edges": self._extract_relationships(),
                "count": len(self.graph.edges)
                if self.graph and hasattr(self.graph, "edges")
                else 0,
                "by_kind": self._count_edges_by_kind(),
            }
            json_path = output_path / "connections.json"
            json_path.write_text(json.dumps(connections, indent=2), encoding="utf-8")
            self.checksums["connections.json"] = self._checksum_dict(connections)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate connections: {e}", exc_info=True)
            return

    def _generate_preferences_constraints(self, output_path: Path) -> None:
        """Generate canonical preferences and constraints JSON."""
        try:
            preferences_constraints = {
                "preferences": self._extract_preferences(),
                "constraints": self._extract_constraints(),
                "objectives": self._extract_objectives(),
            }
            json_path = output_path / "preferences_constraints.json"
            json_path.write_text(json.dumps(preferences_constraints, indent=2), encoding="utf-8")
            self.checksums["preferences_constraints.json"] = self._checksum_dict(
                preferences_constraints
            )
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate preferences_constraints: {e}", exc_info=True)
            return

    def _generate_markov_blanket(self, output_path: Path) -> None:
        """Compute and serialize the Active-Inference Markov blanket.

        Produces two artifacts in the bundle:

        * ``markov_blanket.json`` — full per-node role assignment
          (internal μ / sensory s / active a / external η) with the
          strategy metadata and per-node rationale from
          :func:`cogant.markov.blanket.serialize_blanket`.
        * ``markov_network.json`` — collapsed four-role aggregate
          network with per-EdgeKind breakdowns from
          :func:`cogant.markov.network.build_blanket_network`.

        The seed strategy is driven by ``self.config``:
          - ``config["markov_blanket"]["strategy"]`` — default ``"auto"``.
          - ``config["markov_blanket"]["module_names"]`` — list of module
            names when strategy is ``"module"``.
          - ``config["markov_blanket"]["mapping_kinds"]`` — list of
            mapping kinds when strategy is ``"mapping_kind"``.

        If no semantic mappings are present, the extractor uses its explicit
        configured strategy against the real graph. Generation is
        best-effort: on failure the package still builds, but both files
        are written as explicit ``status: "unavailable"`` placeholders, the
        manifest records ``artifact_status.markov_blanket = "unavailable"``
        plus a warning, and :class:`GNNValidator` reports the placeholder
        as a validation warning so it is never mistaken for evidence.
        """
        mb_cfg = self.config.get("markov_blanket", {}) if isinstance(self.config, dict) else {}
        strategy = mb_cfg.get("strategy", "auto")
        module_names = mb_cfg.get("module_names")
        mapping_kinds = mb_cfg.get("mapping_kinds", ["hidden_state"])

        try:
            if self.graph is None:
                raise ValueError("no program graph available")

            extractor = MarkovBlanketExtractor(self.graph)

            kwargs = {"strategy": strategy}
            if strategy == "module" and module_names:
                kwargs["module_names"] = list(module_names)
            elif strategy == "mapping_kind":
                kwargs["mapping_kinds"] = list(mapping_kinds)
                kwargs["semantic_mappings"] = self.mappings or {}
            elif strategy == "explicit":
                kwargs["seeds"] = mb_cfg.get("seeds") or []

            blanket = extractor.extract(**kwargs)
            network = build_blanket_network(self.graph, blanket)

            blanket_payload = serialize_blanket(
                blanket,
                self.graph,
                include_rationale=mb_cfg.get("include_rationale", True),
                max_nodes_per_role=mb_cfg.get("max_nodes_per_role"),
            )
            network_payload = network.to_dict()

            blanket_path = output_path / "markov_blanket.json"
            network_path = output_path / "markov_network.json"
            blanket_path.write_text(json.dumps(blanket_payload, indent=2), encoding="utf-8")
            network_path.write_text(json.dumps(network_payload, indent=2), encoding="utf-8")
            self.checksums["markov_blanket.json"] = self._checksum_dict(blanket_payload)
            self.checksums["markov_network.json"] = self._checksum_dict(network_payload)

            # Also emit Mermaid diagrams:
            #   - markov_blanket.mmd: the collapsed four-role view.
            #   - markov_blanket_detail.mmd: member-level detail view
            #     with nodes grouped per role and styled by role class.
            diag_dir = output_path / "diagrams"
            diag_dir.mkdir(parents=True, exist_ok=True)
            mmd = network.to_mermaid()
            (diag_dir / "markov_blanket.mmd").write_text(mmd, encoding="utf-8")

            try:
                from cogant.viz.boundary import BoundaryMapper

                bm = BoundaryMapper()
                detail_mmd = bm.markov_blanket_detailed_mermaid(
                    self.graph, blanket=blanket, max_per_role=12
                )
                (diag_dir / "markov_blanket_detail.mmd").write_text(detail_mmd, encoding="utf-8")
            except Exception as e:
                raise RuntimeError("failed to render detailed Markov blanket diagram") from e

            logger.info(
                "Generated markov_blanket.json (strategy=%s, internal=%d, boundary=%d, external=%d)",
                strategy,
                blanket.stats.get("internal_count", 0),
                blanket.stats.get("sensory_count", 0) + blanket.stats.get("active_count", 0),
                blanket.stats.get("external_count", 0),
            )
        except Exception as e:
            # The Markov blanket is a derived diagnostic artifact.  Keep the
            # package structurally consumable when it cannot be computed, but
            # emit an explicit unavailable payload and manifest warning so a
            # validator/publication gate cannot mistake the stub for evidence.
            reason = str(e)
            warning = f"markov blanket unavailable: {reason}"
            self.artifact_warnings.append(warning)
            logger.warning("%s", warning)
            error_payload = {
                "schema_version": "1.0",
                "metadata": {
                    "error": True,
                    "status": "unavailable",
                    "reason": reason,
                },
                "error": reason,
                "roles": {
                    "internal": [],
                    "sensory": [],
                    "active": [],
                    "external": [],
                },
            }
            network_payload = {
                "schema_version": "1.0",
                "metadata": {"error": True, "status": "unavailable", "reason": reason},
                "nodes": [],
                "edges": [],
            }
            for filename, payload in (
                ("markov_blanket.json", error_payload),
                ("markov_network.json", network_payload),
            ):
                path = output_path / filename
                path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
                self.checksums[filename] = self._checksum_dict(payload)

    def _generate_program_graph_json(self, output_path: Path) -> None:
        """Dump the typed ``ProgramGraph`` as a JSON sidecar.

        This is the canonical input for :func:`cogant.viz.png.render_program_graph_png`
        and guarantees that any consumer of a COGANT GNN package (``cogant validate``,
        ``cogant viz``, downstream tooling) can rebuild a NetworkX view of the
        repo without re-running the pipeline.
        """
        try:
            from cogant.api.orchestration import program_graph_to_dict

            data = program_graph_to_dict(self.graph)
            path = output_path / "program_graph.json"
            path.write_text(json.dumps(data, indent=2, default=str), encoding="utf-8")
            self.checksums["program_graph.json"] = self._checksum_dict(data)
            logger.info("Generated program_graph.json")
        except Exception as e:  # noqa: BLE001
            logger.error(f"Could not generate program_graph.json: {e}", exc_info=True)
            return

    def _generate_process_model_json(self, output_path: Path) -> None:
        """Dump the ``ProcessModel`` as a JSON sidecar.

        Mirrors ``_generate_program_graph_json``: gives consumers (notably
        ``render_all_pngs`` → ``render_process_gantt_png``) a standalone file
        to load without re-running ``ProcessExtractor``. The shape matches
        what :func:`cogant.viz.png._load_process_model_from_json`
        expects: ``process_id``, ``stages``, ``policies``, ``timelines``.
        """
        if self.process_model is None:
            return
        try:

            def _to_dict(obj: Any) -> Any:
                if obj is None:
                    return None
                if hasattr(obj, "model_dump"):
                    return obj.model_dump()
                if hasattr(obj, "__dict__"):
                    return {k: _to_dict(v) for k, v in vars(obj).items()}
                if isinstance(obj, list | tuple):
                    return [_to_dict(v) for v in obj]
                if isinstance(obj, dict):
                    return {k: _to_dict(v) for k, v in obj.items()}
                return obj

            data = {
                "process_id": getattr(self.process_model, "process_id", None)
                or getattr(self.process_model, "id", None),
                "stages": [_to_dict(s) for s in getattr(self.process_model, "stages", []) or []],
                "policies": [
                    _to_dict(p) for p in getattr(self.process_model, "policies", []) or []
                ],
                "timelines": [
                    _to_dict(t) for t in getattr(self.process_model, "timelines", []) or []
                ],
                "connections": [
                    _to_dict(c) for c in getattr(self.process_model, "connections", []) or []
                ],
            }
            path = output_path / "process_model.json"
            path.write_text(json.dumps(data, indent=2, default=str), encoding="utf-8")
            self.checksums["process_model.json"] = self._checksum_dict(data)
            logger.info("Generated process_model.json")
        except Exception as e:  # noqa: BLE001
            logger.warning(f"Could not generate process_model.json: {e}")

    def _generate_diagrams(self, output_path: Path) -> None:
        """Generate mermaid diagrams driven by the real graph and state space.

        Uses ``cogant.viz.mermaid.MermaidGenerator`` so that diagrams reflect
        actual classes, modules, transitions, and processes — not hand-coded
        placeholders.
        """
        from cogant.viz.mermaid import MermaidGenerator

        diagrams_dir = output_path / "diagrams"
        diagrams_dir.mkdir(exist_ok=True)
        gen = MermaidGenerator()

        try:
            diagrams = {
                "class_diagram.mermaid": gen.generate_class_diagram(self.graph),
                "state_diagram.mermaid": gen.generate_state_diagram(self.state_space),
                "sequence_diagram.mermaid": gen.generate_sequence_diagram(
                    process_model=self.process_model, graph=self.graph
                ),
                "dependency_diagram.mermaid": gen.generate_dependency_graph(self.graph),
                "active_inference_diagram.mermaid": gen.generate_active_inference_diagram(
                    self.state_space
                ),
            }

            for filename, content in diagrams.items():
                filepath = diagrams_dir / filename
                filepath.write_text(content, encoding="utf-8")
                self.checksums[f"diagrams/{filename}"] = self._checksum(content)
                logger.info(f"Generated {filename}")
        except Exception as e:
            logger.error(f"Failed to generate diagrams: {e}", exc_info=True)
            return

    def _generate_visualizations(self, output_path: Path) -> None:
        """Generate HTML visualizations using the real plotting modules.

        Uses ``cogant.viz.plots.StaticPlotter`` to render the node-type,
        edge-type, and confidence distributions, and the dashboard
        renderer to produce a populated dashboard.html.
        """
        from cogant.viz.plots import StaticPlotter

        viz_dir = output_path / "visualizations"
        viz_dir.mkdir(exist_ok=True)

        try:
            dashboard = self._generate_dashboard_html()
            dashboard_path = viz_dir / "dashboard.html"
            dashboard_path.write_text(dashboard, encoding="utf-8")
            self.checksums["visualizations/dashboard.html"] = self._checksum(dashboard)
            logger.info("Generated dashboard.html")

            charts_dir = viz_dir / "charts"
            charts_dir.mkdir(exist_ok=True)

            plotter = StaticPlotter()
            charts: dict[str, str] = {}
            try:
                charts["node_dist.html"] = plotter.plot_node_type_distribution(self.graph)
            except Exception as e:
                logger.info("node_dist plot unavailable; using deterministic SVG renderer: %s", e)
                charts["node_dist.html"] = self._render_distribution_chart(
                    "Node distribution", self._count_nodes_by_kind()
                )
            try:
                charts["edge_dist.html"] = plotter.plot_edge_type_distribution(self.graph)
            except Exception as e:
                logger.info("edge_dist plot unavailable; using deterministic SVG renderer: %s", e)
                charts["edge_dist.html"] = self._render_distribution_chart(
                    "Edge distribution", self._count_edges_by_kind()
                )
            try:
                charts["confidence.html"] = plotter.plot_confidence_distribution(
                    self.mappings if isinstance(self.mappings, dict) else {}
                )
            except Exception as e:
                logger.info("confidence plot unavailable; using deterministic SVG renderer: %s", e)
                charts["confidence.html"] = self._render_distribution_chart(
                    "Confidence distribution",
                    self._count_mappings_by_tier(),
                )

            for filename, content in charts.items():
                filepath = charts_dir / filename
                filepath.write_text(content, encoding="utf-8")
                self.checksums[f"visualizations/charts/{filename}"] = self._checksum(content)
                logger.info(f"Generated {filename}")
        except Exception as e:
            logger.error(f"Failed to generate visualizations: {e}", exc_info=True)
            return

    def _count_nodes_by_kind(self) -> dict[str, int]:
        """Count nodes by kind for deterministic chart rendering."""
        from collections import defaultdict

        counts: dict[str, int] = defaultdict(int)
        if self.graph and hasattr(self.graph, "nodes"):
            for node in self.graph.nodes.values():
                counts[str(node.kind)] += 1
        return dict(counts)

    def _count_mappings_by_tier(self) -> dict[str, int]:
        """Count semantic mappings by confidence tier."""
        from collections import defaultdict

        counts: dict[str, int] = defaultdict(int)
        if not isinstance(self.mappings, dict):
            return {}
        for m in self.mappings.values():
            tier = getattr(m, "confidence_tier", None)
            label = tier.value if hasattr(tier, "value") else str(tier or "unknown")  # type: ignore[union-attr]
            counts[label] += 1
        return dict(counts)

    def _render_distribution_chart(self, title: str, counts: dict[str, int]) -> str:
        """Render a tiny SVG bar chart from a counts dict.

        Used when the StaticPlotter raises (e.g. matplotlib unavailable
        in the runtime environment). The output is a self-contained HTML
        document with an inline SVG so it never depends on external
        assets.
        """
        max_v = max(counts.values()) if counts else 1
        bar_w = 40
        gap = 12
        chart_h = 200
        x = gap
        bars: list[str] = []
        labels: list[str] = []
        for key, value in sorted(counts.items(), key=lambda kv: -kv[1]):
            bar_h = int((value / max_v) * (chart_h - 30)) if max_v else 0
            y = chart_h - bar_h - 20
            bars.append(
                f'<rect x="{x}" y="{y}" width="{bar_w}" height="{bar_h}" '
                f'fill="#4682B4" stroke="#1e3f6b"/>'
                f'<text x="{x + bar_w / 2}" y="{y - 4}" font-size="10" '
                f'text-anchor="middle">{value}</text>'
            )
            labels.append(
                f'<text x="{x + bar_w / 2}" y="{chart_h - 4}" font-size="9" '
                f'text-anchor="middle" transform="rotate(-15 {x + bar_w / 2} {chart_h - 4})">{key}</text>'
            )
            x += bar_w + gap
        width = max(x + gap, 200)
        return (
            "<!DOCTYPE html><html><head><title>"
            + title
            + '</title></head><body><h1 style="font-family:Arial">'
            + title
            + f'</h1><svg width="{width}" height="{chart_h + 20}" xmlns="http://www.w3.org/2000/svg" '
            + 'style="font-family:Arial">'
            + "".join(bars)
            + "".join(labels)
            + "</svg></body></html>"
        )

    def _create_manifest(self, output_path: Path) -> dict[str, Any]:
        """Create and save the package manifest."""
        manifest = {
            "version": self.PACKAGE_VERSION,
            "timestamp": self.timestamp,
            "package_path": str(output_path),
            "checksums": self.checksums,
            "files": list(self.checksums.keys()),
            "graph_stats": {
                "nodes": self._count_graph_nodes(),
                "edges": self._count_graph_edges(),
            },
            "state_space_stats": self._count_state_space_elements(),
            "semantic_mappings_count": len(self.mappings) if isinstance(self.mappings, dict) else 0,
            "artifact_status": {
                "markov_blanket": "unavailable"
                if any("markov blanket unavailable:" in item for item in self.artifact_warnings)
                else "success"
            },
            "warnings": list(self.artifact_warnings),
        }

        manifest_path = output_path / "manifest.json"
        manifest_path.write_text(json.dumps(manifest, indent=2, default=str), encoding="utf-8")
        logger.info("Generated manifest.json")

        return manifest

    # Data extraction helpers

    def _state_var_object(self, var_id: str) -> Any | None:
        """Resolve a state-space variable id back to its full object.

        ``StateSpaceModel.variables`` is a ``dict[str, StateVariable]``
        keyed by variable id. This helper returns the ``StateVariable``
        for *var_id*, or ``None`` when the id is unknown or the state
        space only carries bare string ids (duck-typed stand-ins).
        """
        variables = getattr(self.state_space, "variables", None)
        if isinstance(variables, dict):
            obj = variables.get(var_id)
            if obj is not None and not isinstance(obj, str):
                return obj
        return None

    def _action_object(self, action_id: str) -> Any | None:
        """Resolve an action id back to its full ``Action`` object."""
        actions = getattr(self.state_space, "actions", None)
        if isinstance(actions, dict):
            return actions.get(action_id)
        return None

    def _extract_state_variables(self) -> list[dict[str, Any]]:
        """Extract state variables with type/cardinality/source info."""
        out: list[dict[str, Any]] = []
        for var_id in getattr(self.state_space, "variables", []) or []:
            obj = self._state_var_object(var_id)
            if obj is None:
                out.append({"id": str(var_id), "name": str(var_id), "type": "variable"})
                continue
            node_id = getattr(obj, "node_id", None)
            out.append(
                {
                    "id": getattr(obj, "id", str(var_id)),
                    "name": getattr(obj, "name", str(var_id)),
                    "var_type": getattr(getattr(obj, "var_type", None), "value", None)
                    or str(getattr(obj, "var_type", "")),
                    "cardinality": getattr(obj, "cardinality", None),
                    "domain": getattr(obj, "domain", None),
                    "factors": list(getattr(obj, "factors", None) or []),
                    "is_discrete": getattr(obj, "is_discrete", None),
                    "observable": getattr(obj, "observable", False),
                    "description": getattr(obj, "description", "") or "",
                    "node_id": node_id,
                    "source_node_ids": [node_id] if node_id else [],
                    "confidence": _enum_value(getattr(obj, "confidence", None)),
                }
            )
        return out

    def _extract_observation_space(self) -> list[dict[str, Any]]:
        """Extract observation space with full modality info."""
        out: list[dict[str, Any]] = []
        observations = getattr(self.state_space, "observations", None)
        if observations is None:
            return out
        if isinstance(observations, dict):
            iterable = observations.values()
        else:
            iterable = observations
        for obs in iterable:
            if hasattr(obs, "name"):
                # ``ObservationModality`` names its channel class
                # ``modality_type``; ``modality`` is kept as the emitted key
                # (and accepted from duck-typed inputs) for compatibility.
                modality = (
                    getattr(obs, "modality_type", None)
                    or getattr(obs, "modality", None)
                    or "symbolic"
                )
                out.append(
                    {
                        "id": getattr(obs, "id", str(obs)),
                        "name": getattr(obs, "name", ""),
                        "modality": str(modality),
                        "modality_type": str(modality),
                        "source_node_id": getattr(obs, "source_node_id", None),
                        "cardinality": getattr(obs, "cardinality", None),
                        "values": getattr(obs, "values", None),
                        "source_channels": getattr(obs, "source_channels", []) or [],
                        "description": getattr(obs, "description", ""),
                        "confidence": _enum_value(getattr(obs, "confidence", None)),
                    }
                )
            else:
                out.append({"id": str(obs), "name": str(obs), "modality": "symbolic"})
        return out

    def _extract_action_space(self) -> list[dict[str, Any]]:
        """Extract action space with controllers and effects."""
        out: list[dict[str, Any]] = []
        actions = getattr(self.state_space, "actions", None)
        if actions is None:
            return out
        iterable = actions.values() if isinstance(actions, dict) else actions
        for action in iterable:
            if hasattr(action, "name"):
                out.append(
                    {
                        "id": getattr(action, "id", str(action)),
                        "name": getattr(action, "name", ""),
                        "controller_id": getattr(action, "controller_id", None),
                        "parameters": getattr(action, "parameters", []) or [],
                        "effects": list(
                            getattr(action, "effects", None)
                            or getattr(action, "affects_state_vars", None)
                            or []
                        ),
                        "preconditions": list(getattr(action, "preconditions", None) or []),
                        "description": getattr(action, "description", ""),
                        "confidence": _enum_value(getattr(action, "confidence", None)),
                    }
                )
            else:
                out.append({"id": str(action), "name": str(action)})
        return out

    def _extract_transition_structure(self) -> dict[str, Any]:
        """Extract transition structure from the real state space."""
        transitions = getattr(self.state_space, "transitions", None) or []
        return {
            "type": "state_transitions",
            "transition_count": len(transitions) if hasattr(transitions, "__len__") else 0,
            "deterministic": self._is_deterministic(),
            "markovian": self._is_markovian(),
            "time_regime": getattr(self.state_space, "time_regime", None),
        }

    def _extract_observation_modalities(self) -> list[str]:
        """Extract observation modalities present in the state space."""
        modalities: list[str] = []
        observations = getattr(self.state_space, "observations", None)
        if observations is not None:
            iterable = observations.values() if isinstance(observations, dict) else observations
            for obs in iterable:
                modality = getattr(obs, "modality", None) or getattr(obs, "modality_type", None)
                if modality and modality not in modalities:
                    modalities.append(str(modality))
        # An empty symbolic state space still has a meaningful observation
        # channel for consumers that need a stable modality dimension.
        return modalities or ["symbolic"]

    def _extract_actions(self) -> list[dict[str, Any]]:
        """Extract actions with full details including effects and preconditions."""
        actions = getattr(self.state_space, "actions", None)
        if actions is None:
            return []

        def _effects_for_action(action: Any) -> list[str]:
            effects = getattr(action, "effects", None)
            if effects is None:
                effects = getattr(action, "affects_state_vars", None)
            return list(effects or [])

        actions_list: list[dict[str, Any]] = []
        iterable: Any
        if isinstance(actions, dict):
            iterable = actions.values()
        else:
            iterable = actions
        for action in iterable:
            if not hasattr(action, "name"):
                actions_list.append({"id": str(action), "name": str(action)})
                continue
            actions_list.append(
                {
                    "id": getattr(action, "id", str(action)),
                    "name": getattr(action, "name", ""),
                    "controller_id": getattr(action, "controller_id", None),
                    "parameters": getattr(action, "parameters", []) or [],
                    "effects": _effects_for_action(action),
                    "preconditions": getattr(action, "preconditions", []) or [],
                    "description": getattr(action, "description", ""),
                    "confidence": _enum_value(getattr(action, "confidence", None)),
                }
            )
        return actions_list

    def _extract_policies(self) -> list[dict[str, Any]]:
        """Extract policies derived from actual POLICY/ORCHESTRATION mappings."""
        out: list[dict[str, Any]] = []
        if isinstance(self.mappings, dict):
            for mid, m in self.mappings.items():
                kind = getattr(m, "kind", None)
                if kind in (MappingKind.POLICY, MappingKind.ORCHESTRATION):
                    out.append(
                        {
                            "id": mid,
                            "label": getattr(m, "semantic_label", "") or mid,
                            "kind": _enum_value(kind),
                            "description": getattr(m, "description", ""),
                            "controller_node_ids": list(
                                getattr(m, "graph_fragment_node_ids", []) or []
                            ),
                            "confidence": getattr(m, "confidence_score", 0.0),
                            "tier": _enum_value(getattr(m, "confidence_tier", None)),
                        }
                    )
        return out

    def _extract_preferences(self) -> list[dict[str, Any]]:
        """Extract preferences from state space."""
        if not hasattr(self.state_space, "preferences"):
            return []
        prefs_list = []
        for _pref_id, pref in self.state_space.preferences.items():
            prefs_list.append(
                {
                    "id": pref.id,
                    "name": pref.name,
                    "description": pref.description,
                    "scope": pref.scope,
                    "expression": pref.expression,
                    "weight": pref.weight,
                    "source": pref.source,
                    "confidence": pref.confidence.value
                    if hasattr(pref.confidence, "value")
                    else str(pref.confidence),
                }
            )
        return prefs_list

    def _extract_constraints(self) -> list[dict[str, Any]]:
        """Extract constraints from CONSTRAINT mappings and state-space preferences."""
        out: list[dict[str, Any]] = []
        if isinstance(self.mappings, dict):
            for mid, m in self.mappings.items():
                if getattr(m, "kind", None) == MappingKind.CONSTRAINT:
                    out.append(
                        {
                            "id": mid,
                            "label": getattr(m, "semantic_label", "") or mid,
                            "description": getattr(m, "description", ""),
                            "scope": list(getattr(m, "graph_fragment_node_ids", []) or []),
                            "confidence": getattr(m, "confidence_score", 0.0),
                            "tier": _enum_value(getattr(m, "confidence_tier", None)),
                            "source": "translation_rule",
                        }
                    )
        prefs = getattr(self.state_space, "preferences", None)
        if isinstance(prefs, dict):
            for pid, pref in prefs.items():
                if getattr(pref, "source", "") == "constraint":
                    out.append(
                        {
                            "id": pid,
                            "label": getattr(pref, "name", "") or pid,
                            "description": getattr(pref, "description", ""),
                            "scope": list(getattr(pref, "scope", []) or []),
                            "confidence": _enum_value(getattr(pref, "confidence", None)),
                            "weight": getattr(pref, "weight", 1.0),
                            "expression": getattr(pref, "expression", ""),
                            "source": "state_space.preferences",
                        }
                    )
        return out

    def _extract_objectives(self) -> list[dict[str, Any]]:
        """Extract objectives from PREFERENCE mappings and state-space preferences."""
        out: list[dict[str, Any]] = []
        if isinstance(self.mappings, dict):
            for mid, m in self.mappings.items():
                if getattr(m, "kind", None) == MappingKind.PREFERENCE:
                    out.append(
                        {
                            "id": mid,
                            "label": getattr(m, "semantic_label", "") or mid,
                            "description": getattr(m, "description", ""),
                            "weight": 1.0,
                            "scope": list(getattr(m, "graph_fragment_node_ids", []) or []),
                            "confidence": getattr(m, "confidence_score", 0.0),
                            "tier": _enum_value(getattr(m, "confidence_tier", None)),
                            "source": "translation_rule",
                        }
                    )
        prefs = getattr(self.state_space, "preferences", None)
        if isinstance(prefs, dict):
            for pid, pref in prefs.items():
                source = getattr(pref, "source", "")
                if source != "constraint":
                    out.append(
                        {
                            "id": pid,
                            "label": getattr(pref, "name", "") or pid,
                            "description": getattr(pref, "description", ""),
                            "weight": getattr(pref, "weight", 1.0),
                            "scope": list(getattr(pref, "scope", []) or []),
                            "expression": getattr(pref, "expression", ""),
                            "confidence": _enum_value(getattr(pref, "confidence", None)),
                            "source": source or "state_space.preferences",
                        }
                    )
        return out

    def _extract_factorization(self) -> dict[str, Any]:
        """Extract factorization structure from the state space.

        Groups state variables by their ``StateVariable.factors`` list
        (assigned by the compiler; a variable may belong to several
        factors). Variables without a factor are collected under a
        ``"default"`` factor so the GNN package always carries a
        factorization view. Returns the factor → variable mapping plus a
        small summary; ``variable_count`` counts distinct variables.
        """
        from collections import defaultdict

        groups: dict[str, list[str]] = defaultdict(list)
        ungrouped: list[str] = []
        seen: set[str] = set()
        for var_id in getattr(self.state_space, "variables", []) or []:
            seen.add(str(var_id))
            obj = self._state_var_object(var_id)
            factors = [str(f) for f in (getattr(obj, "factors", None) or []) if f]
            if factors:
                for factor in dict.fromkeys(factors):
                    groups[factor].append(var_id)
            else:
                ungrouped.append(var_id)
        if ungrouped:
            groups["default"].extend(ungrouped)

        return {
            "type": "factor_partition" if groups else "none",
            "factor_count": len(groups),
            "variable_count": len(seen) if groups else 0,
            "factors": [{"id": fid, "variables": sorted(vs)} for fid, vs in sorted(groups.items())],
        }

    def _extract_factor_list(self) -> list[dict[str, Any]]:
        """Flat list of factor descriptors used by the factors.json export."""
        factorization = self._extract_factorization()
        return list(factorization.get("factors", []))

    def _extract_ontology_mappings(self) -> list[dict[str, Any]]:
        """Extract ontology mappings — one row per semantic mapping with full role info."""
        out: list[dict[str, Any]] = []
        if not isinstance(self.mappings, dict):
            return out
        for mid, m in self.mappings.items():
            out.append(
                {
                    "id": mid,
                    "kind": _enum_value(getattr(m, "kind", None)),
                    "semantic_label": getattr(m, "semantic_label", "") or mid,
                    "description": getattr(m, "description", ""),
                    "graph_node_ids": list(getattr(m, "graph_fragment_node_ids", []) or []),
                    "graph_edge_ids": list(getattr(m, "graph_fragment_edge_ids", []) or []),
                    "confidence": getattr(m, "confidence_score", 0.0),
                    "tier": _enum_value(getattr(m, "confidence_tier", None)),
                    "evidence_count": getattr(m, "evidence_count", 0),
                }
            )
        return out

    def _extract_classes(self) -> list[str]:
        """Extract class definitions."""
        classes = set()
        for _nid, node in self.graph.nodes.items():
            if node.kind == NodeKind.CLASS:
                classes.add(node.name)
        return list(classes)

    def _extract_relationships(self) -> list[dict[str, str]]:
        """Extract relationships."""
        relationships = []
        for _eid, edge in self.graph.edges.items():
            relationships.append(
                {"source": edge.source_id, "target": edge.target_id, "kind": str(edge.kind)}
            )
        return relationships[:100]  # Limit to first 100

    def _extract_source_evidence(self) -> dict[str, Any]:
        """Extract source evidence."""
        return {
            "graph_nodes": self._count_graph_nodes(),
            "graph_edges": self._count_graph_edges(),
            "timestamp": self.timestamp,
        }

    def _count_graph_nodes(self) -> int:
        """Count nodes in graph."""
        return len(self.graph.nodes) if self.graph and hasattr(self.graph, "nodes") else 0

    def _count_graph_edges(self) -> int:
        """Count edges in graph."""
        return len(self.graph.edges) if self.graph and hasattr(self.graph, "edges") else 0

    def _count_edges_by_kind(self) -> dict[str, int]:
        """Count edges by kind."""
        from collections import defaultdict

        counts: dict[str, int] = defaultdict(int)
        if self.graph and hasattr(self.graph, "edges"):
            for edge in self.graph.edges.values():
                counts[str(edge.kind)] += 1
        return dict(counts)

    def _count_state_space_elements(self) -> dict[str, int]:
        """Count state space elements."""
        return {
            "variables": len(self.state_space.variables)
            if hasattr(self.state_space, "variables")
            else 0,
            "observations": len(self.state_space.observations)
            if hasattr(self.state_space, "observations")
            else 0,
            "actions": len(self.state_space.actions) if hasattr(self.state_space, "actions") else 0,
        }

    def _is_deterministic(self) -> bool:
        """Heuristic determinism check.

        A model is treated as non-deterministic when any transition has
        more than one ``to_state`` candidate, or when any likelihood
        spans multiple observations conditioned on the same state set.
        """
        transitions = getattr(self.state_space, "transitions", None) or []
        for t in transitions:
            to_states = getattr(t, "to_states", None) or getattr(t, "successors", None) or []
            if hasattr(to_states, "__len__") and len(to_states) > 1:
                return False
        likelihoods = getattr(self.state_space, "likelihoods", None) or []
        for likelihood in likelihoods:
            obs = getattr(likelihood, "observations", None) or []
            if hasattr(obs, "__len__") and len(obs) > 1:
                return False
        return True

    def _is_markovian(self) -> bool:
        """Heuristic Markov property check.

        A transition that conditions on more than one prior state set
        breaks the Markov assumption.
        """
        transitions = getattr(self.state_space, "transitions", None) or []
        for t in transitions:
            from_states = getattr(t, "from_states", None) or getattr(t, "predecessors", None) or []
            if hasattr(from_states, "__len__") and len(from_states) > 1:
                return False
        return True

    def _generate_dashboard_html(self) -> str:
        """Generate a populated dashboard HTML for the model package.

        This is a small, self-contained dashboard rendered server-side
        from the real graph, mapping, and state-space counts. No
        external assets, no JS execution required.
        """
        nodes_by_kind = self._count_nodes_by_kind()
        edges_by_kind = self._count_edges_by_kind()
        mappings_by_tier = self._count_mappings_by_tier()
        state_space_counts = self._count_state_space_elements()

        def _rows(d: dict[str, Any]) -> str:
            if not d:
                return "<tr><td colspan='2'><em>(none)</em></td></tr>"
            return "".join(
                f"<tr><td>{k}</td><td>{v}</td></tr>"
                for k, v in sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))
            )

        return f"""<!DOCTYPE html>
<html>
<head>
<title>GNN Model Dashboard</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; color: #222 }}
h1 {{ color: #1e3f6b }}
table {{ border-collapse: collapse; margin: 8px 0 16px 0 }}
th, td {{ border: 1px solid #999; padding: 4px 10px; text-align: left }}
.stat {{ margin: 10px 0; padding: 10px 14px; border: 1px solid #ccc; background: #f6f8fb }}
.grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px }}
</style>
</head>
<body>
<h1>GNN Model Package Dashboard</h1>
<div class="stat">
    <h3>Package</h3>
    <p>Version: {self.PACKAGE_VERSION}</p>
    <p>Generated: {self.timestamp}</p>
    <p>Nodes: {self._count_graph_nodes()} &nbsp; Edges: {self._count_graph_edges()} &nbsp;
       Mappings: {len(self.mappings) if isinstance(self.mappings, dict) else 0}</p>
</div>
<div class="grid">
<div class="stat"><h3>Nodes by kind</h3><table><tr><th>Kind</th><th>Count</th></tr>{_rows(nodes_by_kind)}</table></div>
<div class="stat"><h3>Edges by kind</h3><table><tr><th>Kind</th><th>Count</th></tr>{_rows(edges_by_kind)}</table></div>
<div class="stat"><h3>Mappings by confidence tier</h3><table><tr><th>Tier</th><th>Count</th></tr>{_rows(mappings_by_tier)}</table></div>
<div class="stat"><h3>State space</h3><table><tr><th>Component</th><th>Count</th></tr>{_rows(state_space_counts)}</table></div>
</div>
</body>
</html>"""

    # Utility functions

    @staticmethod
    def _checksum(text: str) -> str:
        """Compute SHA256 checksum of text."""
        return hashlib.sha256(text.encode()).hexdigest()

    @staticmethod
    def _checksum_dict(data: dict[str, Any]) -> str:
        """Compute SHA256 checksum of dictionary."""
        text = json.dumps(data, sort_keys=True, default=str)
        return hashlib.sha256(text.encode()).hexdigest()

__init__(graph, state_space, process_model, mappings, config=None)

Initialize the GNN package builder.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
state_space StateSpaceModel

State space model.

required
process_model ProcessModel

Process model.

required
mappings dict[str, Any]

Semantic mappings.

required
config dict[str, Any] | None

Optional configuration dictionary.

None
Source code in py/cogant/gnn/package.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def __init__(
    self,
    graph: ProgramGraph,
    state_space: StateSpaceModel,
    process_model: ProcessModel,
    mappings: dict[str, Any],
    config: dict[str, Any] | None = None,
):
    """
    Initialize the GNN package builder.

    Args:
        graph: Program graph.
        state_space: State space model.
        process_model: Process model.
        mappings: Semantic mappings.
        config: Optional configuration dictionary.
    """
    self.graph = graph
    self.state_space = state_space
    self.process_model = process_model
    self.mappings = mappings
    self.config = config or {}
    self.timestamp = datetime.now(UTC).isoformat()
    self.checksums: dict[str, str] = {}
    self.artifact_warnings: list[str] = []

build(output_dir)

Build the complete GNN package.

Parameters:

Name Type Description Default
output_dir str

Directory to create the package in.

required

Returns:

Type Description
dict[str, Any]

Manifest dictionary with package metadata and checksums.

Source code in py/cogant/gnn/package.py
 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
def build(self, output_dir: str) -> dict[str, Any]:
    """
    Build the complete GNN package.

    Args:
        output_dir: Directory to create the package in.

    Returns:
        Manifest dictionary with package metadata and checksums.
    """
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)
    logger.info(
        "Building GNN package in %s (%d nodes, %d edges, %d mappings)",
        output_path,
        len(self.graph.nodes),
        len(self.graph.edges),
        len(self.mappings) if isinstance(self.mappings, dict) else 0,
    )

    try:
        # 1. Generate core model files
        self._generate_markdown(output_path)
        self._generate_json_model(output_path)
        self._generate_state_space(output_path)
        self._generate_observations(output_path)
        self._generate_actions(output_path)
        self._generate_transitions(output_path)
        self._generate_preferences(output_path)
        self._generate_factors(output_path)
        self._generate_provenance(output_path)
        self._generate_ontology(output_path)

        # 2. Generate canonical section JSON files
        self._generate_actions_policies(output_path)
        self._generate_connections(output_path)
        self._generate_preferences_constraints(output_path)

        # 2b. Generate Markov blanket artifacts (Active Inference partition)
        self._generate_markov_blanket(output_path)

        # 2c. Dump the typed program graph as JSON so PNG rasterizers can
        # rebuild a NetworkX view without re-running the pipeline.
        self._generate_program_graph_json(output_path)

        # 2d. Dump the ProcessModel as JSON so ``render_all_pngs`` can
        # rasterize a Gantt timeline without re-running ProcessExtractor.
        self._generate_process_model_json(output_path)

        # 3. Generate diagrams
        self._generate_diagrams(output_path)

        # 4. Generate visualizations
        self._generate_visualizations(output_path)

        # 5. Create manifest
        manifest = self._create_manifest(output_path)

        # Summarize role distribution across semantic mappings
        role_dist: dict[str, int] = {}
        if isinstance(self.mappings, dict):
            for m in self.mappings.values():
                kind = getattr(m, "kind", None)
                label = kind.value if hasattr(kind, "value") else str(kind or "unknown")
                role_dist[label] = role_dist.get(label, 0) + 1

        role_summary = (
            f" | roles={', '.join(f'{k}={v}' for k, v in sorted(role_dist.items()))}"
            if role_dist
            else ""
        )
        n_vars = (
            len(self.state_space.variables) if hasattr(self.state_space, "variables") else 0
        )
        n_obs = (
            len(self.state_space.observations)
            if hasattr(self.state_space, "observations")
            else 0
        )
        n_actions = len(self.state_space.actions) if hasattr(self.state_space, "actions") else 0

        logger.info(
            "GNN package built: %d files | state_space=%d vars, %d obs, %d actions%s",
            len(self.checksums),
            n_vars,
            n_obs,
            n_actions,
            role_summary,
        )
        return manifest

    except Exception as e:
        logger.error(f"Failed to build GNN package: {e}", exc_info=True)
        raise

GNNValidator

Validates a GNN package against the GNN specification.

Source code in py/cogant/gnn/validator.py
 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
 403
 404
 405
 406
 407
 408
 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
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 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
 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
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 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
 974
 975
 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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
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
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
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
class GNNValidator:
    """Validates a GNN package against the GNN specification."""

    REQUIRED_FILES = [
        "manifest.json",
        "model.gnn.md",
        "model.gnn.json",
        "state_space.json",
        "observations.json",
        "actions.json",
        "transitions.json",
        "preferences.json",
        "factors.json",
        "provenance.json",
        "ontology.json",
        "actions_policies.json",
        "connections.json",
        "preferences_constraints.json",
        "markov_blanket.json",
        "markov_network.json",
    ]

    CANONICAL_SECTIONS = [
        "model_metadata",
        "repository_metadata",
        "source_coverage",
        "state_space",
        "observation_modalities",
        "actions_policies",
        "program_graph_connections",
        "factors",
        "transition_structure",
        "likelihood_structure",
        "preferences_constraints",
        "time_settings",
        "parameterization",
        "ontology_mapping",
        "markov_blanket",
        "provenance",
        "confidence",
        "rendering_hints",
        "validation_notes",
    ]

    # Upstream GNN 2.0.0 headers. COGANT emits these at the top of
    # ``model.gnn.md`` for upstream validation.
    UPSTREAM_SECTIONS = [
        "GNNSection",
        "GNNVersionAndFlags",
        "ModelName",
        "StateSpaceBlock",
        "Connections",
        "InitialParameterization",
        "Equations",
        "Time",
        "ActInfOntologyAnnotation",
        "ModelParameters",
        "Footer",
        "Signature",
    ]

    def __init__(self) -> None:
        """Initialize validator."""
        # ``validate_package`` is the single entry point and always
        # reassigns these before they're read. Type-annotating as
        # non-optional avoids a cascade of union-attr noise in the
        # private ``_check_*`` helpers below without hiding any real
        # null-dereference bug (the helpers are never called first).
        self.result: ValidationResult = ValidationResult()
        self.package_dir: Path = Path(".")
        self._upstream_gnn: bool = False

    def validate_package(
        self,
        package_dir: str,
        *,
        upstream_gnn: bool | None = None,
    ) -> ValidationResult:
        """
        Validate a GNN package.

        Args:
            package_dir: Path to the package directory.
            upstream_gnn: When True, run the Active Inference Institute
                ``generalized-notation-notation`` validator (upstream ``gnn``
                4.x, ``standard`` level) on ``model.gnn.md``; a requested but
                unavailable upstream is reported as a capability error. When
                ``None``, upstream runs only if
                :envvar:`COGANT_ENABLE_UPSTREAM_GNN` is truthy (and never when
                :envvar:`COGANT_DISABLE_UPSTREAM_GNN` is set).

        Returns:
            ValidationResult object.
        """
        self.package_dir = Path(package_dir)
        self.result = ValidationResult()
        self._upstream_gnn = _resolve_upstream_flag(upstream_gnn)
        self.result.capabilities["upstream_gnn"] = {
            "requested": self._upstream_gnn,
            "available": False,
        }
        try:
            from cogant.parsers.registry import parser_capabilities

            self.result.capabilities["parsers"] = {
                language: capability.__dict__
                for language, capability in parser_capabilities().items()
            }
        except Exception as exc:
            self.result.capabilities["parsers"] = {"error": str(exc)}

        logger.info(
            "Validating GNN package: %s (upstream_gnn=%s)",
            self.package_dir,
            self._upstream_gnn,
        )

        # Check 1: Directory exists
        if not self.package_dir.exists():
            self.result.errors.append(f"Package directory not found: {self.package_dir}")
            self.result.valid = False
            self.result.score = 0.0
            return self.result

        if not self.package_dir.is_dir():
            self.result.errors.append(f"Package path is not a directory: {self.package_dir}")
            self.result.score = 0.0
            return self.result

        self.result.artifact_digests = self._artifact_digests()

        # Check 2: Required files present
        self._check_required_files()

        # Check 3: Manifest valid
        manifest = self._check_manifest()

        # Check 4: JSON files valid
        self._check_json_files()

        # Check 4b: best-effort artifacts the builder could not produce
        self._check_artifact_status(manifest)

        # Check 5: A/B/C/D matrix block valid
        self._check_matrices()

        # Check 6: Markdown valid
        self._check_markdown()

        # Check 7: State space valid
        self._check_state_space()

        # Check 8: Provenance valid
        self._check_provenance()

        # Check 9: Checksums match
        if manifest:
            self._check_checksums(manifest)

        # Compute final score and validity
        self._compute_final_score()

        logger.info(
            "Validation complete: %s (score=%.1f%%, %d errors, %d warnings)",
            self.result.valid,
            self.result.score,
            len(self.result.errors),
            len(self.result.warnings),
        )
        return self.result

    def validate_markdown(self, markdown: str) -> list[str]:
        """
        Validate GNN markdown structure.

        Checks both the COGANT-extended canonical sections
        (``## Model Metadata``, ``## Source Coverage``, ``## Markov
        Blanket``, etc.) and the upstream GNN 2.0.0 required headers
        (``## GNNSection``, ``## StateSpaceBlock``, ``## Connections``,
        ``## InitialParameterization``, ``## Equations``, ``## Time``,
        ``## ActInfOntologyAnnotation``, ``## ModelParameters``, etc.). Upstream section
        checks are ordered: they must appear in the spec-mandated
        order at the TOP of the file.

        Args:
            markdown: Markdown content.

        Returns:
            List of errors (empty if valid).
        """
        errors: list[str] = []
        lowered = markdown.lower()

        # 1) COGANT-extended canonical sections (case-insensitive presence check).
        for section in self.CANONICAL_SECTIONS:
            section_header = f"## {section.replace('_', ' ').title()}"
            if section_header.lower() not in lowered:
                errors.append(f"Missing canonical section: {section}")

        # 2) Upstream GNN 2.0.0 required sections — each must be present.
        missing_upstream: list[str] = []
        upstream_offsets: list[tuple[str, int]] = []
        for section in self.UPSTREAM_SECTIONS:
            marker = f"## {section}"
            idx = markdown.find(marker)
            if idx < 0:
                missing_upstream.append(section)
            else:
                upstream_offsets.append((section, idx))
        for section in missing_upstream:
            errors.append(f"Missing upstream GNN 2.0.0 section: {section}")

        # 3) Upstream sections must appear in canonical order.
        if not missing_upstream and upstream_offsets:
            expected_order = list(self.UPSTREAM_SECTIONS)
            found_order = [section for section, _ in sorted(upstream_offsets, key=lambda x: x[1])]
            if expected_order != found_order:
                errors.append(
                    "Upstream GNN 2.0.0 sections out of canonical order: "
                    f"found {found_order}, expected {expected_order}"
                )

        return errors

    def validate_state_space(self, state_space_json: dict[str, Any]) -> list[str]:
        """
        Validate state space structure.

        Args:
            state_space_json: State space JSON.

        Returns:
            List of errors (empty if valid).
        """
        if not isinstance(state_space_json, dict):
            return ["State-space root must be a JSON object"]
        errors: list[str] = []

        # Check required keys
        required_keys = ["variables", "observations", "actions", "transitions"]
        for key in required_keys:
            if key not in state_space_json:
                errors.append(f"Missing state space key: {key}")

        # Check variables are well-formed
        variables = state_space_json.get("variables", [])
        if not isinstance(variables, list):
            errors.append("Variables must be a list")
        elif any(not isinstance(item, dict) for item in variables):
            errors.append("Variables entries must be objects")

        # Check observations are well-formed
        observations = state_space_json.get("observations", [])
        if not isinstance(observations, list):
            errors.append("Observations must be a list")
        elif any(not isinstance(item, dict) for item in observations):
            errors.append("Observations entries must be objects")

        # Check actions are well-formed
        actions = state_space_json.get("actions", [])
        if not isinstance(actions, list):
            errors.append("Actions must be a list")
        elif any(not isinstance(item, dict) for item in actions):
            errors.append("Actions entries must be objects")

        # Check transitions are well-formed
        transitions = state_space_json.get("transitions", {})
        if not isinstance(transitions, dict):
            errors.append("Transitions must be a dict")
        else:
            if not isinstance(transitions.get("transition_count"), int):
                errors.append("Transitions must declare an integer transition_count")
            if not isinstance(transitions.get("time_regime"), str) or not transitions.get(
                "time_regime"
            ):
                errors.append("Transitions must declare a non-empty time_regime")

        metadata = state_space_json.get("metadata")
        if metadata is not None:
            if not isinstance(metadata, dict):
                errors.append("State-space metadata must be an object")
            else:
                for key, values in (
                    ("num_variables", variables),
                    ("num_observations", observations),
                    ("num_actions", actions),
                ):
                    declared = metadata.get(key)
                    if isinstance(values, list) and declared != len(values):
                        errors.append(f"State-space metadata {key} does not match emitted entries")

        return errors

    def validate_matrices(self, matrices_json: dict[str, Any]) -> list[str]:
        """Validate the AII Active Inference matrix block.

        Checks presence and shape of the A/B/C/D matrices emitted by
        :class:`cogant.gnn.matrices.GNNMatrices`. The matrices must
        satisfy:

        * A: shape ``[n_obs x n_states]``, columns sum to 1.0.
        * B: shape ``[n_states x n_states x n_actions]``; when
          ``truncation.applied`` is set (large-repo top-K cut, see
          :meth:`cogant.gnn.matrices.GNNMatrices.compute_B`) the state
          axes are ``n_states_kept`` and ``truncation.kept_state_indices``
          must name those states on the full A/D axis.
        * C: length equal to ``n_obs``.
        * D: length equal to ``n_states``, sums to 1.0.

        Args:
            matrices_json: Dict of the form
                ``{"A": ..., "B": ..., "C": ..., "D": ...,
                "dimensions": {"n_states", "n_obs", "n_actions"}}``.

        Returns:
            List of errors (empty if matrices are well-formed).
        """
        errors: list[str] = []

        for key in ("A", "B", "C", "D"):
            if key not in matrices_json:
                errors.append(f"Missing matrix: {key}")

        A = matrices_json.get("A", [])
        B = matrices_json.get("B", [])
        C = matrices_json.get("C", [])
        D = matrices_json.get("D", [])

        if not isinstance(A, list):
            errors.append("A must be a list")
            A = []
        if not isinstance(B, list):
            errors.append("B must be a list")
            B = []
        if not isinstance(C, list):
            errors.append("C must be a list")
            C = []
        if not isinstance(D, list):
            errors.append("D must be a list")
            D = []
        if any(not isinstance(row, list) for row in A):
            errors.append("A rows must be lists")
            A = [row for row in A if isinstance(row, list)]
        if any(not isinstance(row, list) for row in B):
            errors.append("B rows must be lists")
            B = [row for row in B if isinstance(row, list)]
        if any(not isinstance(cell, list) for row in B for cell in row):
            errors.append("B cells must be lists")
            B = [[cell for cell in row if isinstance(cell, list)] for row in B]

        dims = matrices_json.get("dimensions")
        if not isinstance(dims, dict):
            if dims is None:
                errors.append("dimensions must be declared as an object")
            else:
                errors.append("dimensions must be an object")
            dims = {}

        inferred_states = len(D) or (len(A[0]) if A and A[0] else 0)
        inferred_obs = len(A) or len(C)
        inferred_actions = len(B[0][0]) if B and B[0] and B[0][0] else 0

        def dimension(name: str, inferred: int) -> int:
            if name not in dims:
                return inferred
            value = dims[name]
            if isinstance(value, bool) or not isinstance(value, int) or value < 0:
                errors.append(f"dimensions.{name} must be a non-negative integer")
                return inferred
            return value

        n_states = dimension("n_states", inferred_states)
        n_obs = dimension("n_obs", inferred_obs)
        n_actions = dimension("n_actions", inferred_actions)
        n_b_states = self._truncated_b_state_count(matrices_json, n_states, errors)

        shapes = matrices_json.get("shapes")
        if not isinstance(shapes, dict):
            errors.append("shapes must be declared as an object")
        else:
            expected_shapes = {
                "A": [n_obs, n_states],
                "B": [n_b_states, n_b_states, n_actions],
                "C": [n_obs],
                "D": [n_states],
            }
            for key, expected in expected_shapes.items():
                actual_shape = shapes.get(key)
                if actual_shape != expected:
                    errors.append(f"declared shape for {key} does not match dimensions")

        for name, value, actual in (
            ("n_states", n_states, len(D)),
            ("n_obs", n_obs, len(C)),
        ):
            if name in dims and actual != value:
                errors.append(
                    f"declared {name}={value} does not match {name} vector length {actual}"
                )
        if "n_states" in dims and A and any(len(row) != n_states for row in A):
            errors.append(f"declared n_states={n_states} does not match A column count")
        if "n_obs" in dims and A and len(A) != n_obs:
            errors.append(f"declared n_obs={n_obs} does not match A row count")
        if (
            "n_actions" in dims
            and B
            and B[0]
            and any(len(cell) != n_actions for row in B for cell in row)
        ):
            errors.append(f"declared n_actions={n_actions} does not match B depth")

        # A: rows == n_obs, cols == n_states, columns sum to 1 (column-stochastic).
        if n_obs > 0 and n_states > 0:
            if len(A) != n_obs:
                errors.append(f"A row count {len(A)} != n_obs {n_obs}")
            elif A and any(len(row) != n_states for row in A):
                errors.append(f"A column count mismatch; expected {n_states}")
            else:
                # Tolerance 1e-6 — stability constant. A-matrix encodes
                # P(o|s) and is column-stochastic (AII/pymdp convention):
                # for each fixed hidden state s (a column), the distribution
                # over observation outcomes sums to 1. float64 accumulation
                # introduces ~n_obs * eps drift; 1e-6 leaves ~8 orders of
                # magnitude headroom and matches the pymdp / scipy convention
                # for stochastic-matrix normalization checks.
                if any(
                    not isinstance(A[i][j], (int, float))
                    or not math.isfinite(float(A[i][j]))
                    or A[i][j] < -1e-9
                    for i in range(len(A))
                    for j in range(n_states)
                ):
                    errors.append("A contains negative probabilities")
                for j in range(n_states):
                    col_sum = sum(A[i][j] for i in range(len(A)))
                    if abs(col_sum - 1.0) > 1e-6:
                        errors.append(f"A column {j} does not sum to 1 (sum={col_sum:.6f})")

        elif A:
            errors.append("A must be empty when observations or hidden states are zero")

        # B: shape n_states x n_states x n_actions (n_states_kept when
        # the top-K truncation was applied).
        if n_states > 0:
            if n_actions == 0 and not B:
                pass
            elif len(B) != n_b_states:
                errors.append(f"B first dim {len(B)} != n_states {n_b_states}")
            elif any(len(row) != n_b_states for row in B):
                errors.append(f"B second dim mismatch; expected {n_b_states}")
            elif any(len(cell) != n_actions for row in B for cell in row):
                errors.append(f"B third dim mismatch; expected {n_actions}")
            else:
                if any(
                    not isinstance(B[i][j][k], (int, float))
                    or not math.isfinite(float(B[i][j][k]))
                    or B[i][j][k] < -1e-9
                    for i in range(n_b_states)
                    for j in range(n_b_states)
                    for k in range(n_actions)
                ):
                    errors.append("B contains negative probabilities")
                for k in range(n_actions):
                    for j in range(n_b_states):
                        col_sum = sum(B[i][j][k] for i in range(n_b_states))
                        if abs(col_sum - 1.0) > 1e-6:
                            errors.append(
                                f"B action {k} column {j} does not sum to 1 (sum={col_sum:.6f})"
                            )

        elif B:
            errors.append("B must be empty when hidden states are zero")

        # C: length n_obs.
        if len(C) != n_obs:
            errors.append(f"C length {len(C)} != n_obs {n_obs}")
        elif any(
            not isinstance(value, (int, float)) or not math.isfinite(float(value)) for value in C
        ):
            errors.append("C contains non-finite values")

        # D: length n_states, sums to 1.
        if len(D) != n_states:
            errors.append(f"D length {len(D)} != n_states {n_states}")
        elif n_states > 0:
            if any(
                not isinstance(value, (int, float))
                or not math.isfinite(float(value))
                or value < -1e-9
                for value in D
            ):
                errors.append("D contains negative probabilities")
            elif D and abs(sum(D) - 1.0) > 1e-6:
                # Tolerance 1e-6 — stability constant, same rationale as
                # A-column tolerance above (pymdp/scipy convention for
                # probability-simplex sum checks; ~8 orders of magnitude
                # headroom over float64 accumulation drift).
                errors.append(f"D does not sum to 1 (sum={sum(D):.6f})")

        return errors

    @staticmethod
    def _truncated_b_state_count(
        matrices_json: dict[str, Any], n_states: int, errors: list[str]
    ) -> int:
        """Return the expected B state-axis length, honouring truncation.

        ``GNNMatrices.compute_B`` keeps only the top-K states when the
        full tensor would exceed its entry cap and records the cut under
        ``truncation``. A truncated B is valid only when the metadata says
        how many states were kept and which full-axis states they are.
        """
        truncation = matrices_json.get("truncation")
        if truncation is None:
            return n_states
        if not isinstance(truncation, dict):
            errors.append("truncation must be an object or null")
            return n_states
        if truncation.get("applied") is not True:
            return n_states
        kept = truncation.get("n_states_kept")
        if isinstance(kept, bool) or not isinstance(kept, int) or not 0 < kept <= n_states:
            errors.append(
                f"truncation.n_states_kept must be an integer in [1, n_states={n_states}]"
            )
            return n_states
        full = truncation.get("n_states_full", n_states)
        if full != n_states:
            errors.append(
                f"truncation.n_states_full={full!r} does not match declared n_states={n_states}"
            )
        indices = truncation.get("kept_state_indices")
        if (
            not isinstance(indices, list)
            or len(indices) != kept
            or any(isinstance(i, bool) or not isinstance(i, int) for i in indices)
            or any(not 0 <= i < n_states for i in indices)
            or indices != sorted(set(indices))
        ):
            errors.append(
                "truncation.kept_state_indices must list n_states_kept distinct, ascending "
                "indices into the hidden-state axis"
            )
        return kept

    def _effective_matrix_dimensions(self, matrices_json: dict[str, Any]) -> dict[str, int]:
        """Return matrix dimensions declared in, or inferred from, A/B/C/D."""
        B = matrices_json.get("B", [])
        C = matrices_json.get("C", [])
        D = matrices_json.get("D", [])
        dims = matrices_json.get("dimensions")
        dims = dims if isinstance(dims, dict) else {}
        n_states = dims.get("n_states", len(D) if isinstance(D, list) else 0)
        n_obs = dims.get("n_obs", len(C) if isinstance(C, list) else 0)
        n_actions = dims.get(
            "n_actions",
            len(B[0][0]) if isinstance(B, list) and B and B[0] and B[0][0] else 0,
        )
        if not all(
            isinstance(value, int) and not isinstance(value, bool)
            for value in (n_states, n_obs, n_actions)
        ):
            return {"n_states": 0, "n_obs": 0, "n_actions": 0}
        return {"n_states": n_states, "n_obs": n_obs, "n_actions": n_actions}

    def _state_space_dimensions(self) -> dict[str, int] | None:
        """Return compiled state-space dimensions from ``state_space.json``."""
        state_space_path = self.package_dir / "state_space.json"
        if not state_space_path.exists():
            return None
        try:
            with open(state_space_path) as f:
                loaded = json.load(f)
        except Exception as exc:
            self.result.warnings.append(f"Matrix validation skipped state-space alignment: {exc}")
            return None
        state_space = loaded if isinstance(loaded, dict) else {}

        def _count(key: str) -> int:
            value = state_space.get(key)
            if isinstance(value, (list, dict)):
                return len(value)
            return 0

        return {
            "n_states": _count("variables"),
            "n_obs": _count("observations"),
            "n_actions": _count("actions"),
        }

    def _matrix_state_space_alignment_errors(
        self,
        matrix_dimensions: dict[str, int],
        state_space_dimensions: dict[str, int] | None,
    ) -> tuple[list[str], dict[str, Any]]:
        """Compare matrix dimensions with compiled state-space dimensions."""
        if state_space_dimensions is None:
            return [], {}

        alignment: dict[str, Any] = {
            "matrix_dimensions": matrix_dimensions,
            "state_space_dimensions": state_space_dimensions,
        }
        errors: list[str] = []
        comparisons = (
            ("n_states", "hidden-state"),
            ("n_obs", "observation"),
            ("n_actions", "action"),
        )
        for key, label in comparisons:
            matrix_value = matrix_dimensions.get(key, 0)
            state_value = state_space_dimensions.get(key, 0)
            match = matrix_value == state_value
            alignment[f"{key}_match"] = match
            if not match:
                errors.append(
                    f"{label} dimension mismatch: matrix {key}={matrix_value} "
                    f"!= state_space {key}={state_value}"
                )
        return errors, alignment

    def _matrix_degenerate_warnings(
        self,
        matrices: dict[str, Any],
        matrix_dimensions: dict[str, int],
        state_space_dimensions: dict[str, int] | None,
    ) -> list[str]:
        """Return non-public warnings for valid but degenerate matrix exports."""
        warnings: list[str] = []
        if state_space_dimensions is None:
            return warnings
        if (
            state_space_dimensions.get("n_obs") == 0
            and matrix_dimensions.get("n_obs") == 0
            and not matrices.get("A")
            and not matrices.get("C")
        ):
            warnings.append(
                "Matrix validation: degenerate model has no observation modalities; "
                "A/C are empty and not publication-ready evidence"
            )
        if (
            state_space_dimensions.get("n_states") == 0
            and matrix_dimensions.get("n_states") == 0
            and (not matrices.get("A") or not matrices.get("B") or not matrices.get("D"))
        ):
            warnings.append(
                "Matrix validation: degenerate model has no hidden-state variables; "
                "A/B/D are empty and not publication-ready evidence"
            )
        return warnings

    def validate_provenance(self, provenance_json: dict[str, Any]) -> list[str]:
        """
        Validate provenance structure.

        Args:
            provenance_json: Provenance JSON.

        Returns:
            List of errors (empty if valid).
        """
        if not isinstance(provenance_json, dict):
            return ["Provenance root must be a JSON object"]
        errors: list[str] = []

        # Check required keys
        required_keys = ["timestamp", "sources"]
        for key in required_keys:
            if key not in provenance_json:
                errors.append(f"Missing provenance key: {key}")

        # Check sources
        sources = provenance_json.get("sources", {})
        if not isinstance(sources, dict):
            errors.append("Provenance sources must be a dict")

        return errors

    def generate_validation_badge(self, result: ValidationResult) -> str:
        """
        Generate SVG validation badge.

        Args:
            result: Validation result.

        Returns:
            SVG string.
        """
        return result.badge_svg()

    # Private validation methods

    def _check_required_files(self) -> None:
        """Check that all required files are present."""
        for filename in self.REQUIRED_FILES:
            filepath = self.package_dir / filename
            if not filepath.exists():
                self.result.errors.append(f"Missing required file: {filename}")
            else:
                logger.debug(f"  ✓ Found {filename}")

    def _check_manifest(self) -> dict[str, Any] | None:
        """Check manifest validity and return parsed manifest."""
        manifest_path = self.package_dir / "manifest.json"
        if not manifest_path.exists():
            self.result.errors.append("Missing manifest.json")
            return None

        try:
            with open(manifest_path) as f:
                loaded = json.load(f)
            if not isinstance(loaded, dict):
                self.result.errors.append("manifest.json must contain a JSON object")
                return None
            manifest = dict(loaded)
            logger.debug("  ✓ manifest.json is valid JSON")
            self.result.details["manifest"] = manifest
            return manifest
        except json.JSONDecodeError as e:
            self.result.errors.append(f"Invalid JSON in manifest.json: {e}")
            return None
        except Exception as e:
            self.result.errors.append(f"Failed to read manifest.json: {e}")
            return None

    def _check_json_files(self) -> None:
        """Check that all JSON files are valid."""
        json_files = [
            filename
            for filename in self.REQUIRED_FILES
            if filename.endswith(".json") and filename != "manifest.json"
        ]

        for filename in json_files:
            filepath = self.package_dir / filename
            if not filepath.exists():
                continue

            try:
                with open(filepath) as f:
                    loaded = json.load(f)
                    if not isinstance(loaded, dict):
                        self.result.errors.append(f"JSON root must be an object in {filename}")
                        continue
                logger.debug(f"  ✓ {filename} is valid JSON")
            except json.JSONDecodeError as e:
                self.result.errors.append(f"Invalid JSON in {filename}: {e}")
            except Exception as e:
                self.result.errors.append(f"Failed to read {filename}: {e}")

    # Best-effort artifacts whose failure GNNPackageBuilder records in
    # ``manifest.artifact_status`` while writing a placeholder JSON payload.
    BEST_EFFORT_ARTIFACTS = ("markov_blanket",)

    def _check_artifact_status(self, manifest: dict[str, Any] | None) -> None:
        """Warn about best-effort artifacts that are placeholders, not evidence.

        ``GNNPackageBuilder`` keeps a package structurally consumable when a
        derived artifact (currently the Markov blanket) cannot be computed:
        it writes a stub payload whose ``metadata`` carries ``error: true`` /
        ``status: "unavailable"`` and records the outcome in
        ``manifest.artifact_status``. The stub is valid JSON, so without this
        check the package would be certified with a full score. Each
        non-``"success"`` artifact becomes a validation warning; the status
        map is stored under ``details["artifact_status"]``.
        """
        statuses: dict[str, str] = {}
        raw_status = manifest.get("artifact_status") if isinstance(manifest, dict) else None
        if isinstance(raw_status, dict):
            statuses = {str(name): str(status) for name, status in raw_status.items()}

        for name in self.BEST_EFFORT_ARTIFACTS:
            metadata = self._artifact_metadata(name)
            stub_status = None
            if metadata.get("error") is True or metadata.get("status") == "unavailable":
                stub_status = str(metadata.get("status") or "unavailable")
            if stub_status and statuses.get(name, "success") == "success":
                # Older or hand-edited manifests may not record the failure;
                # the placeholder payload itself still says it is unavailable.
                statuses[name] = stub_status
            elif name not in statuses and (self.package_dir / f"{name}.json").exists():
                statuses[name] = "success"

        self.result.details["artifact_status"] = statuses
        for name, status in sorted(statuses.items()):
            if status == "success":
                continue
            reason = self._artifact_metadata(name).get("reason")
            suffix = f": {reason}" if reason else ""
            self.result.warnings.append(
                f"Artifact {name} is {status}{suffix}; {name}.json is a placeholder "
                "and not publication-ready evidence"
            )

    def _artifact_metadata(self, name: str) -> dict[str, Any]:
        """Return the ``metadata`` object of ``<name>.json`` (empty if absent)."""
        path = self.package_dir / f"{name}.json"
        try:
            loaded = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, ValueError):
            return {}
        metadata = loaded.get("metadata") if isinstance(loaded, dict) else None
        return metadata if isinstance(metadata, dict) else {}

    def _check_matrices(self) -> None:
        """Validate the exported ``model.gnn.json`` A/B/C/D matrix block."""
        model_path = self.package_dir / "model.gnn.json"
        if not model_path.exists():
            self.result.errors.append("Missing model.gnn.json for matrix validation")
            return

        try:
            with open(model_path) as f:
                loaded = json.load(f)
            model = loaded if isinstance(loaded, dict) else {}
            matrices_raw = model.get("matrices")
            if not isinstance(matrices_raw, dict):
                self.result.errors.append("Missing matrices block in model.gnn.json")
                self.result.details["matrices"] = {
                    "present": False,
                    "validation_errors": ["Missing matrices block in model.gnn.json"],
                }
                return
            matrices = matrices_raw
            errors = self.validate_matrices(matrices)
            matrix_dimensions = self._effective_matrix_dimensions(matrices)
            state_space_dimensions = self._state_space_dimensions()
            alignment_errors, dimension_alignment = self._matrix_state_space_alignment_errors(
                matrix_dimensions,
                state_space_dimensions,
            )
            errors.extend(alignment_errors)
            warnings = self._matrix_degenerate_warnings(
                matrices,
                matrix_dimensions,
                state_space_dimensions,
            )
            self.result.details["matrices"] = {
                "present": True,
                "shapes": matrices.get("shapes")
                if isinstance(matrices.get("shapes"), dict)
                else {},
                "dimensions": (
                    matrices.get("dimensions")
                    if isinstance(matrices.get("dimensions"), dict)
                    else {}
                ),
                "effective_dimensions": matrix_dimensions,
                "state_space_dimensions": state_space_dimensions or {},
                "dimension_alignment": dimension_alignment,
                "truncation": matrices.get("truncation"),
                "matrix_keys": [key for key in ("A", "B", "C", "D") if key in matrices],
                "validation_errors": errors,
                "validation_warnings": warnings,
            }
            self.result.dimensions = {
                "matrices": matrix_dimensions,
                "state_space": state_space_dimensions or {},
                "alignment": dimension_alignment,
            }
            if errors:
                self.result.errors.extend(f"Matrix validation: {error}" for error in errors)
            else:
                logger.debug("  ✓ model.gnn.json matrices are well-formed")
            self.result.warnings.extend(warnings)
        except Exception as e:
            self.result.errors.append(f"Failed to validate model.gnn.json matrices: {e}")

    def _check_markdown(self) -> None:
        """Check markdown validity."""
        markdown_path = self.package_dir / "model.gnn.md"
        if not markdown_path.exists():
            self.result.errors.append("Missing model.gnn.md")
            return

        try:
            markdown = markdown_path.read_text(encoding="utf-8")
            errors = self.validate_markdown(markdown)
            if errors:
                self.result.errors.extend(f"Markdown validation: {error}" for error in errors)
            else:
                logger.debug("  ✓ model.gnn.md has all canonical sections")

            if getattr(self, "_upstream_gnn", False):
                from cogant.gnn.upstream_bridge import run_upstream_validate_gnn

                up = run_upstream_validate_gnn(markdown)
                self.result.details["upstream_gnn"] = up.to_dict()
                self.result.capabilities["upstream_gnn"] = up.to_dict()
                if not up.available:
                    self.result.capabilities["upstream_gnn"] = {
                        **up.to_dict(),
                        "requested": True,
                        "available": False,
                        "error_code": GNNCapabilityError.code,
                    }
                    self.result.errors.append(
                        f"{GNNCapabilityError.code}: requested upstream GNN validation is unavailable: "
                        f"{up.skipped_reason or 'install the cogant[upstream] extra'}"
                    )
                elif not up.ok:
                    self.result.errors.extend(f"[upstream GNN] {err}" for err in up.errors)
        except Exception as e:
            self.result.errors.append(f"Failed to read model.gnn.md: {e}")

    def _check_state_space(self) -> None:
        """Check state space validity."""
        state_space_path = self.package_dir / "state_space.json"
        if not state_space_path.exists():
            self.result.errors.append("Missing state_space.json")
            return

        try:
            with open(state_space_path) as f:
                state_space = json.load(f)
            if not isinstance(state_space, dict):
                self.result.errors.append(
                    "State-space validation: state_space.json root must be an object"
                )
                return
            errors = self.validate_state_space(state_space)
            if errors:
                self.result.errors.extend(f"State-space validation: {error}" for error in errors)
            else:
                logger.debug("  ✓ state_space.json is well-formed")
        except Exception as e:
            self.result.errors.append(f"Failed to validate state_space.json: {e}")

    def _check_provenance(self) -> None:
        """Check provenance validity."""
        provenance_path = self.package_dir / "provenance.json"
        if not provenance_path.exists():
            self.result.errors.append("Missing provenance.json")
            return

        try:
            with open(provenance_path) as f:
                provenance = json.load(f)
            if not isinstance(provenance, dict):
                self.result.errors.append(
                    "Provenance validation: provenance.json root must be an object"
                )
                return
            errors = self.validate_provenance(provenance)
            if errors:
                self.result.errors.extend(f"Provenance validation: {error}" for error in errors)
            else:
                logger.debug("  ✓ provenance.json is well-formed")
        except Exception as e:
            self.result.errors.append(f"Failed to validate provenance.json: {e}")

    def _check_checksums(self, manifest: dict[str, Any]) -> None:
        """Check that checksums match."""
        checksums = manifest.get("checksums")
        if not isinstance(checksums, dict) or not checksums:
            self.result.errors.append("Manifest must contain checksums for evidence validation")
            return

        # The manifest owns this table, so including its own digest would be
        # recursive. Every other required artifact must be covered.
        for required in self.REQUIRED_FILES:
            if required == "manifest.json":
                continue
            if required not in checksums:
                self.result.errors.append(
                    f"Manifest is missing checksum for required file: {required}"
                )

        for filename, expected_checksum in checksums.items():
            if not isinstance(filename, str) or not isinstance(expected_checksum, str):
                self.result.errors.append("Manifest checksums must map string filenames to digests")
                continue
            filepath = (self.package_dir / filename).resolve()
            if self.package_dir.resolve() not in filepath.parents:
                self.result.errors.append(f"Checksum path escapes package directory: {filename}")
                continue
            if not filepath.is_file():
                self.result.errors.append(f"Checksum references missing file: {filename}")
                continue

            try:
                if filepath.suffix == ".json":
                    with open(filepath) as f:
                        data = json.load(f)
                    actual = hashlib.sha256(
                        json.dumps(data, sort_keys=True, default=str).encode()
                    ).hexdigest()
                else:
                    actual = hashlib.sha256(filepath.read_bytes()).hexdigest()

                if actual != expected_checksum:
                    message = (
                        f"Checksum mismatch for {filename}: "
                        f"expected {expected_checksum}, got {actual}"
                    )
                    self.result.errors.append(message)
                else:
                    logger.debug(f"  ✓ {filename} checksum matches")
            except Exception as e:
                message = f"Failed to verify checksum for {filename}: {e}"
                self.result.errors.append(message)

    def _artifact_digests(self) -> dict[str, str]:
        """Return raw SHA-256 digests for every regular package artifact."""
        digests: dict[str, str] = {}
        for path in sorted(self.package_dir.rglob("*")):
            if path.is_file() and path.name != "manifest.json":
                digests[str(path.relative_to(self.package_dir))] = hashlib.sha256(
                    path.read_bytes()
                ).hexdigest()
        return digests

    def _compute_final_score(self) -> None:
        """Compute final validation score and validity.

        The score is a human-readable quality signal only. Certification is
        evidence-based: any hard validation error makes the package invalid,
        while advisories remain visible without being converted into a pass.
        """
        # Keep the score monotonic for reports, but never use it to certify a
        # package. One hard error is enough to invalidate evidence.
        max_points = 100  # percentage scale
        points_per_error = 10  # 10 errors → zero score
        points_per_warning = 2  # 5:1 severity ratio vs. errors

        score = max_points
        score -= len(self.result.errors) * points_per_error
        score -= len(self.result.warnings) * points_per_warning
        score = max(0, min(100, score))

        self.result.score = float(score)
        self.result.valid = len(self.result.errors) == 0

        logger.debug(
            f"  Final score: {self.result.score:.1f}% - {'VALID' if self.result.valid else 'INVALID'}"
        )

__init__()

Initialize validator.

Source code in py/cogant/gnn/validator.py
237
238
239
240
241
242
243
244
245
246
def __init__(self) -> None:
    """Initialize validator."""
    # ``validate_package`` is the single entry point and always
    # reassigns these before they're read. Type-annotating as
    # non-optional avoids a cascade of union-attr noise in the
    # private ``_check_*`` helpers below without hiding any real
    # null-dereference bug (the helpers are never called first).
    self.result: ValidationResult = ValidationResult()
    self.package_dir: Path = Path(".")
    self._upstream_gnn: bool = False

generate_validation_badge(result)

Generate SVG validation badge.

Parameters:

Name Type Description Default
result ValidationResult

Validation result.

required

Returns:

Type Description
str

SVG string.

Source code in py/cogant/gnn/validator.py
855
856
857
858
859
860
861
862
863
864
865
def generate_validation_badge(self, result: ValidationResult) -> str:
    """
    Generate SVG validation badge.

    Args:
        result: Validation result.

    Returns:
        SVG string.
    """
    return result.badge_svg()

validate_markdown(markdown)

Validate GNN markdown structure.

Checks both the COGANT-extended canonical sections (## Model Metadata, ## Source Coverage, ## Markov Blanket, etc.) and the upstream GNN 2.0.0 required headers (## GNNSection, ## StateSpaceBlock, ## Connections, ## InitialParameterization, ## Equations, ## Time, ## ActInfOntologyAnnotation, ## ModelParameters, etc.). Upstream section checks are ordered: they must appear in the spec-mandated order at the TOP of the file.

Parameters:

Name Type Description Default
markdown str

Markdown content.

required

Returns:

Type Description
list[str]

List of errors (empty if valid).

Source code in py/cogant/gnn/validator.py
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
def validate_markdown(self, markdown: str) -> list[str]:
    """
    Validate GNN markdown structure.

    Checks both the COGANT-extended canonical sections
    (``## Model Metadata``, ``## Source Coverage``, ``## Markov
    Blanket``, etc.) and the upstream GNN 2.0.0 required headers
    (``## GNNSection``, ``## StateSpaceBlock``, ``## Connections``,
    ``## InitialParameterization``, ``## Equations``, ``## Time``,
    ``## ActInfOntologyAnnotation``, ``## ModelParameters``, etc.). Upstream section
    checks are ordered: they must appear in the spec-mandated
    order at the TOP of the file.

    Args:
        markdown: Markdown content.

    Returns:
        List of errors (empty if valid).
    """
    errors: list[str] = []
    lowered = markdown.lower()

    # 1) COGANT-extended canonical sections (case-insensitive presence check).
    for section in self.CANONICAL_SECTIONS:
        section_header = f"## {section.replace('_', ' ').title()}"
        if section_header.lower() not in lowered:
            errors.append(f"Missing canonical section: {section}")

    # 2) Upstream GNN 2.0.0 required sections — each must be present.
    missing_upstream: list[str] = []
    upstream_offsets: list[tuple[str, int]] = []
    for section in self.UPSTREAM_SECTIONS:
        marker = f"## {section}"
        idx = markdown.find(marker)
        if idx < 0:
            missing_upstream.append(section)
        else:
            upstream_offsets.append((section, idx))
    for section in missing_upstream:
        errors.append(f"Missing upstream GNN 2.0.0 section: {section}")

    # 3) Upstream sections must appear in canonical order.
    if not missing_upstream and upstream_offsets:
        expected_order = list(self.UPSTREAM_SECTIONS)
        found_order = [section for section, _ in sorted(upstream_offsets, key=lambda x: x[1])]
        if expected_order != found_order:
            errors.append(
                "Upstream GNN 2.0.0 sections out of canonical order: "
                f"found {found_order}, expected {expected_order}"
            )

    return errors

validate_matrices(matrices_json)

Validate the AII Active Inference matrix block.

Checks presence and shape of the A/B/C/D matrices emitted by :class:cogant.gnn.matrices.GNNMatrices. The matrices must satisfy:

  • A: shape [n_obs x n_states], columns sum to 1.0.
  • B: shape [n_states x n_states x n_actions]; when truncation.applied is set (large-repo top-K cut, see :meth:cogant.gnn.matrices.GNNMatrices.compute_B) the state axes are n_states_kept and truncation.kept_state_indices must name those states on the full A/D axis.
  • C: length equal to n_obs.
  • D: length equal to n_states, sums to 1.0.

Parameters:

Name Type Description Default
matrices_json dict[str, Any]

Dict of the form {"A": ..., "B": ..., "C": ..., "D": ..., "dimensions": {"n_states", "n_obs", "n_actions"}}.

required

Returns:

Type Description
list[str]

List of errors (empty if matrices are well-formed).

Source code in py/cogant/gnn/validator.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
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
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
def validate_matrices(self, matrices_json: dict[str, Any]) -> list[str]:
    """Validate the AII Active Inference matrix block.

    Checks presence and shape of the A/B/C/D matrices emitted by
    :class:`cogant.gnn.matrices.GNNMatrices`. The matrices must
    satisfy:

    * A: shape ``[n_obs x n_states]``, columns sum to 1.0.
    * B: shape ``[n_states x n_states x n_actions]``; when
      ``truncation.applied`` is set (large-repo top-K cut, see
      :meth:`cogant.gnn.matrices.GNNMatrices.compute_B`) the state
      axes are ``n_states_kept`` and ``truncation.kept_state_indices``
      must name those states on the full A/D axis.
    * C: length equal to ``n_obs``.
    * D: length equal to ``n_states``, sums to 1.0.

    Args:
        matrices_json: Dict of the form
            ``{"A": ..., "B": ..., "C": ..., "D": ...,
            "dimensions": {"n_states", "n_obs", "n_actions"}}``.

    Returns:
        List of errors (empty if matrices are well-formed).
    """
    errors: list[str] = []

    for key in ("A", "B", "C", "D"):
        if key not in matrices_json:
            errors.append(f"Missing matrix: {key}")

    A = matrices_json.get("A", [])
    B = matrices_json.get("B", [])
    C = matrices_json.get("C", [])
    D = matrices_json.get("D", [])

    if not isinstance(A, list):
        errors.append("A must be a list")
        A = []
    if not isinstance(B, list):
        errors.append("B must be a list")
        B = []
    if not isinstance(C, list):
        errors.append("C must be a list")
        C = []
    if not isinstance(D, list):
        errors.append("D must be a list")
        D = []
    if any(not isinstance(row, list) for row in A):
        errors.append("A rows must be lists")
        A = [row for row in A if isinstance(row, list)]
    if any(not isinstance(row, list) for row in B):
        errors.append("B rows must be lists")
        B = [row for row in B if isinstance(row, list)]
    if any(not isinstance(cell, list) for row in B for cell in row):
        errors.append("B cells must be lists")
        B = [[cell for cell in row if isinstance(cell, list)] for row in B]

    dims = matrices_json.get("dimensions")
    if not isinstance(dims, dict):
        if dims is None:
            errors.append("dimensions must be declared as an object")
        else:
            errors.append("dimensions must be an object")
        dims = {}

    inferred_states = len(D) or (len(A[0]) if A and A[0] else 0)
    inferred_obs = len(A) or len(C)
    inferred_actions = len(B[0][0]) if B and B[0] and B[0][0] else 0

    def dimension(name: str, inferred: int) -> int:
        if name not in dims:
            return inferred
        value = dims[name]
        if isinstance(value, bool) or not isinstance(value, int) or value < 0:
            errors.append(f"dimensions.{name} must be a non-negative integer")
            return inferred
        return value

    n_states = dimension("n_states", inferred_states)
    n_obs = dimension("n_obs", inferred_obs)
    n_actions = dimension("n_actions", inferred_actions)
    n_b_states = self._truncated_b_state_count(matrices_json, n_states, errors)

    shapes = matrices_json.get("shapes")
    if not isinstance(shapes, dict):
        errors.append("shapes must be declared as an object")
    else:
        expected_shapes = {
            "A": [n_obs, n_states],
            "B": [n_b_states, n_b_states, n_actions],
            "C": [n_obs],
            "D": [n_states],
        }
        for key, expected in expected_shapes.items():
            actual_shape = shapes.get(key)
            if actual_shape != expected:
                errors.append(f"declared shape for {key} does not match dimensions")

    for name, value, actual in (
        ("n_states", n_states, len(D)),
        ("n_obs", n_obs, len(C)),
    ):
        if name in dims and actual != value:
            errors.append(
                f"declared {name}={value} does not match {name} vector length {actual}"
            )
    if "n_states" in dims and A and any(len(row) != n_states for row in A):
        errors.append(f"declared n_states={n_states} does not match A column count")
    if "n_obs" in dims and A and len(A) != n_obs:
        errors.append(f"declared n_obs={n_obs} does not match A row count")
    if (
        "n_actions" in dims
        and B
        and B[0]
        and any(len(cell) != n_actions for row in B for cell in row)
    ):
        errors.append(f"declared n_actions={n_actions} does not match B depth")

    # A: rows == n_obs, cols == n_states, columns sum to 1 (column-stochastic).
    if n_obs > 0 and n_states > 0:
        if len(A) != n_obs:
            errors.append(f"A row count {len(A)} != n_obs {n_obs}")
        elif A and any(len(row) != n_states for row in A):
            errors.append(f"A column count mismatch; expected {n_states}")
        else:
            # Tolerance 1e-6 — stability constant. A-matrix encodes
            # P(o|s) and is column-stochastic (AII/pymdp convention):
            # for each fixed hidden state s (a column), the distribution
            # over observation outcomes sums to 1. float64 accumulation
            # introduces ~n_obs * eps drift; 1e-6 leaves ~8 orders of
            # magnitude headroom and matches the pymdp / scipy convention
            # for stochastic-matrix normalization checks.
            if any(
                not isinstance(A[i][j], (int, float))
                or not math.isfinite(float(A[i][j]))
                or A[i][j] < -1e-9
                for i in range(len(A))
                for j in range(n_states)
            ):
                errors.append("A contains negative probabilities")
            for j in range(n_states):
                col_sum = sum(A[i][j] for i in range(len(A)))
                if abs(col_sum - 1.0) > 1e-6:
                    errors.append(f"A column {j} does not sum to 1 (sum={col_sum:.6f})")

    elif A:
        errors.append("A must be empty when observations or hidden states are zero")

    # B: shape n_states x n_states x n_actions (n_states_kept when
    # the top-K truncation was applied).
    if n_states > 0:
        if n_actions == 0 and not B:
            pass
        elif len(B) != n_b_states:
            errors.append(f"B first dim {len(B)} != n_states {n_b_states}")
        elif any(len(row) != n_b_states for row in B):
            errors.append(f"B second dim mismatch; expected {n_b_states}")
        elif any(len(cell) != n_actions for row in B for cell in row):
            errors.append(f"B third dim mismatch; expected {n_actions}")
        else:
            if any(
                not isinstance(B[i][j][k], (int, float))
                or not math.isfinite(float(B[i][j][k]))
                or B[i][j][k] < -1e-9
                for i in range(n_b_states)
                for j in range(n_b_states)
                for k in range(n_actions)
            ):
                errors.append("B contains negative probabilities")
            for k in range(n_actions):
                for j in range(n_b_states):
                    col_sum = sum(B[i][j][k] for i in range(n_b_states))
                    if abs(col_sum - 1.0) > 1e-6:
                        errors.append(
                            f"B action {k} column {j} does not sum to 1 (sum={col_sum:.6f})"
                        )

    elif B:
        errors.append("B must be empty when hidden states are zero")

    # C: length n_obs.
    if len(C) != n_obs:
        errors.append(f"C length {len(C)} != n_obs {n_obs}")
    elif any(
        not isinstance(value, (int, float)) or not math.isfinite(float(value)) for value in C
    ):
        errors.append("C contains non-finite values")

    # D: length n_states, sums to 1.
    if len(D) != n_states:
        errors.append(f"D length {len(D)} != n_states {n_states}")
    elif n_states > 0:
        if any(
            not isinstance(value, (int, float))
            or not math.isfinite(float(value))
            or value < -1e-9
            for value in D
        ):
            errors.append("D contains negative probabilities")
        elif D and abs(sum(D) - 1.0) > 1e-6:
            # Tolerance 1e-6 — stability constant, same rationale as
            # A-column tolerance above (pymdp/scipy convention for
            # probability-simplex sum checks; ~8 orders of magnitude
            # headroom over float64 accumulation drift).
            errors.append(f"D does not sum to 1 (sum={sum(D):.6f})")

    return errors

validate_package(package_dir, *, upstream_gnn=None)

Validate a GNN package.

Parameters:

Name Type Description Default
package_dir str

Path to the package directory.

required
upstream_gnn bool | None

When True, run the Active Inference Institute generalized-notation-notation validator (upstream gnn 4.x, standard level) on model.gnn.md; a requested but unavailable upstream is reported as a capability error. When None, upstream runs only if :envvar:COGANT_ENABLE_UPSTREAM_GNN is truthy (and never when :envvar:COGANT_DISABLE_UPSTREAM_GNN is set).

None

Returns:

Type Description
ValidationResult

ValidationResult object.

Source code in py/cogant/gnn/validator.py
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
def validate_package(
    self,
    package_dir: str,
    *,
    upstream_gnn: bool | None = None,
) -> ValidationResult:
    """
    Validate a GNN package.

    Args:
        package_dir: Path to the package directory.
        upstream_gnn: When True, run the Active Inference Institute
            ``generalized-notation-notation`` validator (upstream ``gnn``
            4.x, ``standard`` level) on ``model.gnn.md``; a requested but
            unavailable upstream is reported as a capability error. When
            ``None``, upstream runs only if
            :envvar:`COGANT_ENABLE_UPSTREAM_GNN` is truthy (and never when
            :envvar:`COGANT_DISABLE_UPSTREAM_GNN` is set).

    Returns:
        ValidationResult object.
    """
    self.package_dir = Path(package_dir)
    self.result = ValidationResult()
    self._upstream_gnn = _resolve_upstream_flag(upstream_gnn)
    self.result.capabilities["upstream_gnn"] = {
        "requested": self._upstream_gnn,
        "available": False,
    }
    try:
        from cogant.parsers.registry import parser_capabilities

        self.result.capabilities["parsers"] = {
            language: capability.__dict__
            for language, capability in parser_capabilities().items()
        }
    except Exception as exc:
        self.result.capabilities["parsers"] = {"error": str(exc)}

    logger.info(
        "Validating GNN package: %s (upstream_gnn=%s)",
        self.package_dir,
        self._upstream_gnn,
    )

    # Check 1: Directory exists
    if not self.package_dir.exists():
        self.result.errors.append(f"Package directory not found: {self.package_dir}")
        self.result.valid = False
        self.result.score = 0.0
        return self.result

    if not self.package_dir.is_dir():
        self.result.errors.append(f"Package path is not a directory: {self.package_dir}")
        self.result.score = 0.0
        return self.result

    self.result.artifact_digests = self._artifact_digests()

    # Check 2: Required files present
    self._check_required_files()

    # Check 3: Manifest valid
    manifest = self._check_manifest()

    # Check 4: JSON files valid
    self._check_json_files()

    # Check 4b: best-effort artifacts the builder could not produce
    self._check_artifact_status(manifest)

    # Check 5: A/B/C/D matrix block valid
    self._check_matrices()

    # Check 6: Markdown valid
    self._check_markdown()

    # Check 7: State space valid
    self._check_state_space()

    # Check 8: Provenance valid
    self._check_provenance()

    # Check 9: Checksums match
    if manifest:
        self._check_checksums(manifest)

    # Compute final score and validity
    self._compute_final_score()

    logger.info(
        "Validation complete: %s (score=%.1f%%, %d errors, %d warnings)",
        self.result.valid,
        self.result.score,
        len(self.result.errors),
        len(self.result.warnings),
    )
    return self.result

validate_provenance(provenance_json)

Validate provenance structure.

Parameters:

Name Type Description Default
provenance_json dict[str, Any]

Provenance JSON.

required

Returns:

Type Description
list[str]

List of errors (empty if valid).

Source code in py/cogant/gnn/validator.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
def validate_provenance(self, provenance_json: dict[str, Any]) -> list[str]:
    """
    Validate provenance structure.

    Args:
        provenance_json: Provenance JSON.

    Returns:
        List of errors (empty if valid).
    """
    if not isinstance(provenance_json, dict):
        return ["Provenance root must be a JSON object"]
    errors: list[str] = []

    # Check required keys
    required_keys = ["timestamp", "sources"]
    for key in required_keys:
        if key not in provenance_json:
            errors.append(f"Missing provenance key: {key}")

    # Check sources
    sources = provenance_json.get("sources", {})
    if not isinstance(sources, dict):
        errors.append("Provenance sources must be a dict")

    return errors

validate_state_space(state_space_json)

Validate state space structure.

Parameters:

Name Type Description Default
state_space_json dict[str, Any]

State space JSON.

required

Returns:

Type Description
list[str]

List of errors (empty if valid).

Source code in py/cogant/gnn/validator.py
400
401
402
403
404
405
406
407
408
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
def validate_state_space(self, state_space_json: dict[str, Any]) -> list[str]:
    """
    Validate state space structure.

    Args:
        state_space_json: State space JSON.

    Returns:
        List of errors (empty if valid).
    """
    if not isinstance(state_space_json, dict):
        return ["State-space root must be a JSON object"]
    errors: list[str] = []

    # Check required keys
    required_keys = ["variables", "observations", "actions", "transitions"]
    for key in required_keys:
        if key not in state_space_json:
            errors.append(f"Missing state space key: {key}")

    # Check variables are well-formed
    variables = state_space_json.get("variables", [])
    if not isinstance(variables, list):
        errors.append("Variables must be a list")
    elif any(not isinstance(item, dict) for item in variables):
        errors.append("Variables entries must be objects")

    # Check observations are well-formed
    observations = state_space_json.get("observations", [])
    if not isinstance(observations, list):
        errors.append("Observations must be a list")
    elif any(not isinstance(item, dict) for item in observations):
        errors.append("Observations entries must be objects")

    # Check actions are well-formed
    actions = state_space_json.get("actions", [])
    if not isinstance(actions, list):
        errors.append("Actions must be a list")
    elif any(not isinstance(item, dict) for item in actions):
        errors.append("Actions entries must be objects")

    # Check transitions are well-formed
    transitions = state_space_json.get("transitions", {})
    if not isinstance(transitions, dict):
        errors.append("Transitions must be a dict")
    else:
        if not isinstance(transitions.get("transition_count"), int):
            errors.append("Transitions must declare an integer transition_count")
        if not isinstance(transitions.get("time_regime"), str) or not transitions.get(
            "time_regime"
        ):
            errors.append("Transitions must declare a non-empty time_regime")

    metadata = state_space_json.get("metadata")
    if metadata is not None:
        if not isinstance(metadata, dict):
            errors.append("State-space metadata must be an object")
        else:
            for key, values in (
                ("num_variables", variables),
                ("num_observations", observations),
                ("num_actions", actions),
            ):
                declared = metadata.get(key)
                if isinstance(values, list) and declared != len(values):
                    errors.append(f"State-space metadata {key} does not match emitted entries")

    return errors

ValidationResult

Result of a GNN package validation.

Source code in py/cogant/gnn/validator.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 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
class ValidationResult:
    """Result of a GNN package validation."""

    def __init__(
        self,
        valid: bool = False,
        errors: list[str] | None = None,
        warnings: list[str] | None = None,
        score: float = 0.0,
        advisories: list[str] | None = None,
        capabilities: dict[str, Any] | None = None,
        artifact_digests: dict[str, str] | None = None,
        dimensions: dict[str, Any] | None = None,
    ):
        """
        Initialize validation result.

        Args:
            valid: Whether package is valid.
            errors: List of error messages.
            warnings: List of warning messages.
            score: Validation score 0-100.
        """
        self.valid = valid
        self.errors: list[str] = errors or []
        self.advisories: list[str] = list(advisories if advisories is not None else warnings or [])
        self.score = score
        self.details: dict[str, Any] = {}
        self.section_scores: dict[str, float] = {}
        self.capabilities: dict[str, Any] = dict(capabilities or {})
        self.artifact_digests: dict[str, str] = dict(artifact_digests or {})
        self.dimensions: dict[str, Any] = dict(dimensions or {})

    @property
    def warnings(self) -> list[str]:
        """Current public view of non-fatal validation advisories."""

        return self.advisories

    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary."""
        return {
            "valid": self.valid,
            "score": self.score,
            "errors": self.errors,
            "warnings": self.advisories,
            "advisories": self.advisories,
            "capabilities": self.capabilities,
            "artifact_digests": self.artifact_digests,
            "dimensions": self.dimensions,
            "details": self.details,
            "section_scores": self.section_scores,
        }

    def to_markdown(self) -> str:
        """Generate a human-readable markdown report.

        Returns:
            A markdown string containing a formatted report of the
            validation result, including scores, errors, warnings,
            and section breakdowns.
        """
        lines: list[str] = []

        # Header
        status = "✓ VALID" if self.valid else "✗ INVALID"
        lines.append("# GNN Validation Report\n")
        lines.append(f"**Status**: {status}\n")
        lines.append(f"**Overall Score**: {self.score:.1f}/100\n")

        # Section scores
        if self.section_scores:
            lines.append("## Section Scores\n")
            for section, score in sorted(self.section_scores.items()):
                bar = "█" * int(score / 10) + "░" * (10 - int(score / 10))
                lines.append(f"- **{section}**: {score:.1f}/100 [{bar}]")
            lines.append("")

        # Errors
        if self.errors:
            lines.append("## Errors\n")
            for err in self.errors:
                lines.append(f"- ❌ {err}")
            lines.append("")

        # Warnings
        if self.warnings:
            lines.append("## Warnings\n")
            for warn in self.warnings:
                lines.append(f"- ⚠ {warn}")
            lines.append("")

        # Details
        if self.details:
            lines.append("## Details\n")
            for key, val in self.details.items():
                if isinstance(val, dict):
                    lines.append(f"### {key}")
                    for k, v in val.items():
                        lines.append(f"- {k}: {v}")
                else:
                    lines.append(f"- **{key}**: {val}")
            lines.append("")

        return "\n".join(lines)

    def badge_svg(self) -> str:
        """Generate SVG badge."""
        status = "VALID" if self.valid else "INVALID"
        return f"""<svg xmlns="http://www.w3.org/2000/svg" width="120" height="20">
  <rect width="120" height="20" fill="#333"/>
  <text x="10" y="15" fill="white" font-size="12" font-family="Arial">
    GNN {status} ({self.score:.0f}%)
  </text>
</svg>"""

warnings property

Current public view of non-fatal validation advisories.

__init__(valid=False, errors=None, warnings=None, score=0.0, advisories=None, capabilities=None, artifact_digests=None, dimensions=None)

Initialize validation result.

Parameters:

Name Type Description Default
valid bool

Whether package is valid.

False
errors list[str] | None

List of error messages.

None
warnings list[str] | None

List of warning messages.

None
score float

Validation score 0-100.

0.0
Source code in py/cogant/gnn/validator.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(
    self,
    valid: bool = False,
    errors: list[str] | None = None,
    warnings: list[str] | None = None,
    score: float = 0.0,
    advisories: list[str] | None = None,
    capabilities: dict[str, Any] | None = None,
    artifact_digests: dict[str, str] | None = None,
    dimensions: dict[str, Any] | None = None,
):
    """
    Initialize validation result.

    Args:
        valid: Whether package is valid.
        errors: List of error messages.
        warnings: List of warning messages.
        score: Validation score 0-100.
    """
    self.valid = valid
    self.errors: list[str] = errors or []
    self.advisories: list[str] = list(advisories if advisories is not None else warnings or [])
    self.score = score
    self.details: dict[str, Any] = {}
    self.section_scores: dict[str, float] = {}
    self.capabilities: dict[str, Any] = dict(capabilities or {})
    self.artifact_digests: dict[str, str] = dict(artifact_digests or {})
    self.dimensions: dict[str, Any] = dict(dimensions or {})

badge_svg()

Generate SVG badge.

Source code in py/cogant/gnn/validator.py
165
166
167
168
169
170
171
172
173
    def badge_svg(self) -> str:
        """Generate SVG badge."""
        status = "VALID" if self.valid else "INVALID"
        return f"""<svg xmlns="http://www.w3.org/2000/svg" width="120" height="20">
  <rect width="120" height="20" fill="#333"/>
  <text x="10" y="15" fill="white" font-size="12" font-family="Arial">
    GNN {status} ({self.score:.0f}%)
  </text>
</svg>"""

to_dict()

Convert to dictionary.

Source code in py/cogant/gnn/validator.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def to_dict(self) -> dict[str, Any]:
    """Convert to dictionary."""
    return {
        "valid": self.valid,
        "score": self.score,
        "errors": self.errors,
        "warnings": self.advisories,
        "advisories": self.advisories,
        "capabilities": self.capabilities,
        "artifact_digests": self.artifact_digests,
        "dimensions": self.dimensions,
        "details": self.details,
        "section_scores": self.section_scores,
    }

to_markdown()

Generate a human-readable markdown report.

Returns:

Type Description
str

A markdown string containing a formatted report of the

str

validation result, including scores, errors, warnings,

str

and section breakdowns.

Source code in py/cogant/gnn/validator.py
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
def to_markdown(self) -> str:
    """Generate a human-readable markdown report.

    Returns:
        A markdown string containing a formatted report of the
        validation result, including scores, errors, warnings,
        and section breakdowns.
    """
    lines: list[str] = []

    # Header
    status = "✓ VALID" if self.valid else "✗ INVALID"
    lines.append("# GNN Validation Report\n")
    lines.append(f"**Status**: {status}\n")
    lines.append(f"**Overall Score**: {self.score:.1f}/100\n")

    # Section scores
    if self.section_scores:
        lines.append("## Section Scores\n")
        for section, score in sorted(self.section_scores.items()):
            bar = "█" * int(score / 10) + "░" * (10 - int(score / 10))
            lines.append(f"- **{section}**: {score:.1f}/100 [{bar}]")
        lines.append("")

    # Errors
    if self.errors:
        lines.append("## Errors\n")
        for err in self.errors:
            lines.append(f"- ❌ {err}")
        lines.append("")

    # Warnings
    if self.warnings:
        lines.append("## Warnings\n")
        for warn in self.warnings:
            lines.append(f"- ⚠ {warn}")
        lines.append("")

    # Details
    if self.details:
        lines.append("## Details\n")
        for key, val in self.details.items():
            if isinstance(val, dict):
                lines.append(f"### {key}")
                for k, v in val.items():
                    lines.append(f"- {k}: {v}")
            else:
                lines.append(f"- **{key}**: {val}")
        lines.append("")

    return "\n".join(lines)

Package builder

cogant.gnn.package

GNN package builder — creates a complete, self-contained GNN model package.

Builds a package with: - manifest.json: metadata and checksums - model.gnn.md: canonical GNN markdown - model.gnn.json: machine-readable model - state_space.json: detailed state space - observations.json: observation modalities - actions.json: actions and policies - transitions.json: transition structure - preferences.json: preferences and constraints - factors.json: factorization structure - provenance.json: full provenance chain - ontology.json: ontology mappings - diagrams/: mermaid diagrams - visualizations/: HTML visualizations

GNNPackageBuilder

Builds a complete, self-contained GNN model package.

Source code in py/cogant/gnn/package.py
  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
  78
  79
  80
  81
  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
 403
 404
 405
 406
 407
 408
 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
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 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
 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
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 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
 974
 975
 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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
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
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
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
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
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
class GNNPackageBuilder:
    """Builds a complete, self-contained GNN model package."""

    PACKAGE_VERSION = "1.0.0"
    REQUIRED_FILES = [
        "manifest.json",
        "model.gnn.md",
        "model.gnn.json",
        "state_space.json",
        "observations.json",
        "actions.json",
        "transitions.json",
        "preferences.json",
        "factors.json",
        "provenance.json",
        "ontology.json",
        "actions_policies.json",
        "connections.json",
        "preferences_constraints.json",
        "markov_blanket.json",
        "markov_network.json",
    ]

    def __init__(
        self,
        graph: ProgramGraph,
        state_space: StateSpaceModel,
        process_model: ProcessModel,
        mappings: dict[str, Any],
        config: dict[str, Any] | None = None,
    ):
        """
        Initialize the GNN package builder.

        Args:
            graph: Program graph.
            state_space: State space model.
            process_model: Process model.
            mappings: Semantic mappings.
            config: Optional configuration dictionary.
        """
        self.graph = graph
        self.state_space = state_space
        self.process_model = process_model
        self.mappings = mappings
        self.config = config or {}
        self.timestamp = datetime.now(UTC).isoformat()
        self.checksums: dict[str, str] = {}
        self.artifact_warnings: list[str] = []

    def build(self, output_dir: str) -> dict[str, Any]:
        """
        Build the complete GNN package.

        Args:
            output_dir: Directory to create the package in.

        Returns:
            Manifest dictionary with package metadata and checksums.
        """
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        logger.info(
            "Building GNN package in %s (%d nodes, %d edges, %d mappings)",
            output_path,
            len(self.graph.nodes),
            len(self.graph.edges),
            len(self.mappings) if isinstance(self.mappings, dict) else 0,
        )

        try:
            # 1. Generate core model files
            self._generate_markdown(output_path)
            self._generate_json_model(output_path)
            self._generate_state_space(output_path)
            self._generate_observations(output_path)
            self._generate_actions(output_path)
            self._generate_transitions(output_path)
            self._generate_preferences(output_path)
            self._generate_factors(output_path)
            self._generate_provenance(output_path)
            self._generate_ontology(output_path)

            # 2. Generate canonical section JSON files
            self._generate_actions_policies(output_path)
            self._generate_connections(output_path)
            self._generate_preferences_constraints(output_path)

            # 2b. Generate Markov blanket artifacts (Active Inference partition)
            self._generate_markov_blanket(output_path)

            # 2c. Dump the typed program graph as JSON so PNG rasterizers can
            # rebuild a NetworkX view without re-running the pipeline.
            self._generate_program_graph_json(output_path)

            # 2d. Dump the ProcessModel as JSON so ``render_all_pngs`` can
            # rasterize a Gantt timeline without re-running ProcessExtractor.
            self._generate_process_model_json(output_path)

            # 3. Generate diagrams
            self._generate_diagrams(output_path)

            # 4. Generate visualizations
            self._generate_visualizations(output_path)

            # 5. Create manifest
            manifest = self._create_manifest(output_path)

            # Summarize role distribution across semantic mappings
            role_dist: dict[str, int] = {}
            if isinstance(self.mappings, dict):
                for m in self.mappings.values():
                    kind = getattr(m, "kind", None)
                    label = kind.value if hasattr(kind, "value") else str(kind or "unknown")
                    role_dist[label] = role_dist.get(label, 0) + 1

            role_summary = (
                f" | roles={', '.join(f'{k}={v}' for k, v in sorted(role_dist.items()))}"
                if role_dist
                else ""
            )
            n_vars = (
                len(self.state_space.variables) if hasattr(self.state_space, "variables") else 0
            )
            n_obs = (
                len(self.state_space.observations)
                if hasattr(self.state_space, "observations")
                else 0
            )
            n_actions = len(self.state_space.actions) if hasattr(self.state_space, "actions") else 0

            logger.info(
                "GNN package built: %d files | state_space=%d vars, %d obs, %d actions%s",
                len(self.checksums),
                n_vars,
                n_obs,
                n_actions,
                role_summary,
            )
            return manifest

        except Exception as e:
            logger.error(f"Failed to build GNN package: {e}", exc_info=True)
            raise

    def _generate_markdown(self, output_path: Path) -> None:
        """Generate canonical GNN markdown."""
        try:
            formatter = GNNMarkdownFormatter(
                self.graph, self.state_space, self.process_model, self.mappings
            )
            markdown = formatter.format()
            markdown_path = output_path / "model.gnn.md"
            markdown_path.write_text(markdown, encoding="utf-8")
            self.checksums["model.gnn.md"] = self._checksum(markdown)
            logger.info(f"Generated {markdown_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate markdown: {e}", exc_info=True)
            raise

    def _generate_json_model(self, output_path: Path) -> None:
        """Generate machine-readable GNN JSON model."""
        try:
            exporter = GNNJSONExporter(
                self.graph, self.state_space, self.process_model, self.mappings
            )
            json_data = exporter.export()
            json_path = output_path / "model.gnn.json"
            json_path.write_text(json.dumps(json_data, indent=2, default=str), encoding="utf-8")
            self.checksums["model.gnn.json"] = self._checksum_dict(json_data)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate JSON model: {e}", exc_info=True)
            raise

    def _generate_state_space(self, output_path: Path) -> None:
        """Generate detailed state space JSON."""
        try:
            state_space_data = {
                "variables": self._extract_state_variables(),
                "observations": self._extract_observation_space(),
                "actions": self._extract_action_space(),
                "transitions": self._extract_transition_structure(),
                "metadata": {
                    "num_variables": len(self.state_space.variables)
                    if hasattr(self.state_space, "variables")
                    else 0,
                    "num_observations": len(self.state_space.observations)
                    if hasattr(self.state_space, "observations")
                    else 0,
                    "num_actions": len(self.state_space.actions)
                    if hasattr(self.state_space, "actions")
                    else 0,
                },
            }
            json_path = output_path / "state_space.json"
            json_path.write_text(json.dumps(state_space_data, indent=2), encoding="utf-8")
            self.checksums["state_space.json"] = self._checksum_dict(state_space_data)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate state space: {e}", exc_info=True)
            # Derived package sections are best-effort.  The manifest records
            # the files that were actually emitted, so callers can distinguish
            # an incomplete optional export from a valid complete package.
            return

    def _generate_observations(self, output_path: Path) -> None:
        """Generate observation modalities JSON."""
        try:
            observations = {
                "modalities": self._extract_observation_modalities(),
                "count": len(self.state_space.observations)
                if hasattr(self.state_space, "observations")
                else 0,
            }
            json_path = output_path / "observations.json"
            json_path.write_text(json.dumps(observations, indent=2), encoding="utf-8")
            self.checksums["observations.json"] = self._checksum_dict(observations)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate observations: {e}", exc_info=True)
            return

    def _generate_actions(self, output_path: Path) -> None:
        """Generate actions and policies JSON."""
        try:
            actions = {
                "actions": self._extract_actions(),
                "policies": self._extract_policies(),
                "count": len(self.state_space.actions)
                if hasattr(self.state_space, "actions")
                else 0,
            }
            json_path = output_path / "actions.json"
            json_path.write_text(json.dumps(actions, indent=2), encoding="utf-8")
            self.checksums["actions.json"] = self._checksum_dict(actions)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate actions: {e}", exc_info=True)
            return

    def _generate_transitions(self, output_path: Path) -> None:
        """Generate transition structure JSON."""
        try:
            transitions = {
                "structure": self._extract_transition_structure(),
                "deterministic": self._is_deterministic(),
                "markovian": self._is_markovian(),
            }
            json_path = output_path / "transitions.json"
            json_path.write_text(json.dumps(transitions, indent=2), encoding="utf-8")
            self.checksums["transitions.json"] = self._checksum_dict(transitions)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate transitions: {e}", exc_info=True)
            return

    def _generate_preferences(self, output_path: Path) -> None:
        """Generate preferences and constraints JSON."""
        try:
            preferences = {
                "preferences": self._extract_preferences(),
                "constraints": self._extract_constraints(),
                "objectives": self._extract_objectives(),
            }
            json_path = output_path / "preferences.json"
            json_path.write_text(json.dumps(preferences, indent=2), encoding="utf-8")
            self.checksums["preferences.json"] = self._checksum_dict(preferences)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate preferences: {e}", exc_info=True)
            return

    def _generate_factors(self, output_path: Path) -> None:
        """Generate factorization structure JSON."""
        try:
            factors = {
                "factorization": self._extract_factorization(),
                "factors": self._extract_factor_list(),
            }
            json_path = output_path / "factors.json"
            json_path.write_text(json.dumps(factors, indent=2), encoding="utf-8")
            self.checksums["factors.json"] = self._checksum_dict(factors)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate factors: {e}", exc_info=True)
            return

    def _generate_provenance(self, output_path: Path) -> None:
        """Generate full provenance chain JSON."""
        try:
            provenance = {
                "timestamp": self.timestamp,
                "graph_nodes": self._count_graph_nodes(),
                "graph_edges": self._count_graph_edges(),
                "state_space_elements": self._count_state_space_elements(),
                "semantic_mappings": len(self.mappings) if isinstance(self.mappings, dict) else 0,
                "sources": self._extract_source_evidence(),
            }
            json_path = output_path / "provenance.json"
            json_path.write_text(json.dumps(provenance, indent=2, default=str), encoding="utf-8")
            self.checksums["provenance.json"] = self._checksum_dict(provenance)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate provenance: {e}", exc_info=True)
            return

    def _generate_ontology(self, output_path: Path) -> None:
        """Generate ontology mappings JSON."""
        try:
            ontology = {
                "mappings": self._extract_ontology_mappings(),
                "classes": self._extract_classes(),
                "relationships": self._extract_relationships(),
            }
            json_path = output_path / "ontology.json"
            json_path.write_text(json.dumps(ontology, indent=2), encoding="utf-8")
            self.checksums["ontology.json"] = self._checksum_dict(ontology)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate ontology: {e}", exc_info=True)
            return

    def _generate_actions_policies(self, output_path: Path) -> None:
        """Generate canonical actions and policies JSON."""
        try:
            actions_policies = {
                "actions": self._extract_actions(),
                "policies": self._extract_policies(),
                "count": len(self.state_space.actions)
                if hasattr(self.state_space, "actions")
                else 0,
            }
            json_path = output_path / "actions_policies.json"
            json_path.write_text(json.dumps(actions_policies, indent=2), encoding="utf-8")
            self.checksums["actions_policies.json"] = self._checksum_dict(actions_policies)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate actions_policies: {e}", exc_info=True)
            return

    def _generate_connections(self, output_path: Path) -> None:
        """Generate connections (graph edges) JSON."""
        try:
            connections = {
                "edges": self._extract_relationships(),
                "count": len(self.graph.edges)
                if self.graph and hasattr(self.graph, "edges")
                else 0,
                "by_kind": self._count_edges_by_kind(),
            }
            json_path = output_path / "connections.json"
            json_path.write_text(json.dumps(connections, indent=2), encoding="utf-8")
            self.checksums["connections.json"] = self._checksum_dict(connections)
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate connections: {e}", exc_info=True)
            return

    def _generate_preferences_constraints(self, output_path: Path) -> None:
        """Generate canonical preferences and constraints JSON."""
        try:
            preferences_constraints = {
                "preferences": self._extract_preferences(),
                "constraints": self._extract_constraints(),
                "objectives": self._extract_objectives(),
            }
            json_path = output_path / "preferences_constraints.json"
            json_path.write_text(json.dumps(preferences_constraints, indent=2), encoding="utf-8")
            self.checksums["preferences_constraints.json"] = self._checksum_dict(
                preferences_constraints
            )
            logger.info(f"Generated {json_path.name}")
        except Exception as e:
            logger.error(f"Failed to generate preferences_constraints: {e}", exc_info=True)
            return

    def _generate_markov_blanket(self, output_path: Path) -> None:
        """Compute and serialize the Active-Inference Markov blanket.

        Produces two artifacts in the bundle:

        * ``markov_blanket.json`` — full per-node role assignment
          (internal μ / sensory s / active a / external η) with the
          strategy metadata and per-node rationale from
          :func:`cogant.markov.blanket.serialize_blanket`.
        * ``markov_network.json`` — collapsed four-role aggregate
          network with per-EdgeKind breakdowns from
          :func:`cogant.markov.network.build_blanket_network`.

        The seed strategy is driven by ``self.config``:
          - ``config["markov_blanket"]["strategy"]`` — default ``"auto"``.
          - ``config["markov_blanket"]["module_names"]`` — list of module
            names when strategy is ``"module"``.
          - ``config["markov_blanket"]["mapping_kinds"]`` — list of
            mapping kinds when strategy is ``"mapping_kind"``.

        If no semantic mappings are present, the extractor uses its explicit
        configured strategy against the real graph. Generation is
        best-effort: on failure the package still builds, but both files
        are written as explicit ``status: "unavailable"`` placeholders, the
        manifest records ``artifact_status.markov_blanket = "unavailable"``
        plus a warning, and :class:`GNNValidator` reports the placeholder
        as a validation warning so it is never mistaken for evidence.
        """
        mb_cfg = self.config.get("markov_blanket", {}) if isinstance(self.config, dict) else {}
        strategy = mb_cfg.get("strategy", "auto")
        module_names = mb_cfg.get("module_names")
        mapping_kinds = mb_cfg.get("mapping_kinds", ["hidden_state"])

        try:
            if self.graph is None:
                raise ValueError("no program graph available")

            extractor = MarkovBlanketExtractor(self.graph)

            kwargs = {"strategy": strategy}
            if strategy == "module" and module_names:
                kwargs["module_names"] = list(module_names)
            elif strategy == "mapping_kind":
                kwargs["mapping_kinds"] = list(mapping_kinds)
                kwargs["semantic_mappings"] = self.mappings or {}
            elif strategy == "explicit":
                kwargs["seeds"] = mb_cfg.get("seeds") or []

            blanket = extractor.extract(**kwargs)
            network = build_blanket_network(self.graph, blanket)

            blanket_payload = serialize_blanket(
                blanket,
                self.graph,
                include_rationale=mb_cfg.get("include_rationale", True),
                max_nodes_per_role=mb_cfg.get("max_nodes_per_role"),
            )
            network_payload = network.to_dict()

            blanket_path = output_path / "markov_blanket.json"
            network_path = output_path / "markov_network.json"
            blanket_path.write_text(json.dumps(blanket_payload, indent=2), encoding="utf-8")
            network_path.write_text(json.dumps(network_payload, indent=2), encoding="utf-8")
            self.checksums["markov_blanket.json"] = self._checksum_dict(blanket_payload)
            self.checksums["markov_network.json"] = self._checksum_dict(network_payload)

            # Also emit Mermaid diagrams:
            #   - markov_blanket.mmd: the collapsed four-role view.
            #   - markov_blanket_detail.mmd: member-level detail view
            #     with nodes grouped per role and styled by role class.
            diag_dir = output_path / "diagrams"
            diag_dir.mkdir(parents=True, exist_ok=True)
            mmd = network.to_mermaid()
            (diag_dir / "markov_blanket.mmd").write_text(mmd, encoding="utf-8")

            try:
                from cogant.viz.boundary import BoundaryMapper

                bm = BoundaryMapper()
                detail_mmd = bm.markov_blanket_detailed_mermaid(
                    self.graph, blanket=blanket, max_per_role=12
                )
                (diag_dir / "markov_blanket_detail.mmd").write_text(detail_mmd, encoding="utf-8")
            except Exception as e:
                raise RuntimeError("failed to render detailed Markov blanket diagram") from e

            logger.info(
                "Generated markov_blanket.json (strategy=%s, internal=%d, boundary=%d, external=%d)",
                strategy,
                blanket.stats.get("internal_count", 0),
                blanket.stats.get("sensory_count", 0) + blanket.stats.get("active_count", 0),
                blanket.stats.get("external_count", 0),
            )
        except Exception as e:
            # The Markov blanket is a derived diagnostic artifact.  Keep the
            # package structurally consumable when it cannot be computed, but
            # emit an explicit unavailable payload and manifest warning so a
            # validator/publication gate cannot mistake the stub for evidence.
            reason = str(e)
            warning = f"markov blanket unavailable: {reason}"
            self.artifact_warnings.append(warning)
            logger.warning("%s", warning)
            error_payload = {
                "schema_version": "1.0",
                "metadata": {
                    "error": True,
                    "status": "unavailable",
                    "reason": reason,
                },
                "error": reason,
                "roles": {
                    "internal": [],
                    "sensory": [],
                    "active": [],
                    "external": [],
                },
            }
            network_payload = {
                "schema_version": "1.0",
                "metadata": {"error": True, "status": "unavailable", "reason": reason},
                "nodes": [],
                "edges": [],
            }
            for filename, payload in (
                ("markov_blanket.json", error_payload),
                ("markov_network.json", network_payload),
            ):
                path = output_path / filename
                path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
                self.checksums[filename] = self._checksum_dict(payload)

    def _generate_program_graph_json(self, output_path: Path) -> None:
        """Dump the typed ``ProgramGraph`` as a JSON sidecar.

        This is the canonical input for :func:`cogant.viz.png.render_program_graph_png`
        and guarantees that any consumer of a COGANT GNN package (``cogant validate``,
        ``cogant viz``, downstream tooling) can rebuild a NetworkX view of the
        repo without re-running the pipeline.
        """
        try:
            from cogant.api.orchestration import program_graph_to_dict

            data = program_graph_to_dict(self.graph)
            path = output_path / "program_graph.json"
            path.write_text(json.dumps(data, indent=2, default=str), encoding="utf-8")
            self.checksums["program_graph.json"] = self._checksum_dict(data)
            logger.info("Generated program_graph.json")
        except Exception as e:  # noqa: BLE001
            logger.error(f"Could not generate program_graph.json: {e}", exc_info=True)
            return

    def _generate_process_model_json(self, output_path: Path) -> None:
        """Dump the ``ProcessModel`` as a JSON sidecar.

        Mirrors ``_generate_program_graph_json``: gives consumers (notably
        ``render_all_pngs`` → ``render_process_gantt_png``) a standalone file
        to load without re-running ``ProcessExtractor``. The shape matches
        what :func:`cogant.viz.png._load_process_model_from_json`
        expects: ``process_id``, ``stages``, ``policies``, ``timelines``.
        """
        if self.process_model is None:
            return
        try:

            def _to_dict(obj: Any) -> Any:
                if obj is None:
                    return None
                if hasattr(obj, "model_dump"):
                    return obj.model_dump()
                if hasattr(obj, "__dict__"):
                    return {k: _to_dict(v) for k, v in vars(obj).items()}
                if isinstance(obj, list | tuple):
                    return [_to_dict(v) for v in obj]
                if isinstance(obj, dict):
                    return {k: _to_dict(v) for k, v in obj.items()}
                return obj

            data = {
                "process_id": getattr(self.process_model, "process_id", None)
                or getattr(self.process_model, "id", None),
                "stages": [_to_dict(s) for s in getattr(self.process_model, "stages", []) or []],
                "policies": [
                    _to_dict(p) for p in getattr(self.process_model, "policies", []) or []
                ],
                "timelines": [
                    _to_dict(t) for t in getattr(self.process_model, "timelines", []) or []
                ],
                "connections": [
                    _to_dict(c) for c in getattr(self.process_model, "connections", []) or []
                ],
            }
            path = output_path / "process_model.json"
            path.write_text(json.dumps(data, indent=2, default=str), encoding="utf-8")
            self.checksums["process_model.json"] = self._checksum_dict(data)
            logger.info("Generated process_model.json")
        except Exception as e:  # noqa: BLE001
            logger.warning(f"Could not generate process_model.json: {e}")

    def _generate_diagrams(self, output_path: Path) -> None:
        """Generate mermaid diagrams driven by the real graph and state space.

        Uses ``cogant.viz.mermaid.MermaidGenerator`` so that diagrams reflect
        actual classes, modules, transitions, and processes — not hand-coded
        placeholders.
        """
        from cogant.viz.mermaid import MermaidGenerator

        diagrams_dir = output_path / "diagrams"
        diagrams_dir.mkdir(exist_ok=True)
        gen = MermaidGenerator()

        try:
            diagrams = {
                "class_diagram.mermaid": gen.generate_class_diagram(self.graph),
                "state_diagram.mermaid": gen.generate_state_diagram(self.state_space),
                "sequence_diagram.mermaid": gen.generate_sequence_diagram(
                    process_model=self.process_model, graph=self.graph
                ),
                "dependency_diagram.mermaid": gen.generate_dependency_graph(self.graph),
                "active_inference_diagram.mermaid": gen.generate_active_inference_diagram(
                    self.state_space
                ),
            }

            for filename, content in diagrams.items():
                filepath = diagrams_dir / filename
                filepath.write_text(content, encoding="utf-8")
                self.checksums[f"diagrams/{filename}"] = self._checksum(content)
                logger.info(f"Generated {filename}")
        except Exception as e:
            logger.error(f"Failed to generate diagrams: {e}", exc_info=True)
            return

    def _generate_visualizations(self, output_path: Path) -> None:
        """Generate HTML visualizations using the real plotting modules.

        Uses ``cogant.viz.plots.StaticPlotter`` to render the node-type,
        edge-type, and confidence distributions, and the dashboard
        renderer to produce a populated dashboard.html.
        """
        from cogant.viz.plots import StaticPlotter

        viz_dir = output_path / "visualizations"
        viz_dir.mkdir(exist_ok=True)

        try:
            dashboard = self._generate_dashboard_html()
            dashboard_path = viz_dir / "dashboard.html"
            dashboard_path.write_text(dashboard, encoding="utf-8")
            self.checksums["visualizations/dashboard.html"] = self._checksum(dashboard)
            logger.info("Generated dashboard.html")

            charts_dir = viz_dir / "charts"
            charts_dir.mkdir(exist_ok=True)

            plotter = StaticPlotter()
            charts: dict[str, str] = {}
            try:
                charts["node_dist.html"] = plotter.plot_node_type_distribution(self.graph)
            except Exception as e:
                logger.info("node_dist plot unavailable; using deterministic SVG renderer: %s", e)
                charts["node_dist.html"] = self._render_distribution_chart(
                    "Node distribution", self._count_nodes_by_kind()
                )
            try:
                charts["edge_dist.html"] = plotter.plot_edge_type_distribution(self.graph)
            except Exception as e:
                logger.info("edge_dist plot unavailable; using deterministic SVG renderer: %s", e)
                charts["edge_dist.html"] = self._render_distribution_chart(
                    "Edge distribution", self._count_edges_by_kind()
                )
            try:
                charts["confidence.html"] = plotter.plot_confidence_distribution(
                    self.mappings if isinstance(self.mappings, dict) else {}
                )
            except Exception as e:
                logger.info("confidence plot unavailable; using deterministic SVG renderer: %s", e)
                charts["confidence.html"] = self._render_distribution_chart(
                    "Confidence distribution",
                    self._count_mappings_by_tier(),
                )

            for filename, content in charts.items():
                filepath = charts_dir / filename
                filepath.write_text(content, encoding="utf-8")
                self.checksums[f"visualizations/charts/{filename}"] = self._checksum(content)
                logger.info(f"Generated {filename}")
        except Exception as e:
            logger.error(f"Failed to generate visualizations: {e}", exc_info=True)
            return

    def _count_nodes_by_kind(self) -> dict[str, int]:
        """Count nodes by kind for deterministic chart rendering."""
        from collections import defaultdict

        counts: dict[str, int] = defaultdict(int)
        if self.graph and hasattr(self.graph, "nodes"):
            for node in self.graph.nodes.values():
                counts[str(node.kind)] += 1
        return dict(counts)

    def _count_mappings_by_tier(self) -> dict[str, int]:
        """Count semantic mappings by confidence tier."""
        from collections import defaultdict

        counts: dict[str, int] = defaultdict(int)
        if not isinstance(self.mappings, dict):
            return {}
        for m in self.mappings.values():
            tier = getattr(m, "confidence_tier", None)
            label = tier.value if hasattr(tier, "value") else str(tier or "unknown")  # type: ignore[union-attr]
            counts[label] += 1
        return dict(counts)

    def _render_distribution_chart(self, title: str, counts: dict[str, int]) -> str:
        """Render a tiny SVG bar chart from a counts dict.

        Used when the StaticPlotter raises (e.g. matplotlib unavailable
        in the runtime environment). The output is a self-contained HTML
        document with an inline SVG so it never depends on external
        assets.
        """
        max_v = max(counts.values()) if counts else 1
        bar_w = 40
        gap = 12
        chart_h = 200
        x = gap
        bars: list[str] = []
        labels: list[str] = []
        for key, value in sorted(counts.items(), key=lambda kv: -kv[1]):
            bar_h = int((value / max_v) * (chart_h - 30)) if max_v else 0
            y = chart_h - bar_h - 20
            bars.append(
                f'<rect x="{x}" y="{y}" width="{bar_w}" height="{bar_h}" '
                f'fill="#4682B4" stroke="#1e3f6b"/>'
                f'<text x="{x + bar_w / 2}" y="{y - 4}" font-size="10" '
                f'text-anchor="middle">{value}</text>'
            )
            labels.append(
                f'<text x="{x + bar_w / 2}" y="{chart_h - 4}" font-size="9" '
                f'text-anchor="middle" transform="rotate(-15 {x + bar_w / 2} {chart_h - 4})">{key}</text>'
            )
            x += bar_w + gap
        width = max(x + gap, 200)
        return (
            "<!DOCTYPE html><html><head><title>"
            + title
            + '</title></head><body><h1 style="font-family:Arial">'
            + title
            + f'</h1><svg width="{width}" height="{chart_h + 20}" xmlns="http://www.w3.org/2000/svg" '
            + 'style="font-family:Arial">'
            + "".join(bars)
            + "".join(labels)
            + "</svg></body></html>"
        )

    def _create_manifest(self, output_path: Path) -> dict[str, Any]:
        """Create and save the package manifest."""
        manifest = {
            "version": self.PACKAGE_VERSION,
            "timestamp": self.timestamp,
            "package_path": str(output_path),
            "checksums": self.checksums,
            "files": list(self.checksums.keys()),
            "graph_stats": {
                "nodes": self._count_graph_nodes(),
                "edges": self._count_graph_edges(),
            },
            "state_space_stats": self._count_state_space_elements(),
            "semantic_mappings_count": len(self.mappings) if isinstance(self.mappings, dict) else 0,
            "artifact_status": {
                "markov_blanket": "unavailable"
                if any("markov blanket unavailable:" in item for item in self.artifact_warnings)
                else "success"
            },
            "warnings": list(self.artifact_warnings),
        }

        manifest_path = output_path / "manifest.json"
        manifest_path.write_text(json.dumps(manifest, indent=2, default=str), encoding="utf-8")
        logger.info("Generated manifest.json")

        return manifest

    # Data extraction helpers

    def _state_var_object(self, var_id: str) -> Any | None:
        """Resolve a state-space variable id back to its full object.

        ``StateSpaceModel.variables`` is a ``dict[str, StateVariable]``
        keyed by variable id. This helper returns the ``StateVariable``
        for *var_id*, or ``None`` when the id is unknown or the state
        space only carries bare string ids (duck-typed stand-ins).
        """
        variables = getattr(self.state_space, "variables", None)
        if isinstance(variables, dict):
            obj = variables.get(var_id)
            if obj is not None and not isinstance(obj, str):
                return obj
        return None

    def _action_object(self, action_id: str) -> Any | None:
        """Resolve an action id back to its full ``Action`` object."""
        actions = getattr(self.state_space, "actions", None)
        if isinstance(actions, dict):
            return actions.get(action_id)
        return None

    def _extract_state_variables(self) -> list[dict[str, Any]]:
        """Extract state variables with type/cardinality/source info."""
        out: list[dict[str, Any]] = []
        for var_id in getattr(self.state_space, "variables", []) or []:
            obj = self._state_var_object(var_id)
            if obj is None:
                out.append({"id": str(var_id), "name": str(var_id), "type": "variable"})
                continue
            node_id = getattr(obj, "node_id", None)
            out.append(
                {
                    "id": getattr(obj, "id", str(var_id)),
                    "name": getattr(obj, "name", str(var_id)),
                    "var_type": getattr(getattr(obj, "var_type", None), "value", None)
                    or str(getattr(obj, "var_type", "")),
                    "cardinality": getattr(obj, "cardinality", None),
                    "domain": getattr(obj, "domain", None),
                    "factors": list(getattr(obj, "factors", None) or []),
                    "is_discrete": getattr(obj, "is_discrete", None),
                    "observable": getattr(obj, "observable", False),
                    "description": getattr(obj, "description", "") or "",
                    "node_id": node_id,
                    "source_node_ids": [node_id] if node_id else [],
                    "confidence": _enum_value(getattr(obj, "confidence", None)),
                }
            )
        return out

    def _extract_observation_space(self) -> list[dict[str, Any]]:
        """Extract observation space with full modality info."""
        out: list[dict[str, Any]] = []
        observations = getattr(self.state_space, "observations", None)
        if observations is None:
            return out
        if isinstance(observations, dict):
            iterable = observations.values()
        else:
            iterable = observations
        for obs in iterable:
            if hasattr(obs, "name"):
                # ``ObservationModality`` names its channel class
                # ``modality_type``; ``modality`` is kept as the emitted key
                # (and accepted from duck-typed inputs) for compatibility.
                modality = (
                    getattr(obs, "modality_type", None)
                    or getattr(obs, "modality", None)
                    or "symbolic"
                )
                out.append(
                    {
                        "id": getattr(obs, "id", str(obs)),
                        "name": getattr(obs, "name", ""),
                        "modality": str(modality),
                        "modality_type": str(modality),
                        "source_node_id": getattr(obs, "source_node_id", None),
                        "cardinality": getattr(obs, "cardinality", None),
                        "values": getattr(obs, "values", None),
                        "source_channels": getattr(obs, "source_channels", []) or [],
                        "description": getattr(obs, "description", ""),
                        "confidence": _enum_value(getattr(obs, "confidence", None)),
                    }
                )
            else:
                out.append({"id": str(obs), "name": str(obs), "modality": "symbolic"})
        return out

    def _extract_action_space(self) -> list[dict[str, Any]]:
        """Extract action space with controllers and effects."""
        out: list[dict[str, Any]] = []
        actions = getattr(self.state_space, "actions", None)
        if actions is None:
            return out
        iterable = actions.values() if isinstance(actions, dict) else actions
        for action in iterable:
            if hasattr(action, "name"):
                out.append(
                    {
                        "id": getattr(action, "id", str(action)),
                        "name": getattr(action, "name", ""),
                        "controller_id": getattr(action, "controller_id", None),
                        "parameters": getattr(action, "parameters", []) or [],
                        "effects": list(
                            getattr(action, "effects", None)
                            or getattr(action, "affects_state_vars", None)
                            or []
                        ),
                        "preconditions": list(getattr(action, "preconditions", None) or []),
                        "description": getattr(action, "description", ""),
                        "confidence": _enum_value(getattr(action, "confidence", None)),
                    }
                )
            else:
                out.append({"id": str(action), "name": str(action)})
        return out

    def _extract_transition_structure(self) -> dict[str, Any]:
        """Extract transition structure from the real state space."""
        transitions = getattr(self.state_space, "transitions", None) or []
        return {
            "type": "state_transitions",
            "transition_count": len(transitions) if hasattr(transitions, "__len__") else 0,
            "deterministic": self._is_deterministic(),
            "markovian": self._is_markovian(),
            "time_regime": getattr(self.state_space, "time_regime", None),
        }

    def _extract_observation_modalities(self) -> list[str]:
        """Extract observation modalities present in the state space."""
        modalities: list[str] = []
        observations = getattr(self.state_space, "observations", None)
        if observations is not None:
            iterable = observations.values() if isinstance(observations, dict) else observations
            for obs in iterable:
                modality = getattr(obs, "modality", None) or getattr(obs, "modality_type", None)
                if modality and modality not in modalities:
                    modalities.append(str(modality))
        # An empty symbolic state space still has a meaningful observation
        # channel for consumers that need a stable modality dimension.
        return modalities or ["symbolic"]

    def _extract_actions(self) -> list[dict[str, Any]]:
        """Extract actions with full details including effects and preconditions."""
        actions = getattr(self.state_space, "actions", None)
        if actions is None:
            return []

        def _effects_for_action(action: Any) -> list[str]:
            effects = getattr(action, "effects", None)
            if effects is None:
                effects = getattr(action, "affects_state_vars", None)
            return list(effects or [])

        actions_list: list[dict[str, Any]] = []
        iterable: Any
        if isinstance(actions, dict):
            iterable = actions.values()
        else:
            iterable = actions
        for action in iterable:
            if not hasattr(action, "name"):
                actions_list.append({"id": str(action), "name": str(action)})
                continue
            actions_list.append(
                {
                    "id": getattr(action, "id", str(action)),
                    "name": getattr(action, "name", ""),
                    "controller_id": getattr(action, "controller_id", None),
                    "parameters": getattr(action, "parameters", []) or [],
                    "effects": _effects_for_action(action),
                    "preconditions": getattr(action, "preconditions", []) or [],
                    "description": getattr(action, "description", ""),
                    "confidence": _enum_value(getattr(action, "confidence", None)),
                }
            )
        return actions_list

    def _extract_policies(self) -> list[dict[str, Any]]:
        """Extract policies derived from actual POLICY/ORCHESTRATION mappings."""
        out: list[dict[str, Any]] = []
        if isinstance(self.mappings, dict):
            for mid, m in self.mappings.items():
                kind = getattr(m, "kind", None)
                if kind in (MappingKind.POLICY, MappingKind.ORCHESTRATION):
                    out.append(
                        {
                            "id": mid,
                            "label": getattr(m, "semantic_label", "") or mid,
                            "kind": _enum_value(kind),
                            "description": getattr(m, "description", ""),
                            "controller_node_ids": list(
                                getattr(m, "graph_fragment_node_ids", []) or []
                            ),
                            "confidence": getattr(m, "confidence_score", 0.0),
                            "tier": _enum_value(getattr(m, "confidence_tier", None)),
                        }
                    )
        return out

    def _extract_preferences(self) -> list[dict[str, Any]]:
        """Extract preferences from state space."""
        if not hasattr(self.state_space, "preferences"):
            return []
        prefs_list = []
        for _pref_id, pref in self.state_space.preferences.items():
            prefs_list.append(
                {
                    "id": pref.id,
                    "name": pref.name,
                    "description": pref.description,
                    "scope": pref.scope,
                    "expression": pref.expression,
                    "weight": pref.weight,
                    "source": pref.source,
                    "confidence": pref.confidence.value
                    if hasattr(pref.confidence, "value")
                    else str(pref.confidence),
                }
            )
        return prefs_list

    def _extract_constraints(self) -> list[dict[str, Any]]:
        """Extract constraints from CONSTRAINT mappings and state-space preferences."""
        out: list[dict[str, Any]] = []
        if isinstance(self.mappings, dict):
            for mid, m in self.mappings.items():
                if getattr(m, "kind", None) == MappingKind.CONSTRAINT:
                    out.append(
                        {
                            "id": mid,
                            "label": getattr(m, "semantic_label", "") or mid,
                            "description": getattr(m, "description", ""),
                            "scope": list(getattr(m, "graph_fragment_node_ids", []) or []),
                            "confidence": getattr(m, "confidence_score", 0.0),
                            "tier": _enum_value(getattr(m, "confidence_tier", None)),
                            "source": "translation_rule",
                        }
                    )
        prefs = getattr(self.state_space, "preferences", None)
        if isinstance(prefs, dict):
            for pid, pref in prefs.items():
                if getattr(pref, "source", "") == "constraint":
                    out.append(
                        {
                            "id": pid,
                            "label": getattr(pref, "name", "") or pid,
                            "description": getattr(pref, "description", ""),
                            "scope": list(getattr(pref, "scope", []) or []),
                            "confidence": _enum_value(getattr(pref, "confidence", None)),
                            "weight": getattr(pref, "weight", 1.0),
                            "expression": getattr(pref, "expression", ""),
                            "source": "state_space.preferences",
                        }
                    )
        return out

    def _extract_objectives(self) -> list[dict[str, Any]]:
        """Extract objectives from PREFERENCE mappings and state-space preferences."""
        out: list[dict[str, Any]] = []
        if isinstance(self.mappings, dict):
            for mid, m in self.mappings.items():
                if getattr(m, "kind", None) == MappingKind.PREFERENCE:
                    out.append(
                        {
                            "id": mid,
                            "label": getattr(m, "semantic_label", "") or mid,
                            "description": getattr(m, "description", ""),
                            "weight": 1.0,
                            "scope": list(getattr(m, "graph_fragment_node_ids", []) or []),
                            "confidence": getattr(m, "confidence_score", 0.0),
                            "tier": _enum_value(getattr(m, "confidence_tier", None)),
                            "source": "translation_rule",
                        }
                    )
        prefs = getattr(self.state_space, "preferences", None)
        if isinstance(prefs, dict):
            for pid, pref in prefs.items():
                source = getattr(pref, "source", "")
                if source != "constraint":
                    out.append(
                        {
                            "id": pid,
                            "label": getattr(pref, "name", "") or pid,
                            "description": getattr(pref, "description", ""),
                            "weight": getattr(pref, "weight", 1.0),
                            "scope": list(getattr(pref, "scope", []) or []),
                            "expression": getattr(pref, "expression", ""),
                            "confidence": _enum_value(getattr(pref, "confidence", None)),
                            "source": source or "state_space.preferences",
                        }
                    )
        return out

    def _extract_factorization(self) -> dict[str, Any]:
        """Extract factorization structure from the state space.

        Groups state variables by their ``StateVariable.factors`` list
        (assigned by the compiler; a variable may belong to several
        factors). Variables without a factor are collected under a
        ``"default"`` factor so the GNN package always carries a
        factorization view. Returns the factor → variable mapping plus a
        small summary; ``variable_count`` counts distinct variables.
        """
        from collections import defaultdict

        groups: dict[str, list[str]] = defaultdict(list)
        ungrouped: list[str] = []
        seen: set[str] = set()
        for var_id in getattr(self.state_space, "variables", []) or []:
            seen.add(str(var_id))
            obj = self._state_var_object(var_id)
            factors = [str(f) for f in (getattr(obj, "factors", None) or []) if f]
            if factors:
                for factor in dict.fromkeys(factors):
                    groups[factor].append(var_id)
            else:
                ungrouped.append(var_id)
        if ungrouped:
            groups["default"].extend(ungrouped)

        return {
            "type": "factor_partition" if groups else "none",
            "factor_count": len(groups),
            "variable_count": len(seen) if groups else 0,
            "factors": [{"id": fid, "variables": sorted(vs)} for fid, vs in sorted(groups.items())],
        }

    def _extract_factor_list(self) -> list[dict[str, Any]]:
        """Flat list of factor descriptors used by the factors.json export."""
        factorization = self._extract_factorization()
        return list(factorization.get("factors", []))

    def _extract_ontology_mappings(self) -> list[dict[str, Any]]:
        """Extract ontology mappings — one row per semantic mapping with full role info."""
        out: list[dict[str, Any]] = []
        if not isinstance(self.mappings, dict):
            return out
        for mid, m in self.mappings.items():
            out.append(
                {
                    "id": mid,
                    "kind": _enum_value(getattr(m, "kind", None)),
                    "semantic_label": getattr(m, "semantic_label", "") or mid,
                    "description": getattr(m, "description", ""),
                    "graph_node_ids": list(getattr(m, "graph_fragment_node_ids", []) or []),
                    "graph_edge_ids": list(getattr(m, "graph_fragment_edge_ids", []) or []),
                    "confidence": getattr(m, "confidence_score", 0.0),
                    "tier": _enum_value(getattr(m, "confidence_tier", None)),
                    "evidence_count": getattr(m, "evidence_count", 0),
                }
            )
        return out

    def _extract_classes(self) -> list[str]:
        """Extract class definitions."""
        classes = set()
        for _nid, node in self.graph.nodes.items():
            if node.kind == NodeKind.CLASS:
                classes.add(node.name)
        return list(classes)

    def _extract_relationships(self) -> list[dict[str, str]]:
        """Extract relationships."""
        relationships = []
        for _eid, edge in self.graph.edges.items():
            relationships.append(
                {"source": edge.source_id, "target": edge.target_id, "kind": str(edge.kind)}
            )
        return relationships[:100]  # Limit to first 100

    def _extract_source_evidence(self) -> dict[str, Any]:
        """Extract source evidence."""
        return {
            "graph_nodes": self._count_graph_nodes(),
            "graph_edges": self._count_graph_edges(),
            "timestamp": self.timestamp,
        }

    def _count_graph_nodes(self) -> int:
        """Count nodes in graph."""
        return len(self.graph.nodes) if self.graph and hasattr(self.graph, "nodes") else 0

    def _count_graph_edges(self) -> int:
        """Count edges in graph."""
        return len(self.graph.edges) if self.graph and hasattr(self.graph, "edges") else 0

    def _count_edges_by_kind(self) -> dict[str, int]:
        """Count edges by kind."""
        from collections import defaultdict

        counts: dict[str, int] = defaultdict(int)
        if self.graph and hasattr(self.graph, "edges"):
            for edge in self.graph.edges.values():
                counts[str(edge.kind)] += 1
        return dict(counts)

    def _count_state_space_elements(self) -> dict[str, int]:
        """Count state space elements."""
        return {
            "variables": len(self.state_space.variables)
            if hasattr(self.state_space, "variables")
            else 0,
            "observations": len(self.state_space.observations)
            if hasattr(self.state_space, "observations")
            else 0,
            "actions": len(self.state_space.actions) if hasattr(self.state_space, "actions") else 0,
        }

    def _is_deterministic(self) -> bool:
        """Heuristic determinism check.

        A model is treated as non-deterministic when any transition has
        more than one ``to_state`` candidate, or when any likelihood
        spans multiple observations conditioned on the same state set.
        """
        transitions = getattr(self.state_space, "transitions", None) or []
        for t in transitions:
            to_states = getattr(t, "to_states", None) or getattr(t, "successors", None) or []
            if hasattr(to_states, "__len__") and len(to_states) > 1:
                return False
        likelihoods = getattr(self.state_space, "likelihoods", None) or []
        for likelihood in likelihoods:
            obs = getattr(likelihood, "observations", None) or []
            if hasattr(obs, "__len__") and len(obs) > 1:
                return False
        return True

    def _is_markovian(self) -> bool:
        """Heuristic Markov property check.

        A transition that conditions on more than one prior state set
        breaks the Markov assumption.
        """
        transitions = getattr(self.state_space, "transitions", None) or []
        for t in transitions:
            from_states = getattr(t, "from_states", None) or getattr(t, "predecessors", None) or []
            if hasattr(from_states, "__len__") and len(from_states) > 1:
                return False
        return True

    def _generate_dashboard_html(self) -> str:
        """Generate a populated dashboard HTML for the model package.

        This is a small, self-contained dashboard rendered server-side
        from the real graph, mapping, and state-space counts. No
        external assets, no JS execution required.
        """
        nodes_by_kind = self._count_nodes_by_kind()
        edges_by_kind = self._count_edges_by_kind()
        mappings_by_tier = self._count_mappings_by_tier()
        state_space_counts = self._count_state_space_elements()

        def _rows(d: dict[str, Any]) -> str:
            if not d:
                return "<tr><td colspan='2'><em>(none)</em></td></tr>"
            return "".join(
                f"<tr><td>{k}</td><td>{v}</td></tr>"
                for k, v in sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))
            )

        return f"""<!DOCTYPE html>
<html>
<head>
<title>GNN Model Dashboard</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; color: #222 }}
h1 {{ color: #1e3f6b }}
table {{ border-collapse: collapse; margin: 8px 0 16px 0 }}
th, td {{ border: 1px solid #999; padding: 4px 10px; text-align: left }}
.stat {{ margin: 10px 0; padding: 10px 14px; border: 1px solid #ccc; background: #f6f8fb }}
.grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px }}
</style>
</head>
<body>
<h1>GNN Model Package Dashboard</h1>
<div class="stat">
    <h3>Package</h3>
    <p>Version: {self.PACKAGE_VERSION}</p>
    <p>Generated: {self.timestamp}</p>
    <p>Nodes: {self._count_graph_nodes()} &nbsp; Edges: {self._count_graph_edges()} &nbsp;
       Mappings: {len(self.mappings) if isinstance(self.mappings, dict) else 0}</p>
</div>
<div class="grid">
<div class="stat"><h3>Nodes by kind</h3><table><tr><th>Kind</th><th>Count</th></tr>{_rows(nodes_by_kind)}</table></div>
<div class="stat"><h3>Edges by kind</h3><table><tr><th>Kind</th><th>Count</th></tr>{_rows(edges_by_kind)}</table></div>
<div class="stat"><h3>Mappings by confidence tier</h3><table><tr><th>Tier</th><th>Count</th></tr>{_rows(mappings_by_tier)}</table></div>
<div class="stat"><h3>State space</h3><table><tr><th>Component</th><th>Count</th></tr>{_rows(state_space_counts)}</table></div>
</div>
</body>
</html>"""

    # Utility functions

    @staticmethod
    def _checksum(text: str) -> str:
        """Compute SHA256 checksum of text."""
        return hashlib.sha256(text.encode()).hexdigest()

    @staticmethod
    def _checksum_dict(data: dict[str, Any]) -> str:
        """Compute SHA256 checksum of dictionary."""
        text = json.dumps(data, sort_keys=True, default=str)
        return hashlib.sha256(text.encode()).hexdigest()

__init__(graph, state_space, process_model, mappings, config=None)

Initialize the GNN package builder.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
state_space StateSpaceModel

State space model.

required
process_model ProcessModel

Process model.

required
mappings dict[str, Any]

Semantic mappings.

required
config dict[str, Any] | None

Optional configuration dictionary.

None
Source code in py/cogant/gnn/package.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def __init__(
    self,
    graph: ProgramGraph,
    state_space: StateSpaceModel,
    process_model: ProcessModel,
    mappings: dict[str, Any],
    config: dict[str, Any] | None = None,
):
    """
    Initialize the GNN package builder.

    Args:
        graph: Program graph.
        state_space: State space model.
        process_model: Process model.
        mappings: Semantic mappings.
        config: Optional configuration dictionary.
    """
    self.graph = graph
    self.state_space = state_space
    self.process_model = process_model
    self.mappings = mappings
    self.config = config or {}
    self.timestamp = datetime.now(UTC).isoformat()
    self.checksums: dict[str, str] = {}
    self.artifact_warnings: list[str] = []

build(output_dir)

Build the complete GNN package.

Parameters:

Name Type Description Default
output_dir str

Directory to create the package in.

required

Returns:

Type Description
dict[str, Any]

Manifest dictionary with package metadata and checksums.

Source code in py/cogant/gnn/package.py
 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
def build(self, output_dir: str) -> dict[str, Any]:
    """
    Build the complete GNN package.

    Args:
        output_dir: Directory to create the package in.

    Returns:
        Manifest dictionary with package metadata and checksums.
    """
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)
    logger.info(
        "Building GNN package in %s (%d nodes, %d edges, %d mappings)",
        output_path,
        len(self.graph.nodes),
        len(self.graph.edges),
        len(self.mappings) if isinstance(self.mappings, dict) else 0,
    )

    try:
        # 1. Generate core model files
        self._generate_markdown(output_path)
        self._generate_json_model(output_path)
        self._generate_state_space(output_path)
        self._generate_observations(output_path)
        self._generate_actions(output_path)
        self._generate_transitions(output_path)
        self._generate_preferences(output_path)
        self._generate_factors(output_path)
        self._generate_provenance(output_path)
        self._generate_ontology(output_path)

        # 2. Generate canonical section JSON files
        self._generate_actions_policies(output_path)
        self._generate_connections(output_path)
        self._generate_preferences_constraints(output_path)

        # 2b. Generate Markov blanket artifacts (Active Inference partition)
        self._generate_markov_blanket(output_path)

        # 2c. Dump the typed program graph as JSON so PNG rasterizers can
        # rebuild a NetworkX view without re-running the pipeline.
        self._generate_program_graph_json(output_path)

        # 2d. Dump the ProcessModel as JSON so ``render_all_pngs`` can
        # rasterize a Gantt timeline without re-running ProcessExtractor.
        self._generate_process_model_json(output_path)

        # 3. Generate diagrams
        self._generate_diagrams(output_path)

        # 4. Generate visualizations
        self._generate_visualizations(output_path)

        # 5. Create manifest
        manifest = self._create_manifest(output_path)

        # Summarize role distribution across semantic mappings
        role_dist: dict[str, int] = {}
        if isinstance(self.mappings, dict):
            for m in self.mappings.values():
                kind = getattr(m, "kind", None)
                label = kind.value if hasattr(kind, "value") else str(kind or "unknown")
                role_dist[label] = role_dist.get(label, 0) + 1

        role_summary = (
            f" | roles={', '.join(f'{k}={v}' for k, v in sorted(role_dist.items()))}"
            if role_dist
            else ""
        )
        n_vars = (
            len(self.state_space.variables) if hasattr(self.state_space, "variables") else 0
        )
        n_obs = (
            len(self.state_space.observations)
            if hasattr(self.state_space, "observations")
            else 0
        )
        n_actions = len(self.state_space.actions) if hasattr(self.state_space, "actions") else 0

        logger.info(
            "GNN package built: %d files | state_space=%d vars, %d obs, %d actions%s",
            len(self.checksums),
            n_vars,
            n_obs,
            n_actions,
            role_summary,
        )
        return manifest

    except Exception as e:
        logger.error(f"Failed to build GNN package: {e}", exc_info=True)
        raise

Matrix builder

Builds the A / B / C / D generative-model matrices from the rule output and the Markov blanket.

cogant.gnn.matrices

GNN A/B/C/D matrix derivation from program graph and semantic mappings.

Implements the four core probabilistic matrices required by the Active Inference Institute (AII) upstream Generalized Notation Notation (GNN) specification:

  • A — likelihood matrix P(o | s) (observation given hidden state), shape [n_obs x n_states]. Columns sum to 1.0 (column-stochastic per AII/pymdp convention: for each fixed hidden state s, the distribution over observation outcomes sum_o P(o | s) == 1).
  • B — transition tensor P(s' | s, a) (next state given current state and action), shape [n_states x n_states x n_actions]. For each action slice, columns sum to 1.0 (column-stochastic per AII convention).
  • C — log-preference vector over observations, shape [n_obs]. Positive values indicate preferred observations, negative values indicate aversive observations. This is NOT a probability — it is a log-preference in the sense of the Friston expected-free-energy functional.
  • D — initial prior over hidden states, shape [n_states]. Entries sum to 1.0.

These matrices are derived deterministically from the COGANT program graph (ProgramGraph), the extracted semantic mappings (SemanticMapping), and the compiled state space (StateSpaceModel) without any external numerical dependencies. COGANT cannot in general recover the ground-truth parameters of an Active Inference model from arbitrary source code, so the derivation uses principled heuristics:

  • A comes from READS/OBSERVES edges between observation nodes and hidden-state nodes.
  • B comes from WRITES/MUTATES edges from action nodes to hidden-state nodes.
  • C comes from CONSTRAINT/PREFERENCE mapping confidence scores.
  • D comes from CONFIGURATION nodes and any initial-value metadata.

All arithmetic uses plain Python lists — numpy is intentionally not a dependency of this module.

GNNMatrices

Derives GNN A/B/C/D matrices from COGANT analysis artifacts.

The matrices are computed once on construction-time demand via the compute_* methods. Callers that need all four at once should use :meth:to_dict or :meth:to_gnn_markdown_block.

Source code in py/cogant/gnn/matrices.py
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
403
404
405
406
407
408
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
471
472
473
474
475
476
477
478
479
480
481
482
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
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
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
class GNNMatrices:
    """Derives GNN A/B/C/D matrices from COGANT analysis artifacts.

    The matrices are computed once on construction-time demand via the
    ``compute_*`` methods. Callers that need all four at once should use
    :meth:`to_dict` or :meth:`to_gnn_markdown_block`.
    """

    def __init__(
        self,
        graph: ProgramGraph,
        mappings: Any,
        state_space: StateSpaceModel,
    ) -> None:
        """Initialize the matrix deriver.

        Args:
            graph: The program graph with nodes and edges.
            mappings: Semantic mappings; accepted as either a ``dict``
                keyed by mapping ID or a list of ``SemanticMapping``.
            state_space: The compiled state space model.
        """
        self.graph = graph
        self.state_space = state_space

        # Normalize mappings to a list for convenient filtering while
        # preserving a stable ordering.
        if isinstance(mappings, dict):
            mapping_list: list[SemanticMapping] = list(mappings.values())
        elif isinstance(mappings, list):
            mapping_list = list(mappings)
        elif mappings is None:
            mapping_list = []
        else:
            mapping_list = list(mappings)
        self._mappings: list[SemanticMapping] = mapping_list

        # Enumerate spaces.
        self._hidden_states: list[SemanticMapping] = [
            m for m in self._mappings if m.kind == MappingKind.HIDDEN_STATE
        ]
        self._observations: list[SemanticMapping] = [
            m for m in self._mappings if m.kind == MappingKind.OBSERVATION
        ]
        self._actions: list[SemanticMapping] = [
            m for m in self._mappings if m.kind in (MappingKind.ACTION, MappingKind.POLICY)
        ]
        self._constraints: list[SemanticMapping] = [
            m for m in self._mappings if m.kind in (MappingKind.CONSTRAINT, MappingKind.PREFERENCE)
        ]

        # The compiled state-space variables are the authoritative hidden-state
        # axis. A single HIDDEN_STATE mapping can cover multiple graph-fragment
        # nodes, and the state-space compiler expands those into distinct
        # variables. Using the compiled variables here keeps A/B/D dimensions
        # aligned with ``state_space.json`` and avoids losing matrix-bearing
        # states when a mapping spans more than one node.
        self._state_space_vars = list(self.state_space.variables.values())
        self._use_state_space_vars = bool(self._state_space_vars)

        # Populated by compute_B() when the full B tensor would exceed
        # _MAX_B_ENTRIES.  Callers can inspect these to understand the
        # approximation that was applied.
        self._b_truncated: bool = False
        self._b_n_states_full: int = 0  # untruncated n_states
        self._b_n_states_kept: int = 0  # n_states after truncation
        # Indices (into the full A-column / D state axis) of the states
        # kept on the B axis, ascending. B index ``j`` is full state
        # ``self._b_kept_state_indices[j]``.
        self._b_kept_state_indices: list[int] = []

    # ------------------------------------------------------------------
    # Dimensions
    # ------------------------------------------------------------------
    @property
    def n_states(self) -> int:
        """Number of hidden-state dimensions."""
        if self._use_state_space_vars:
            return len(self._state_space_vars)
        return len(self._hidden_states)

    @property
    def n_obs(self) -> int:
        """Number of observation dimensions."""
        if self.state_space.observations:
            return len(self.state_space.observations)
        return len(self._observations)

    @property
    def n_actions(self) -> int:
        """Number of action dimensions.

        Zero is a valid dimension for a degenerate empty state space.  The
        matrix exporter preserves that fact instead of inventing an action
        dimension, which keeps the declared dimensions consistent with the
        compiled state-space model.
        """
        if self._actions:
            return len(self._actions)
        return len(self.state_space.actions)

    # ------------------------------------------------------------------
    # Helpers
    # ------------------------------------------------------------------
    def _state_node_ids(self) -> list[str]:
        """Return the ordered list of graph node IDs backing hidden states."""
        if self._use_state_space_vars:
            return [v.node_id for v in self._state_space_vars]
        ids: list[str] = []
        for mapping in self._hidden_states:
            if mapping.graph_fragment_node_ids:
                ids.append(mapping.graph_fragment_node_ids[0])
            else:
                ids.append("")
        return ids

    def _obs_node_ids(self) -> list[str]:
        """Return the ordered list of graph node IDs backing observations."""
        # The compiler expands multi-node mappings and deduplicates channels.
        # Use its axis for both A and C, including its declared row order.
        if self.state_space.observations:
            return [o.source_node_id for o in self.state_space.observations.values()]
        if self._observations:
            ids: list[str] = []
            for mapping in self._observations:
                if mapping.graph_fragment_node_ids:
                    ids.append(mapping.graph_fragment_node_ids[0])
                else:
                    ids.append("")
            return ids
        return []

    def _action_node_ids(self) -> list[str]:
        """Return the ordered list of graph node IDs backing actions."""
        if self._actions:
            ids: list[str] = []
            for mapping in self._actions:
                if mapping.graph_fragment_node_ids:
                    ids.append(mapping.graph_fragment_node_ids[0])
                else:
                    ids.append("")
            return ids
        return [a.controller_id for a in self.state_space.actions.values()]

    def _edges_from(self, node_id: str) -> list[Any]:
        """Return outgoing edges from ``node_id`` (or an empty list)."""
        if not node_id:
            return []
        return [e for e in self.graph.edges.values() if e.source_id == node_id]

    def _edges_to(self, node_id: str) -> list[Any]:
        """Return incoming edges to ``node_id`` (or an empty list)."""
        if not node_id:
            return []
        return [e for e in self.graph.edges.values() if e.target_id == node_id]

    def _top_k_state_indices(self, state_ids: list[str], k: int) -> list[int]:
        """Return indices of the *k* states with the highest combined degree.

        Used by :meth:`compute_B` when the full ``n_states × n_states ×
        n_actions`` tensor would exceed ``_MAX_B_ENTRIES``.  We keep the
        highest-degree nodes because they carry the most transition
        information; the approximation is a principal submatrix of the
        full B tensor restricted to the top-k row/column indices.

        Args:
            state_ids: Full ordered list of state node IDs.
            k: Number of states to keep.

        Returns:
            At most *k* indices into ``state_ids``, in ascending order so
            the kept B axis preserves the A/D state order. Ties in degree
            are broken by original position, so the selection is
            deterministic.
        """
        if k >= len(state_ids):
            return list(range(len(state_ids)))

        # Count in+out degree for each state node using a single pass
        # over the full edge list (O(|E|), not O(|V|²)).
        degree: dict[str, int] = {nid: 0 for nid in state_ids if nid}
        state_id_set = set(degree)
        for edge in self.graph.edges.values():
            if edge.source_id in state_id_set:
                degree[edge.source_id] += 1
            if edge.target_id in state_id_set:
                degree[edge.target_id] += 1

        # Sort by descending degree, preserving original order for ties
        # so the truncated matrix is deterministic.
        ranked = sorted(range(len(state_ids)), key=lambda j: -degree.get(state_ids[j], 0))
        return sorted(ranked[: max(k, 0)])

    def _top_k_state_ids(self, state_ids: list[str], k: int) -> list[str]:
        """Return the *k* state node IDs with the highest combined degree.

        Thin wrapper over :meth:`_top_k_state_indices`; the IDs are
        returned in their original (A/D axis) order.
        """
        return [state_ids[j] for j in self._top_k_state_indices(state_ids, k)]

    def _state_axis_ids(self) -> list[str]:
        """Return a stable identifier per hidden state on the A/D axis.

        Compiled state-space variable ids when available, otherwise the
        HIDDEN_STATE mapping ids.
        """
        if self._use_state_space_vars:
            return [v.id for v in self._state_space_vars]
        return [m.id for m in self._hidden_states]

    # ------------------------------------------------------------------
    # A matrix — likelihood
    # ------------------------------------------------------------------
    def compute_A(self) -> list[list[float]]:
        """Compute the likelihood matrix ``A[n_obs x n_states]``.

        ``A[i][j] = P(observation_i | hidden_state_j)``.

        Derivation:
            For each observation ``i``, find the set of hidden-state
            nodes that it directly reads (READS/OBSERVES edges from the
            observation's node). Those direct reads receive a high
            probability mass; all other states share the residual mass
            uniformly. Columns are then normalized so each hidden state
            defines a distribution over observations.
        """
        n_obs = self.n_obs
        n_states = self.n_states
        if n_obs == 0 or n_states == 0:
            return []

        state_ids = self._state_node_ids()
        obs_ids = self._obs_node_ids()
        state_index = {nid: j for j, nid in enumerate(state_ids) if nid}

        direct_kinds = {EdgeKind.READS, EdgeKind.OBSERVES, EdgeKind.DEPENDS_ON}

        A: list[list[float]] = [[0.0] * n_states for _ in range(n_obs)]
        n_uniform = 0  # count of rows with no direct evidence

        for i in range(n_obs):
            obs_node_id = obs_ids[i] if i < len(obs_ids) else ""
            direct: list[int] = []
            if obs_node_id:
                for edge in self._edges_from(obs_node_id):
                    if edge.kind in direct_kinds and edge.target_id in state_index:
                        j = state_index[edge.target_id]
                        if j not in direct:
                            direct.append(j)
                # Also look at incoming edges that go TO this observation
                # node (e.g., state->obs "OBSERVES" edges in the reverse
                # direction).
                for edge in self._edges_to(obs_node_id):
                    if edge.kind in direct_kinds and edge.source_id in state_index:
                        j = state_index[edge.source_id]
                        if j not in direct:
                            direct.append(j)

            n_direct = len(direct)
            n_indirect = n_states - n_direct
            if n_direct == 0:
                # No evidence linking this observation to any state: assign
                # equal pre-normalization mass across states. After the
                # column normalization below this row contributes uniformly
                # to every state-column (a maximally vague observation).
                A[i] = [1.0 / n_states] * n_states
                n_uniform += 1
                continue
            direct_share = _DEFAULT_DIRECT_MASS / n_direct
            indirect_share = _DEFAULT_INDIRECT_MASS / n_indirect if n_indirect > 0 else 0.0
            for j in range(n_states):
                A[i][j] = direct_share if j in direct else indirect_share

        # Column-stochastic normalization (AII/pymdp convention). ``A`` holds
        # ``A[o][s] = P(o | s)``, so for every fixed hidden state ``s`` the
        # distribution over observation outcomes must sum to 1: each *column*
        # sums to 1, not each row. (Row-normalizing would make ``sum_s
        # P(o|s) = 1``, which is not a valid likelihood and breaks the
        # predicted-observation update ``pred_obs[o] = sum_s A[o][s]·q(s)``
        # in ``simulate/free_energy.py``.)
        for j in range(n_states):
            col_total = sum(A[i][j] for i in range(n_obs))
            if col_total <= _EPSILON:
                # A state observed by nothing: uniform over observations.
                for i in range(n_obs):
                    A[i][j] = 1.0 / n_obs
            else:
                for i in range(n_obs):
                    A[i][j] = A[i][j] / col_total

        # Log A matrix computation details
        n_informed = n_obs - n_uniform
        logger.info(
            "A matrix computed: shape [%d x %d], %d/%d observations with direct evidence, "
            "%d observations uniform before column normalization (no READS/OBSERVES edges)",
            n_obs,
            n_states,
            n_informed,
            n_obs,
            n_uniform,
        )

        return A

    # ------------------------------------------------------------------
    # B matrix — transition
    # ------------------------------------------------------------------
    def compute_B(self) -> list[list[list[float]]]:
        """Compute the transition tensor ``B[n_states x n_states x n_actions]``.

        ``B[next][cur][action] = P(next_state | current_state, action)``.

        Derivation:
            For each action ``k``, find the hidden-state nodes that it
            WRITES/MUTATES. Those destinations become high-probability
            successors of every current state; otherwise the transition
            defaults to an identity (stay) move. Every column
            ``(cur, action)`` is normalized so that it sums to 1.0.

        Truncation:
            When ``n_states² × n_actions`` would exceed ``_MAX_B_ENTRIES``
            (default 5 M), the state space is reduced to the top-K
            highest-degree nodes so that the tensor fits in memory and
            serializes in reasonable time. The kept states stay in their
            original A/D order, so B index ``j`` is full state
            ``self._b_kept_state_indices[j]``. The truncation is recorded
            in ``self._b_truncated``, ``self._b_n_states_full``,
            ``self._b_n_states_kept`` and ``self._b_kept_state_indices``,
            and surfaced in :meth:`to_dict` under the ``"truncation"`` key.
            This approximation is a principal submatrix of the full B
            restricted to the most structurally important state nodes.
        """
        n_states = self.n_states
        n_actions = self.n_actions
        if n_states == 0:
            return []

        state_ids = self._state_node_ids()
        action_ids = self._action_node_ids()

        # ---- Truncation guard ----------------------------------------
        # If the full tensor would exceed _MAX_B_ENTRIES, keep only the
        # top-K state nodes ranked by in+out degree.  This turns an O(S²A)
        # explosion into O(_MAX_B_ENTRIES) work, preserving the most
        # structurally important nodes.
        full_b_entries = n_states * n_states * n_actions
        self._b_n_states_full = n_states
        self._b_truncated = False
        self._b_kept_state_indices = list(range(n_states))

        if full_b_entries > _MAX_B_ENTRIES and n_actions > 0:
            # Solve for max_k: k² × n_actions ≤ _MAX_B_ENTRIES
            import math

            max_k = max(1, int(math.isqrt(_MAX_B_ENTRIES // n_actions)))
            self._b_truncated = True
            self._b_n_states_kept = max_k
            logger.warning(
                "B tensor would be %d entries (%d states × %d states × %d actions) "
                "which exceeds _MAX_B_ENTRIES=%d. Truncating to top-%d state nodes "
                "by graph degree. Set _MAX_B_ENTRIES higher to disable truncation.",
                full_b_entries,
                n_states,
                n_states,
                n_actions,
                _MAX_B_ENTRIES,
                max_k,
            )
            logger.info(
                "B tensor truncated: %d → %d state nodes (%.1f%% reduction, %d → %d entries)",
                n_states,
                max_k,
                (1 - max_k / n_states) * 100 if n_states > 0 else 0.0,
                full_b_entries,
                max_k * max_k * n_actions,
            )
            kept = self._top_k_state_indices(state_ids, max_k)
            self._b_kept_state_indices = kept
            self._b_n_states_kept = len(kept)
            state_ids = [state_ids[j] for j in kept]
            n_states = len(state_ids)
        else:
            self._b_n_states_kept = n_states
        # ---------------------------------------------------------------

        state_index = {nid: j for j, nid in enumerate(state_ids) if nid}

        write_kinds = {EdgeKind.WRITES, EdgeKind.MUTATES}

        # Initialize to identity per action so that non-writing actions
        # leave the state unchanged (a valid default transition).
        B: list[list[list[float]]] = [
            [[0.0] * n_actions for _ in range(n_states)] for _ in range(n_states)
        ]
        for cur in range(n_states):
            for k in range(n_actions):
                B[cur][cur][k] = 1.0

        n_identity_actions = 0  # actions with no WRITES/MUTATES edges
        n_writing_actions = 0

        for k in range(n_actions):
            act_node_id = action_ids[k] if k < len(action_ids) else ""
            written: list[int] = []
            if act_node_id:
                for edge in self._edges_from(act_node_id):
                    if edge.kind in write_kinds and edge.target_id in state_index:
                        j = state_index[edge.target_id]
                        if j not in written:
                            written.append(j)

            if not written:
                # Already identity — nothing to update for this action.
                n_identity_actions += 1
                continue
            n_writing_actions += 1

            # For every current state ``cur``, redistribute mass so the
            # written destinations receive _DEFAULT_DIRECT_MASS and the
            # identity "stay" move receives _DEFAULT_INDIRECT_MASS.
            for cur in range(n_states):
                column = [0.0] * n_states
                n_w = len(written)
                direct_share = _DEFAULT_DIRECT_MASS / n_w
                for j in written:
                    column[j] = direct_share
                # Residual mass on the identity move (or uniform if the
                # current state is itself a written destination — in that
                # case ``column[cur]`` already received its share above and
                # we normalize as-is below).
                if cur not in written:
                    column[cur] += _DEFAULT_INDIRECT_MASS
                column = _normalize_row(column)
                for nxt in range(n_states):
                    B[nxt][cur][k] = column[nxt]

        # Log B tensor computation details
        logger.info(
            "B tensor computed: shape [%d x %d x %d], %d/%d writing actions "
            "(%d identity/stay), direct_mass=%.2f",
            n_states,
            n_states,
            n_actions,
            n_writing_actions,
            n_actions,
            n_identity_actions,
            _DEFAULT_DIRECT_MASS,
        )

        return B

    # ------------------------------------------------------------------
    # C vector — log preferences over observations
    # ------------------------------------------------------------------
    def compute_C(self) -> list[float]:
        """Compute the log-preference vector ``C[n_obs]``.

        Derivation:
            Each observation receives a log-preference derived from the
            confidence scores of CONSTRAINT/PREFERENCE mappings whose
            graph fragments intersect with the observation's node set.
            Preferences with CONSTRAINT kind contribute a positive
            preference (the constraint describes a desired observation);
            absent any matching constraint, C defaults to 0.0 (neutral).
        """
        n_obs = self.n_obs
        if n_obs == 0:
            return []

        obs_node_ids = self._obs_node_ids()
        C: list[float] = [0.0] * n_obs

        n_preferred = 0  # observations with nonzero preference
        n_aversive = 0  # observations with negative preference
        for i in range(n_obs):
            obs_nid = obs_node_ids[i] if i < len(obs_node_ids) else ""
            if not obs_nid:
                continue
            # Sum signed log-preference contributions from constraints
            # that touch the observation's node (or any graph neighbor).
            total = 0.0
            for mapping in self._constraints:
                if obs_nid in mapping.graph_fragment_node_ids:
                    # Constraint: higher confidence → stronger preference.
                    sign = 1.0
                    if mapping.kind == MappingKind.CONSTRAINT:
                        # Constraints are "must hold" → strongly preferred.
                        sign = 1.0
                    elif mapping.kind == MappingKind.PREFERENCE:
                        # Preferences can be soft and may be aversive if
                        # the mapping semantic label starts with "avoid"
                        # or "reject".
                        label = (mapping.semantic_label or "").lower()
                        if label.startswith(("avoid", "reject", "!")):
                            sign = -1.0
                    total += sign * float(mapping.confidence_score or 0.0)
            C[i] = total
            if total > 0:
                n_preferred += 1
            elif total < 0:
                n_aversive += 1

        # Log C vector computation details
        n_neutral = n_obs - n_preferred - n_aversive
        logger.info(
            "C vector computed: length %d, %d preferred, %d aversive, %d neutral",
            n_obs,
            n_preferred,
            n_aversive,
            n_neutral,
        )

        return C

    # ------------------------------------------------------------------
    # D vector — initial prior over hidden states
    # ------------------------------------------------------------------
    def compute_D(self) -> list[float]:
        """Compute the initial prior ``D[n_states]``.

        Derivation:
            If any hidden state has an explicit ``default_value`` or an
            attached CONFIGURATION node with a value, concentrate mass
            on that state. Otherwise return a uniform prior. The vector
            always sums to 1.0.
        """
        n_states = self.n_states
        if n_states == 0:
            return []

        # Base: uniform prior.
        D: list[float] = [1.0 / n_states] * n_states

        if self._use_state_space_vars:
            # Bias toward any variable whose StateVariable has a default
            # value or a CONFIGURATION neighbor in the graph.
            biased = [0.0] * n_states
            any_bias = False
            for j, var in enumerate(self._state_space_vars):
                bias = 1.0
                # Explicit domain/default bias.
                meta_default = getattr(var, "domain", None)
                if meta_default:
                    any_bias = True
                    bias += 1.0
                # CONFIGURATION neighbor in the graph → stronger prior.
                node_id = getattr(var, "node_id", "")
                if node_id and node_id in self.graph.nodes:
                    for edge in self._edges_to(node_id) + self._edges_from(node_id):
                        other_id = edge.source_id if edge.target_id == node_id else edge.target_id
                        other = self.graph.nodes.get(other_id)
                        if other and other.kind == NodeKind.CONFIGURATION:
                            any_bias = True
                            bias += 2.0
                            break
                biased[j] = bias
            if any_bias:
                D = _normalize_vector(biased)
            else:
                D = _normalize_vector(D)
        else:
            # Hidden-state semantic mappings: use mapping confidence as
            # a soft prior weight so that high-confidence hidden states
            # receive more prior mass.
            weights = [max(float(m.confidence_score or 0.0), _EPSILON) for m in self._hidden_states]
            D = _normalize_vector(weights)

        # Log D vector computation details
        peak_idx = max(range(len(D)), key=lambda j: D[j]) if D else -1
        peak_val = D[peak_idx] if peak_idx >= 0 else 0.0
        logger.info(
            "D vector computed: length %d, peak at index %d (%.4f), source=%s",
            len(D),
            peak_idx,
            peak_val,
            "state_space_vars" if self._use_state_space_vars else "hidden_state_mappings",
        )

        return D

    # ------------------------------------------------------------------
    # Output formatting
    # ------------------------------------------------------------------
    def to_dict(self) -> dict[str, Any]:
        """Return a JSON-serializable dict of all four matrices.

        Returns:
            ``{"A": ..., "B": ..., "C": ..., "D": ..., "shapes": ...,
            "dimensions": ..., "truncation": ...}``

            The ``"truncation"`` key is ``None`` when no truncation
            occurred; otherwise it is a dict with:

            * ``"applied"``: ``True``
            * ``"n_states_full"``: original (un-truncated) n_states
            * ``"n_states_kept"``: n_states after truncation
            * ``"max_b_entries"``: the ``_MAX_B_ENTRIES`` threshold
            * ``"kept_state_indices"``: ascending indices into the full
                A-column / D state axis; B index ``j`` is full state
                ``kept_state_indices[j]``
            * ``"kept_state_ids"``: the matching state ids
            * ``"reason"``: human-readable explanation

            ``"shapes"`` reports the emitted arrays, so a truncated B is
            declared as ``[n_states_kept, n_states_kept, n_actions]``
            while ``"dimensions"`` keeps the full ``n_states``.
        """
        A = self.compute_A()
        B = self.compute_B()
        C = self.compute_C()
        D = self.compute_D()

        truncation: dict[str, Any] | None = None
        if self._b_truncated:
            axis_ids = self._state_axis_ids()
            kept = list(self._b_kept_state_indices)
            truncation = {
                "applied": True,
                "n_states_full": self._b_n_states_full,
                "n_states_kept": self._b_n_states_kept,
                "max_b_entries": _MAX_B_ENTRIES,
                "kept_state_indices": kept,
                "kept_state_ids": [axis_ids[j] if j < len(axis_ids) else "" for j in kept],
                "reason": (
                    f"B tensor ({self._b_n_states_full}² × {self.n_actions} = "
                    f"{self._b_n_states_full**2 * self.n_actions:,} entries) "
                    f"exceeded _MAX_B_ENTRIES={_MAX_B_ENTRIES:,}; "
                    f"kept top-{self._b_n_states_kept} state nodes by degree."
                ),
            }

        # Declared shapes are the logical array shapes. An empty A (zero
        # observations or zero hidden states) or an empty B (zero hidden
        # states) is still an ``[n_obs, n_states]`` /
        # ``[n_states, n_states, n_actions]`` array with a zero axis, so
        # fall back to the dimensions instead of collapsing to ``[0, 0]``.
        return {
            "A": A,
            "B": B,
            "C": C,
            "D": D,
            "shapes": {
                "A": [len(A), len(A[0])] if A else [self.n_obs, self.n_states],
                "B": [len(B), len(B[0]), len(B[0][0]) if B[0] else 0]
                if B
                else [0, 0, self.n_actions],
                "C": [len(C)],
                "D": [len(D)],
            },
            "dimensions": {
                "n_states": self.n_states,
                "n_obs": self.n_obs,
                "n_actions": self.n_actions,
            },
            "truncation": truncation,
        }

    def to_gnn_markdown_block(self) -> str:
        """Format the matrices as a GNN-compatible markdown block.

        Emits AII-style sections with ``rows=``, ``cols=``, ``depth=``
        bracket headers. This block is additive to the existing
        ``StateSpaceBlock`` / ``InitialParameterization`` sections; it is
        meant to be embedded as a COGANT extension.
        """
        A = self.compute_A()
        B = self.compute_B()
        C = self.compute_C()
        D = self.compute_D()

        lines: list[str] = []

        n_rows = len(A)
        n_cols = len(A[0]) if A else self.n_states
        lines.append(f"A[[rows={n_rows}][cols={n_cols}]]")
        for row in A:
            lines.append("  " + " ".join(repr(float(v)) for v in row))
        lines.append("")

        # --- B tensor ---
        if B:
            n_rows = len(B)
            n_cols = len(B[0]) if B else 0
            n_depth = len(B[0][0]) if (B and B[0]) else 0
            lines.append(f"B[[rows={n_rows}][cols={n_cols}][depth={n_depth}]]")
            for k in range(n_depth):
                lines.append(f"  # action={k}")
                for r in range(n_rows):
                    row_vals = [B[r][c][k] for c in range(n_cols)]
                    lines.append("  " + " ".join(repr(float(v)) for v in row_vals))
            lines.append("")
        else:
            lines.extend(("B[[rows=0][cols=0][depth=0]]", ""))

        # --- C vector ---
        lines.append(f"C[[rows={len(C)}]]")
        for v in C:
            lines.append(f"  {float(v)!r}")
        lines.append("")

        # --- D vector ---
        lines.append(f"D[[rows={len(D)}]]")
        for v in D:
            lines.append(f"  {float(v)!r}")
        lines.append("")

        return "\n".join(lines).rstrip()

    # ------------------------------------------------------------------
    # Validation helpers
    # ------------------------------------------------------------------
    def validate_shapes(self) -> tuple[bool, list[str]]:
        """Validate that all four matrices have the expected shapes.

        Returns:
            ``(ok, errors)`` where ``ok`` is True if no shape errors
            were found.
        """
        errors: list[str] = []
        A = self.compute_A()
        B = self.compute_B()
        C = self.compute_C()
        D = self.compute_D()

        n_s = self.n_states
        n_o = self.n_obs
        n_a = self.n_actions
        # A truncated B covers only the kept states (see compute_B).
        n_b = self._b_n_states_kept if self._b_truncated else n_s

        # A: n_obs x n_states, columns sum to 1.
        # Column-sum tolerance 1e-6 — principled default, matches the
        # PyMDP validator tolerance and is ~7 orders of magnitude
        # above float64 round-off noise (~1e-16) for a typical
        # n_states <= 50. Strict enough to catch normalization bugs
        # but loose enough to tolerate accumulated rounding across
        # multiple ``_normalize_row`` passes.
        if n_o > 0 and n_s > 0:
            if len(A) != n_o:
                errors.append(f"A row count {len(A)} != n_obs {n_o}")
            elif A and any(len(row) != n_s for row in A):
                errors.append(f"A has inconsistent column count (expected {n_s})")
            else:
                # A is column-stochastic: P(o|s) sums to 1 over observation
                # outcomes for each fixed hidden state s (a column).
                for j in range(n_s):
                    col_sum = sum(A[i][j] for i in range(len(A)))
                    if abs(col_sum - 1.0) > 1e-6:  # col-norm tolerance
                        errors.append(f"A column {j} does not sum to 1 (sum={col_sum:.6f})")

        # B: n_states x n_states x n_actions (n_states_kept when truncated)
        if n_s > 0:
            if len(B) != n_b:
                errors.append(f"B first dim {len(B)} != n_states {n_b}")
            elif any(len(row) != n_b for row in B):
                errors.append(f"B second dim != n_states {n_b}")
            elif any(len(cell) != n_a for row in B for cell in row):
                errors.append(f"B third dim != n_actions {n_a}")
            else:
                if any(
                    B[i][j][k] < -1e-9 for i in range(n_b) for j in range(n_b) for k in range(n_a)
                ):
                    errors.append("B contains negative probabilities")
                for k in range(n_a):
                    for j in range(n_b):
                        col_sum = sum(B[i][j][k] for i in range(n_b))
                        if abs(col_sum - 1.0) > 1e-6:  # same tolerance as A columns
                            errors.append(
                                f"B action {k} column {j} does not sum to 1 (sum={col_sum:.6f})"
                            )

        # C: length n_obs
        if len(C) != n_o:
            errors.append(f"C length {len(C)} != n_obs {n_o}")

        # D: length n_states, sums to 1 (same 1e-6 tolerance as A/B
        # simplex-normalization check above).
        if len(D) != n_s:
            errors.append(f"D length {len(D)} != n_states {n_s}")
        elif D and abs(sum(D) - 1.0) > 1e-6:  # same tolerance as A/B columns
            errors.append(f"D does not sum to 1 (sum={sum(D):.6f})")

        return (len(errors) == 0, errors)

    def validate(self) -> list[str]:
        """Validate dimensional consistency across A/B/C/D matrices.

        Checks that all four matrices have the expected shapes and that
        stochastic constraints are satisfied (column sums for A, column
        sums for B slices, sum for D).

        Returns:
            A list of validation issues. Empty list means all matrices
            are dimensionally consistent and satisfy stochastic constraints.
        """
        _, errors = self.validate_shapes()
        return errors

    def to_plain_dict(self) -> dict[str, Any]:
        """Export matrices as plain Python lists for JSON serialization.

        Unlike :meth:`to_dict`, this method guarantees all values are plain
        Python lists/floats with no numpy arrays or other special types.

        Returns:
            A dict with keys "A", "B", "C", "D" containing the matrices
            as plain Python lists.  Additional keys include "n_states",
            "n_obs", "n_actions" for shape information, and metadata like
            "b_truncated" if the B tensor was truncated.
        """
        A = self.compute_A()
        B = self.compute_B()
        C = self.compute_C()
        D = self.compute_D()

        # A, B, C, D are always plain Python lists — explicit ``list(...)``
        # copies guarantee independence from the cached compute_* outputs
        # so callers may mutate the returned dict safely.
        result: dict[str, Any] = {
            "A": [list(row) for row in A],
            "B": [[list(cell) for cell in row] for row in B],
            "C": list(C),
            "D": list(D),
            "n_states": self.n_states,
            "n_obs": self.n_obs,
            "n_actions": self.n_actions,
        }

        # Include truncation metadata if B was truncated.
        if self._b_truncated:
            result["b_truncated"] = True
            result["b_n_states_full"] = self._b_n_states_full
            result["b_n_states_kept"] = self._b_n_states_kept
            result["b_kept_state_indices"] = list(self._b_kept_state_indices)

        return result

n_actions property

Number of action dimensions.

Zero is a valid dimension for a degenerate empty state space. The matrix exporter preserves that fact instead of inventing an action dimension, which keeps the declared dimensions consistent with the compiled state-space model.

n_obs property

Number of observation dimensions.

n_states property

Number of hidden-state dimensions.

__init__(graph, mappings, state_space)

Initialize the matrix deriver.

Parameters:

Name Type Description Default
graph ProgramGraph

The program graph with nodes and edges.

required
mappings Any

Semantic mappings; accepted as either a dict keyed by mapping ID or a list of SemanticMapping.

required
state_space StateSpaceModel

The compiled state space model.

required
Source code in py/cogant/gnn/matrices.py
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
def __init__(
    self,
    graph: ProgramGraph,
    mappings: Any,
    state_space: StateSpaceModel,
) -> None:
    """Initialize the matrix deriver.

    Args:
        graph: The program graph with nodes and edges.
        mappings: Semantic mappings; accepted as either a ``dict``
            keyed by mapping ID or a list of ``SemanticMapping``.
        state_space: The compiled state space model.
    """
    self.graph = graph
    self.state_space = state_space

    # Normalize mappings to a list for convenient filtering while
    # preserving a stable ordering.
    if isinstance(mappings, dict):
        mapping_list: list[SemanticMapping] = list(mappings.values())
    elif isinstance(mappings, list):
        mapping_list = list(mappings)
    elif mappings is None:
        mapping_list = []
    else:
        mapping_list = list(mappings)
    self._mappings: list[SemanticMapping] = mapping_list

    # Enumerate spaces.
    self._hidden_states: list[SemanticMapping] = [
        m for m in self._mappings if m.kind == MappingKind.HIDDEN_STATE
    ]
    self._observations: list[SemanticMapping] = [
        m for m in self._mappings if m.kind == MappingKind.OBSERVATION
    ]
    self._actions: list[SemanticMapping] = [
        m for m in self._mappings if m.kind in (MappingKind.ACTION, MappingKind.POLICY)
    ]
    self._constraints: list[SemanticMapping] = [
        m for m in self._mappings if m.kind in (MappingKind.CONSTRAINT, MappingKind.PREFERENCE)
    ]

    # The compiled state-space variables are the authoritative hidden-state
    # axis. A single HIDDEN_STATE mapping can cover multiple graph-fragment
    # nodes, and the state-space compiler expands those into distinct
    # variables. Using the compiled variables here keeps A/B/D dimensions
    # aligned with ``state_space.json`` and avoids losing matrix-bearing
    # states when a mapping spans more than one node.
    self._state_space_vars = list(self.state_space.variables.values())
    self._use_state_space_vars = bool(self._state_space_vars)

    # Populated by compute_B() when the full B tensor would exceed
    # _MAX_B_ENTRIES.  Callers can inspect these to understand the
    # approximation that was applied.
    self._b_truncated: bool = False
    self._b_n_states_full: int = 0  # untruncated n_states
    self._b_n_states_kept: int = 0  # n_states after truncation
    # Indices (into the full A-column / D state axis) of the states
    # kept on the B axis, ascending. B index ``j`` is full state
    # ``self._b_kept_state_indices[j]``.
    self._b_kept_state_indices: list[int] = []

compute_A()

Compute the likelihood matrix A[n_obs x n_states].

A[i][j] = P(observation_i | hidden_state_j).

Derivation

For each observation i, find the set of hidden-state nodes that it directly reads (READS/OBSERVES edges from the observation's node). Those direct reads receive a high probability mass; all other states share the residual mass uniformly. Columns are then normalized so each hidden state defines a distribution over observations.

Source code in py/cogant/gnn/matrices.py
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
403
404
405
406
def compute_A(self) -> list[list[float]]:
    """Compute the likelihood matrix ``A[n_obs x n_states]``.

    ``A[i][j] = P(observation_i | hidden_state_j)``.

    Derivation:
        For each observation ``i``, find the set of hidden-state
        nodes that it directly reads (READS/OBSERVES edges from the
        observation's node). Those direct reads receive a high
        probability mass; all other states share the residual mass
        uniformly. Columns are then normalized so each hidden state
        defines a distribution over observations.
    """
    n_obs = self.n_obs
    n_states = self.n_states
    if n_obs == 0 or n_states == 0:
        return []

    state_ids = self._state_node_ids()
    obs_ids = self._obs_node_ids()
    state_index = {nid: j for j, nid in enumerate(state_ids) if nid}

    direct_kinds = {EdgeKind.READS, EdgeKind.OBSERVES, EdgeKind.DEPENDS_ON}

    A: list[list[float]] = [[0.0] * n_states for _ in range(n_obs)]
    n_uniform = 0  # count of rows with no direct evidence

    for i in range(n_obs):
        obs_node_id = obs_ids[i] if i < len(obs_ids) else ""
        direct: list[int] = []
        if obs_node_id:
            for edge in self._edges_from(obs_node_id):
                if edge.kind in direct_kinds and edge.target_id in state_index:
                    j = state_index[edge.target_id]
                    if j not in direct:
                        direct.append(j)
            # Also look at incoming edges that go TO this observation
            # node (e.g., state->obs "OBSERVES" edges in the reverse
            # direction).
            for edge in self._edges_to(obs_node_id):
                if edge.kind in direct_kinds and edge.source_id in state_index:
                    j = state_index[edge.source_id]
                    if j not in direct:
                        direct.append(j)

        n_direct = len(direct)
        n_indirect = n_states - n_direct
        if n_direct == 0:
            # No evidence linking this observation to any state: assign
            # equal pre-normalization mass across states. After the
            # column normalization below this row contributes uniformly
            # to every state-column (a maximally vague observation).
            A[i] = [1.0 / n_states] * n_states
            n_uniform += 1
            continue
        direct_share = _DEFAULT_DIRECT_MASS / n_direct
        indirect_share = _DEFAULT_INDIRECT_MASS / n_indirect if n_indirect > 0 else 0.0
        for j in range(n_states):
            A[i][j] = direct_share if j in direct else indirect_share

    # Column-stochastic normalization (AII/pymdp convention). ``A`` holds
    # ``A[o][s] = P(o | s)``, so for every fixed hidden state ``s`` the
    # distribution over observation outcomes must sum to 1: each *column*
    # sums to 1, not each row. (Row-normalizing would make ``sum_s
    # P(o|s) = 1``, which is not a valid likelihood and breaks the
    # predicted-observation update ``pred_obs[o] = sum_s A[o][s]·q(s)``
    # in ``simulate/free_energy.py``.)
    for j in range(n_states):
        col_total = sum(A[i][j] for i in range(n_obs))
        if col_total <= _EPSILON:
            # A state observed by nothing: uniform over observations.
            for i in range(n_obs):
                A[i][j] = 1.0 / n_obs
        else:
            for i in range(n_obs):
                A[i][j] = A[i][j] / col_total

    # Log A matrix computation details
    n_informed = n_obs - n_uniform
    logger.info(
        "A matrix computed: shape [%d x %d], %d/%d observations with direct evidence, "
        "%d observations uniform before column normalization (no READS/OBSERVES edges)",
        n_obs,
        n_states,
        n_informed,
        n_obs,
        n_uniform,
    )

    return A

compute_B()

Compute the transition tensor B[n_states x n_states x n_actions].

B[next][cur][action] = P(next_state | current_state, action).

Derivation

For each action k, find the hidden-state nodes that it WRITES/MUTATES. Those destinations become high-probability successors of every current state; otherwise the transition defaults to an identity (stay) move. Every column (cur, action) is normalized so that it sums to 1.0.

Truncation

When n_states² × n_actions would exceed _MAX_B_ENTRIES (default 5 M), the state space is reduced to the top-K highest-degree nodes so that the tensor fits in memory and serializes in reasonable time. The kept states stay in their original A/D order, so B index j is full state self._b_kept_state_indices[j]. The truncation is recorded in self._b_truncated, self._b_n_states_full, self._b_n_states_kept and self._b_kept_state_indices, and surfaced in :meth:to_dict under the "truncation" key. This approximation is a principal submatrix of the full B restricted to the most structurally important state nodes.

Source code in py/cogant/gnn/matrices.py
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
471
472
473
474
475
476
477
478
479
480
481
482
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
def compute_B(self) -> list[list[list[float]]]:
    """Compute the transition tensor ``B[n_states x n_states x n_actions]``.

    ``B[next][cur][action] = P(next_state | current_state, action)``.

    Derivation:
        For each action ``k``, find the hidden-state nodes that it
        WRITES/MUTATES. Those destinations become high-probability
        successors of every current state; otherwise the transition
        defaults to an identity (stay) move. Every column
        ``(cur, action)`` is normalized so that it sums to 1.0.

    Truncation:
        When ``n_states² × n_actions`` would exceed ``_MAX_B_ENTRIES``
        (default 5 M), the state space is reduced to the top-K
        highest-degree nodes so that the tensor fits in memory and
        serializes in reasonable time. The kept states stay in their
        original A/D order, so B index ``j`` is full state
        ``self._b_kept_state_indices[j]``. The truncation is recorded
        in ``self._b_truncated``, ``self._b_n_states_full``,
        ``self._b_n_states_kept`` and ``self._b_kept_state_indices``,
        and surfaced in :meth:`to_dict` under the ``"truncation"`` key.
        This approximation is a principal submatrix of the full B
        restricted to the most structurally important state nodes.
    """
    n_states = self.n_states
    n_actions = self.n_actions
    if n_states == 0:
        return []

    state_ids = self._state_node_ids()
    action_ids = self._action_node_ids()

    # ---- Truncation guard ----------------------------------------
    # If the full tensor would exceed _MAX_B_ENTRIES, keep only the
    # top-K state nodes ranked by in+out degree.  This turns an O(S²A)
    # explosion into O(_MAX_B_ENTRIES) work, preserving the most
    # structurally important nodes.
    full_b_entries = n_states * n_states * n_actions
    self._b_n_states_full = n_states
    self._b_truncated = False
    self._b_kept_state_indices = list(range(n_states))

    if full_b_entries > _MAX_B_ENTRIES and n_actions > 0:
        # Solve for max_k: k² × n_actions ≤ _MAX_B_ENTRIES
        import math

        max_k = max(1, int(math.isqrt(_MAX_B_ENTRIES // n_actions)))
        self._b_truncated = True
        self._b_n_states_kept = max_k
        logger.warning(
            "B tensor would be %d entries (%d states × %d states × %d actions) "
            "which exceeds _MAX_B_ENTRIES=%d. Truncating to top-%d state nodes "
            "by graph degree. Set _MAX_B_ENTRIES higher to disable truncation.",
            full_b_entries,
            n_states,
            n_states,
            n_actions,
            _MAX_B_ENTRIES,
            max_k,
        )
        logger.info(
            "B tensor truncated: %d → %d state nodes (%.1f%% reduction, %d → %d entries)",
            n_states,
            max_k,
            (1 - max_k / n_states) * 100 if n_states > 0 else 0.0,
            full_b_entries,
            max_k * max_k * n_actions,
        )
        kept = self._top_k_state_indices(state_ids, max_k)
        self._b_kept_state_indices = kept
        self._b_n_states_kept = len(kept)
        state_ids = [state_ids[j] for j in kept]
        n_states = len(state_ids)
    else:
        self._b_n_states_kept = n_states
    # ---------------------------------------------------------------

    state_index = {nid: j for j, nid in enumerate(state_ids) if nid}

    write_kinds = {EdgeKind.WRITES, EdgeKind.MUTATES}

    # Initialize to identity per action so that non-writing actions
    # leave the state unchanged (a valid default transition).
    B: list[list[list[float]]] = [
        [[0.0] * n_actions for _ in range(n_states)] for _ in range(n_states)
    ]
    for cur in range(n_states):
        for k in range(n_actions):
            B[cur][cur][k] = 1.0

    n_identity_actions = 0  # actions with no WRITES/MUTATES edges
    n_writing_actions = 0

    for k in range(n_actions):
        act_node_id = action_ids[k] if k < len(action_ids) else ""
        written: list[int] = []
        if act_node_id:
            for edge in self._edges_from(act_node_id):
                if edge.kind in write_kinds and edge.target_id in state_index:
                    j = state_index[edge.target_id]
                    if j not in written:
                        written.append(j)

        if not written:
            # Already identity — nothing to update for this action.
            n_identity_actions += 1
            continue
        n_writing_actions += 1

        # For every current state ``cur``, redistribute mass so the
        # written destinations receive _DEFAULT_DIRECT_MASS and the
        # identity "stay" move receives _DEFAULT_INDIRECT_MASS.
        for cur in range(n_states):
            column = [0.0] * n_states
            n_w = len(written)
            direct_share = _DEFAULT_DIRECT_MASS / n_w
            for j in written:
                column[j] = direct_share
            # Residual mass on the identity move (or uniform if the
            # current state is itself a written destination — in that
            # case ``column[cur]`` already received its share above and
            # we normalize as-is below).
            if cur not in written:
                column[cur] += _DEFAULT_INDIRECT_MASS
            column = _normalize_row(column)
            for nxt in range(n_states):
                B[nxt][cur][k] = column[nxt]

    # Log B tensor computation details
    logger.info(
        "B tensor computed: shape [%d x %d x %d], %d/%d writing actions "
        "(%d identity/stay), direct_mass=%.2f",
        n_states,
        n_states,
        n_actions,
        n_writing_actions,
        n_actions,
        n_identity_actions,
        _DEFAULT_DIRECT_MASS,
    )

    return B

compute_C()

Compute the log-preference vector C[n_obs].

Derivation

Each observation receives a log-preference derived from the confidence scores of CONSTRAINT/PREFERENCE mappings whose graph fragments intersect with the observation's node set. Preferences with CONSTRAINT kind contribute a positive preference (the constraint describes a desired observation); absent any matching constraint, C defaults to 0.0 (neutral).

Source code in py/cogant/gnn/matrices.py
558
559
560
561
562
563
564
565
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
def compute_C(self) -> list[float]:
    """Compute the log-preference vector ``C[n_obs]``.

    Derivation:
        Each observation receives a log-preference derived from the
        confidence scores of CONSTRAINT/PREFERENCE mappings whose
        graph fragments intersect with the observation's node set.
        Preferences with CONSTRAINT kind contribute a positive
        preference (the constraint describes a desired observation);
        absent any matching constraint, C defaults to 0.0 (neutral).
    """
    n_obs = self.n_obs
    if n_obs == 0:
        return []

    obs_node_ids = self._obs_node_ids()
    C: list[float] = [0.0] * n_obs

    n_preferred = 0  # observations with nonzero preference
    n_aversive = 0  # observations with negative preference
    for i in range(n_obs):
        obs_nid = obs_node_ids[i] if i < len(obs_node_ids) else ""
        if not obs_nid:
            continue
        # Sum signed log-preference contributions from constraints
        # that touch the observation's node (or any graph neighbor).
        total = 0.0
        for mapping in self._constraints:
            if obs_nid in mapping.graph_fragment_node_ids:
                # Constraint: higher confidence → stronger preference.
                sign = 1.0
                if mapping.kind == MappingKind.CONSTRAINT:
                    # Constraints are "must hold" → strongly preferred.
                    sign = 1.0
                elif mapping.kind == MappingKind.PREFERENCE:
                    # Preferences can be soft and may be aversive if
                    # the mapping semantic label starts with "avoid"
                    # or "reject".
                    label = (mapping.semantic_label or "").lower()
                    if label.startswith(("avoid", "reject", "!")):
                        sign = -1.0
                total += sign * float(mapping.confidence_score or 0.0)
        C[i] = total
        if total > 0:
            n_preferred += 1
        elif total < 0:
            n_aversive += 1

    # Log C vector computation details
    n_neutral = n_obs - n_preferred - n_aversive
    logger.info(
        "C vector computed: length %d, %d preferred, %d aversive, %d neutral",
        n_obs,
        n_preferred,
        n_aversive,
        n_neutral,
    )

    return C

compute_D()

Compute the initial prior D[n_states].

Derivation

If any hidden state has an explicit default_value or an attached CONFIGURATION node with a value, concentrate mass on that state. Otherwise return a uniform prior. The vector always sums to 1.0.

Source code in py/cogant/gnn/matrices.py
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
def compute_D(self) -> list[float]:
    """Compute the initial prior ``D[n_states]``.

    Derivation:
        If any hidden state has an explicit ``default_value`` or an
        attached CONFIGURATION node with a value, concentrate mass
        on that state. Otherwise return a uniform prior. The vector
        always sums to 1.0.
    """
    n_states = self.n_states
    if n_states == 0:
        return []

    # Base: uniform prior.
    D: list[float] = [1.0 / n_states] * n_states

    if self._use_state_space_vars:
        # Bias toward any variable whose StateVariable has a default
        # value or a CONFIGURATION neighbor in the graph.
        biased = [0.0] * n_states
        any_bias = False
        for j, var in enumerate(self._state_space_vars):
            bias = 1.0
            # Explicit domain/default bias.
            meta_default = getattr(var, "domain", None)
            if meta_default:
                any_bias = True
                bias += 1.0
            # CONFIGURATION neighbor in the graph → stronger prior.
            node_id = getattr(var, "node_id", "")
            if node_id and node_id in self.graph.nodes:
                for edge in self._edges_to(node_id) + self._edges_from(node_id):
                    other_id = edge.source_id if edge.target_id == node_id else edge.target_id
                    other = self.graph.nodes.get(other_id)
                    if other and other.kind == NodeKind.CONFIGURATION:
                        any_bias = True
                        bias += 2.0
                        break
            biased[j] = bias
        if any_bias:
            D = _normalize_vector(biased)
        else:
            D = _normalize_vector(D)
    else:
        # Hidden-state semantic mappings: use mapping confidence as
        # a soft prior weight so that high-confidence hidden states
        # receive more prior mass.
        weights = [max(float(m.confidence_score or 0.0), _EPSILON) for m in self._hidden_states]
        D = _normalize_vector(weights)

    # Log D vector computation details
    peak_idx = max(range(len(D)), key=lambda j: D[j]) if D else -1
    peak_val = D[peak_idx] if peak_idx >= 0 else 0.0
    logger.info(
        "D vector computed: length %d, peak at index %d (%.4f), source=%s",
        len(D),
        peak_idx,
        peak_val,
        "state_space_vars" if self._use_state_space_vars else "hidden_state_mappings",
    )

    return D

to_dict()

Return a JSON-serializable dict of all four matrices.

Returns:

Type Description
dict[str, Any]

``{"A": ..., "B": ..., "C": ..., "D": ..., "shapes": ...,

dict[str, Any]

"dimensions": ..., "truncation": ...}``

dict[str, Any]

The "truncation" key is None when no truncation

dict[str, Any]

occurred; otherwise it is a dict with:

dict[str, Any]
  • "applied": True
dict[str, Any]
  • "n_states_full": original (un-truncated) n_states
dict[str, Any]
  • "n_states_kept": n_states after truncation
dict[str, Any]
  • "max_b_entries": the _MAX_B_ENTRIES threshold
dict[str, Any]
  • "kept_state_indices": ascending indices into the full A-column / D state axis; B index j is full state kept_state_indices[j]
dict[str, Any]
  • "kept_state_ids": the matching state ids
dict[str, Any]
  • "reason": human-readable explanation
dict[str, Any]

"shapes" reports the emitted arrays, so a truncated B is

dict[str, Any]

declared as [n_states_kept, n_states_kept, n_actions]

dict[str, Any]

while "dimensions" keeps the full n_states.

Source code in py/cogant/gnn/matrices.py
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
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-serializable dict of all four matrices.

    Returns:
        ``{"A": ..., "B": ..., "C": ..., "D": ..., "shapes": ...,
        "dimensions": ..., "truncation": ...}``

        The ``"truncation"`` key is ``None`` when no truncation
        occurred; otherwise it is a dict with:

        * ``"applied"``: ``True``
        * ``"n_states_full"``: original (un-truncated) n_states
        * ``"n_states_kept"``: n_states after truncation
        * ``"max_b_entries"``: the ``_MAX_B_ENTRIES`` threshold
        * ``"kept_state_indices"``: ascending indices into the full
            A-column / D state axis; B index ``j`` is full state
            ``kept_state_indices[j]``
        * ``"kept_state_ids"``: the matching state ids
        * ``"reason"``: human-readable explanation

        ``"shapes"`` reports the emitted arrays, so a truncated B is
        declared as ``[n_states_kept, n_states_kept, n_actions]``
        while ``"dimensions"`` keeps the full ``n_states``.
    """
    A = self.compute_A()
    B = self.compute_B()
    C = self.compute_C()
    D = self.compute_D()

    truncation: dict[str, Any] | None = None
    if self._b_truncated:
        axis_ids = self._state_axis_ids()
        kept = list(self._b_kept_state_indices)
        truncation = {
            "applied": True,
            "n_states_full": self._b_n_states_full,
            "n_states_kept": self._b_n_states_kept,
            "max_b_entries": _MAX_B_ENTRIES,
            "kept_state_indices": kept,
            "kept_state_ids": [axis_ids[j] if j < len(axis_ids) else "" for j in kept],
            "reason": (
                f"B tensor ({self._b_n_states_full}² × {self.n_actions} = "
                f"{self._b_n_states_full**2 * self.n_actions:,} entries) "
                f"exceeded _MAX_B_ENTRIES={_MAX_B_ENTRIES:,}; "
                f"kept top-{self._b_n_states_kept} state nodes by degree."
            ),
        }

    # Declared shapes are the logical array shapes. An empty A (zero
    # observations or zero hidden states) or an empty B (zero hidden
    # states) is still an ``[n_obs, n_states]`` /
    # ``[n_states, n_states, n_actions]`` array with a zero axis, so
    # fall back to the dimensions instead of collapsing to ``[0, 0]``.
    return {
        "A": A,
        "B": B,
        "C": C,
        "D": D,
        "shapes": {
            "A": [len(A), len(A[0])] if A else [self.n_obs, self.n_states],
            "B": [len(B), len(B[0]), len(B[0][0]) if B[0] else 0]
            if B
            else [0, 0, self.n_actions],
            "C": [len(C)],
            "D": [len(D)],
        },
        "dimensions": {
            "n_states": self.n_states,
            "n_obs": self.n_obs,
            "n_actions": self.n_actions,
        },
        "truncation": truncation,
    }

to_gnn_markdown_block()

Format the matrices as a GNN-compatible markdown block.

Emits AII-style sections with rows=, cols=, depth= bracket headers. This block is additive to the existing StateSpaceBlock / InitialParameterization sections; it is meant to be embedded as a COGANT extension.

Source code in py/cogant/gnn/matrices.py
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
def to_gnn_markdown_block(self) -> str:
    """Format the matrices as a GNN-compatible markdown block.

    Emits AII-style sections with ``rows=``, ``cols=``, ``depth=``
    bracket headers. This block is additive to the existing
    ``StateSpaceBlock`` / ``InitialParameterization`` sections; it is
    meant to be embedded as a COGANT extension.
    """
    A = self.compute_A()
    B = self.compute_B()
    C = self.compute_C()
    D = self.compute_D()

    lines: list[str] = []

    n_rows = len(A)
    n_cols = len(A[0]) if A else self.n_states
    lines.append(f"A[[rows={n_rows}][cols={n_cols}]]")
    for row in A:
        lines.append("  " + " ".join(repr(float(v)) for v in row))
    lines.append("")

    # --- B tensor ---
    if B:
        n_rows = len(B)
        n_cols = len(B[0]) if B else 0
        n_depth = len(B[0][0]) if (B and B[0]) else 0
        lines.append(f"B[[rows={n_rows}][cols={n_cols}][depth={n_depth}]]")
        for k in range(n_depth):
            lines.append(f"  # action={k}")
            for r in range(n_rows):
                row_vals = [B[r][c][k] for c in range(n_cols)]
                lines.append("  " + " ".join(repr(float(v)) for v in row_vals))
        lines.append("")
    else:
        lines.extend(("B[[rows=0][cols=0][depth=0]]", ""))

    # --- C vector ---
    lines.append(f"C[[rows={len(C)}]]")
    for v in C:
        lines.append(f"  {float(v)!r}")
    lines.append("")

    # --- D vector ---
    lines.append(f"D[[rows={len(D)}]]")
    for v in D:
        lines.append(f"  {float(v)!r}")
    lines.append("")

    return "\n".join(lines).rstrip()

to_plain_dict()

Export matrices as plain Python lists for JSON serialization.

Unlike :meth:to_dict, this method guarantees all values are plain Python lists/floats with no numpy arrays or other special types.

Returns:

Type Description
dict[str, Any]

A dict with keys "A", "B", "C", "D" containing the matrices

dict[str, Any]

as plain Python lists. Additional keys include "n_states",

dict[str, Any]

"n_obs", "n_actions" for shape information, and metadata like

dict[str, Any]

"b_truncated" if the B tensor was truncated.

Source code in py/cogant/gnn/matrices.py
902
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
def to_plain_dict(self) -> dict[str, Any]:
    """Export matrices as plain Python lists for JSON serialization.

    Unlike :meth:`to_dict`, this method guarantees all values are plain
    Python lists/floats with no numpy arrays or other special types.

    Returns:
        A dict with keys "A", "B", "C", "D" containing the matrices
        as plain Python lists.  Additional keys include "n_states",
        "n_obs", "n_actions" for shape information, and metadata like
        "b_truncated" if the B tensor was truncated.
    """
    A = self.compute_A()
    B = self.compute_B()
    C = self.compute_C()
    D = self.compute_D()

    # A, B, C, D are always plain Python lists — explicit ``list(...)``
    # copies guarantee independence from the cached compute_* outputs
    # so callers may mutate the returned dict safely.
    result: dict[str, Any] = {
        "A": [list(row) for row in A],
        "B": [[list(cell) for cell in row] for row in B],
        "C": list(C),
        "D": list(D),
        "n_states": self.n_states,
        "n_obs": self.n_obs,
        "n_actions": self.n_actions,
    }

    # Include truncation metadata if B was truncated.
    if self._b_truncated:
        result["b_truncated"] = True
        result["b_n_states_full"] = self._b_n_states_full
        result["b_n_states_kept"] = self._b_n_states_kept
        result["b_kept_state_indices"] = list(self._b_kept_state_indices)

    return result

validate()

Validate dimensional consistency across A/B/C/D matrices.

Checks that all four matrices have the expected shapes and that stochastic constraints are satisfied (column sums for A, column sums for B slices, sum for D).

Returns:

Type Description
list[str]

A list of validation issues. Empty list means all matrices

list[str]

are dimensionally consistent and satisfy stochastic constraints.

Source code in py/cogant/gnn/matrices.py
888
889
890
891
892
893
894
895
896
897
898
899
900
def validate(self) -> list[str]:
    """Validate dimensional consistency across A/B/C/D matrices.

    Checks that all four matrices have the expected shapes and that
    stochastic constraints are satisfied (column sums for A, column
    sums for B slices, sum for D).

    Returns:
        A list of validation issues. Empty list means all matrices
        are dimensionally consistent and satisfy stochastic constraints.
    """
    _, errors = self.validate_shapes()
    return errors

validate_shapes()

Validate that all four matrices have the expected shapes.

Returns:

Type Description
bool

(ok, errors) where ok is True if no shape errors

list[str]

were found.

Source code in py/cogant/gnn/matrices.py
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
def validate_shapes(self) -> tuple[bool, list[str]]:
    """Validate that all four matrices have the expected shapes.

    Returns:
        ``(ok, errors)`` where ``ok`` is True if no shape errors
        were found.
    """
    errors: list[str] = []
    A = self.compute_A()
    B = self.compute_B()
    C = self.compute_C()
    D = self.compute_D()

    n_s = self.n_states
    n_o = self.n_obs
    n_a = self.n_actions
    # A truncated B covers only the kept states (see compute_B).
    n_b = self._b_n_states_kept if self._b_truncated else n_s

    # A: n_obs x n_states, columns sum to 1.
    # Column-sum tolerance 1e-6 — principled default, matches the
    # PyMDP validator tolerance and is ~7 orders of magnitude
    # above float64 round-off noise (~1e-16) for a typical
    # n_states <= 50. Strict enough to catch normalization bugs
    # but loose enough to tolerate accumulated rounding across
    # multiple ``_normalize_row`` passes.
    if n_o > 0 and n_s > 0:
        if len(A) != n_o:
            errors.append(f"A row count {len(A)} != n_obs {n_o}")
        elif A and any(len(row) != n_s for row in A):
            errors.append(f"A has inconsistent column count (expected {n_s})")
        else:
            # A is column-stochastic: P(o|s) sums to 1 over observation
            # outcomes for each fixed hidden state s (a column).
            for j in range(n_s):
                col_sum = sum(A[i][j] for i in range(len(A)))
                if abs(col_sum - 1.0) > 1e-6:  # col-norm tolerance
                    errors.append(f"A column {j} does not sum to 1 (sum={col_sum:.6f})")

    # B: n_states x n_states x n_actions (n_states_kept when truncated)
    if n_s > 0:
        if len(B) != n_b:
            errors.append(f"B first dim {len(B)} != n_states {n_b}")
        elif any(len(row) != n_b for row in B):
            errors.append(f"B second dim != n_states {n_b}")
        elif any(len(cell) != n_a for row in B for cell in row):
            errors.append(f"B third dim != n_actions {n_a}")
        else:
            if any(
                B[i][j][k] < -1e-9 for i in range(n_b) for j in range(n_b) for k in range(n_a)
            ):
                errors.append("B contains negative probabilities")
            for k in range(n_a):
                for j in range(n_b):
                    col_sum = sum(B[i][j][k] for i in range(n_b))
                    if abs(col_sum - 1.0) > 1e-6:  # same tolerance as A columns
                        errors.append(
                            f"B action {k} column {j} does not sum to 1 (sum={col_sum:.6f})"
                        )

    # C: length n_obs
    if len(C) != n_o:
        errors.append(f"C length {len(C)} != n_obs {n_o}")

    # D: length n_states, sums to 1 (same 1e-6 tolerance as A/B
    # simplex-normalization check above).
    if len(D) != n_s:
        errors.append(f"D length {len(D)} != n_states {n_s}")
    elif D and abs(sum(D) - 1.0) > 1e-6:  # same tolerance as A/B columns
        errors.append(f"D does not sum to 1 (sum={sum(D):.6f})")

    return (len(errors) == 0, errors)

Runner

cogant.gnn.runner

Execute a package's declared matrices through the shared categorical kernel.

ExecutionTrace dataclass

Posterior beliefs and the subsequent action-conditioned prediction.

Source code in py/cogant/gnn/execution.py
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
@dataclass(frozen=True, slots=True)
class ExecutionTrace:
    """Posterior beliefs and the subsequent action-conditioned prediction."""

    step: int
    state: dict[str, float]
    action: str
    observation: str
    beliefs: dict[str, float]
    beliefs_prior: dict[str, float]
    free_energy_after: float
    policy_scores: list[tuple[str, float]]
    predicted_state: dict[str, float]

    @classmethod
    def from_record(cls, record: InferenceRecord, labels: AxisLabels) -> ExecutionTrace:
        """Attach axis labels without inferring semantics from their spelling."""
        prior = dict(zip(labels.states, record.prior, strict=True))
        return cls(
            step=record.t,
            state=prior.copy(),
            action=labels.actions[record.action],
            observation=labels.observations[record.observation],
            beliefs=dict(zip(labels.states, record.posterior, strict=True)),
            beliefs_prior=prior,
            free_energy_after=record.free_energy,
            policy_scores=list(zip(labels.actions, record.policy_scores, strict=True)),
            predicted_state=dict(zip(labels.states, record.predicted_belief, strict=True)),
        )

    def to_dict(self) -> dict[str, JsonValue]:
        """Return JSON-ready copies so consumers cannot mutate the trace."""
        return {
            "step": self.step,
            "state": dict(self.state),
            "action": self.action,
            "observation": self.observation,
            "beliefs": dict(self.beliefs),
            "beliefs_prior": dict(self.beliefs_prior),
            "free_energy_after": self.free_energy_after,
            "policy_scores": [[action, score] for action, score in self.policy_scores],
            "predicted_state": dict(self.predicted_state),
        }

from_record(record, labels) classmethod

Attach axis labels without inferring semantics from their spelling.

Source code in py/cogant/gnn/execution.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@classmethod
def from_record(cls, record: InferenceRecord, labels: AxisLabels) -> ExecutionTrace:
    """Attach axis labels without inferring semantics from their spelling."""
    prior = dict(zip(labels.states, record.prior, strict=True))
    return cls(
        step=record.t,
        state=prior.copy(),
        action=labels.actions[record.action],
        observation=labels.observations[record.observation],
        beliefs=dict(zip(labels.states, record.posterior, strict=True)),
        beliefs_prior=prior,
        free_energy_after=record.free_energy,
        policy_scores=list(zip(labels.actions, record.policy_scores, strict=True)),
        predicted_state=dict(zip(labels.states, record.predicted_belief, strict=True)),
    )

to_dict()

Return JSON-ready copies so consumers cannot mutate the trace.

Source code in py/cogant/gnn/execution.py
43
44
45
46
47
48
49
50
51
52
53
54
55
def to_dict(self) -> dict[str, JsonValue]:
    """Return JSON-ready copies so consumers cannot mutate the trace."""
    return {
        "step": self.step,
        "state": dict(self.state),
        "action": self.action,
        "observation": self.observation,
        "beliefs": dict(self.beliefs),
        "beliefs_prior": dict(self.beliefs_prior),
        "free_energy_after": self.free_energy_after,
        "policy_scores": [[action, score] for action, score in self.policy_scores],
        "predicted_state": dict(self.predicted_state),
    }

GNNModelRunner

Own a validated GNN snapshot and its most recent model rollout.

Observations are modes of A times the incoming belief, not measurements of source program execution. Actions minimize one-step risk-plus-ambiguity expected free energy.

Source code in py/cogant/gnn/runner.py
 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
 78
 79
 80
 81
 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
class GNNModelRunner:
    """Own a validated GNN snapshot and its most recent model rollout.

    Observations are modes of A times the incoming belief, not measurements
    of source program execution. Actions minimize one-step risk-plus-ambiguity
    expected free energy.
    """

    def __init__(self) -> None:
        self.package_dir = Path(".")
        self.manifest: dict[str, JsonValue] = {}
        self.traces: list[ExecutionTrace] = []
        self.beliefs_history: list[dict[str, float]] = []
        self.free_energy_trajectory: list[float] = []
        self.action_counts: dict[str, int] = {}
        self.last_error: str | None = None
        self._source: str | None = None
        self._result: RunnerResult | None = None
        self._work_per_step = 0

    def _clear_run(self) -> None:
        self.traces = []
        self.beliefs_history = []
        self.free_energy_trajectory = []
        self.action_counts = {}
        self.last_error = None
        self._result = None

    def load_package(self, package_dir: str) -> dict[str, JsonValue]:
        """Load complete model.gnn.md matrices; invalidate stale state on failure."""
        self._source = None
        self.manifest = {}
        self._clear_run()
        self.package_dir = Path(package_dir)
        manifest = TypeAdapter(dict[str, JsonValue]).validate_json(
            (self.package_dir / "manifest.json").read_bytes()
        )
        source = (self.package_dir / "model.gnn.md").read_bytes().decode("utf-8")
        model = parse_gnn(source)
        if model.degraded:
            raise ValueError("execution requires complete, non-degraded GNN matrices")
        functions = MatrixFunctions(model)
        categorical = CategoricalModel(functions.A, functions.B, functions.C, functions.D)
        states, observations = len(functions.D), len(functions.A)
        self._work_per_step = categorical.n_actions * (states * states + states * observations)
        self.manifest = manifest
        self._source = source
        return manifest

    def run(self, steps: int = 10) -> RunnerResult:
        """Execute 1 to 10,000 steps; invalid input fails without a success report."""
        self._clear_run()
        if self._source is None:
            raise RuntimeError("Package not loaded. Call load_package first.")
        try:
            inference = run_gnn_inference(self._source, InferenceOptions(steps=steps))
        except ValueError as error:
            self.last_error = str(error)
            raise
        self.traces = [
            ExecutionTrace.from_record(record, inference.labels) for record in inference.trace
        ]
        self.beliefs_history = [
            dict(zip(inference.labels.states, inference.matrices.D, strict=True))
        ]
        self.beliefs_history.extend(trace.beliefs.copy() for trace in self.traces)
        self.free_energy_trajectory = [trace.free_energy_after for trace in self.traces]
        for trace in self.traces:
            self.action_counts[trace.action] = self.action_counts.get(trace.action, 0) + 1
        self._result = execution_result(inference, self.traces, self.action_counts)
        return self._result

    def generate_execution_report(self, trace: RunnerResult | None = None) -> str:
        """Describe matrix inference without claiming program or control success."""
        result = trace if trace is not None else self._result
        if result is None:
            detail = (
                f"Execution rejected: {self.last_error}"
                if self.last_error
                else "No traces to report."
            )
            return f"# GNN Execution Report\n\n{detail}\n"
        return render_report(result)

    def run_with_profiling(
        self, num_steps: int = 10, num_trials: int = 1
    ) -> tuple[list[dict[str, JsonValue]], dict[str, float]]:
        """Measure complete inference runs; each trial restarts from exported D."""
        self._clear_run()
        InferenceOptions(steps=num_trials)
        InferenceOptions(steps=num_steps)
        if num_steps * num_trials > 10_000:
            raise ValueError("profiling exceeds the 10,000 total-step budget")
        if num_steps * num_trials * self._work_per_step > InferenceOptions().max_work_units:
            raise ValueError("profiling exceeds the combined matrix-work budget")
        traces: list[dict[str, JsonValue]] = []
        start = time.perf_counter()
        for trial in range(num_trials):
            result = self.run(num_steps)
            for item in result["traces"]:
                record = item.copy()
                record["trial"] = trial
                traces.append(record)
        return traces, {"total_ms": (time.perf_counter() - start) * 1000.0}

generate_execution_report(trace=None)

Describe matrix inference without claiming program or control success.

Source code in py/cogant/gnn/runner.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def generate_execution_report(self, trace: RunnerResult | None = None) -> str:
    """Describe matrix inference without claiming program or control success."""
    result = trace if trace is not None else self._result
    if result is None:
        detail = (
            f"Execution rejected: {self.last_error}"
            if self.last_error
            else "No traces to report."
        )
        return f"# GNN Execution Report\n\n{detail}\n"
    return render_report(result)

load_package(package_dir)

Load complete model.gnn.md matrices; invalidate stale state on failure.

Source code in py/cogant/gnn/runner.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def load_package(self, package_dir: str) -> dict[str, JsonValue]:
    """Load complete model.gnn.md matrices; invalidate stale state on failure."""
    self._source = None
    self.manifest = {}
    self._clear_run()
    self.package_dir = Path(package_dir)
    manifest = TypeAdapter(dict[str, JsonValue]).validate_json(
        (self.package_dir / "manifest.json").read_bytes()
    )
    source = (self.package_dir / "model.gnn.md").read_bytes().decode("utf-8")
    model = parse_gnn(source)
    if model.degraded:
        raise ValueError("execution requires complete, non-degraded GNN matrices")
    functions = MatrixFunctions(model)
    categorical = CategoricalModel(functions.A, functions.B, functions.C, functions.D)
    states, observations = len(functions.D), len(functions.A)
    self._work_per_step = categorical.n_actions * (states * states + states * observations)
    self.manifest = manifest
    self._source = source
    return manifest

run(steps=10)

Execute 1 to 10,000 steps; invalid input fails without a success report.

Source code in py/cogant/gnn/runner.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def run(self, steps: int = 10) -> RunnerResult:
    """Execute 1 to 10,000 steps; invalid input fails without a success report."""
    self._clear_run()
    if self._source is None:
        raise RuntimeError("Package not loaded. Call load_package first.")
    try:
        inference = run_gnn_inference(self._source, InferenceOptions(steps=steps))
    except ValueError as error:
        self.last_error = str(error)
        raise
    self.traces = [
        ExecutionTrace.from_record(record, inference.labels) for record in inference.trace
    ]
    self.beliefs_history = [
        dict(zip(inference.labels.states, inference.matrices.D, strict=True))
    ]
    self.beliefs_history.extend(trace.beliefs.copy() for trace in self.traces)
    self.free_energy_trajectory = [trace.free_energy_after for trace in self.traces]
    for trace in self.traces:
        self.action_counts[trace.action] = self.action_counts.get(trace.action, 0) + 1
    self._result = execution_result(inference, self.traces, self.action_counts)
    return self._result

run_with_profiling(num_steps=10, num_trials=1)

Measure complete inference runs; each trial restarts from exported D.

Source code in py/cogant/gnn/runner.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def run_with_profiling(
    self, num_steps: int = 10, num_trials: int = 1
) -> tuple[list[dict[str, JsonValue]], dict[str, float]]:
    """Measure complete inference runs; each trial restarts from exported D."""
    self._clear_run()
    InferenceOptions(steps=num_trials)
    InferenceOptions(steps=num_steps)
    if num_steps * num_trials > 10_000:
        raise ValueError("profiling exceeds the 10,000 total-step budget")
    if num_steps * num_trials * self._work_per_step > InferenceOptions().max_work_units:
        raise ValueError("profiling exceeds the combined matrix-work budget")
    traces: list[dict[str, JsonValue]] = []
    start = time.perf_counter()
    for trial in range(num_trials):
        result = self.run(num_steps)
        for item in result["traces"]:
            record = item.copy()
            record["trial"] = trial
            traces.append(record)
    return traces, {"total_ms": (time.perf_counter() - start) * 1000.0}

Validator

cogant.gnn.validator

GNN validator — validates a GNN package against the GNN specification.

Checks: - All required files present - JSON valid and well-formed - Markdown has all canonical sections in correct order - State space well-formed and connected - No orphan references - Checksums match - Provenance complete

GNNCapabilityError

Bases: RuntimeError

Raised when an explicitly requested validator capability is unavailable.

Source code in py/cogant/gnn/validator.py
25
26
27
28
class GNNCapabilityError(RuntimeError):
    """Raised when an explicitly requested validator capability is unavailable."""

    code = "CAPABILITY_UNAVAILABLE"

GNNValidator

Validates a GNN package against the GNN specification.

Source code in py/cogant/gnn/validator.py
 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
 403
 404
 405
 406
 407
 408
 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
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 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
 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
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 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
 974
 975
 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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
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
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
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
class GNNValidator:
    """Validates a GNN package against the GNN specification."""

    REQUIRED_FILES = [
        "manifest.json",
        "model.gnn.md",
        "model.gnn.json",
        "state_space.json",
        "observations.json",
        "actions.json",
        "transitions.json",
        "preferences.json",
        "factors.json",
        "provenance.json",
        "ontology.json",
        "actions_policies.json",
        "connections.json",
        "preferences_constraints.json",
        "markov_blanket.json",
        "markov_network.json",
    ]

    CANONICAL_SECTIONS = [
        "model_metadata",
        "repository_metadata",
        "source_coverage",
        "state_space",
        "observation_modalities",
        "actions_policies",
        "program_graph_connections",
        "factors",
        "transition_structure",
        "likelihood_structure",
        "preferences_constraints",
        "time_settings",
        "parameterization",
        "ontology_mapping",
        "markov_blanket",
        "provenance",
        "confidence",
        "rendering_hints",
        "validation_notes",
    ]

    # Upstream GNN 2.0.0 headers. COGANT emits these at the top of
    # ``model.gnn.md`` for upstream validation.
    UPSTREAM_SECTIONS = [
        "GNNSection",
        "GNNVersionAndFlags",
        "ModelName",
        "StateSpaceBlock",
        "Connections",
        "InitialParameterization",
        "Equations",
        "Time",
        "ActInfOntologyAnnotation",
        "ModelParameters",
        "Footer",
        "Signature",
    ]

    def __init__(self) -> None:
        """Initialize validator."""
        # ``validate_package`` is the single entry point and always
        # reassigns these before they're read. Type-annotating as
        # non-optional avoids a cascade of union-attr noise in the
        # private ``_check_*`` helpers below without hiding any real
        # null-dereference bug (the helpers are never called first).
        self.result: ValidationResult = ValidationResult()
        self.package_dir: Path = Path(".")
        self._upstream_gnn: bool = False

    def validate_package(
        self,
        package_dir: str,
        *,
        upstream_gnn: bool | None = None,
    ) -> ValidationResult:
        """
        Validate a GNN package.

        Args:
            package_dir: Path to the package directory.
            upstream_gnn: When True, run the Active Inference Institute
                ``generalized-notation-notation`` validator (upstream ``gnn``
                4.x, ``standard`` level) on ``model.gnn.md``; a requested but
                unavailable upstream is reported as a capability error. When
                ``None``, upstream runs only if
                :envvar:`COGANT_ENABLE_UPSTREAM_GNN` is truthy (and never when
                :envvar:`COGANT_DISABLE_UPSTREAM_GNN` is set).

        Returns:
            ValidationResult object.
        """
        self.package_dir = Path(package_dir)
        self.result = ValidationResult()
        self._upstream_gnn = _resolve_upstream_flag(upstream_gnn)
        self.result.capabilities["upstream_gnn"] = {
            "requested": self._upstream_gnn,
            "available": False,
        }
        try:
            from cogant.parsers.registry import parser_capabilities

            self.result.capabilities["parsers"] = {
                language: capability.__dict__
                for language, capability in parser_capabilities().items()
            }
        except Exception as exc:
            self.result.capabilities["parsers"] = {"error": str(exc)}

        logger.info(
            "Validating GNN package: %s (upstream_gnn=%s)",
            self.package_dir,
            self._upstream_gnn,
        )

        # Check 1: Directory exists
        if not self.package_dir.exists():
            self.result.errors.append(f"Package directory not found: {self.package_dir}")
            self.result.valid = False
            self.result.score = 0.0
            return self.result

        if not self.package_dir.is_dir():
            self.result.errors.append(f"Package path is not a directory: {self.package_dir}")
            self.result.score = 0.0
            return self.result

        self.result.artifact_digests = self._artifact_digests()

        # Check 2: Required files present
        self._check_required_files()

        # Check 3: Manifest valid
        manifest = self._check_manifest()

        # Check 4: JSON files valid
        self._check_json_files()

        # Check 4b: best-effort artifacts the builder could not produce
        self._check_artifact_status(manifest)

        # Check 5: A/B/C/D matrix block valid
        self._check_matrices()

        # Check 6: Markdown valid
        self._check_markdown()

        # Check 7: State space valid
        self._check_state_space()

        # Check 8: Provenance valid
        self._check_provenance()

        # Check 9: Checksums match
        if manifest:
            self._check_checksums(manifest)

        # Compute final score and validity
        self._compute_final_score()

        logger.info(
            "Validation complete: %s (score=%.1f%%, %d errors, %d warnings)",
            self.result.valid,
            self.result.score,
            len(self.result.errors),
            len(self.result.warnings),
        )
        return self.result

    def validate_markdown(self, markdown: str) -> list[str]:
        """
        Validate GNN markdown structure.

        Checks both the COGANT-extended canonical sections
        (``## Model Metadata``, ``## Source Coverage``, ``## Markov
        Blanket``, etc.) and the upstream GNN 2.0.0 required headers
        (``## GNNSection``, ``## StateSpaceBlock``, ``## Connections``,
        ``## InitialParameterization``, ``## Equations``, ``## Time``,
        ``## ActInfOntologyAnnotation``, ``## ModelParameters``, etc.). Upstream section
        checks are ordered: they must appear in the spec-mandated
        order at the TOP of the file.

        Args:
            markdown: Markdown content.

        Returns:
            List of errors (empty if valid).
        """
        errors: list[str] = []
        lowered = markdown.lower()

        # 1) COGANT-extended canonical sections (case-insensitive presence check).
        for section in self.CANONICAL_SECTIONS:
            section_header = f"## {section.replace('_', ' ').title()}"
            if section_header.lower() not in lowered:
                errors.append(f"Missing canonical section: {section}")

        # 2) Upstream GNN 2.0.0 required sections — each must be present.
        missing_upstream: list[str] = []
        upstream_offsets: list[tuple[str, int]] = []
        for section in self.UPSTREAM_SECTIONS:
            marker = f"## {section}"
            idx = markdown.find(marker)
            if idx < 0:
                missing_upstream.append(section)
            else:
                upstream_offsets.append((section, idx))
        for section in missing_upstream:
            errors.append(f"Missing upstream GNN 2.0.0 section: {section}")

        # 3) Upstream sections must appear in canonical order.
        if not missing_upstream and upstream_offsets:
            expected_order = list(self.UPSTREAM_SECTIONS)
            found_order = [section for section, _ in sorted(upstream_offsets, key=lambda x: x[1])]
            if expected_order != found_order:
                errors.append(
                    "Upstream GNN 2.0.0 sections out of canonical order: "
                    f"found {found_order}, expected {expected_order}"
                )

        return errors

    def validate_state_space(self, state_space_json: dict[str, Any]) -> list[str]:
        """
        Validate state space structure.

        Args:
            state_space_json: State space JSON.

        Returns:
            List of errors (empty if valid).
        """
        if not isinstance(state_space_json, dict):
            return ["State-space root must be a JSON object"]
        errors: list[str] = []

        # Check required keys
        required_keys = ["variables", "observations", "actions", "transitions"]
        for key in required_keys:
            if key not in state_space_json:
                errors.append(f"Missing state space key: {key}")

        # Check variables are well-formed
        variables = state_space_json.get("variables", [])
        if not isinstance(variables, list):
            errors.append("Variables must be a list")
        elif any(not isinstance(item, dict) for item in variables):
            errors.append("Variables entries must be objects")

        # Check observations are well-formed
        observations = state_space_json.get("observations", [])
        if not isinstance(observations, list):
            errors.append("Observations must be a list")
        elif any(not isinstance(item, dict) for item in observations):
            errors.append("Observations entries must be objects")

        # Check actions are well-formed
        actions = state_space_json.get("actions", [])
        if not isinstance(actions, list):
            errors.append("Actions must be a list")
        elif any(not isinstance(item, dict) for item in actions):
            errors.append("Actions entries must be objects")

        # Check transitions are well-formed
        transitions = state_space_json.get("transitions", {})
        if not isinstance(transitions, dict):
            errors.append("Transitions must be a dict")
        else:
            if not isinstance(transitions.get("transition_count"), int):
                errors.append("Transitions must declare an integer transition_count")
            if not isinstance(transitions.get("time_regime"), str) or not transitions.get(
                "time_regime"
            ):
                errors.append("Transitions must declare a non-empty time_regime")

        metadata = state_space_json.get("metadata")
        if metadata is not None:
            if not isinstance(metadata, dict):
                errors.append("State-space metadata must be an object")
            else:
                for key, values in (
                    ("num_variables", variables),
                    ("num_observations", observations),
                    ("num_actions", actions),
                ):
                    declared = metadata.get(key)
                    if isinstance(values, list) and declared != len(values):
                        errors.append(f"State-space metadata {key} does not match emitted entries")

        return errors

    def validate_matrices(self, matrices_json: dict[str, Any]) -> list[str]:
        """Validate the AII Active Inference matrix block.

        Checks presence and shape of the A/B/C/D matrices emitted by
        :class:`cogant.gnn.matrices.GNNMatrices`. The matrices must
        satisfy:

        * A: shape ``[n_obs x n_states]``, columns sum to 1.0.
        * B: shape ``[n_states x n_states x n_actions]``; when
          ``truncation.applied`` is set (large-repo top-K cut, see
          :meth:`cogant.gnn.matrices.GNNMatrices.compute_B`) the state
          axes are ``n_states_kept`` and ``truncation.kept_state_indices``
          must name those states on the full A/D axis.
        * C: length equal to ``n_obs``.
        * D: length equal to ``n_states``, sums to 1.0.

        Args:
            matrices_json: Dict of the form
                ``{"A": ..., "B": ..., "C": ..., "D": ...,
                "dimensions": {"n_states", "n_obs", "n_actions"}}``.

        Returns:
            List of errors (empty if matrices are well-formed).
        """
        errors: list[str] = []

        for key in ("A", "B", "C", "D"):
            if key not in matrices_json:
                errors.append(f"Missing matrix: {key}")

        A = matrices_json.get("A", [])
        B = matrices_json.get("B", [])
        C = matrices_json.get("C", [])
        D = matrices_json.get("D", [])

        if not isinstance(A, list):
            errors.append("A must be a list")
            A = []
        if not isinstance(B, list):
            errors.append("B must be a list")
            B = []
        if not isinstance(C, list):
            errors.append("C must be a list")
            C = []
        if not isinstance(D, list):
            errors.append("D must be a list")
            D = []
        if any(not isinstance(row, list) for row in A):
            errors.append("A rows must be lists")
            A = [row for row in A if isinstance(row, list)]
        if any(not isinstance(row, list) for row in B):
            errors.append("B rows must be lists")
            B = [row for row in B if isinstance(row, list)]
        if any(not isinstance(cell, list) for row in B for cell in row):
            errors.append("B cells must be lists")
            B = [[cell for cell in row if isinstance(cell, list)] for row in B]

        dims = matrices_json.get("dimensions")
        if not isinstance(dims, dict):
            if dims is None:
                errors.append("dimensions must be declared as an object")
            else:
                errors.append("dimensions must be an object")
            dims = {}

        inferred_states = len(D) or (len(A[0]) if A and A[0] else 0)
        inferred_obs = len(A) or len(C)
        inferred_actions = len(B[0][0]) if B and B[0] and B[0][0] else 0

        def dimension(name: str, inferred: int) -> int:
            if name not in dims:
                return inferred
            value = dims[name]
            if isinstance(value, bool) or not isinstance(value, int) or value < 0:
                errors.append(f"dimensions.{name} must be a non-negative integer")
                return inferred
            return value

        n_states = dimension("n_states", inferred_states)
        n_obs = dimension("n_obs", inferred_obs)
        n_actions = dimension("n_actions", inferred_actions)
        n_b_states = self._truncated_b_state_count(matrices_json, n_states, errors)

        shapes = matrices_json.get("shapes")
        if not isinstance(shapes, dict):
            errors.append("shapes must be declared as an object")
        else:
            expected_shapes = {
                "A": [n_obs, n_states],
                "B": [n_b_states, n_b_states, n_actions],
                "C": [n_obs],
                "D": [n_states],
            }
            for key, expected in expected_shapes.items():
                actual_shape = shapes.get(key)
                if actual_shape != expected:
                    errors.append(f"declared shape for {key} does not match dimensions")

        for name, value, actual in (
            ("n_states", n_states, len(D)),
            ("n_obs", n_obs, len(C)),
        ):
            if name in dims and actual != value:
                errors.append(
                    f"declared {name}={value} does not match {name} vector length {actual}"
                )
        if "n_states" in dims and A and any(len(row) != n_states for row in A):
            errors.append(f"declared n_states={n_states} does not match A column count")
        if "n_obs" in dims and A and len(A) != n_obs:
            errors.append(f"declared n_obs={n_obs} does not match A row count")
        if (
            "n_actions" in dims
            and B
            and B[0]
            and any(len(cell) != n_actions for row in B for cell in row)
        ):
            errors.append(f"declared n_actions={n_actions} does not match B depth")

        # A: rows == n_obs, cols == n_states, columns sum to 1 (column-stochastic).
        if n_obs > 0 and n_states > 0:
            if len(A) != n_obs:
                errors.append(f"A row count {len(A)} != n_obs {n_obs}")
            elif A and any(len(row) != n_states for row in A):
                errors.append(f"A column count mismatch; expected {n_states}")
            else:
                # Tolerance 1e-6 — stability constant. A-matrix encodes
                # P(o|s) and is column-stochastic (AII/pymdp convention):
                # for each fixed hidden state s (a column), the distribution
                # over observation outcomes sums to 1. float64 accumulation
                # introduces ~n_obs * eps drift; 1e-6 leaves ~8 orders of
                # magnitude headroom and matches the pymdp / scipy convention
                # for stochastic-matrix normalization checks.
                if any(
                    not isinstance(A[i][j], (int, float))
                    or not math.isfinite(float(A[i][j]))
                    or A[i][j] < -1e-9
                    for i in range(len(A))
                    for j in range(n_states)
                ):
                    errors.append("A contains negative probabilities")
                for j in range(n_states):
                    col_sum = sum(A[i][j] for i in range(len(A)))
                    if abs(col_sum - 1.0) > 1e-6:
                        errors.append(f"A column {j} does not sum to 1 (sum={col_sum:.6f})")

        elif A:
            errors.append("A must be empty when observations or hidden states are zero")

        # B: shape n_states x n_states x n_actions (n_states_kept when
        # the top-K truncation was applied).
        if n_states > 0:
            if n_actions == 0 and not B:
                pass
            elif len(B) != n_b_states:
                errors.append(f"B first dim {len(B)} != n_states {n_b_states}")
            elif any(len(row) != n_b_states for row in B):
                errors.append(f"B second dim mismatch; expected {n_b_states}")
            elif any(len(cell) != n_actions for row in B for cell in row):
                errors.append(f"B third dim mismatch; expected {n_actions}")
            else:
                if any(
                    not isinstance(B[i][j][k], (int, float))
                    or not math.isfinite(float(B[i][j][k]))
                    or B[i][j][k] < -1e-9
                    for i in range(n_b_states)
                    for j in range(n_b_states)
                    for k in range(n_actions)
                ):
                    errors.append("B contains negative probabilities")
                for k in range(n_actions):
                    for j in range(n_b_states):
                        col_sum = sum(B[i][j][k] for i in range(n_b_states))
                        if abs(col_sum - 1.0) > 1e-6:
                            errors.append(
                                f"B action {k} column {j} does not sum to 1 (sum={col_sum:.6f})"
                            )

        elif B:
            errors.append("B must be empty when hidden states are zero")

        # C: length n_obs.
        if len(C) != n_obs:
            errors.append(f"C length {len(C)} != n_obs {n_obs}")
        elif any(
            not isinstance(value, (int, float)) or not math.isfinite(float(value)) for value in C
        ):
            errors.append("C contains non-finite values")

        # D: length n_states, sums to 1.
        if len(D) != n_states:
            errors.append(f"D length {len(D)} != n_states {n_states}")
        elif n_states > 0:
            if any(
                not isinstance(value, (int, float))
                or not math.isfinite(float(value))
                or value < -1e-9
                for value in D
            ):
                errors.append("D contains negative probabilities")
            elif D and abs(sum(D) - 1.0) > 1e-6:
                # Tolerance 1e-6 — stability constant, same rationale as
                # A-column tolerance above (pymdp/scipy convention for
                # probability-simplex sum checks; ~8 orders of magnitude
                # headroom over float64 accumulation drift).
                errors.append(f"D does not sum to 1 (sum={sum(D):.6f})")

        return errors

    @staticmethod
    def _truncated_b_state_count(
        matrices_json: dict[str, Any], n_states: int, errors: list[str]
    ) -> int:
        """Return the expected B state-axis length, honouring truncation.

        ``GNNMatrices.compute_B`` keeps only the top-K states when the
        full tensor would exceed its entry cap and records the cut under
        ``truncation``. A truncated B is valid only when the metadata says
        how many states were kept and which full-axis states they are.
        """
        truncation = matrices_json.get("truncation")
        if truncation is None:
            return n_states
        if not isinstance(truncation, dict):
            errors.append("truncation must be an object or null")
            return n_states
        if truncation.get("applied") is not True:
            return n_states
        kept = truncation.get("n_states_kept")
        if isinstance(kept, bool) or not isinstance(kept, int) or not 0 < kept <= n_states:
            errors.append(
                f"truncation.n_states_kept must be an integer in [1, n_states={n_states}]"
            )
            return n_states
        full = truncation.get("n_states_full", n_states)
        if full != n_states:
            errors.append(
                f"truncation.n_states_full={full!r} does not match declared n_states={n_states}"
            )
        indices = truncation.get("kept_state_indices")
        if (
            not isinstance(indices, list)
            or len(indices) != kept
            or any(isinstance(i, bool) or not isinstance(i, int) for i in indices)
            or any(not 0 <= i < n_states for i in indices)
            or indices != sorted(set(indices))
        ):
            errors.append(
                "truncation.kept_state_indices must list n_states_kept distinct, ascending "
                "indices into the hidden-state axis"
            )
        return kept

    def _effective_matrix_dimensions(self, matrices_json: dict[str, Any]) -> dict[str, int]:
        """Return matrix dimensions declared in, or inferred from, A/B/C/D."""
        B = matrices_json.get("B", [])
        C = matrices_json.get("C", [])
        D = matrices_json.get("D", [])
        dims = matrices_json.get("dimensions")
        dims = dims if isinstance(dims, dict) else {}
        n_states = dims.get("n_states", len(D) if isinstance(D, list) else 0)
        n_obs = dims.get("n_obs", len(C) if isinstance(C, list) else 0)
        n_actions = dims.get(
            "n_actions",
            len(B[0][0]) if isinstance(B, list) and B and B[0] and B[0][0] else 0,
        )
        if not all(
            isinstance(value, int) and not isinstance(value, bool)
            for value in (n_states, n_obs, n_actions)
        ):
            return {"n_states": 0, "n_obs": 0, "n_actions": 0}
        return {"n_states": n_states, "n_obs": n_obs, "n_actions": n_actions}

    def _state_space_dimensions(self) -> dict[str, int] | None:
        """Return compiled state-space dimensions from ``state_space.json``."""
        state_space_path = self.package_dir / "state_space.json"
        if not state_space_path.exists():
            return None
        try:
            with open(state_space_path) as f:
                loaded = json.load(f)
        except Exception as exc:
            self.result.warnings.append(f"Matrix validation skipped state-space alignment: {exc}")
            return None
        state_space = loaded if isinstance(loaded, dict) else {}

        def _count(key: str) -> int:
            value = state_space.get(key)
            if isinstance(value, (list, dict)):
                return len(value)
            return 0

        return {
            "n_states": _count("variables"),
            "n_obs": _count("observations"),
            "n_actions": _count("actions"),
        }

    def _matrix_state_space_alignment_errors(
        self,
        matrix_dimensions: dict[str, int],
        state_space_dimensions: dict[str, int] | None,
    ) -> tuple[list[str], dict[str, Any]]:
        """Compare matrix dimensions with compiled state-space dimensions."""
        if state_space_dimensions is None:
            return [], {}

        alignment: dict[str, Any] = {
            "matrix_dimensions": matrix_dimensions,
            "state_space_dimensions": state_space_dimensions,
        }
        errors: list[str] = []
        comparisons = (
            ("n_states", "hidden-state"),
            ("n_obs", "observation"),
            ("n_actions", "action"),
        )
        for key, label in comparisons:
            matrix_value = matrix_dimensions.get(key, 0)
            state_value = state_space_dimensions.get(key, 0)
            match = matrix_value == state_value
            alignment[f"{key}_match"] = match
            if not match:
                errors.append(
                    f"{label} dimension mismatch: matrix {key}={matrix_value} "
                    f"!= state_space {key}={state_value}"
                )
        return errors, alignment

    def _matrix_degenerate_warnings(
        self,
        matrices: dict[str, Any],
        matrix_dimensions: dict[str, int],
        state_space_dimensions: dict[str, int] | None,
    ) -> list[str]:
        """Return non-public warnings for valid but degenerate matrix exports."""
        warnings: list[str] = []
        if state_space_dimensions is None:
            return warnings
        if (
            state_space_dimensions.get("n_obs") == 0
            and matrix_dimensions.get("n_obs") == 0
            and not matrices.get("A")
            and not matrices.get("C")
        ):
            warnings.append(
                "Matrix validation: degenerate model has no observation modalities; "
                "A/C are empty and not publication-ready evidence"
            )
        if (
            state_space_dimensions.get("n_states") == 0
            and matrix_dimensions.get("n_states") == 0
            and (not matrices.get("A") or not matrices.get("B") or not matrices.get("D"))
        ):
            warnings.append(
                "Matrix validation: degenerate model has no hidden-state variables; "
                "A/B/D are empty and not publication-ready evidence"
            )
        return warnings

    def validate_provenance(self, provenance_json: dict[str, Any]) -> list[str]:
        """
        Validate provenance structure.

        Args:
            provenance_json: Provenance JSON.

        Returns:
            List of errors (empty if valid).
        """
        if not isinstance(provenance_json, dict):
            return ["Provenance root must be a JSON object"]
        errors: list[str] = []

        # Check required keys
        required_keys = ["timestamp", "sources"]
        for key in required_keys:
            if key not in provenance_json:
                errors.append(f"Missing provenance key: {key}")

        # Check sources
        sources = provenance_json.get("sources", {})
        if not isinstance(sources, dict):
            errors.append("Provenance sources must be a dict")

        return errors

    def generate_validation_badge(self, result: ValidationResult) -> str:
        """
        Generate SVG validation badge.

        Args:
            result: Validation result.

        Returns:
            SVG string.
        """
        return result.badge_svg()

    # Private validation methods

    def _check_required_files(self) -> None:
        """Check that all required files are present."""
        for filename in self.REQUIRED_FILES:
            filepath = self.package_dir / filename
            if not filepath.exists():
                self.result.errors.append(f"Missing required file: {filename}")
            else:
                logger.debug(f"  ✓ Found {filename}")

    def _check_manifest(self) -> dict[str, Any] | None:
        """Check manifest validity and return parsed manifest."""
        manifest_path = self.package_dir / "manifest.json"
        if not manifest_path.exists():
            self.result.errors.append("Missing manifest.json")
            return None

        try:
            with open(manifest_path) as f:
                loaded = json.load(f)
            if not isinstance(loaded, dict):
                self.result.errors.append("manifest.json must contain a JSON object")
                return None
            manifest = dict(loaded)
            logger.debug("  ✓ manifest.json is valid JSON")
            self.result.details["manifest"] = manifest
            return manifest
        except json.JSONDecodeError as e:
            self.result.errors.append(f"Invalid JSON in manifest.json: {e}")
            return None
        except Exception as e:
            self.result.errors.append(f"Failed to read manifest.json: {e}")
            return None

    def _check_json_files(self) -> None:
        """Check that all JSON files are valid."""
        json_files = [
            filename
            for filename in self.REQUIRED_FILES
            if filename.endswith(".json") and filename != "manifest.json"
        ]

        for filename in json_files:
            filepath = self.package_dir / filename
            if not filepath.exists():
                continue

            try:
                with open(filepath) as f:
                    loaded = json.load(f)
                    if not isinstance(loaded, dict):
                        self.result.errors.append(f"JSON root must be an object in {filename}")
                        continue
                logger.debug(f"  ✓ {filename} is valid JSON")
            except json.JSONDecodeError as e:
                self.result.errors.append(f"Invalid JSON in {filename}: {e}")
            except Exception as e:
                self.result.errors.append(f"Failed to read {filename}: {e}")

    # Best-effort artifacts whose failure GNNPackageBuilder records in
    # ``manifest.artifact_status`` while writing a placeholder JSON payload.
    BEST_EFFORT_ARTIFACTS = ("markov_blanket",)

    def _check_artifact_status(self, manifest: dict[str, Any] | None) -> None:
        """Warn about best-effort artifacts that are placeholders, not evidence.

        ``GNNPackageBuilder`` keeps a package structurally consumable when a
        derived artifact (currently the Markov blanket) cannot be computed:
        it writes a stub payload whose ``metadata`` carries ``error: true`` /
        ``status: "unavailable"`` and records the outcome in
        ``manifest.artifact_status``. The stub is valid JSON, so without this
        check the package would be certified with a full score. Each
        non-``"success"`` artifact becomes a validation warning; the status
        map is stored under ``details["artifact_status"]``.
        """
        statuses: dict[str, str] = {}
        raw_status = manifest.get("artifact_status") if isinstance(manifest, dict) else None
        if isinstance(raw_status, dict):
            statuses = {str(name): str(status) for name, status in raw_status.items()}

        for name in self.BEST_EFFORT_ARTIFACTS:
            metadata = self._artifact_metadata(name)
            stub_status = None
            if metadata.get("error") is True or metadata.get("status") == "unavailable":
                stub_status = str(metadata.get("status") or "unavailable")
            if stub_status and statuses.get(name, "success") == "success":
                # Older or hand-edited manifests may not record the failure;
                # the placeholder payload itself still says it is unavailable.
                statuses[name] = stub_status
            elif name not in statuses and (self.package_dir / f"{name}.json").exists():
                statuses[name] = "success"

        self.result.details["artifact_status"] = statuses
        for name, status in sorted(statuses.items()):
            if status == "success":
                continue
            reason = self._artifact_metadata(name).get("reason")
            suffix = f": {reason}" if reason else ""
            self.result.warnings.append(
                f"Artifact {name} is {status}{suffix}; {name}.json is a placeholder "
                "and not publication-ready evidence"
            )

    def _artifact_metadata(self, name: str) -> dict[str, Any]:
        """Return the ``metadata`` object of ``<name>.json`` (empty if absent)."""
        path = self.package_dir / f"{name}.json"
        try:
            loaded = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, ValueError):
            return {}
        metadata = loaded.get("metadata") if isinstance(loaded, dict) else None
        return metadata if isinstance(metadata, dict) else {}

    def _check_matrices(self) -> None:
        """Validate the exported ``model.gnn.json`` A/B/C/D matrix block."""
        model_path = self.package_dir / "model.gnn.json"
        if not model_path.exists():
            self.result.errors.append("Missing model.gnn.json for matrix validation")
            return

        try:
            with open(model_path) as f:
                loaded = json.load(f)
            model = loaded if isinstance(loaded, dict) else {}
            matrices_raw = model.get("matrices")
            if not isinstance(matrices_raw, dict):
                self.result.errors.append("Missing matrices block in model.gnn.json")
                self.result.details["matrices"] = {
                    "present": False,
                    "validation_errors": ["Missing matrices block in model.gnn.json"],
                }
                return
            matrices = matrices_raw
            errors = self.validate_matrices(matrices)
            matrix_dimensions = self._effective_matrix_dimensions(matrices)
            state_space_dimensions = self._state_space_dimensions()
            alignment_errors, dimension_alignment = self._matrix_state_space_alignment_errors(
                matrix_dimensions,
                state_space_dimensions,
            )
            errors.extend(alignment_errors)
            warnings = self._matrix_degenerate_warnings(
                matrices,
                matrix_dimensions,
                state_space_dimensions,
            )
            self.result.details["matrices"] = {
                "present": True,
                "shapes": matrices.get("shapes")
                if isinstance(matrices.get("shapes"), dict)
                else {},
                "dimensions": (
                    matrices.get("dimensions")
                    if isinstance(matrices.get("dimensions"), dict)
                    else {}
                ),
                "effective_dimensions": matrix_dimensions,
                "state_space_dimensions": state_space_dimensions or {},
                "dimension_alignment": dimension_alignment,
                "truncation": matrices.get("truncation"),
                "matrix_keys": [key for key in ("A", "B", "C", "D") if key in matrices],
                "validation_errors": errors,
                "validation_warnings": warnings,
            }
            self.result.dimensions = {
                "matrices": matrix_dimensions,
                "state_space": state_space_dimensions or {},
                "alignment": dimension_alignment,
            }
            if errors:
                self.result.errors.extend(f"Matrix validation: {error}" for error in errors)
            else:
                logger.debug("  ✓ model.gnn.json matrices are well-formed")
            self.result.warnings.extend(warnings)
        except Exception as e:
            self.result.errors.append(f"Failed to validate model.gnn.json matrices: {e}")

    def _check_markdown(self) -> None:
        """Check markdown validity."""
        markdown_path = self.package_dir / "model.gnn.md"
        if not markdown_path.exists():
            self.result.errors.append("Missing model.gnn.md")
            return

        try:
            markdown = markdown_path.read_text(encoding="utf-8")
            errors = self.validate_markdown(markdown)
            if errors:
                self.result.errors.extend(f"Markdown validation: {error}" for error in errors)
            else:
                logger.debug("  ✓ model.gnn.md has all canonical sections")

            if getattr(self, "_upstream_gnn", False):
                from cogant.gnn.upstream_bridge import run_upstream_validate_gnn

                up = run_upstream_validate_gnn(markdown)
                self.result.details["upstream_gnn"] = up.to_dict()
                self.result.capabilities["upstream_gnn"] = up.to_dict()
                if not up.available:
                    self.result.capabilities["upstream_gnn"] = {
                        **up.to_dict(),
                        "requested": True,
                        "available": False,
                        "error_code": GNNCapabilityError.code,
                    }
                    self.result.errors.append(
                        f"{GNNCapabilityError.code}: requested upstream GNN validation is unavailable: "
                        f"{up.skipped_reason or 'install the cogant[upstream] extra'}"
                    )
                elif not up.ok:
                    self.result.errors.extend(f"[upstream GNN] {err}" for err in up.errors)
        except Exception as e:
            self.result.errors.append(f"Failed to read model.gnn.md: {e}")

    def _check_state_space(self) -> None:
        """Check state space validity."""
        state_space_path = self.package_dir / "state_space.json"
        if not state_space_path.exists():
            self.result.errors.append("Missing state_space.json")
            return

        try:
            with open(state_space_path) as f:
                state_space = json.load(f)
            if not isinstance(state_space, dict):
                self.result.errors.append(
                    "State-space validation: state_space.json root must be an object"
                )
                return
            errors = self.validate_state_space(state_space)
            if errors:
                self.result.errors.extend(f"State-space validation: {error}" for error in errors)
            else:
                logger.debug("  ✓ state_space.json is well-formed")
        except Exception as e:
            self.result.errors.append(f"Failed to validate state_space.json: {e}")

    def _check_provenance(self) -> None:
        """Check provenance validity."""
        provenance_path = self.package_dir / "provenance.json"
        if not provenance_path.exists():
            self.result.errors.append("Missing provenance.json")
            return

        try:
            with open(provenance_path) as f:
                provenance = json.load(f)
            if not isinstance(provenance, dict):
                self.result.errors.append(
                    "Provenance validation: provenance.json root must be an object"
                )
                return
            errors = self.validate_provenance(provenance)
            if errors:
                self.result.errors.extend(f"Provenance validation: {error}" for error in errors)
            else:
                logger.debug("  ✓ provenance.json is well-formed")
        except Exception as e:
            self.result.errors.append(f"Failed to validate provenance.json: {e}")

    def _check_checksums(self, manifest: dict[str, Any]) -> None:
        """Check that checksums match."""
        checksums = manifest.get("checksums")
        if not isinstance(checksums, dict) or not checksums:
            self.result.errors.append("Manifest must contain checksums for evidence validation")
            return

        # The manifest owns this table, so including its own digest would be
        # recursive. Every other required artifact must be covered.
        for required in self.REQUIRED_FILES:
            if required == "manifest.json":
                continue
            if required not in checksums:
                self.result.errors.append(
                    f"Manifest is missing checksum for required file: {required}"
                )

        for filename, expected_checksum in checksums.items():
            if not isinstance(filename, str) or not isinstance(expected_checksum, str):
                self.result.errors.append("Manifest checksums must map string filenames to digests")
                continue
            filepath = (self.package_dir / filename).resolve()
            if self.package_dir.resolve() not in filepath.parents:
                self.result.errors.append(f"Checksum path escapes package directory: {filename}")
                continue
            if not filepath.is_file():
                self.result.errors.append(f"Checksum references missing file: {filename}")
                continue

            try:
                if filepath.suffix == ".json":
                    with open(filepath) as f:
                        data = json.load(f)
                    actual = hashlib.sha256(
                        json.dumps(data, sort_keys=True, default=str).encode()
                    ).hexdigest()
                else:
                    actual = hashlib.sha256(filepath.read_bytes()).hexdigest()

                if actual != expected_checksum:
                    message = (
                        f"Checksum mismatch for {filename}: "
                        f"expected {expected_checksum}, got {actual}"
                    )
                    self.result.errors.append(message)
                else:
                    logger.debug(f"  ✓ {filename} checksum matches")
            except Exception as e:
                message = f"Failed to verify checksum for {filename}: {e}"
                self.result.errors.append(message)

    def _artifact_digests(self) -> dict[str, str]:
        """Return raw SHA-256 digests for every regular package artifact."""
        digests: dict[str, str] = {}
        for path in sorted(self.package_dir.rglob("*")):
            if path.is_file() and path.name != "manifest.json":
                digests[str(path.relative_to(self.package_dir))] = hashlib.sha256(
                    path.read_bytes()
                ).hexdigest()
        return digests

    def _compute_final_score(self) -> None:
        """Compute final validation score and validity.

        The score is a human-readable quality signal only. Certification is
        evidence-based: any hard validation error makes the package invalid,
        while advisories remain visible without being converted into a pass.
        """
        # Keep the score monotonic for reports, but never use it to certify a
        # package. One hard error is enough to invalidate evidence.
        max_points = 100  # percentage scale
        points_per_error = 10  # 10 errors → zero score
        points_per_warning = 2  # 5:1 severity ratio vs. errors

        score = max_points
        score -= len(self.result.errors) * points_per_error
        score -= len(self.result.warnings) * points_per_warning
        score = max(0, min(100, score))

        self.result.score = float(score)
        self.result.valid = len(self.result.errors) == 0

        logger.debug(
            f"  Final score: {self.result.score:.1f}% - {'VALID' if self.result.valid else 'INVALID'}"
        )

__init__()

Initialize validator.

Source code in py/cogant/gnn/validator.py
237
238
239
240
241
242
243
244
245
246
def __init__(self) -> None:
    """Initialize validator."""
    # ``validate_package`` is the single entry point and always
    # reassigns these before they're read. Type-annotating as
    # non-optional avoids a cascade of union-attr noise in the
    # private ``_check_*`` helpers below without hiding any real
    # null-dereference bug (the helpers are never called first).
    self.result: ValidationResult = ValidationResult()
    self.package_dir: Path = Path(".")
    self._upstream_gnn: bool = False

generate_validation_badge(result)

Generate SVG validation badge.

Parameters:

Name Type Description Default
result ValidationResult

Validation result.

required

Returns:

Type Description
str

SVG string.

Source code in py/cogant/gnn/validator.py
855
856
857
858
859
860
861
862
863
864
865
def generate_validation_badge(self, result: ValidationResult) -> str:
    """
    Generate SVG validation badge.

    Args:
        result: Validation result.

    Returns:
        SVG string.
    """
    return result.badge_svg()

validate_markdown(markdown)

Validate GNN markdown structure.

Checks both the COGANT-extended canonical sections (## Model Metadata, ## Source Coverage, ## Markov Blanket, etc.) and the upstream GNN 2.0.0 required headers (## GNNSection, ## StateSpaceBlock, ## Connections, ## InitialParameterization, ## Equations, ## Time, ## ActInfOntologyAnnotation, ## ModelParameters, etc.). Upstream section checks are ordered: they must appear in the spec-mandated order at the TOP of the file.

Parameters:

Name Type Description Default
markdown str

Markdown content.

required

Returns:

Type Description
list[str]

List of errors (empty if valid).

Source code in py/cogant/gnn/validator.py
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
def validate_markdown(self, markdown: str) -> list[str]:
    """
    Validate GNN markdown structure.

    Checks both the COGANT-extended canonical sections
    (``## Model Metadata``, ``## Source Coverage``, ``## Markov
    Blanket``, etc.) and the upstream GNN 2.0.0 required headers
    (``## GNNSection``, ``## StateSpaceBlock``, ``## Connections``,
    ``## InitialParameterization``, ``## Equations``, ``## Time``,
    ``## ActInfOntologyAnnotation``, ``## ModelParameters``, etc.). Upstream section
    checks are ordered: they must appear in the spec-mandated
    order at the TOP of the file.

    Args:
        markdown: Markdown content.

    Returns:
        List of errors (empty if valid).
    """
    errors: list[str] = []
    lowered = markdown.lower()

    # 1) COGANT-extended canonical sections (case-insensitive presence check).
    for section in self.CANONICAL_SECTIONS:
        section_header = f"## {section.replace('_', ' ').title()}"
        if section_header.lower() not in lowered:
            errors.append(f"Missing canonical section: {section}")

    # 2) Upstream GNN 2.0.0 required sections — each must be present.
    missing_upstream: list[str] = []
    upstream_offsets: list[tuple[str, int]] = []
    for section in self.UPSTREAM_SECTIONS:
        marker = f"## {section}"
        idx = markdown.find(marker)
        if idx < 0:
            missing_upstream.append(section)
        else:
            upstream_offsets.append((section, idx))
    for section in missing_upstream:
        errors.append(f"Missing upstream GNN 2.0.0 section: {section}")

    # 3) Upstream sections must appear in canonical order.
    if not missing_upstream and upstream_offsets:
        expected_order = list(self.UPSTREAM_SECTIONS)
        found_order = [section for section, _ in sorted(upstream_offsets, key=lambda x: x[1])]
        if expected_order != found_order:
            errors.append(
                "Upstream GNN 2.0.0 sections out of canonical order: "
                f"found {found_order}, expected {expected_order}"
            )

    return errors

validate_matrices(matrices_json)

Validate the AII Active Inference matrix block.

Checks presence and shape of the A/B/C/D matrices emitted by :class:cogant.gnn.matrices.GNNMatrices. The matrices must satisfy:

  • A: shape [n_obs x n_states], columns sum to 1.0.
  • B: shape [n_states x n_states x n_actions]; when truncation.applied is set (large-repo top-K cut, see :meth:cogant.gnn.matrices.GNNMatrices.compute_B) the state axes are n_states_kept and truncation.kept_state_indices must name those states on the full A/D axis.
  • C: length equal to n_obs.
  • D: length equal to n_states, sums to 1.0.

Parameters:

Name Type Description Default
matrices_json dict[str, Any]

Dict of the form {"A": ..., "B": ..., "C": ..., "D": ..., "dimensions": {"n_states", "n_obs", "n_actions"}}.

required

Returns:

Type Description
list[str]

List of errors (empty if matrices are well-formed).

Source code in py/cogant/gnn/validator.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
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
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
def validate_matrices(self, matrices_json: dict[str, Any]) -> list[str]:
    """Validate the AII Active Inference matrix block.

    Checks presence and shape of the A/B/C/D matrices emitted by
    :class:`cogant.gnn.matrices.GNNMatrices`. The matrices must
    satisfy:

    * A: shape ``[n_obs x n_states]``, columns sum to 1.0.
    * B: shape ``[n_states x n_states x n_actions]``; when
      ``truncation.applied`` is set (large-repo top-K cut, see
      :meth:`cogant.gnn.matrices.GNNMatrices.compute_B`) the state
      axes are ``n_states_kept`` and ``truncation.kept_state_indices``
      must name those states on the full A/D axis.
    * C: length equal to ``n_obs``.
    * D: length equal to ``n_states``, sums to 1.0.

    Args:
        matrices_json: Dict of the form
            ``{"A": ..., "B": ..., "C": ..., "D": ...,
            "dimensions": {"n_states", "n_obs", "n_actions"}}``.

    Returns:
        List of errors (empty if matrices are well-formed).
    """
    errors: list[str] = []

    for key in ("A", "B", "C", "D"):
        if key not in matrices_json:
            errors.append(f"Missing matrix: {key}")

    A = matrices_json.get("A", [])
    B = matrices_json.get("B", [])
    C = matrices_json.get("C", [])
    D = matrices_json.get("D", [])

    if not isinstance(A, list):
        errors.append("A must be a list")
        A = []
    if not isinstance(B, list):
        errors.append("B must be a list")
        B = []
    if not isinstance(C, list):
        errors.append("C must be a list")
        C = []
    if not isinstance(D, list):
        errors.append("D must be a list")
        D = []
    if any(not isinstance(row, list) for row in A):
        errors.append("A rows must be lists")
        A = [row for row in A if isinstance(row, list)]
    if any(not isinstance(row, list) for row in B):
        errors.append("B rows must be lists")
        B = [row for row in B if isinstance(row, list)]
    if any(not isinstance(cell, list) for row in B for cell in row):
        errors.append("B cells must be lists")
        B = [[cell for cell in row if isinstance(cell, list)] for row in B]

    dims = matrices_json.get("dimensions")
    if not isinstance(dims, dict):
        if dims is None:
            errors.append("dimensions must be declared as an object")
        else:
            errors.append("dimensions must be an object")
        dims = {}

    inferred_states = len(D) or (len(A[0]) if A and A[0] else 0)
    inferred_obs = len(A) or len(C)
    inferred_actions = len(B[0][0]) if B and B[0] and B[0][0] else 0

    def dimension(name: str, inferred: int) -> int:
        if name not in dims:
            return inferred
        value = dims[name]
        if isinstance(value, bool) or not isinstance(value, int) or value < 0:
            errors.append(f"dimensions.{name} must be a non-negative integer")
            return inferred
        return value

    n_states = dimension("n_states", inferred_states)
    n_obs = dimension("n_obs", inferred_obs)
    n_actions = dimension("n_actions", inferred_actions)
    n_b_states = self._truncated_b_state_count(matrices_json, n_states, errors)

    shapes = matrices_json.get("shapes")
    if not isinstance(shapes, dict):
        errors.append("shapes must be declared as an object")
    else:
        expected_shapes = {
            "A": [n_obs, n_states],
            "B": [n_b_states, n_b_states, n_actions],
            "C": [n_obs],
            "D": [n_states],
        }
        for key, expected in expected_shapes.items():
            actual_shape = shapes.get(key)
            if actual_shape != expected:
                errors.append(f"declared shape for {key} does not match dimensions")

    for name, value, actual in (
        ("n_states", n_states, len(D)),
        ("n_obs", n_obs, len(C)),
    ):
        if name in dims and actual != value:
            errors.append(
                f"declared {name}={value} does not match {name} vector length {actual}"
            )
    if "n_states" in dims and A and any(len(row) != n_states for row in A):
        errors.append(f"declared n_states={n_states} does not match A column count")
    if "n_obs" in dims and A and len(A) != n_obs:
        errors.append(f"declared n_obs={n_obs} does not match A row count")
    if (
        "n_actions" in dims
        and B
        and B[0]
        and any(len(cell) != n_actions for row in B for cell in row)
    ):
        errors.append(f"declared n_actions={n_actions} does not match B depth")

    # A: rows == n_obs, cols == n_states, columns sum to 1 (column-stochastic).
    if n_obs > 0 and n_states > 0:
        if len(A) != n_obs:
            errors.append(f"A row count {len(A)} != n_obs {n_obs}")
        elif A and any(len(row) != n_states for row in A):
            errors.append(f"A column count mismatch; expected {n_states}")
        else:
            # Tolerance 1e-6 — stability constant. A-matrix encodes
            # P(o|s) and is column-stochastic (AII/pymdp convention):
            # for each fixed hidden state s (a column), the distribution
            # over observation outcomes sums to 1. float64 accumulation
            # introduces ~n_obs * eps drift; 1e-6 leaves ~8 orders of
            # magnitude headroom and matches the pymdp / scipy convention
            # for stochastic-matrix normalization checks.
            if any(
                not isinstance(A[i][j], (int, float))
                or not math.isfinite(float(A[i][j]))
                or A[i][j] < -1e-9
                for i in range(len(A))
                for j in range(n_states)
            ):
                errors.append("A contains negative probabilities")
            for j in range(n_states):
                col_sum = sum(A[i][j] for i in range(len(A)))
                if abs(col_sum - 1.0) > 1e-6:
                    errors.append(f"A column {j} does not sum to 1 (sum={col_sum:.6f})")

    elif A:
        errors.append("A must be empty when observations or hidden states are zero")

    # B: shape n_states x n_states x n_actions (n_states_kept when
    # the top-K truncation was applied).
    if n_states > 0:
        if n_actions == 0 and not B:
            pass
        elif len(B) != n_b_states:
            errors.append(f"B first dim {len(B)} != n_states {n_b_states}")
        elif any(len(row) != n_b_states for row in B):
            errors.append(f"B second dim mismatch; expected {n_b_states}")
        elif any(len(cell) != n_actions for row in B for cell in row):
            errors.append(f"B third dim mismatch; expected {n_actions}")
        else:
            if any(
                not isinstance(B[i][j][k], (int, float))
                or not math.isfinite(float(B[i][j][k]))
                or B[i][j][k] < -1e-9
                for i in range(n_b_states)
                for j in range(n_b_states)
                for k in range(n_actions)
            ):
                errors.append("B contains negative probabilities")
            for k in range(n_actions):
                for j in range(n_b_states):
                    col_sum = sum(B[i][j][k] for i in range(n_b_states))
                    if abs(col_sum - 1.0) > 1e-6:
                        errors.append(
                            f"B action {k} column {j} does not sum to 1 (sum={col_sum:.6f})"
                        )

    elif B:
        errors.append("B must be empty when hidden states are zero")

    # C: length n_obs.
    if len(C) != n_obs:
        errors.append(f"C length {len(C)} != n_obs {n_obs}")
    elif any(
        not isinstance(value, (int, float)) or not math.isfinite(float(value)) for value in C
    ):
        errors.append("C contains non-finite values")

    # D: length n_states, sums to 1.
    if len(D) != n_states:
        errors.append(f"D length {len(D)} != n_states {n_states}")
    elif n_states > 0:
        if any(
            not isinstance(value, (int, float))
            or not math.isfinite(float(value))
            or value < -1e-9
            for value in D
        ):
            errors.append("D contains negative probabilities")
        elif D and abs(sum(D) - 1.0) > 1e-6:
            # Tolerance 1e-6 — stability constant, same rationale as
            # A-column tolerance above (pymdp/scipy convention for
            # probability-simplex sum checks; ~8 orders of magnitude
            # headroom over float64 accumulation drift).
            errors.append(f"D does not sum to 1 (sum={sum(D):.6f})")

    return errors

validate_package(package_dir, *, upstream_gnn=None)

Validate a GNN package.

Parameters:

Name Type Description Default
package_dir str

Path to the package directory.

required
upstream_gnn bool | None

When True, run the Active Inference Institute generalized-notation-notation validator (upstream gnn 4.x, standard level) on model.gnn.md; a requested but unavailable upstream is reported as a capability error. When None, upstream runs only if :envvar:COGANT_ENABLE_UPSTREAM_GNN is truthy (and never when :envvar:COGANT_DISABLE_UPSTREAM_GNN is set).

None

Returns:

Type Description
ValidationResult

ValidationResult object.

Source code in py/cogant/gnn/validator.py
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
def validate_package(
    self,
    package_dir: str,
    *,
    upstream_gnn: bool | None = None,
) -> ValidationResult:
    """
    Validate a GNN package.

    Args:
        package_dir: Path to the package directory.
        upstream_gnn: When True, run the Active Inference Institute
            ``generalized-notation-notation`` validator (upstream ``gnn``
            4.x, ``standard`` level) on ``model.gnn.md``; a requested but
            unavailable upstream is reported as a capability error. When
            ``None``, upstream runs only if
            :envvar:`COGANT_ENABLE_UPSTREAM_GNN` is truthy (and never when
            :envvar:`COGANT_DISABLE_UPSTREAM_GNN` is set).

    Returns:
        ValidationResult object.
    """
    self.package_dir = Path(package_dir)
    self.result = ValidationResult()
    self._upstream_gnn = _resolve_upstream_flag(upstream_gnn)
    self.result.capabilities["upstream_gnn"] = {
        "requested": self._upstream_gnn,
        "available": False,
    }
    try:
        from cogant.parsers.registry import parser_capabilities

        self.result.capabilities["parsers"] = {
            language: capability.__dict__
            for language, capability in parser_capabilities().items()
        }
    except Exception as exc:
        self.result.capabilities["parsers"] = {"error": str(exc)}

    logger.info(
        "Validating GNN package: %s (upstream_gnn=%s)",
        self.package_dir,
        self._upstream_gnn,
    )

    # Check 1: Directory exists
    if not self.package_dir.exists():
        self.result.errors.append(f"Package directory not found: {self.package_dir}")
        self.result.valid = False
        self.result.score = 0.0
        return self.result

    if not self.package_dir.is_dir():
        self.result.errors.append(f"Package path is not a directory: {self.package_dir}")
        self.result.score = 0.0
        return self.result

    self.result.artifact_digests = self._artifact_digests()

    # Check 2: Required files present
    self._check_required_files()

    # Check 3: Manifest valid
    manifest = self._check_manifest()

    # Check 4: JSON files valid
    self._check_json_files()

    # Check 4b: best-effort artifacts the builder could not produce
    self._check_artifact_status(manifest)

    # Check 5: A/B/C/D matrix block valid
    self._check_matrices()

    # Check 6: Markdown valid
    self._check_markdown()

    # Check 7: State space valid
    self._check_state_space()

    # Check 8: Provenance valid
    self._check_provenance()

    # Check 9: Checksums match
    if manifest:
        self._check_checksums(manifest)

    # Compute final score and validity
    self._compute_final_score()

    logger.info(
        "Validation complete: %s (score=%.1f%%, %d errors, %d warnings)",
        self.result.valid,
        self.result.score,
        len(self.result.errors),
        len(self.result.warnings),
    )
    return self.result

validate_provenance(provenance_json)

Validate provenance structure.

Parameters:

Name Type Description Default
provenance_json dict[str, Any]

Provenance JSON.

required

Returns:

Type Description
list[str]

List of errors (empty if valid).

Source code in py/cogant/gnn/validator.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
def validate_provenance(self, provenance_json: dict[str, Any]) -> list[str]:
    """
    Validate provenance structure.

    Args:
        provenance_json: Provenance JSON.

    Returns:
        List of errors (empty if valid).
    """
    if not isinstance(provenance_json, dict):
        return ["Provenance root must be a JSON object"]
    errors: list[str] = []

    # Check required keys
    required_keys = ["timestamp", "sources"]
    for key in required_keys:
        if key not in provenance_json:
            errors.append(f"Missing provenance key: {key}")

    # Check sources
    sources = provenance_json.get("sources", {})
    if not isinstance(sources, dict):
        errors.append("Provenance sources must be a dict")

    return errors

validate_state_space(state_space_json)

Validate state space structure.

Parameters:

Name Type Description Default
state_space_json dict[str, Any]

State space JSON.

required

Returns:

Type Description
list[str]

List of errors (empty if valid).

Source code in py/cogant/gnn/validator.py
400
401
402
403
404
405
406
407
408
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
def validate_state_space(self, state_space_json: dict[str, Any]) -> list[str]:
    """
    Validate state space structure.

    Args:
        state_space_json: State space JSON.

    Returns:
        List of errors (empty if valid).
    """
    if not isinstance(state_space_json, dict):
        return ["State-space root must be a JSON object"]
    errors: list[str] = []

    # Check required keys
    required_keys = ["variables", "observations", "actions", "transitions"]
    for key in required_keys:
        if key not in state_space_json:
            errors.append(f"Missing state space key: {key}")

    # Check variables are well-formed
    variables = state_space_json.get("variables", [])
    if not isinstance(variables, list):
        errors.append("Variables must be a list")
    elif any(not isinstance(item, dict) for item in variables):
        errors.append("Variables entries must be objects")

    # Check observations are well-formed
    observations = state_space_json.get("observations", [])
    if not isinstance(observations, list):
        errors.append("Observations must be a list")
    elif any(not isinstance(item, dict) for item in observations):
        errors.append("Observations entries must be objects")

    # Check actions are well-formed
    actions = state_space_json.get("actions", [])
    if not isinstance(actions, list):
        errors.append("Actions must be a list")
    elif any(not isinstance(item, dict) for item in actions):
        errors.append("Actions entries must be objects")

    # Check transitions are well-formed
    transitions = state_space_json.get("transitions", {})
    if not isinstance(transitions, dict):
        errors.append("Transitions must be a dict")
    else:
        if not isinstance(transitions.get("transition_count"), int):
            errors.append("Transitions must declare an integer transition_count")
        if not isinstance(transitions.get("time_regime"), str) or not transitions.get(
            "time_regime"
        ):
            errors.append("Transitions must declare a non-empty time_regime")

    metadata = state_space_json.get("metadata")
    if metadata is not None:
        if not isinstance(metadata, dict):
            errors.append("State-space metadata must be an object")
        else:
            for key, values in (
                ("num_variables", variables),
                ("num_observations", observations),
                ("num_actions", actions),
            ):
                declared = metadata.get(key)
                if isinstance(values, list) and declared != len(values):
                    errors.append(f"State-space metadata {key} does not match emitted entries")

    return errors

ValidationResult

Result of a GNN package validation.

Source code in py/cogant/gnn/validator.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 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
class ValidationResult:
    """Result of a GNN package validation."""

    def __init__(
        self,
        valid: bool = False,
        errors: list[str] | None = None,
        warnings: list[str] | None = None,
        score: float = 0.0,
        advisories: list[str] | None = None,
        capabilities: dict[str, Any] | None = None,
        artifact_digests: dict[str, str] | None = None,
        dimensions: dict[str, Any] | None = None,
    ):
        """
        Initialize validation result.

        Args:
            valid: Whether package is valid.
            errors: List of error messages.
            warnings: List of warning messages.
            score: Validation score 0-100.
        """
        self.valid = valid
        self.errors: list[str] = errors or []
        self.advisories: list[str] = list(advisories if advisories is not None else warnings or [])
        self.score = score
        self.details: dict[str, Any] = {}
        self.section_scores: dict[str, float] = {}
        self.capabilities: dict[str, Any] = dict(capabilities or {})
        self.artifact_digests: dict[str, str] = dict(artifact_digests or {})
        self.dimensions: dict[str, Any] = dict(dimensions or {})

    @property
    def warnings(self) -> list[str]:
        """Current public view of non-fatal validation advisories."""

        return self.advisories

    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary."""
        return {
            "valid": self.valid,
            "score": self.score,
            "errors": self.errors,
            "warnings": self.advisories,
            "advisories": self.advisories,
            "capabilities": self.capabilities,
            "artifact_digests": self.artifact_digests,
            "dimensions": self.dimensions,
            "details": self.details,
            "section_scores": self.section_scores,
        }

    def to_markdown(self) -> str:
        """Generate a human-readable markdown report.

        Returns:
            A markdown string containing a formatted report of the
            validation result, including scores, errors, warnings,
            and section breakdowns.
        """
        lines: list[str] = []

        # Header
        status = "✓ VALID" if self.valid else "✗ INVALID"
        lines.append("# GNN Validation Report\n")
        lines.append(f"**Status**: {status}\n")
        lines.append(f"**Overall Score**: {self.score:.1f}/100\n")

        # Section scores
        if self.section_scores:
            lines.append("## Section Scores\n")
            for section, score in sorted(self.section_scores.items()):
                bar = "█" * int(score / 10) + "░" * (10 - int(score / 10))
                lines.append(f"- **{section}**: {score:.1f}/100 [{bar}]")
            lines.append("")

        # Errors
        if self.errors:
            lines.append("## Errors\n")
            for err in self.errors:
                lines.append(f"- ❌ {err}")
            lines.append("")

        # Warnings
        if self.warnings:
            lines.append("## Warnings\n")
            for warn in self.warnings:
                lines.append(f"- ⚠ {warn}")
            lines.append("")

        # Details
        if self.details:
            lines.append("## Details\n")
            for key, val in self.details.items():
                if isinstance(val, dict):
                    lines.append(f"### {key}")
                    for k, v in val.items():
                        lines.append(f"- {k}: {v}")
                else:
                    lines.append(f"- **{key}**: {val}")
            lines.append("")

        return "\n".join(lines)

    def badge_svg(self) -> str:
        """Generate SVG badge."""
        status = "VALID" if self.valid else "INVALID"
        return f"""<svg xmlns="http://www.w3.org/2000/svg" width="120" height="20">
  <rect width="120" height="20" fill="#333"/>
  <text x="10" y="15" fill="white" font-size="12" font-family="Arial">
    GNN {status} ({self.score:.0f}%)
  </text>
</svg>"""

warnings property

Current public view of non-fatal validation advisories.

__init__(valid=False, errors=None, warnings=None, score=0.0, advisories=None, capabilities=None, artifact_digests=None, dimensions=None)

Initialize validation result.

Parameters:

Name Type Description Default
valid bool

Whether package is valid.

False
errors list[str] | None

List of error messages.

None
warnings list[str] | None

List of warning messages.

None
score float

Validation score 0-100.

0.0
Source code in py/cogant/gnn/validator.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(
    self,
    valid: bool = False,
    errors: list[str] | None = None,
    warnings: list[str] | None = None,
    score: float = 0.0,
    advisories: list[str] | None = None,
    capabilities: dict[str, Any] | None = None,
    artifact_digests: dict[str, str] | None = None,
    dimensions: dict[str, Any] | None = None,
):
    """
    Initialize validation result.

    Args:
        valid: Whether package is valid.
        errors: List of error messages.
        warnings: List of warning messages.
        score: Validation score 0-100.
    """
    self.valid = valid
    self.errors: list[str] = errors or []
    self.advisories: list[str] = list(advisories if advisories is not None else warnings or [])
    self.score = score
    self.details: dict[str, Any] = {}
    self.section_scores: dict[str, float] = {}
    self.capabilities: dict[str, Any] = dict(capabilities or {})
    self.artifact_digests: dict[str, str] = dict(artifact_digests or {})
    self.dimensions: dict[str, Any] = dict(dimensions or {})

badge_svg()

Generate SVG badge.

Source code in py/cogant/gnn/validator.py
165
166
167
168
169
170
171
172
173
    def badge_svg(self) -> str:
        """Generate SVG badge."""
        status = "VALID" if self.valid else "INVALID"
        return f"""<svg xmlns="http://www.w3.org/2000/svg" width="120" height="20">
  <rect width="120" height="20" fill="#333"/>
  <text x="10" y="15" fill="white" font-size="12" font-family="Arial">
    GNN {status} ({self.score:.0f}%)
  </text>
</svg>"""

to_dict()

Convert to dictionary.

Source code in py/cogant/gnn/validator.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def to_dict(self) -> dict[str, Any]:
    """Convert to dictionary."""
    return {
        "valid": self.valid,
        "score": self.score,
        "errors": self.errors,
        "warnings": self.advisories,
        "advisories": self.advisories,
        "capabilities": self.capabilities,
        "artifact_digests": self.artifact_digests,
        "dimensions": self.dimensions,
        "details": self.details,
        "section_scores": self.section_scores,
    }

to_markdown()

Generate a human-readable markdown report.

Returns:

Type Description
str

A markdown string containing a formatted report of the

str

validation result, including scores, errors, warnings,

str

and section breakdowns.

Source code in py/cogant/gnn/validator.py
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
def to_markdown(self) -> str:
    """Generate a human-readable markdown report.

    Returns:
        A markdown string containing a formatted report of the
        validation result, including scores, errors, warnings,
        and section breakdowns.
    """
    lines: list[str] = []

    # Header
    status = "✓ VALID" if self.valid else "✗ INVALID"
    lines.append("# GNN Validation Report\n")
    lines.append(f"**Status**: {status}\n")
    lines.append(f"**Overall Score**: {self.score:.1f}/100\n")

    # Section scores
    if self.section_scores:
        lines.append("## Section Scores\n")
        for section, score in sorted(self.section_scores.items()):
            bar = "█" * int(score / 10) + "░" * (10 - int(score / 10))
            lines.append(f"- **{section}**: {score:.1f}/100 [{bar}]")
        lines.append("")

    # Errors
    if self.errors:
        lines.append("## Errors\n")
        for err in self.errors:
            lines.append(f"- ❌ {err}")
        lines.append("")

    # Warnings
    if self.warnings:
        lines.append("## Warnings\n")
        for warn in self.warnings:
            lines.append(f"- ⚠ {warn}")
        lines.append("")

    # Details
    if self.details:
        lines.append("## Details\n")
        for key, val in self.details.items():
            if isinstance(val, dict):
                lines.append(f"### {key}")
                for k, v in val.items():
                    lines.append(f"- {k}: {v}")
            else:
                lines.append(f"- **{key}**: {val}")
        lines.append("")

    return "\n".join(lines)

JSON export

cogant.gnn.json_export

GNN JSON exporter for machine-readable output.

Emits machine-readable JSON with IDs that are stable across sections and serialises every model component (graph, state space, process model, semantic mappings) in a single nested document.

GNNJSONExporter

Exports GNN models to machine-readable JSON format with stable IDs.

Source code in py/cogant/gnn/json_export.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 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
403
404
405
406
407
408
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
471
472
473
474
475
476
477
478
479
480
481
482
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
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
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
class GNNJSONExporter:
    """
    Exports GNN models to machine-readable JSON format with stable IDs.
    """

    def __init__(
        self,
        program_graph: ProgramGraph,
        state_space_model: StateSpaceModel,
        process_model: ProcessModel,
        semantic_mappings: dict[str, Any],
    ):
        """
        Initialize the exporter.

        Args:
            program_graph: The program graph.
            state_space_model: The state space model.
            process_model: The process model.
            semantic_mappings: Semantic mappings dictionary.
        """
        self.graph = program_graph
        self.state_space = state_space_model
        self.process = process_model
        self.mappings = semantic_mappings

    def export(self) -> dict[str, Any]:
        """
        Export the complete GNN model as a JSON-serializable dictionary.

        Returns:
            Dictionary ready for JSON serialization.
        """
        logger.info(
            "Exporting GNN model to JSON: %d nodes, %d edges, %d vars, %d obs, %d actions",
            len(self.graph.nodes),
            len(self.graph.edges),
            len(self.state_space.variables),
            len(self.state_space.observations),
            len(self.state_space.actions),
        )

        # Debug: check mappings type - ensure it's always a dict
        if not isinstance(self.mappings, dict):
            logger.warning(f"WARNING: mappings is {type(self.mappings)}, not dict. Converting...")
            if isinstance(self.mappings, list):
                self.mappings = {m.id: m for m in self.mappings}
            else:
                self.mappings = {}

        # Build all 19 canonical sections
        output = {
            # Core identifiers and metadata
            "model_id": self.state_space.id,
            "schema_name": self.state_space.schema_name,
            # Canonical sections (19 total)
            "model_metadata": self._export_metadata(),
            "repository_metadata": self._export_repository_metadata(),
            "source_coverage": self._export_source_coverage(),
            "state_space": self._export_state_space(),
            "observation_modalities": self._export_observation_modalities(),
            "actions_policies": self._export_actions_policies(),
            "connections": self._export_connections(),
            "factors": self._export_factors_section(),
            "transition_structure": self._export_transition_structure(),
            "likelihood_structure": self._export_likelihood_structure(),
            "preferences_constraints": self._export_preferences_constraints(),
            "time_settings": self._export_time_settings(),
            "parameterization": self._export_parameterization(),
            "ontology_mapping": self._export_ontology_mapping(),
            "markov_blanket": self._export_markov_blanket(),
            "provenance": self._export_provenance_section(),
            "confidence": self._export_confidence(),
            "rendering_hints": self._export_rendering_hints(),
            "validation_notes": self._export_validation_notes(),
            # AII Active Inference matrices (A, B, C, D)
            "matrices": self._export_matrices(),
            # Additional cross-reference sections
            "program_graph": self._export_program_graph(),
            "process_model": self._export_process_model(),
            "mappings": self._export_mappings(),
        }

        # Log matrix shapes and section summary at INFO level
        matrices_raw = output.get("matrices", {})
        matrices = matrices_raw if isinstance(matrices_raw, dict) else {}
        shapes_raw = matrices.get("shapes", {})
        shapes = shapes_raw if isinstance(shapes_raw, dict) else {}
        n_sections = len(output)
        logger.info(
            "GNN JSON export complete: %d sections + matrices (A=%s, B=%s, C=%s, D=%s)",
            n_sections,
            shapes.get("A", [0, 0]),
            shapes.get("B", [0, 0, 0]),
            shapes.get("C", [0]),
            shapes.get("D", [0]),
        )

        return output

    def _export_matrices(self) -> dict[str, Any]:
        """Export the AII Active Inference A/B/C/D matrices.

        Delegates to :class:`cogant.gnn.matrices.GNNMatrices`. On failure
        (e.g. empty state space) a safe empty structure is returned so
        the downstream validator can cleanly skip the check.
        """
        try:
            matrices = GNNMatrices(
                graph=self.graph,
                mappings=self.mappings,
                state_space=self.state_space,
            )
            return matrices.to_dict()
        except (ValueError, KeyError, AttributeError) as exc:
            logger.warning(
                "Failed to derive GNN matrices for export: %s: %s",
                type(exc).__name__,
                exc,
            )
            logger.info("Matrix export failed; returning empty A/B/C/D structures")
            return {
                "A": [],
                "B": [],
                "C": [],
                "D": [],
                "shapes": {"A": [0, 0], "B": [0, 0, 0], "C": [0], "D": [0]},
                "dimensions": {"n_states": 0, "n_obs": 0, "n_actions": 0},
            }

    def export_to_string(self, indent: int | None = 2) -> str:
        """
        Export the model to a JSON string.

        Args:
            indent: Number of spaces for indentation, or None for compact.

        Returns:
            JSON string.
        """
        data = self.export()
        return json.dumps(data, indent=indent, default=str)

    def _export_metadata(self) -> dict[str, Any]:
        """Build the ``metadata`` block.

        Always populates ``generated_at``, ``schema_version``,
        ``cogant_version``, ``model_id``, and ``schema_name``. When the
        program graph carries ``RepositoryMetadata``, also adds a
        ``repository`` sub-object (uri, languages, version, timestamps,
        evidence sources, optional ``custom`` field) and the state-space
        derived metrics block.
        """
        metadata: dict[str, Any] = {
            "generated_at": datetime.now().isoformat(),
            "schema_version": "1.0",
            "cogant_version": _cogant_version(),
            "model_id": self.state_space.id,
            "schema_name": self.state_space.schema_name,
        }

        # Add graph metadata
        if self.graph.metadata:
            meta = self.graph.metadata
            metadata["repository"] = {
                "uri": meta.repo_uri,
                "languages": list(meta.languages),
                "version": meta.version,
                "created_at": meta.created_at.isoformat(),
                "updated_at": meta.updated_at.isoformat(),
                "evidence_sources": meta.evidence_sources,
            }
            if meta.custom_metadata:
                metadata["repository"]["custom"] = meta.custom_metadata

        # Add state space metrics
        metadata["metrics"] = {
            "node_count": len(self.graph.nodes),
            "edge_count": len(self.graph.edges),
            "state_variables": len(self.state_space.variables),
            "observations": len(self.state_space.observations),
            "actions": len(self.state_space.actions),
            "transitions": len(self.state_space.transitions),
            "processes": len(self.process.stages),
            "mappings": len(self.mappings),
        }

        # Pipeline and extraction info
        if self.state_space.metadata:
            if "pipeline_stages" in self.state_space.metadata:
                metadata["pipeline_stages"] = self.state_space.metadata["pipeline_stages"]
            if "extraction_time_ms" in self.state_space.metadata:
                metadata["extraction_time_ms"] = self.state_space.metadata["extraction_time_ms"]

        return metadata

    def _export_repository_metadata(self) -> dict[str, Any]:
        """Export repository metadata section."""
        if self.graph.metadata:
            meta = self.graph.metadata
            return {
                "uri": meta.repo_uri,
                "languages": list(meta.languages),
                "version": meta.version,
                "created_at": meta.created_at.isoformat(),
                "updated_at": meta.updated_at.isoformat(),
                "evidence_sources": meta.evidence_sources,
                "custom": meta.custom_metadata or {},
            }
        return {}

    def _export_source_coverage(self) -> dict[str, Any]:
        """Export source coverage information."""
        return {
            "nodes": len(self.graph.nodes),
            "edges": len(self.graph.edges),
            "evidence_sources": self.graph.metadata.evidence_sources if self.graph.metadata else [],
            "coverage_percentage": self._compute_coverage(),
        }

    def _compute_coverage(self) -> float:
        """Compute coverage percentage."""
        if not self.graph.nodes:
            return 0.0
        # Coverage is based on all nodes being covered
        return 100.0

    def _export_observation_modalities(self) -> dict[str, Any]:
        """Export observation modalities section."""
        return {
            "modalities": self._extract_modality_list(),
            "count": len(self.state_space.observations),
            "observations": self._export_observation_details(),
        }

    def _extract_modality_list(self) -> list[str]:
        """Extract list of observation modalities."""
        modalities = set()
        for obs in self.state_space.observations.values():
            if hasattr(obs, "modality_type") and obs.modality_type:
                modalities.add(obs.modality_type)
        return sorted(modalities) if modalities else ["symbolic"]

    def _export_observation_details(self) -> dict[str, Any]:
        """Export observation details for canonical section."""
        observations: dict[str, dict[str, Any]] = {}
        for obs_id, obs in self.state_space.observations.items():
            observations[obs_id] = {
                "id": obs.id,
                "name": obs.name,
                "source_node_id": obs.source_node_id,
                "modality_type": obs.modality_type,
                "cardinality": obs.cardinality or [],
                "description": obs.description,
                "confidence": obs.confidence.value
                if hasattr(obs.confidence, "value")
                else str(obs.confidence),
            }
        return observations

    def _export_actions_policies(self) -> dict[str, Any]:
        """Export actions and policies as canonical section."""
        actions = {}
        for action_id, action in self.state_space.actions.items():
            actions[action_id] = {
                "id": action.id,
                "name": action.name,
                "controller_id": action.controller_id,
                "parameters": action.parameters or {},
                "effects": action.effects or {},
                "preconditions": action.preconditions or {},
                "description": action.description,
            }
        return {
            "actions": actions,
            "policies": self._extract_policy_details(),
            "count": len(actions),
        }

    def _extract_policy_details(self) -> list[dict[str, Any]]:
        """Extract policy details."""
        return [
            {"type": "deterministic", "coverage": 1.0, "actions": len(self.state_space.actions)}
        ]

    def _export_connections(self) -> dict[str, Any]:
        """Export connections (edges) as canonical section."""
        edges: dict[str, dict[str, Any]] = {}
        edge_kinds: dict[str, int] = defaultdict(int)
        for edge_id, edge in self.graph.edges.items():
            edge_kinds[edge.kind.value] += 1
            edges[edge_id] = {
                "id": edge.id,
                "source_id": edge.source_id,
                "target_id": edge.target_id,
                "kind": edge.kind.value,
                "weight": edge.weight,
                "evidence_sources": edge.evidence_sources or [],
                "metadata": edge.metadata or {},
            }
        return {
            "edges": edges,
            "count": len(edges),
            "by_kind": dict(edge_kinds),
        }

    def _export_factors_section(self) -> dict[str, Any]:
        """Export factorization as canonical section."""
        var_by_factor = defaultdict(list)
        for var_id, var in self.state_space.variables.items():
            if var.factors:
                for factor in var.factors:
                    var_by_factor[factor].append(var_id)
        return {
            "factorization": dict(var_by_factor.items()),
            "factors": list(var_by_factor.keys()),
            "count": len(var_by_factor),
        }

    def _export_transition_structure(self) -> dict[str, Any]:
        """Export transition structure as canonical section."""
        transitions = {}
        for trans_id, trans in self.state_space.transitions.items():
            transitions[trans_id] = {
                "id": trans.id,
                "source_state": trans.source_state,
                "target_state": trans.target_state,
                "action_id": trans.action_id,
                "triggered_by": trans.triggered_by,
                "probability": trans.probability or 0.0,
                "confidence": trans.confidence.value
                if hasattr(trans.confidence, "value")
                else str(trans.confidence),
            }
        return {
            "transitions": transitions,
            "deterministic": self._is_deterministic(),
            "markovian": self._is_markovian(),
            "count": len(transitions),
        }

    def _is_deterministic(self) -> bool:
        """Check if model is deterministic."""
        return all(t.probability in [None, 1.0] for t in self.state_space.transitions.values())

    def _is_markovian(self) -> bool:
        """Check if model is Markovian."""
        return True  # Default assumption

    def _export_likelihood_structure(self) -> dict[str, Any]:
        """Export likelihood structure as canonical section."""
        likelihoods = {}
        for like_id, like in self.state_space.likelihoods.items():
            likelihoods[like_id] = {
                "id": like.id,
                "variable_id": like.variable_id,
                "distribution_type": like.distribution_type,
                "parameters": like.parameters or {},
                "confidence": like.confidence.value
                if hasattr(like.confidence, "value")
                else str(like.confidence),
            }
        return {
            "likelihoods": likelihoods,
            "count": len(likelihoods),
        }

    def _export_preferences_constraints(self) -> dict[str, Any]:
        """Export preferences and constraints as canonical section."""
        preferences = {}
        for pref_id, pref in self.state_space.preferences.items():
            preferences[pref_id] = {
                "id": pref.id,
                "name": pref.name,
                "description": pref.description,
                "scope": pref.scope,
                "expression": pref.expression,
                "weight": pref.weight,
                "source": pref.source,
                "confidence": pref.confidence.value
                if hasattr(pref.confidence, "value")
                else str(pref.confidence),
            }
        return {
            "preferences": preferences,
            "constraints": [],
            "count": len(preferences),
        }

    def _export_time_settings(self) -> dict[str, Any]:
        """Export time regime and settings."""
        return {
            "time_regime": self.state_space.time_regime.value
            if hasattr(self.state_space.time_regime, "value")
            else str(self.state_space.time_regime),
            "time_scale": "discrete",
            "synchronous": True,
        }

    def _export_parameterization(self) -> dict[str, Any]:
        """Export parameterization details."""
        return {
            "parameters": {},
            "hyperparameters": {},
            "configuration": self.state_space.metadata.copy() if self.state_space.metadata else {},
        }

    def _export_ontology_mapping(self) -> dict[str, Any]:
        """Export ontology mapping as canonical section."""
        mappings_data = {}
        for mapping_id, mapping in self.mappings.items():
            mappings_data[mapping_id] = {
                "id": mapping_id,
                "semantic_label": mapping.semantic_label
                if hasattr(mapping, "semantic_label")
                else "",
                "graph_nodes": mapping.graph_fragment_node_ids
                if hasattr(mapping, "graph_fragment_node_ids")
                else [],
                "graph_edges": mapping.graph_fragment_edge_ids
                if hasattr(mapping, "graph_fragment_edge_ids")
                else [],
            }
        return {
            "mappings": mappings_data,
            "count": len(mappings_data),
        }

    def _export_markov_blanket(self) -> dict[str, Any]:
        """Export Markov blanket partition as canonical section.

        Extracts a real Markov blanket from the program graph using
        :class:`cogant.markov.extractor.MarkovBlanketExtractor` with the
        ``"auto"`` strategy, then serializes it via
        :func:`cogant.markov.blanket.serialize_blanket`.  If extraction
        fails (e.g. empty graph), a safe empty structure is returned so
        the downstream validator can cleanly skip the check.
        """
        try:
            extractor = MarkovBlanketExtractor(self.graph)
            blanket = extractor.extract(strategy="auto")
            serialized = serialize_blanket(
                blanket,
                self.graph,
                include_rationale=False,
            )
            # Merge the serialized blanket with partition-level
            # summary fields expected by the GNN validator.
            stats = dict(blanket.stats)
            return {
                "partition": serialized["roles"],
                "seed_strategy": blanket.metadata.get("strategy", "auto"),
                "boundary_ratio": stats.get("boundary_ratio", 0.0),
                "stats": stats,
                "metadata": serialized.get("metadata", {}),
            }
        except (ValueError, KeyError, AttributeError) as exc:
            logger.warning(
                "Failed to extract Markov blanket for export: %s: %s",
                type(exc).__name__,
                exc,
            )
            return {
                "partition": {
                    "internal": [],
                    "sensory": [],
                    "active": [],
                    "external": [],
                },
                "seed_strategy": "auto",
                "boundary_ratio": 0.0,
            }

    def _export_provenance_section(self) -> dict[str, Any]:
        """Export provenance as canonical section."""
        return {
            "timestamp": datetime.now().isoformat(),
            "graph_nodes": len(self.graph.nodes),
            "graph_edges": len(self.graph.edges),
            "state_space_elements": {
                "variables": len(self.state_space.variables),
                "observations": len(self.state_space.observations),
                "actions": len(self.state_space.actions),
            },
            "sources": self.graph.metadata.evidence_sources if self.graph.metadata else [],
        }

    def _export_confidence(self) -> dict[str, Any]:
        """Export confidence metrics as canonical section."""
        return {
            "overall_confidence": self._compute_average_confidence(),
            "by_component": {
                "variables": self._compute_component_confidence("variables"),
                "observations": self._compute_component_confidence("observations"),
                "actions": self._compute_component_confidence("actions"),
                "transitions": self._compute_component_confidence("transitions"),
                "semantic_mappings": self._compute_component_confidence("semantic_mappings"),
            },
        }

    def _compute_average_confidence(self) -> float:
        """Compute average confidence across all components."""
        confidences: list[float] = []
        for component in ("variables", "observations", "actions", "transitions"):
            confidences.extend(self._component_confidences(component))
        confidences.extend(self._mapping_confidences())
        return sum(confidences) / len(confidences) if confidences else 0.5

    def _component_confidences(self, component: str) -> list[float]:
        components: Any
        if component == "variables":
            components = self.state_space.variables.values()
        elif component == "observations":
            components = self.state_space.observations.values()
        elif component == "actions":
            components = self.state_space.actions.values()
        elif component == "transitions":
            components = self.state_space.transitions.values()
        else:
            return []

        confidences: list[float] = []
        for comp in components:
            if not hasattr(comp, "confidence"):
                continue
            val = _confidence_to_float(comp.confidence)
            if val is not None:
                confidences.append(val)
            elif comp.confidence:
                logger.debug(
                    "Skipping uncoercible confidence value in component %r: %r",
                    component,
                    comp,
                )
        return confidences

    def _mapping_confidences(self) -> list[float]:
        if not isinstance(self.mappings, dict):
            return []
        confidences: list[float] = []
        for mapping in self.mappings.values():
            val = _confidence_to_float(getattr(mapping, "confidence_score", None))
            if val is not None:
                confidences.append(val)
        return confidences

    def _compute_component_confidence(self, component: str) -> float:
        """Compute confidence for a specific component."""
        if component == "semantic_mappings":
            confidences = self._mapping_confidences()
            return sum(confidences) / len(confidences) if confidences else 0.5
        if component not in {"variables", "observations", "actions", "transitions"}:
            return 0.5
        confidences = self._component_confidences(component)
        return sum(confidences) / len(confidences) if confidences else 0.5

    def _export_rendering_hints(self) -> dict[str, Any]:
        """Export rendering hints for visualization."""
        return {
            "layout": "force-directed",
            "colors": {
                "nodes": "by_kind",
                "edges": "by_kind",
            },
            "features": ["interactive", "zoomable", "searchable"],
        }

    def _export_validation_notes(self) -> dict[str, Any]:
        """Export validation notes and metadata."""
        return {
            "schema_version": "1.0",
            "cogant_version": _cogant_version(),
            "last_validated": datetime.now().isoformat(),
            "validation_status": "valid",
        }

    def _export_program_graph(self) -> dict[str, Any]:
        """Export program graph with rich metadata."""
        nodes: dict[str, dict[str, Any]] = {}
        node_kinds: dict[str, int] = defaultdict(int)

        for node_id, node in self.graph.nodes.items():
            node_kinds[node.kind.value] += 1
            nodes[node_id] = {
                "id": node.id,
                "name": node.name,
                "kind": node.kind.value,
                "qualified_name": node.qualified_name,
                "path": node.path,
                "language": node.language,
                "source_range": node.source_range,
                "metadata": node.metadata,
                "created_at": node.created_at.isoformat(),
            }

        edges: dict[str, dict[str, Any]] = {}
        edge_kinds: dict[str, int] = defaultdict(int)

        for edge_id, edge in self.graph.edges.items():
            edge_kinds[edge.kind.value] += 1
            edges[edge_id] = {
                "id": edge.id,
                "source_id": edge.source_id,
                "target_id": edge.target_id,
                "kind": edge.kind.value,
                "weight": edge.weight,
                "evidence_sources": edge.evidence_sources,
                "metadata": edge.metadata,
                "created_at": edge.created_at.isoformat(),
            }

        return {
            "summary": {
                "node_count": len(nodes),
                "edge_count": len(edges),
                "node_kinds": dict(node_kinds),
                "edge_kinds": dict(edge_kinds),
            },
            "nodes": nodes,
            "edges": edges,
        }

    def _export_state_space(self) -> dict[str, Any]:
        """Build the ``state_space`` block.

        Serialises every variable, observation, action, transition,
        likelihood, and preference to plain dicts and returns them
        alongside a ``summary`` carrying the time regime, the per-class
        counts, and the ``factorization`` map (factor → variable ids).
        """
        variables = {}
        var_by_factor = defaultdict(list)

        for var_id, var in self.state_space.variables.items():
            variables[var_id] = {
                "id": var.id,
                "name": var.name,
                "type": var.var_type.value if hasattr(var.var_type, "value") else str(var.var_type),
                "node_id": var.node_id,
                "cardinality": var.cardinality or [],
                "domain": var.domain or [],
                "factors": var.factors or [],
                "is_discrete": var.is_discrete,
                "confidence": var.confidence.value
                if hasattr(var.confidence, "value")
                else str(var.confidence),
                "description": var.description,
            }
            if var.factors:
                for factor in var.factors:
                    var_by_factor[factor].append(var_id)

        observations: dict[str, dict[str, Any]] = {}
        for obs_id, obs in self.state_space.observations.items():
            observations[obs_id] = {
                "id": obs.id,
                "name": obs.name,
                "source_node_id": obs.source_node_id,
                "modality_type": obs.modality_type,
                "cardinality": obs.cardinality or [],
                "description": obs.description,
                "confidence": obs.confidence.value
                if hasattr(obs.confidence, "value")
                else str(obs.confidence),
            }

        actions: dict[str, dict[str, Any]] = {}
        for action_id, action in self.state_space.actions.items():
            actions[action_id] = {
                "id": action.id,
                "name": action.name,
                "controller_id": action.controller_id,
                "parameters": action.parameters or {},
                "effects": action.effects or {},
                "preconditions": action.preconditions or {},
                "description": action.description,
                "confidence": action.confidence.value
                if hasattr(action.confidence, "value")
                else str(action.confidence),
            }

        transitions = {}
        for trans_id, trans in self.state_space.transitions.items():
            transitions[trans_id] = {
                "id": trans.id,
                "source_state": trans.source_state,
                "target_state": trans.target_state,
                "action_id": trans.action_id,
                "triggered_by": trans.triggered_by,
                "probability": trans.probability or 0.0,
                "confidence": trans.confidence.value
                if hasattr(trans.confidence, "value")
                else str(trans.confidence),
            }

        likelihoods = {}
        for like_id, like in self.state_space.likelihoods.items():
            likelihoods[like_id] = {
                "id": like.id,
                "variable_id": like.variable_id,
                "distribution_type": like.distribution_type,
                "parameters": like.parameters or {},
                "confidence": like.confidence.value
                if hasattr(like.confidence, "value")
                else str(like.confidence),
            }

        preferences = {}
        for pref_id, pref in self.state_space.preferences.items():
            preferences[pref_id] = {
                "id": pref.id,
                "name": pref.name,
                "description": pref.description,
                "scope": pref.scope,
                "expression": pref.expression,
                "weight": pref.weight,
                "source": pref.source,
                "confidence": pref.confidence.value
                if hasattr(pref.confidence, "value")
                else str(pref.confidence),
            }

        return {
            "summary": {
                "time_regime": self.state_space.time_regime.value
                if hasattr(self.state_space.time_regime, "value")
                else str(self.state_space.time_regime),
                "variable_count": len(variables),
                "observation_count": len(observations),
                "action_count": len(actions),
                "transition_count": len(transitions),
                "likelihood_count": len(likelihoods),
                "preference_count": len(preferences),
                "factorization": {factor: len(vars) for factor, vars in var_by_factor.items()},
            },
            "variables": variables,
            "observations": observations,
            "actions": actions,
            "transitions": transitions,
            "likelihoods": likelihoods,
            "preferences": preferences,
        }

    def _export_process_model(self) -> dict[str, Any]:
        """Build the ``process_model`` block.

        Emits each ``Stage`` (id, name, description, contained
        ``node_ids``, entry/exit points, side effects, expected
        duration, confidence) and each ``Connection`` (source/target
        stages, trigger, condition, success rate) plus a ``summary``
        with stage and connection counts and the entry/exit ids.
        """
        stages = {}
        if self.process.stages:
            for stage_id, stage in self.process.stages.items():
                stages[stage_id] = {
                    "id": stage.id,
                    "name": stage.name,
                    "description": stage.description,
                    "node_ids": stage.node_ids,
                    "entry_points": stage.entry_points,
                    "exit_points": stage.exit_points,
                    "side_effects": stage.side_effects,
                    "expected_duration": stage.expected_duration,
                    "confidence": stage.confidence,
                }

        connections = {}
        if self.process.connections:
            for conn_id, conn in self.process.connections.items():
                connections[conn_id] = {
                    "id": conn.id,
                    "source_stage_id": conn.source_stage_id,
                    "target_stage_id": conn.target_stage_id,
                    "trigger": conn.trigger,
                    "condition": conn.condition,
                    "success_rate": conn.success_rate,
                }

        return {
            "summary": {
                "stage_count": len(stages),
                "connection_count": len(connections),
                "entry_stage_id": self.process.entry_stage_id
                if hasattr(self.process, "entry_stage_id")
                else None,
                "exit_stage_ids": self.process.exit_stage_ids
                if hasattr(self.process, "exit_stage_ids")
                else [],
            },
            "stages": stages,
            "connections": connections,
        }

    def _export_mappings(self) -> dict[str, Any]:
        """Build the ``mappings`` block.

        Walks every ``SemanticMapping``, serialising the source
        ``node_id``, ``kind``, ``tier``, ``status``, confidence, and any
        evidence. Returns the per-mapping dicts alongside a ``summary``
        with tally counts grouped by ``kind``, ``tier``, and ``status``.
        """
        mappings: dict[str, dict[str, Any]] = {}
        kind_counts: dict[str, int] = defaultdict(int)
        tier_counts: dict[str, int] = defaultdict(int)
        status_counts: dict[str, int] = defaultdict(int)

        for mapping_id, mapping in self.mappings.items():
            kind = mapping.kind.value if hasattr(mapping, "kind") else "unknown"
            kind_counts[kind] += 1

            if hasattr(mapping, "confidence_tier"):
                tier_counts[mapping.confidence_tier.value] += 1
            if hasattr(mapping, "status"):
                status_counts[mapping.status] += 1

            mappings[mapping_id] = {
                "id": mapping_id,
                "kind": kind,
                "semantic_label": mapping.semantic_label
                if hasattr(mapping, "semantic_label")
                else "",
                "description": mapping.description if hasattr(mapping, "description") else "",
                "graph_fragment_node_ids": mapping.graph_fragment_node_ids
                if hasattr(mapping, "graph_fragment_node_ids")
                else [],
                "graph_fragment_edge_ids": mapping.graph_fragment_edge_ids
                if hasattr(mapping, "graph_fragment_edge_ids")
                else [],
                "confidence_score": mapping.confidence_score
                if hasattr(mapping, "confidence_score")
                else 0.0,
                "confidence_tier": mapping.confidence_tier.value
                if hasattr(mapping, "confidence_tier")
                else "unknown",
                "evidence_count": mapping.evidence_count
                if hasattr(mapping, "evidence_count")
                else 0,
                "evidence_diversity": mapping.evidence_diversity
                if hasattr(mapping, "evidence_diversity")
                else 0.0,
                "parser_certainty": mapping.parser_certainty
                if hasattr(mapping, "parser_certainty")
                else 0.0,
                "status": mapping.status if hasattr(mapping, "status") else "unknown",
                "reviewed_by": mapping.reviewed_by if hasattr(mapping, "reviewed_by") else None,
                "reviewed_at": mapping.reviewed_at.isoformat()
                if hasattr(mapping, "reviewed_at") and mapping.reviewed_at
                else None,
                "created_at": mapping.created_at.isoformat()
                if hasattr(mapping, "created_at")
                else None,
            }

            # Include provenance if available
            if hasattr(mapping, "provenance") and mapping.provenance:
                mappings[mapping_id]["provenance"] = [
                    {
                        "source": p.source,
                        "timestamp": p.timestamp.isoformat() if p.timestamp else None,
                        "confidence": p.confidence,
                    }
                    for p in mapping.provenance
                ]

        return {
            "summary": {
                "total_mappings": len(mappings),
                "mapping_kinds": dict(kind_counts),
                "confidence_tiers": dict(tier_counts),
                "status_distribution": dict(status_counts),
            },
            "mappings": mappings,
        }

__init__(program_graph, state_space_model, process_model, semantic_mappings)

Initialize the exporter.

Parameters:

Name Type Description Default
program_graph ProgramGraph

The program graph.

required
state_space_model StateSpaceModel

The state space model.

required
process_model ProcessModel

The process model.

required
semantic_mappings dict[str, Any]

Semantic mappings dictionary.

required
Source code in py/cogant/gnn/json_export.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def __init__(
    self,
    program_graph: ProgramGraph,
    state_space_model: StateSpaceModel,
    process_model: ProcessModel,
    semantic_mappings: dict[str, Any],
):
    """
    Initialize the exporter.

    Args:
        program_graph: The program graph.
        state_space_model: The state space model.
        process_model: The process model.
        semantic_mappings: Semantic mappings dictionary.
    """
    self.graph = program_graph
    self.state_space = state_space_model
    self.process = process_model
    self.mappings = semantic_mappings

export()

Export the complete GNN model as a JSON-serializable dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary ready for JSON serialization.

Source code in py/cogant/gnn/json_export.py
 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
def export(self) -> dict[str, Any]:
    """
    Export the complete GNN model as a JSON-serializable dictionary.

    Returns:
        Dictionary ready for JSON serialization.
    """
    logger.info(
        "Exporting GNN model to JSON: %d nodes, %d edges, %d vars, %d obs, %d actions",
        len(self.graph.nodes),
        len(self.graph.edges),
        len(self.state_space.variables),
        len(self.state_space.observations),
        len(self.state_space.actions),
    )

    # Debug: check mappings type - ensure it's always a dict
    if not isinstance(self.mappings, dict):
        logger.warning(f"WARNING: mappings is {type(self.mappings)}, not dict. Converting...")
        if isinstance(self.mappings, list):
            self.mappings = {m.id: m for m in self.mappings}
        else:
            self.mappings = {}

    # Build all 19 canonical sections
    output = {
        # Core identifiers and metadata
        "model_id": self.state_space.id,
        "schema_name": self.state_space.schema_name,
        # Canonical sections (19 total)
        "model_metadata": self._export_metadata(),
        "repository_metadata": self._export_repository_metadata(),
        "source_coverage": self._export_source_coverage(),
        "state_space": self._export_state_space(),
        "observation_modalities": self._export_observation_modalities(),
        "actions_policies": self._export_actions_policies(),
        "connections": self._export_connections(),
        "factors": self._export_factors_section(),
        "transition_structure": self._export_transition_structure(),
        "likelihood_structure": self._export_likelihood_structure(),
        "preferences_constraints": self._export_preferences_constraints(),
        "time_settings": self._export_time_settings(),
        "parameterization": self._export_parameterization(),
        "ontology_mapping": self._export_ontology_mapping(),
        "markov_blanket": self._export_markov_blanket(),
        "provenance": self._export_provenance_section(),
        "confidence": self._export_confidence(),
        "rendering_hints": self._export_rendering_hints(),
        "validation_notes": self._export_validation_notes(),
        # AII Active Inference matrices (A, B, C, D)
        "matrices": self._export_matrices(),
        # Additional cross-reference sections
        "program_graph": self._export_program_graph(),
        "process_model": self._export_process_model(),
        "mappings": self._export_mappings(),
    }

    # Log matrix shapes and section summary at INFO level
    matrices_raw = output.get("matrices", {})
    matrices = matrices_raw if isinstance(matrices_raw, dict) else {}
    shapes_raw = matrices.get("shapes", {})
    shapes = shapes_raw if isinstance(shapes_raw, dict) else {}
    n_sections = len(output)
    logger.info(
        "GNN JSON export complete: %d sections + matrices (A=%s, B=%s, C=%s, D=%s)",
        n_sections,
        shapes.get("A", [0, 0]),
        shapes.get("B", [0, 0, 0]),
        shapes.get("C", [0]),
        shapes.get("D", [0]),
    )

    return output

export_to_string(indent=2)

Export the model to a JSON string.

Parameters:

Name Type Description Default
indent int | None

Number of spaces for indentation, or None for compact.

2

Returns:

Type Description
str

JSON string.

Source code in py/cogant/gnn/json_export.py
192
193
194
195
196
197
198
199
200
201
202
203
def export_to_string(self, indent: int | None = 2) -> str:
    """
    Export the model to a JSON string.

    Args:
        indent: Number of spaces for indentation, or None for compact.

    Returns:
        JSON string.
    """
    data = self.export()
    return json.dumps(data, indent=indent, default=str)

export_for_pymdp(bundle)

Export matrices in pymdp-compatible format.

Takes a GNN bundle containing A, B, C, D matrices and exports them in a format compatible with the PyMDP library, with matrices as JSON-serializable lists.

Parameters:

Name Type Description Default
bundle dict[str, Any]

The GNN bundle dict containing matrices and metadata.

required

Returns:

Type Description
dict[str, Any]

A dict with keys "A", "B", "C", "D" containing the matrices

dict[str, Any]

in pymdp format, plus metadata about shapes and truncation.

Source code in py/cogant/gnn/json_export.py
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
974
975
976
977
def export_for_pymdp(bundle: dict[str, Any]) -> dict[str, Any]:
    """Export matrices in pymdp-compatible format.

    Takes a GNN bundle containing A, B, C, D matrices and exports them
    in a format compatible with the PyMDP library, with matrices
    as JSON-serializable lists.

    Args:
        bundle: The GNN bundle dict containing matrices and metadata.

    Returns:
        A dict with keys "A", "B", "C", "D" containing the matrices
        in pymdp format, plus metadata about shapes and truncation.
    """
    matrices = bundle.get("matrices", {})

    result: dict[str, Any] = {
        "A": matrices.get("A", []),
        "B": matrices.get("B", []),
        "C": matrices.get("C", []),
        "D": matrices.get("D", []),
        "metadata": {
            "n_states": matrices.get("n_states", 0),
            "n_obs": matrices.get("n_obs", 0),
            "n_actions": matrices.get("n_actions", 0),
            "exported_at": datetime.now(UTC).isoformat(),
        },
    }

    # Include truncation info if present
    if matrices.get("b_truncated"):
        result["metadata"]["b_truncation"] = {
            "truncated": True,
            "n_states_full": matrices.get("b_n_states_full"),
            "n_states_kept": matrices.get("b_n_states_kept"),
            # B index j is full hidden state kept_state_indices[j].
            "kept_state_indices": matrices.get("b_kept_state_indices"),
        }

    return result

export_summary(bundle)

Export a compact summary of the GNN bundle.

Parameters:

Name Type Description Default
bundle dict[str, Any]

The GNN bundle dict.

required

Returns:

Type Description
dict[str, Any]

A compact dict with key metadata and matrix shapes suitable

dict[str, Any]

for quick inspection.

Source code in py/cogant/gnn/json_export.py
 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
def export_summary(bundle: dict[str, Any]) -> dict[str, Any]:
    """Export a compact summary of the GNN bundle.

    Args:
        bundle: The GNN bundle dict.

    Returns:
        A compact dict with key metadata and matrix shapes suitable
        for quick inspection.
    """
    matrices = bundle.get("matrices", {})
    state_space = bundle.get("state_space", {})

    summary: dict[str, Any] = {
        "model_id": bundle.get("model_id"),
        "model_name": state_space.get("model_name", "unknown"),
        "schema_version": bundle.get("schema_name", "unknown"),
        "dimensions": {
            "n_states": matrices.get("n_states", 0),
            "n_obs": matrices.get("n_obs", 0),
            "n_actions": matrices.get("n_actions", 0),
        },
        "matrix_shapes": {
            "A": f"({matrices.get('n_obs', 0)}, {matrices.get('n_states', 0)})",
            "B": f"({matrices.get('n_states', 0)}, {matrices.get('n_states', 0)}, {matrices.get('n_actions', 0)})",
            "C": f"({matrices.get('n_obs', 0)},)",
            "D": f"({matrices.get('n_states', 0)},)",
        },
        "coverage": {
            "total_nodes": len(bundle.get("program_graph", {}).get("nodes", {})),
            "total_mappings": len(bundle.get("mappings", {}).get("mappings", [])),
        },
        "timestamp": bundle.get("provenance", {}).get("timestamp", "unknown"),
    }

    return summary

Upstream bridge

Thin facades to the optional, commit-pinned generalized-notation-notation package (cogant[upstream], GNN v5.1.0 release), which installs the top-level gnn package. COGANT callers should not import gnn directly: the bridge enforces GNN >= 4.0 and upstream ownership of gnn, keeps the heavy import lazy, and maps the facades onto the upstream GNN >= 4 API (validate_gnn_syntax, validate_gnn_source, check_gnn_file_structure). Use the re-exported symbols on cogant.gnn (run_upstream_validate_gnn, parse_upstream_model_gnn_md, run_upstream_pipeline, …) or the additional helpers in cogant.gnn.upstream_bridge (see py/cogant/gnn/AGENTS.md).

cogant.gnn.upstream_bridge

Integration with the Active Inference Institute generalized-notation-notation package.

The PyPI distribution name is generalized-notation-notation; since GNN 4.x the installed wheel ships the top-level gnn package (the GNN 2.x src.gnn import surface was removed upstream). This is an optional COGANT extra (cogant[upstream]); the bridge requires GNN >= 4.0, whose public API uses validate_gnn_syntax / validate_gnn_source / check_gnn_file_structure (the GNN 2.x validate_gnn* aliases were deleted upstream).

Upstream is CC-BY-NC-SA-4.0; see LICENSES.md at the package root.

All call sites use lazy importlib loading so importing cogant does not eagerly initialize JAX/PyTorch until a bridge function runs.

Enable upstream validation explicitly with COGANT_ENABLE_UPSTREAM_GNN=1 or the validator/pipeline/CLI option.

DEFAULT_SKIP_STEPS = frozenset({1, 2, 11, 12}) module-attribute

Steps suppressed by default (see the module docstring for rationale).

  • 1_setup — upstream environment provisioning (mutates the caller's environment when run from an installed wheel).
  • 2_tests — upstream repository test suite (not shipped in the wheel).
  • 11_render — framework-specific simulation code generation.
  • 12_execute — runs the rendered simulations (heavy optional deps).

DEFAULT_VALIDATION_LEVEL = 'standard' module-attribute

Upstream ValidationLevel used by :func:run_upstream_validate_gnn.

MIN_UPSTREAM_MAJOR = 4 module-attribute

Oldest upstream major release whose public API this bridge targets.

UPSTREAM_DISTRIBUTION = 'generalized-notation-notation' module-attribute

PyPI distribution that provides the upstream gnn package.

UPSTREAM_IMPORT_NAME = 'gnn' module-attribute

Top-level import package shipped by the upstream wheel (GNN >= 4.0).

UPSTREAM_STEP_SCRIPTS = ('0_template.py', '1_setup.py', '2_tests.py', '3_gnn.py', '4_model_registry.py', '5_type_checker.py', '6_validation.py', '7_export.py', '8_visualization.py', '9_advanced_viz.py', '10_ontology.py', '11_render.py', '12_execute.py', '13_llm.py', '14_ml_integration.py', '15_audio.py', '16_analysis.py', '17_integration.py', '18_security.py', '19_research.py', '20_website.py', '21_mcp.py', '22_gui.py', '23_report.py', '24_intelligent_analysis.py') module-attribute

Canonical 25 numbered scripts in the upstream pipeline (steps 0 → 24).

Indexed by step number: UPSTREAM_STEP_SCRIPTS[3] == "3_gnn.py".

UpstreamGNNValidation dataclass

Outcome of calling upstream validate_gnn_syntax on markdown content.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
@dataclass(frozen=True)
class UpstreamGNNValidation:
    """Outcome of calling upstream ``validate_gnn_syntax`` on markdown content."""

    available: bool
    ok: bool
    errors: list[str] = field(default_factory=list)
    version: str | None = None
    skipped_reason: str | None = None

    def to_dict(self) -> dict[str, Any]:
        return {
            "available": self.available,
            "ok": self.ok,
            "errors": list(self.errors),
            "version": self.version,
            "skipped_reason": self.skipped_reason,
        }

UpstreamPipelineConfig dataclass

Inputs for :func:run_upstream_pipeline.

Attributes:

Name Type Description
target_dir Path

Directory containing the GNN markdown model (the COGANT gnn_package/ works because it ships model.gnn.md at the root). Required.

output_dir Path

Upstream output root (per-step sub-directories plus 00_pipeline_summary/). Required.

only_steps list[int] | None

Restrict execution to these step indices. None means "every step in the catalogue".

skip_steps list[int]

Step indices to drop. Defaults to :data:DEFAULT_SKIP_STEPS.

frameworks str

Forwarded to upstream --frameworks (used by 11_render/12_execute; e.g. "lite", "all", "pymdp,jax").

llm_model str | None

OLLAMA_MODEL for 13_llm in the upstream child process (None leaves the inherited value alone). The caller's own environment is never modified.

timesteps int

Forwarded to upstream --timesteps (12_execute).

verbose bool

Forwarded to upstream --verbose.

skip_llm bool

Forwarded to upstream --skip-llm.

timeout_s float

Bridge-level wall-clock ceiling for the invocation.

Source code in py/cogant/gnn/upstream_bridge/pipeline.py
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
@dataclass
class UpstreamPipelineConfig:
    """Inputs for :func:`run_upstream_pipeline`.

    Attributes:
        target_dir: Directory containing the GNN markdown model (the COGANT
            ``gnn_package/`` works because it ships ``model.gnn.md`` at the
            root). Required.
        output_dir: Upstream output root (per-step sub-directories plus
            ``00_pipeline_summary/``). Required.
        only_steps: Restrict execution to these step indices. ``None`` means
            "every step in the catalogue".
        skip_steps: Step indices to drop. Defaults to
            :data:`DEFAULT_SKIP_STEPS`.
        frameworks: Forwarded to upstream ``--frameworks`` (used by
            ``11_render``/``12_execute``; e.g. ``"lite"``, ``"all"``,
            ``"pymdp,jax"``).
        llm_model: ``OLLAMA_MODEL`` for ``13_llm`` in the upstream child
            process (``None`` leaves the inherited value alone). The
            caller's own environment is never modified.
        timesteps: Forwarded to upstream ``--timesteps`` (``12_execute``).
        verbose: Forwarded to upstream ``--verbose``.
        skip_llm: Forwarded to upstream ``--skip-llm``.
        timeout_s: Bridge-level wall-clock ceiling for the invocation.
    """

    target_dir: Path
    output_dir: Path
    only_steps: list[int] | None = None
    skip_steps: list[int] = field(default_factory=lambda: sorted(DEFAULT_SKIP_STEPS))
    frameworks: str = "lite"
    llm_model: str | None = None
    timesteps: int = 15
    verbose: bool = False
    skip_llm: bool = False
    timeout_s: float = DEFAULT_TIMEOUT_S

    def __post_init__(self) -> None:
        self.target_dir = Path(self.target_dir).resolve()
        self.output_dir = Path(self.output_dir).resolve()

UpstreamPipelineResult dataclass

Aggregated outcome of an upstream pipeline run.

Attributes:

Name Type Description
available bool

False when gnn.main could not be imported (in which case steps is empty and error describes why).

steps list[UpstreamStepResult]

Per-step results in execution order.

executed list[int]

Step indices requested from upstream plus any it auto-included (see auto_included).

skipped list[int]

Step indices that did not run.

total_duration_s float

Wall-clock duration of the upstream invocation.

output_dir str | None

Absolute path to the upstream output root.

target_dir str | None

Absolute path to the GNN package directory used as input.

error str | None

Bridge-level error (e.g. gnn.main import failure, a timeout, or a missing upstream summary).

upstream_status str | None

Upstream overall_status for the invocation, when the summary was produced.

run_id str | None

Upstream invocation ID (GNN_RUN_ID), when reported.

auto_included list[int]

Steps upstream ran as declared prerequisites of the requested steps although the caller did not request them.

Source code in py/cogant/gnn/upstream_bridge/pipeline.py
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
@dataclass(frozen=True)
class UpstreamPipelineResult:
    """Aggregated outcome of an upstream pipeline run.

    Attributes:
        available: ``False`` when ``gnn.main`` could not be imported (in
            which case ``steps`` is empty and ``error`` describes why).
        steps: Per-step results in execution order.
        executed: Step indices requested from upstream plus any it
            auto-included (see ``auto_included``).
        skipped: Step indices that did not run.
        total_duration_s: Wall-clock duration of the upstream invocation.
        output_dir: Absolute path to the upstream output root.
        target_dir: Absolute path to the GNN package directory used as
            input.
        error: Bridge-level error (e.g. ``gnn.main`` import failure, a
            timeout, or a missing upstream summary).
        upstream_status: Upstream ``overall_status`` for the invocation, when
            the summary was produced.
        run_id: Upstream invocation ID (``GNN_RUN_ID``), when reported.
        auto_included: Steps upstream ran as declared prerequisites of the
            requested steps although the caller did not request them.
    """

    available: bool
    steps: list[UpstreamStepResult] = field(default_factory=list)
    executed: list[int] = field(default_factory=list)
    skipped: list[int] = field(default_factory=list)
    total_duration_s: float = 0.0
    output_dir: str | None = None
    target_dir: str | None = None
    error: str | None = None
    upstream_status: str | None = None
    run_id: str | None = None
    auto_included: list[int] = field(default_factory=list)

    @property
    def success_count(self) -> int:
        return sum(1 for s in self.steps if s.success)

    @property
    def failure_count(self) -> int:
        return sum(1 for s in self.steps if not s.success)

    @property
    def success_rate(self) -> float:
        """Fraction of executed steps that succeeded; ``0.0`` for empty runs."""
        if not self.steps:
            return 0.0
        return self.success_count / len(self.steps)

    def to_dict(self) -> dict[str, Any]:
        return {
            "available": self.available,
            "executed": list(self.executed),
            "skipped": list(self.skipped),
            "success_count": self.success_count,
            "failure_count": self.failure_count,
            "success_rate": self.success_rate,
            "total_duration_s": self.total_duration_s,
            "output_dir": self.output_dir,
            "target_dir": self.target_dir,
            "error": self.error,
            "upstream_status": self.upstream_status,
            "run_id": self.run_id,
            "auto_included": list(self.auto_included),
            "steps": [s.to_dict() for s in self.steps],
        }

success_rate property

Fraction of executed steps that succeeded; 0.0 for empty runs.

UpstreamStepResult dataclass

Outcome of running a single upstream pipeline step.

Attributes:

Name Type Description
step_index int

Step number (0..24).

script str

Script filename (e.g. "3_gnn.py").

status str

Upstream-reported status string ("SUCCESS" / "SUCCESS_WITH_WARNINGS" / "SKIPPED" / "FAILED" / "TIMEOUT" / "NOT_RUN" / "BRIDGE_ERROR").

success bool

True iff status is one of {"SUCCESS", "SUCCESS_WITH_WARNINGS", "SKIPPED"}.

duration_s float

Wall-clock duration in seconds.

exit_code int

Subprocess exit code (-1 when not available).

memory_delta_mb float

Resident-memory growth observed by upstream.

output_dir str | None

Absolute path to the per-step output directory, when known.

error str | None

Free-form error message when success is False.

Source code in py/cogant/gnn/upstream_bridge/pipeline.py
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
@dataclass(frozen=True)
class UpstreamStepResult:
    """Outcome of running a single upstream pipeline step.

    Attributes:
        step_index: Step number (0..24).
        script: Script filename (e.g. ``"3_gnn.py"``).
        status: Upstream-reported status string
            (``"SUCCESS"`` / ``"SUCCESS_WITH_WARNINGS"`` / ``"SKIPPED"`` /
            ``"FAILED"`` / ``"TIMEOUT"`` / ``"NOT_RUN"`` / ``"BRIDGE_ERROR"``).
        success: ``True`` iff ``status`` is one of
            ``{"SUCCESS", "SUCCESS_WITH_WARNINGS", "SKIPPED"}``.
        duration_s: Wall-clock duration in seconds.
        exit_code: Subprocess exit code (``-1`` when not available).
        memory_delta_mb: Resident-memory growth observed by upstream.
        output_dir: Absolute path to the per-step output directory, when
            known.
        error: Free-form error message when ``success`` is ``False``.
    """

    step_index: int
    script: str
    status: str
    success: bool
    duration_s: float
    exit_code: int = -1
    memory_delta_mb: float = 0.0
    output_dir: str | None = None
    error: str | None = None

    def to_dict(self) -> dict[str, Any]:
        return {
            "step_index": self.step_index,
            "script": self.script,
            "status": self.status,
            "success": self.success,
            "duration_s": self.duration_s,
            "exit_code": self.exit_code,
            "memory_delta_mb": self.memory_delta_mb,
            "output_dir": self.output_dir,
            "error": self.error,
        }

get_upstream_gnn_format_enum()

Return GNNFormat enum class from upstream.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
344
345
346
347
def get_upstream_gnn_format_enum() -> Any:
    """Return `GNNFormat` enum class from upstream."""
    mod = _require_upstream_gnn()
    return mod.GNNFormat

get_upstream_parsing_system()

Return a new GNNParsingSystem instance.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
338
339
340
341
def get_upstream_parsing_system() -> Any:
    """Return a new ``GNNParsingSystem`` instance."""
    mod = _require_upstream_gnn()
    return mod.GNNParsingSystem()

is_upstream_gnn_available()

Return True if the upstream gnn package (GNN >= 4.0) imports successfully.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
149
150
151
152
153
154
155
def is_upstream_gnn_available() -> bool:
    """Return True if the upstream ``gnn`` package (GNN >= 4.0) imports successfully."""
    try:
        _require_upstream_gnn()
    except ImportError:
        return False
    return True

json_safe(obj)

Best-effort JSON-serializable view of an upstream return value.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def json_safe(obj: Any) -> Any:
    """Best-effort JSON-serializable view of an upstream return value."""
    if obj is None or isinstance(obj, str | int | float | bool):
        return obj
    if isinstance(obj, Path):
        return str(obj)
    if isinstance(obj, dict):
        return {str(k): json_safe(v) for k, v in obj.items()}
    if isinstance(obj, (list, tuple)):
        return [json_safe(x) for x in obj]
    if hasattr(obj, "model_dump") and callable(obj.model_dump):
        try:
            return json_safe(obj.model_dump())
        except Exception:
            pass
    if hasattr(obj, "__dict__"):
        try:
            return json_safe(vars(obj))
        except Exception:
            pass
    return str(obj)

parse_upstream_model_gnn_md(package_dir)

Parse model.gnn.md inside a COGANT GNN package directory; JSON-safe summary.

Returns {"path", "parse"} on success. When the optional cogant[upstream] extra is not installed (an expected configuration) returns {"path", "error", "available": False} and logs only at debug level; a genuine upstream parse failure returns {"path", "error"} and logs a warning with the traceback.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def parse_upstream_model_gnn_md(package_dir: str | Path) -> dict[str, Any]:
    """Parse ``model.gnn.md`` inside a COGANT GNN package directory; JSON-safe summary.

    Returns ``{"path", "parse"}`` on success. When the optional
    ``cogant[upstream]`` extra is not installed (an expected configuration)
    returns ``{"path", "error", "available": False}`` and logs only at debug
    level; a genuine upstream parse failure returns ``{"path", "error"}`` and
    logs a warning with the traceback.
    """
    p = Path(package_dir) / "model.gnn.md"
    if not p.is_file():
        return {"error": f"missing {p}"}
    try:
        _require_upstream_gnn()
    except ImportError as e:
        logger.debug("upstream parse_gnn_file skipped: %s", e)
        return {"path": str(p), "error": str(e), "available": False}
    try:
        info = upstream_parse_file(p)
        return {"path": str(p), "parse": json_safe(info)}
    except Exception as e:
        logger.warning("upstream parse_gnn_file failed: %s", e, exc_info=True)
        return {"path": str(p), "error": str(e)}

resolve_steps(only, skip)

Return the ordered list of step indices to execute.

Parameters:

Name Type Description Default
only list[int] | None

When set, restrict to these step indices (preserving canonical order). When None, start from all 25 steps.

required
skip list[int] | None

Step indices to drop after applying only. Ignored entries outside range(25) are silently dropped (callers should validate beforehand).

required

Returns:

Type Description
list[int]

Sorted list of integers in [0, 25).

Examples:

>>> resolve_steps(None, [11, 12])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
>>> resolve_steps([3, 5, 7], None)
[3, 5, 7]
>>> resolve_steps([3, 5, 7], [5])
[3, 7]
Source code in py/cogant/gnn/upstream_bridge/pipeline.py
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
def resolve_steps(
    only: list[int] | None,
    skip: list[int] | None,
) -> list[int]:
    """Return the ordered list of step indices to execute.

    Args:
        only: When set, restrict to these step indices (preserving canonical
            order). When ``None``, start from all 25 steps.
        skip: Step indices to drop after applying ``only``. Ignored entries
            outside ``range(25)`` are silently dropped (callers should
            validate beforehand).

    Returns:
        Sorted list of integers in ``[0, 25)``.

    Examples:
        >>> resolve_steps(None, [11, 12])
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
        >>> resolve_steps([3, 5, 7], None)
        [3, 5, 7]
        >>> resolve_steps([3, 5, 7], [5])
        [3, 7]
    """
    universe = set(range(len(UPSTREAM_STEP_SCRIPTS)))
    chosen = set(only) & universe if only is not None else set(universe)
    if skip:
        chosen -= set(skip)
    return sorted(chosen)

run_upstream_pipeline(cfg)

Execute the configured subset of upstream pipeline steps.

Issues one python -m gnn.main --only-steps … invocation against a staged copy of the package's GNN markdown, then reads per-step outcomes from the upstream run summary. One failing step does not abort the run (upstream continues past non-critical failures); bridge-level problems — timeout, a crashed invocation, a missing summary — are reported per requested step with status TIMEOUT / BRIDGE_ERROR and on :attr:UpstreamPipelineResult.error. The upstream console log is written to <output_dir>/upstream_pipeline.log and the bridge summary to <output_dir>/upstream_pipeline_summary.json.

Parameters:

Name Type Description Default
cfg UpstreamPipelineConfig

Pipeline configuration.

required

Returns:

Type Description
UpstreamPipelineResult

class:UpstreamPipelineResult with one :class:UpstreamStepResult

UpstreamPipelineResult

per requested step.

Source code in py/cogant/gnn/upstream_bridge/pipeline.py
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
def run_upstream_pipeline(
    cfg: UpstreamPipelineConfig,
) -> UpstreamPipelineResult:
    """Execute the configured subset of upstream pipeline steps.

    Issues one ``python -m gnn.main --only-steps …`` invocation against a
    staged copy of the package's GNN markdown, then reads per-step outcomes
    from the upstream run summary. One failing step does not abort the run
    (upstream continues past non-critical failures); bridge-level problems —
    timeout, a crashed invocation, a missing summary — are reported per
    requested step with ``status`` ``TIMEOUT`` / ``BRIDGE_ERROR`` and on
    :attr:`UpstreamPipelineResult.error`. The upstream console log is written
    to ``<output_dir>/upstream_pipeline.log`` and the bridge summary to
    ``<output_dir>/upstream_pipeline_summary.json``.

    Args:
        cfg: Pipeline configuration.

    Returns:
        :class:`UpstreamPipelineResult` with one :class:`UpstreamStepResult`
        per requested step.
    """
    if _import_gnn_main() is None:
        return UpstreamPipelineResult(
            available=False,
            error=(
                "gnn.main not importable; install the optional cogant[upstream] "
                "extra (generalized-notation-notation)"
            ),
            target_dir=str(cfg.target_dir),
            output_dir=str(cfg.output_dir),
        )

    chosen = resolve_steps(cfg.only_steps, _effective_skip(cfg))
    skipped = [i for i in range(len(UPSTREAM_STEP_SCRIPTS)) if i not in chosen]
    if not chosen:
        # Upstream rejects an empty step selection at admission; an empty
        # request is a no-op, not a failure.
        return UpstreamPipelineResult(
            available=True,
            skipped=skipped,
            target_dir=str(cfg.target_dir),
            output_dir=str(cfg.output_dir),
        )

    cfg.output_dir.mkdir(parents=True, exist_ok=True)
    cmd = _build_main_command(cfg, _stage_target_dir(cfg), chosen)

    logger.info(
        "Upstream GNN pipeline: %d/%d steps selected (skipping %s) target=%s",
        len(chosen),
        len(UPSTREAM_STEP_SCRIPTS),
        skipped,
        cfg.target_dir,
    )

    log_path = cfg.output_dir / _LOG_FILENAME
    invocation_id = uuid.uuid4().hex
    total_start = time.perf_counter()
    returncode: int | None = None
    bridge_error: str | None = None
    bridge_status = "BRIDGE_ERROR"
    try:
        with log_path.open("w", encoding="utf-8") as log_handle:
            completed = subprocess.run(
                cmd,
                cwd=cfg.output_dir,
                env=_child_env(cfg, invocation_id),
                stdin=subprocess.DEVNULL,
                stdout=log_handle,
                stderr=subprocess.STDOUT,
                timeout=cfg.timeout_s,
                check=False,
            )
        returncode = completed.returncode
    except subprocess.TimeoutExpired:
        bridge_status = "TIMEOUT"
        bridge_error = f"upstream gnn.main exceeded the {cfg.timeout_s:g}s bridge timeout"
    except OSError as exc:
        bridge_error = f"could not launch upstream gnn.main: {exc}"
    total = time.perf_counter() - total_start

    summary = None
    if bridge_error is None:
        try:
            summary = _read_summary(cfg.output_dir, invocation_id)
        except (OSError, ValueError) as exc:
            bridge_error = f"could not verify upstream pipeline summary: {exc}"
    upstream_status: str | None = None
    run_id: str | None = None
    auto_included: list[int] = []
    if summary is not None:
        steps = _steps_from_summary(summary, cfg, chosen)
        upstream_status = str(summary.get("overall_status") or "") or None
        run_id = invocation_id
        auto_included = sorted(s.step_index for s in steps if s.step_index not in chosen)
    else:
        if bridge_error is None:
            tail = _last_line(_read_log_tail(log_path)) or "no output"
            bridge_error = (
                f"upstream gnn.main exited {returncode} without a pipeline summary: {tail}"
            )
        steps = _bridge_failure_steps(cfg, chosen, bridge_status, bridge_error)

    for step in steps:
        log = logger.info if step.success else logger.warning
        log(
            "Upstream step %s -> %s in %.2fs%s",
            step.script,
            step.status,
            step.duration_s,
            f" ({step.error})" if step.error else "",
        )

    executed = sorted(set(chosen) | set(auto_included))
    result = UpstreamPipelineResult(
        available=True,
        steps=steps,
        executed=executed,
        skipped=[i for i in skipped if i not in auto_included],
        total_duration_s=total,
        output_dir=str(cfg.output_dir),
        target_dir=str(cfg.target_dir),
        error=bridge_error,
        upstream_status=upstream_status,
        run_id=run_id,
        auto_included=auto_included,
    )
    _write_bridge_summary(cfg, result)
    return result

run_upstream_validate_gnn(markdown, *, validation_level=DEFAULT_VALIDATION_LEVEL)

Run upstream validate_gnn_syntax on GNN markdown.

Upstream gnn.validate_gnn_syntax delegates to the formal schema_validator pipeline: every required section must be present with substantive content, and (at standard and above) connection endpoints must reference declared variables. The markdown is staged to a temporary .gnn.md file so the verdict never depends on upstream's path-versus-content probe of the input string.

Parameters:

Name Type Description Default
markdown str

GNN markdown document.

required
validation_level str

Upstream ValidationLevel name (basic / standard / strict / research / round_trip). Unknown levels are reported as a validation error by upstream rather than silently skipped.

DEFAULT_VALIDATION_LEVEL
Source code in py/cogant/gnn/upstream_bridge/__init__.py
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
def run_upstream_validate_gnn(
    markdown: str,
    *,
    validation_level: str = DEFAULT_VALIDATION_LEVEL,
) -> UpstreamGNNValidation:
    """Run upstream ``validate_gnn_syntax`` on GNN markdown.

    Upstream ``gnn.validate_gnn_syntax`` delegates to the formal
    ``schema_validator`` pipeline: every required section must be present with
    substantive content, and (at ``standard`` and above) connection endpoints
    must reference declared variables. The markdown is staged to a temporary
    ``.gnn.md`` file so the verdict never depends on upstream's
    path-versus-content probe of the input string.

    Args:
        markdown: GNN markdown document.
        validation_level: Upstream ``ValidationLevel`` name
            (``basic`` / ``standard`` / ``strict`` / ``research`` /
            ``round_trip``). Unknown levels are reported as a validation
            error by upstream rather than silently skipped.
    """
    import tempfile

    try:
        mod = _require_upstream_gnn()
    except ImportError as e:
        return UpstreamGNNValidation(
            available=False,
            ok=True,
            skipped_reason=(
                f"{e} core COGANT validation remains available; this optional upstream "
                "check was skipped."
            ),
        )

    validate_gnn_syntax = getattr(mod, "validate_gnn_syntax", None)
    if validate_gnn_syntax is None:
        return UpstreamGNNValidation(
            available=False,
            ok=True,
            skipped_reason="upstream gnn has no validate_gnn_syntax",
        )

    ver = upstream_version()

    try:
        with tempfile.NamedTemporaryFile(
            mode="w",
            suffix=".gnn.md",
            delete=False,
            encoding="utf-8",
        ) as tmp:
            tmp.write(markdown)
            tmp_path = Path(tmp.name)
        try:
            ok, errors = validate_gnn_syntax(tmp_path, validation_level)
        finally:
            try:
                tmp_path.unlink()
            except OSError:
                pass
        err_list = [str(e) for e in errors] if errors else []
        return UpstreamGNNValidation(
            available=True,
            ok=bool(ok),
            errors=err_list,
            version=ver,
        )
    except Exception as e:
        logger.warning("Upstream validate_gnn_syntax raised: %s", e, exc_info=True)
        return UpstreamGNNValidation(
            available=True,
            ok=False,
            errors=[f"upstream validate_gnn_syntax raised: {e}"],
            version=ver,
        )

upstream_discover_files(root)

Call upstream discover_gnn_files.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
271
272
273
274
def upstream_discover_files(root: str | Path) -> Any:
    """Call upstream ``discover_gnn_files``."""
    mod = _require_upstream_gnn()
    return mod.discover_gnn_files(Path(root))

upstream_generate_report(*args, **kwargs)

Call upstream generate_gnn_report.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
297
298
299
300
def upstream_generate_report(*args: Any, **kwargs: Any) -> Any:
    """Call upstream ``generate_gnn_report``."""
    mod = _require_upstream_gnn()
    return mod.generate_gnn_report(*args, **kwargs)

upstream_module_info(*args, **kwargs)

Call upstream get_module_info.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
309
310
311
312
def upstream_module_info(*args: Any, **kwargs: Any) -> Any:
    """Call upstream ``get_module_info``."""
    mod = _require_upstream_gnn()
    return mod.get_module_info(*args, **kwargs)

upstream_parse_file(path)

Call upstream parse_gnn_file.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
265
266
267
268
def upstream_parse_file(path: str | Path) -> Any:
    """Call upstream ``parse_gnn_file``."""
    mod = _require_upstream_gnn()
    return mod.parse_gnn_file(Path(path))

upstream_parse_formal(*args, **kwargs)

Call upstream parse_gnn_formal.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
326
327
328
329
def upstream_parse_formal(*args: Any, **kwargs: Any) -> Any:
    """Call upstream ``parse_gnn_formal``."""
    mod = _require_upstream_gnn()
    return mod.parse_gnn_formal(*args, **kwargs)

upstream_process_directory(input_dir, output_dir, **kwargs)

Call upstream process_gnn_directory.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
277
278
279
280
281
282
283
284
def upstream_process_directory(
    input_dir: str | Path,
    output_dir: str | Path,
    **kwargs: Any,
) -> Any:
    """Call upstream ``process_gnn_directory``."""
    mod = _require_upstream_gnn()
    return mod.process_gnn_directory(Path(input_dir), Path(output_dir), **kwargs)

upstream_process_directory_lightweight(input_dir, output_dir, **kwargs)

Call upstream process_gnn_directory_lightweight.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
287
288
289
290
291
292
293
294
def upstream_process_directory_lightweight(
    input_dir: str | Path,
    output_dir: str | Path,
    **kwargs: Any,
) -> Any:
    """Call upstream ``process_gnn_directory_lightweight``."""
    mod = _require_upstream_gnn()
    return mod.process_gnn_directory_lightweight(Path(input_dir), Path(output_dir), **kwargs)

upstream_process_multi_format(input_dir, output_dir, log=None, **kwargs)

Call upstream process_gnn_multi_format (may import upstream pipeline helpers).

Source code in py/cogant/gnn/upstream_bridge/__init__.py
315
316
317
318
319
320
321
322
323
def upstream_process_multi_format(
    input_dir: str | Path,
    output_dir: str | Path,
    log: Any | None = None,
    **kwargs: Any,
) -> Any:
    """Call upstream ``process_gnn_multi_format`` (may import upstream pipeline helpers)."""
    mod = _require_upstream_gnn()
    return mod.process_gnn_multi_format(Path(input_dir), Path(output_dir), log or logger, **kwargs)

upstream_validate_file_content(content, *, is_content=True)

Call upstream validate_gnn_source (path or raw content).

Source code in py/cogant/gnn/upstream_bridge/__init__.py
251
252
253
254
255
256
257
258
259
260
261
262
def upstream_validate_file_content(
    content: str,
    *,
    is_content: bool = True,
) -> dict[str, Any]:
    """Call upstream ``validate_gnn_source`` (path or raw content)."""
    mod = _require_upstream_gnn()
    fn = getattr(mod, "validate_gnn_source", None)
    if fn is None:
        return {"is_valid": False, "errors": ["upstream gnn has no validate_gnn_source"]}
    r = fn(content, is_content=is_content)
    return json_safe(r) if isinstance(r, dict) else {"result": json_safe(r)}

upstream_validate_markdown(markdown)

Alias for :func:run_upstream_validate_gnn.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
246
247
248
def upstream_validate_markdown(markdown: str) -> UpstreamGNNValidation:
    """Alias for :func:`run_upstream_validate_gnn`."""
    return run_upstream_validate_gnn(markdown)

upstream_validate_structure(*args, **kwargs)

Call upstream check_gnn_file_structure (GNN 2.x validate_gnn_structure).

Source code in py/cogant/gnn/upstream_bridge/__init__.py
303
304
305
306
def upstream_validate_structure(*args: Any, **kwargs: Any) -> Any:
    """Call upstream ``check_gnn_file_structure`` (GNN 2.x ``validate_gnn_structure``)."""
    mod = _require_upstream_gnn()
    return mod.check_gnn_file_structure(*args, **kwargs)

upstream_validate_syntax_formal(*args, **kwargs)

Call upstream validate_gnn_syntax (GNN 2.x validate_gnn_syntax_formal).

Source code in py/cogant/gnn/upstream_bridge/__init__.py
332
333
334
335
def upstream_validate_syntax_formal(*args: Any, **kwargs: Any) -> Any:
    """Call upstream ``validate_gnn_syntax`` (GNN 2.x ``validate_gnn_syntax_formal``)."""
    mod = _require_upstream_gnn()
    return mod.validate_gnn_syntax(*args, **kwargs)

upstream_version()

Return the upstream gnn.__version__ if available.

Source code in py/cogant/gnn/upstream_bridge/__init__.py
158
159
160
161
162
163
164
165
def upstream_version() -> str | None:
    """Return the upstream ``gnn.__version__`` if available."""
    try:
        mod = _require_upstream_gnn()
    except ImportError:
        return None
    v = getattr(mod, "__version__", None)
    return v if isinstance(v, str) else None

Examples

Every public symbol exported by cogant.gnn (GNNPackageBuilder, GNNValidator, the matrix builder, the runner, the JSON exporter, and upstream bridge helpers) is exercised by the following references: