pgc-compiler 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. compiler/VERSION +1 -0
  2. compiler/__init__.py +1 -0
  3. compiler/atoms/__init__.py +54 -0
  4. compiler/atoms/error_codes.py +160 -0
  5. compiler/atoms/errors.py +125 -0
  6. compiler/atoms/fqdn.py +204 -0
  7. compiler/atoms/invariants.py +106 -0
  8. compiler/atoms/phase.py +99 -0
  9. compiler/atoms/pipeline.py +51 -0
  10. compiler/atoms/snapshot_gate.py +51 -0
  11. compiler/atoms/sorting.py +125 -0
  12. compiler/cli.py +637 -0
  13. compiler/diagnostics/__init__.py +6 -0
  14. compiler/diagnostics/determination.py +148 -0
  15. compiler/diagnostics/machine_block_health.py +199 -0
  16. compiler/governance/__init__.py +6 -0
  17. compiler/governance_engine/__init__.py +0 -0
  18. compiler/governance_engine/artifact_kinds.py +221 -0
  19. compiler/governance_engine/assertions/__init__.py +0 -0
  20. compiler/governance_engine/assertions/handlers/__init__.py +200 -0
  21. compiler/governance_engine/assertions/handlers/assert_ac_declaration_well_formed_v0.py +70 -0
  22. compiler/governance_engine/assertions/handlers/assert_actor_authority_separation_v0.py +17 -0
  23. compiler/governance_engine/assertions/handlers/assert_artifact_content_hash_declared_v0.py +60 -0
  24. compiler/governance_engine/assertions/handlers/assert_assert_not_runtime_referenced_v0.py +49 -0
  25. compiler/governance_engine/assertions/handlers/assert_assert_parity_v0.py +169 -0
  26. compiler/governance_engine/assertions/handlers/assert_atom_output_purity_v0.py +186 -0
  27. compiler/governance_engine/assertions/handlers/assert_authority_constituted_v0.py +56 -0
  28. compiler/governance_engine/assertions/handlers/assert_authority_required_for_execution_v0.py +16 -0
  29. compiler/governance_engine/assertions/handlers/assert_authority_state_well_formed_v0.py +17 -0
  30. compiler/governance_engine/assertions/handlers/assert_binding_integrity_v0.py +64 -0
  31. compiler/governance_engine/assertions/handlers/assert_binding_surface_closed_v0.py +92 -0
  32. compiler/governance_engine/assertions/handlers/assert_cc_capability_binding_valid_v0.py +85 -0
  33. compiler/governance_engine/assertions/handlers/assert_cc_inputs_satisfied_v0.py +89 -0
  34. compiler/governance_engine/assertions/handlers/assert_cc_no_implicit_chaining_v0.py +89 -0
  35. compiler/governance_engine/assertions/handlers/assert_cc_no_missing_dependencies_v0.py +89 -0
  36. compiler/governance_engine/assertions/handlers/assert_cc_no_unused_outputs_v0.py +81 -0
  37. compiler/governance_engine/assertions/handlers/assert_cc_storage_op_conformance_v0.py +74 -0
  38. compiler/governance_engine/assertions/handlers/assert_compiler_governance_declared_v0.py +65 -0
  39. compiler/governance_engine/assertions/handlers/assert_compiler_no_execution_v0.py +86 -0
  40. compiler/governance_engine/assertions/handlers/assert_concern_not_authority_v0.py +51 -0
  41. compiler/governance_engine/assertions/handlers/assert_conformance_assertion_mode_valid_v0.py +35 -0
  42. compiler/governance_engine/assertions/handlers/assert_cryptographic_trust_declared_v0.py +51 -0
  43. compiler/governance_engine/assertions/handlers/assert_cs_isolated_execution_v0.py +35 -0
  44. compiler/governance_engine/assertions/handlers/assert_cs_surface_closed_v0.py +241 -0
  45. compiler/governance_engine/assertions/handlers/assert_cs_traceable_v0.py +35 -0
  46. compiler/governance_engine/assertions/handlers/assert_ct_output_contract_match_v0.py +167 -0
  47. compiler/governance_engine/assertions/handlers/assert_ct_surface_closed_v0.py +173 -0
  48. compiler/governance_engine/assertions/handlers/assert_ct_surface_derived_closed_v0.py +108 -0
  49. compiler/governance_engine/assertions/handlers/assert_ct_test_data_outcome_declared_v0.py +112 -0
  50. compiler/governance_engine/assertions/handlers/assert_ev_append_only_v0.py +70 -0
  51. compiler/governance_engine/assertions/handlers/assert_ev_schema_required_v0.py +59 -0
  52. compiler/governance_engine/assertions/handlers/assert_execution_placement_declared_v0.py +51 -0
  53. compiler/governance_engine/assertions/handlers/assert_execution_scheduling_declared_v0.py +51 -0
  54. compiler/governance_engine/assertions/handlers/assert_fqdn_namespace_authorized_v0.py +38 -0
  55. compiler/governance_engine/assertions/handlers/assert_fqdn_only_references_v0.py +89 -0
  56. compiler/governance_engine/assertions/handlers/assert_governance_declaration_resolves_v0.py +126 -0
  57. compiler/governance_engine/assertions/handlers/assert_handler_registry_closed_v0.py +75 -0
  58. compiler/governance_engine/assertions/handlers/assert_identity_authority_separation_v0.py +19 -0
  59. compiler/governance_engine/assertions/handlers/assert_identity_fqdn_consistency.py +75 -0
  60. compiler/governance_engine/assertions/handlers/assert_implementation_admissible_v0.py +66 -0
  61. compiler/governance_engine/assertions/handlers/assert_in_no_execution_logic_v0.py +82 -0
  62. compiler/governance_engine/assertions/handlers/assert_in_schema_required_v0.py +74 -0
  63. compiler/governance_engine/assertions/handlers/assert_in_workflow_binding_v0.py +101 -0
  64. compiler/governance_engine/assertions/handlers/assert_inspection_capability_read_only_v0.py +114 -0
  65. compiler/governance_engine/assertions/handlers/assert_no_ambient_authority_v0.py +17 -0
  66. compiler/governance_engine/assertions/handlers/assert_no_runtime_authorization_v0.py +18 -0
  67. compiler/governance_engine/assertions/handlers/assert_no_runtime_topology_synthesis_v0.py +18 -0
  68. compiler/governance_engine/assertions/handlers/assert_no_smart_execution_v0.py +102 -0
  69. compiler/governance_engine/assertions/handlers/assert_no_undeclared_behavior_surface_v0.py +52 -0
  70. compiler/governance_engine/assertions/handlers/assert_no_workflow_authorization_logic_v0.py +18 -0
  71. compiler/governance_engine/assertions/handlers/assert_protocol_surface_closed_v0.py +119 -0
  72. compiler/governance_engine/assertions/handlers/assert_rb_binding_policy_conformance_v0.py +124 -0
  73. compiler/governance_engine/assertions/handlers/assert_rb_cs_only_v0.py +68 -0
  74. compiler/governance_engine/assertions/handlers/assert_rb_no_logic_v0.py +81 -0
  75. compiler/governance_engine/assertions/handlers/assert_rb_parameters_declared_v0.py +117 -0
  76. compiler/governance_engine/assertions/handlers/assert_rb_storage_subdomain_owned_v0.py +118 -0
  77. compiler/governance_engine/assertions/handlers/assert_runtime_invariant_wired_v0.py +163 -0
  78. compiler/governance_engine/assertions/handlers/assert_schema_conformance_v0.py +64 -0
  79. compiler/governance_engine/assertions/handlers/assert_schema_description_well_formed_v0.py +97 -0
  80. compiler/governance_engine/assertions/handlers/assert_security_domain_declared_v0.py +51 -0
  81. compiler/governance_engine/assertions/handlers/assert_structure_paths_well_formed_v0.py +118 -0
  82. compiler/governance_engine/assertions/handlers/assert_superseded_not_referenced_v0.py +134 -0
  83. compiler/governance_engine/assertions/handlers/assert_test_data_match_ct_output_v0.py +134 -0
  84. compiler/governance_engine/assertions/handlers/assert_topology_acyclic_v0.py +53 -0
  85. compiler/governance_engine/assertions/handlers/assert_topology_authority_orthogonal_v0.py +110 -0
  86. compiler/governance_engine/assertions/handlers/assert_topology_capability_reference_unique_v0.py +63 -0
  87. compiler/governance_engine/assertions/handlers/assert_topology_contract_closed_v0.py +113 -0
  88. compiler/governance_engine/assertions/handlers/assert_topology_immutable_after_compilation_v0.py +17 -0
  89. compiler/governance_engine/assertions/handlers/assert_topology_input_reference_declared_v0.py +112 -0
  90. compiler/governance_engine/assertions/handlers/assert_topology_routing_complete_v0.py +82 -0
  91. compiler/governance_engine/assertions/handlers/assert_topology_step_declared_v0.py +77 -0
  92. compiler/governance_engine/assertions/handlers/assert_topology_step_id_unique_v0.py +60 -0
  93. compiler/governance_engine/assertions/handlers/assert_topology_surface_canonical_v0.py +180 -0
  94. compiler/governance_engine/assertions/handlers/assert_topology_transport_orthogonal_v0.py +113 -0
  95. compiler/governance_engine/assertions/handlers/assert_trace_authority_binding_required_v0.py +18 -0
  96. compiler/governance_engine/assertions/handlers/assert_transport_canonical_normalization_v0.py +83 -0
  97. compiler/governance_engine/assertions/handlers/assert_transport_no_dynamic_routing_v0.py +93 -0
  98. compiler/governance_engine/assertions/handlers/assert_transport_no_workflow_semantics_v0.py +106 -0
  99. compiler/governance_engine/assertions/handlers/assert_transport_operation_identity_independence_v0.py +56 -0
  100. compiler/governance_engine/assertions/handlers/assert_transport_response_projection_external_v0.py +38 -0
  101. compiler/governance_engine/assertions/handlers/assert_transport_result_class_protocol_independence_v0.py +48 -0
  102. compiler/governance_engine/assertions/handlers/assert_transport_target_exists_v0.py +132 -0
  103. compiler/governance_engine/assertions/handlers/assert_unique_artifact_id_v0.py +58 -0
  104. compiler/governance_engine/assertions/handlers/assert_vocabulary_symbols_well_formed_v0.py +163 -0
  105. compiler/governance_engine/assertions/handlers/assert_wf_announcement_distinct_v0.py +85 -0
  106. compiler/governance_engine/assertions/handlers/assert_wf_cc_only_nodes_v0.py +60 -0
  107. compiler/governance_engine/assertions/handlers/assert_wf_entry_intent_v0.py +68 -0
  108. compiler/governance_engine/assertions/handlers/assert_wf_execution_path_valid_v0.py +89 -0
  109. compiler/governance_engine/assertions/handlers/assert_wf_node_key_binding_unique_v0.py +107 -0
  110. compiler/governance_engine/platform_root.py +102 -0
  111. compiler/governance_engine/structure/__init__.py +56 -0
  112. compiler/governance_engine/structure/discovery/__init__.py +28 -0
  113. compiler/governance_engine/structure/discovery/artifact_locator.py +210 -0
  114. compiler/governance_engine/structure/exceptions.py +113 -0
  115. compiler/governance_engine/structure/loading/__init__.py +88 -0
  116. compiler/governance_engine/structure/loading/fs_reader.py +225 -0
  117. compiler/governance_engine/structure/loading/markdown_parser.py +148 -0
  118. compiler/governance_engine/structure/loading/protocol_loader.py +587 -0
  119. compiler/governance_engine/structure/loading/test_case_provider.py +125 -0
  120. compiler/governance_engine/structure/loading/trace_reader.py +98 -0
  121. compiler/governance_engine/structure/loading/vocabulary_loader.py +174 -0
  122. compiler/governance_engine/structure/loading/yaml_parser.py +209 -0
  123. compiler/governance_engine/structure/resolution/__init__.py +22 -0
  124. compiler/governance_engine/structure/resolution/domain_resolver.py +124 -0
  125. compiler/governance_engine/structure/resolution/layer_resolver.py +572 -0
  126. compiler/governance_engine/structure/resolution/path_registry.py +1054 -0
  127. compiler/graph/__init__.py +38 -0
  128. compiler/graph/addressing.py +153 -0
  129. compiler/graph/edge.py +100 -0
  130. compiler/graph/evidence.py +637 -0
  131. compiler/graph/graph.py +269 -0
  132. compiler/graph/hashing.py +89 -0
  133. compiler/graph/node.py +134 -0
  134. compiler/graph/query.py +215 -0
  135. compiler/graph/state.py +237 -0
  136. compiler/graph/trace.py +97 -0
  137. compiler/graph/types.py +71 -0
  138. compiler/projections/__init__.py +207 -0
  139. compiler/projections/artifact_index.py +225 -0
  140. compiler/projections/canonical.py +173 -0
  141. compiler/projections/dispatch.py +532 -0
  142. compiler/projections/evidence.py +170 -0
  143. compiler/projections/handlers.py +224 -0
  144. compiler/projections/ipm.py +388 -0
  145. compiler/projections/reverse.py +165 -0
  146. compiler/projections/tokenized.py +135 -0
  147. compiler/projections/vocabulary.py +108 -0
  148. compiler/stages/__init__.py +28 -0
  149. compiler/stages/s1_extract.py +867 -0
  150. compiler/stages/s2_canonicalize.py +516 -0
  151. compiler/stages/s3_semantic_addressing.py +66 -0
  152. compiler/stages/s4_govern.py +754 -0
  153. compiler/stages/s5_construct.py +537 -0
  154. compiler/stages/s6_project.py +94 -0
  155. compiler/stages/s7_materialize.py +1170 -0
  156. compiler/stages/s8_verify.py +643 -0
  157. compiler/stages/s9_attest.py +184 -0
  158. compiler/structure_loader.py +132 -0
  159. compiler/visualization/__init__.py +12 -0
  160. compiler/visualization/consumers/__init__.py +28 -0
  161. compiler/visualization/consumers/evidence_projection.py +162 -0
  162. compiler/visualization/consumers/evidence_query.py +296 -0
  163. compiler/visualization/consumers/evidence_reader.py +127 -0
  164. compiler/visualization/views/__init__.py +70 -0
  165. compiler/visualization/views/_png_writer.py +45 -0
  166. compiler/visualization/views/artifact_lineage.py +180 -0
  167. compiler/visualization/views/family_view.py +164 -0
  168. compiler/visualization/views/materialization_view.py +150 -0
  169. compiler/visualization/views/structural_dag.py +158 -0
  170. compiler/visualization/wf_graph_generator.py +534 -0
  171. pgc_compiler-2.0.0.dist-info/METADATA +203 -0
  172. pgc_compiler-2.0.0.dist-info/RECORD +177 -0
  173. pgc_compiler-2.0.0.dist-info/WHEEL +5 -0
  174. pgc_compiler-2.0.0.dist-info/entry_points.txt +2 -0
  175. pgc_compiler-2.0.0.dist-info/licenses/LICENSE +67 -0
  176. pgc_compiler-2.0.0.dist-info/licenses/NOTICE +11 -0
  177. pgc_compiler-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,180 @@
1
+ """
2
+ Artifact Lineage view — causality chain per materialized artifact (DOT format).
3
+
4
+ ISOLATION INVARIANT: Only imports from visualization.consumers. No compiler internals.
5
+
6
+ Core question answered: "Why does this artifact exist?"
7
+
8
+ What it shows:
9
+ For each materialized output path, walk the causality chain backward
10
+ from the artifact_written event to its root cause — showing every event
11
+ that directly or indirectly caused the artifact to be produced.
12
+
13
+ DTO:
14
+ ArtifactLineageView — one lineage chain per materialized artifact
15
+
16
+ Renderer:
17
+ render_artifact_lineage(view) → DOT string
18
+
19
+ Each artifact appears as a cluster. Events are nodes shaped by their family.
20
+ Causality edges flow from root → leaf (cause → effect), so graph reads top-to-bottom.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import dataclass, field
26
+ from pathlib import Path
27
+
28
+ from ..consumers.evidence_query import EvidenceQuery, TraceEventDTO
29
+ from ..consumers.evidence_projection import EvidenceProjection
30
+ from ._png_writer import write_png_from_dot
31
+
32
+
33
+ @dataclass
34
+ class ArtifactLineage:
35
+ """
36
+ Causality chain for a single materialized artifact.
37
+
38
+ Fields:
39
+ output_path — the artifact output path (from artifact_written event detail)
40
+ chain — events in causality chain, root-first (ascending event_id)
41
+ """
42
+ output_path: str
43
+ chain: list[TraceEventDTO] = field(default_factory=list)
44
+
45
+
46
+ @dataclass
47
+ class ArtifactLineageView:
48
+ """
49
+ All lineage chains for a compiled structure.
50
+
51
+ Fields:
52
+ structure_id — identifier for the compiled structure
53
+ lineages — one ArtifactLineage per materialized output, sorted by path
54
+ """
55
+ structure_id: str
56
+ lineages: list[ArtifactLineage] = field(default_factory=list)
57
+
58
+
59
+ def build_artifact_lineage_view(query: EvidenceQuery) -> ArtifactLineageView:
60
+ """
61
+ Build an ArtifactLineageView from an EvidenceQuery.
62
+
63
+ Only calls EvidenceQuery and EvidenceProjection methods.
64
+ No compiler imports, no inference beyond what the consumer layer provides.
65
+ """
66
+ projection = EvidenceProjection(query)
67
+ lineages: list[ArtifactLineage] = []
68
+
69
+ for output_path in sorted(query.materialized_outputs()):
70
+ # Find the artifact_written event for this path
71
+ written_events = [
72
+ ev for ev in query.by_operation("artifact_written")
73
+ if ev.detail.get("output_path") == output_path
74
+ ]
75
+ if not written_events:
76
+ continue
77
+
78
+ # Use subject_fqdn of the written event as the provenance key
79
+ written_ev = written_events[0]
80
+ fqdn = written_ev.subject_fqdn
81
+
82
+ # Walk causality chain via EvidenceProjection
83
+ chain = projection.artifact_provenance(fqdn) if fqdn else query.causality_chain(written_ev.event_id)
84
+
85
+ lineages.append(ArtifactLineage(
86
+ output_path=output_path,
87
+ chain=chain,
88
+ ))
89
+
90
+ return ArtifactLineageView(
91
+ structure_id=query.structure_id,
92
+ lineages=lineages,
93
+ )
94
+
95
+
96
+ # Family → shape (DOT node shape)
97
+ _FAMILY_SHAPE: dict[str, str] = {
98
+ "DISCOVERY": "ellipse",
99
+ "TOPOLOGY": "diamond",
100
+ "ADDRESSING": "parallelogram",
101
+ "GOVERNANCE": "hexagon",
102
+ "CONSTRUCTION": "box",
103
+ "PROJECTION": "trapezium",
104
+ "MATERIALIZATION": "invhouse",
105
+ "VERIFICATION": "octagon",
106
+ }
107
+ _DEFAULT_SHAPE = "box"
108
+
109
+
110
+ def render_artifact_lineage(view: ArtifactLineageView) -> str:
111
+ """
112
+ Render an ArtifactLineageView as a DOT string.
113
+
114
+ Each artifact gets a subgraph cluster containing its causality chain.
115
+ Events are shaped by family. Edges flow cause → effect (top-to-bottom).
116
+ Output is deterministic: same ArtifactLineageView → same DOT string.
117
+ """
118
+ lines: list[str] = []
119
+ lines.append(f'digraph "artifact_lineage_{view.structure_id}" {{')
120
+ lines.append(' graph [rankdir=TB fontname="monospace" label="Artifact Lineage" pad="0.5"];')
121
+ lines.append(' node [fontname="monospace" fontsize=9 style=filled fillcolor="#f4f4f4"];')
122
+ lines.append(' edge [fontname="monospace" fontsize=8 style=solid color="#555555"];')
123
+ lines.append("")
124
+
125
+ # Track all event_id nodes already emitted to avoid duplicates across chains
126
+ emitted_nodes: set[int] = set()
127
+
128
+ for lidx, lineage in enumerate(view.lineages):
129
+ # Truncate long paths for cluster label
130
+ label = lineage.output_path
131
+ if len(label) > 60:
132
+ label = "..." + label[-57:]
133
+
134
+ lines.append(f" subgraph cluster_lineage_{lidx} {{")
135
+ lines.append(f' label="{label}";')
136
+ lines.append(' style=rounded; color="#666666";')
137
+ lines.append("")
138
+
139
+ for ev in lineage.chain:
140
+ if ev.event_id in emitted_nodes:
141
+ continue
142
+ emitted_nodes.add(ev.event_id)
143
+ shape = _FAMILY_SHAPE.get(ev.family, _DEFAULT_SHAPE)
144
+ op_label = ev.operation
145
+ node_label = f"{op_label}\\n(#{ev.event_id} {ev.stage})"
146
+ lines.append(
147
+ f' n{ev.event_id} [label="{node_label}" shape={shape}];'
148
+ )
149
+
150
+ lines.append(" }")
151
+ lines.append("")
152
+
153
+ # Causality edges within each chain (cause → effect ascending event_id pairs)
154
+ lines.append(" // Causality edges within lineage chains")
155
+ emitted_edges: set[tuple[int, int]] = set()
156
+
157
+ for lineage in view.lineages:
158
+ # Edges: consecutive pairs in causality chain (root → ... → artifact)
159
+ # The chain is root-first; adjacent events are causally connected.
160
+ # We use the fact that chain[i].event_id < chain[i+1].event_id (monotonic).
161
+ for i in range(len(lineage.chain) - 1):
162
+ src_id = lineage.chain[i].event_id
163
+ tgt_id = lineage.chain[i + 1].event_id
164
+ key = (src_id, tgt_id)
165
+ if key not in emitted_edges:
166
+ emitted_edges.add(key)
167
+ lines.append(f" n{src_id} -> n{tgt_id};")
168
+
169
+ lines.append("}")
170
+ return "\n".join(lines)
171
+
172
+
173
+ def write_artifact_lineage_png(view: ArtifactLineageView, output_path: Path) -> bool:
174
+ """
175
+ Render ArtifactLineageView → PNG using graphviz (dot command).
176
+
177
+ DOT is internal only — not written to disk.
178
+ Returns True if PNG was written, False if graphviz is unavailable.
179
+ """
180
+ return write_png_from_dot(render_artifact_lineage(view), output_path)
@@ -0,0 +1,164 @@
1
+ """
2
+ Family View — event family distribution as deterministic DOT (→ PNG).
3
+
4
+ ISOLATION INVARIANT: Only imports from visualization.consumers. No compiler internals.
5
+
6
+ What it shows:
7
+ - One node per EventFamily present in the evidence graph
8
+ - Family node labeled with: family name, event count, operations used
9
+ - Stage → Family edges (dashed): which stages contribute to which families
10
+ - Gives semantic observability: correct family tagging = correct edge topology
11
+
12
+ DTO:
13
+ FamilyViewDTO — family names, counts, per-stage contributions
14
+
15
+ Renderer:
16
+ render_family_view(view) → DOT string (internal only)
17
+ write_family_view_png(view, output_path) → writes PNG
18
+
19
+ The DOT output is deterministic: same FamilyViewDTO → same DOT string.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+
27
+ from ..consumers.evidence_query import EvidenceQuery
28
+ from ._png_writer import write_png_from_dot
29
+
30
+
31
+ @dataclass
32
+ class FamilyStageStat:
33
+ """How many events of a given family came from a specific stage."""
34
+ stage: str
35
+ count: int
36
+
37
+
38
+ @dataclass
39
+ class FamilyViewDTO:
40
+ """
41
+ Event family distribution summary.
42
+
43
+ Fields:
44
+ structure_id — identifier for the compiled structure
45
+ families — sorted list of family names present
46
+ event_count_by_family — {family: total event count}
47
+ operations_by_family — {family: sorted list of distinct operations}
48
+ stage_contributions — {family: [FamilyStageStat]} stages that emit this family
49
+ """
50
+ structure_id: str
51
+ families: list[str]
52
+ event_count_by_family: dict[str, int] = field(default_factory=dict)
53
+ operations_by_family: dict[str, list[str]] = field(default_factory=dict)
54
+ stage_contributions: dict[str, list[FamilyStageStat]] = field(default_factory=dict)
55
+
56
+
57
+ def build_family_view(query: EvidenceQuery) -> FamilyViewDTO:
58
+ """
59
+ Build a FamilyViewDTO from an EvidenceQuery.
60
+
61
+ Only calls EvidenceQuery methods — no compiler imports, no inference.
62
+ """
63
+ families = query.families()
64
+
65
+ event_count_by_family: dict[str, int] = {}
66
+ operations_by_family: dict[str, list[str]] = {}
67
+ stage_contributions: dict[str, list[FamilyStageStat]] = {}
68
+
69
+ for family in families:
70
+ events = query.by_family(family)
71
+ event_count_by_family[family] = len(events)
72
+ operations_by_family[family] = sorted({ev.operation for ev in events})
73
+
74
+ # Count per-stage contributions to this family
75
+ stage_counts: dict[str, int] = {}
76
+ for ev in events:
77
+ stage_counts[ev.stage] = stage_counts.get(ev.stage, 0) + 1
78
+ stage_contributions[family] = [
79
+ FamilyStageStat(stage=s, count=c)
80
+ for s, c in sorted(stage_counts.items())
81
+ ]
82
+
83
+ return FamilyViewDTO(
84
+ structure_id=query.structure_id,
85
+ families=families,
86
+ event_count_by_family=event_count_by_family,
87
+ operations_by_family=operations_by_family,
88
+ stage_contributions=stage_contributions,
89
+ )
90
+
91
+
92
+ # Family → greyscale fill
93
+ _FAMILY_FILL: dict[str, str] = {
94
+ "DISCOVERY": "#f0f0f0",
95
+ "TOPOLOGY": "#e0e0e0",
96
+ "ADDRESSING": "#d4d4d4",
97
+ "GOVERNANCE": "#c8c8c8",
98
+ "CONSTRUCTION": "#bcbcbc",
99
+ "PROJECTION": "#b0b0b0",
100
+ "MATERIALIZATION": "#a4a4a4",
101
+ "VERIFICATION": "#989898",
102
+ }
103
+ _DEFAULT_FILL = "#f8f8f8"
104
+
105
+
106
+ def render_family_view(view: FamilyViewDTO) -> str:
107
+ """
108
+ Render a FamilyViewDTO as a DOT string (internal representation only).
109
+
110
+ Family nodes are rectangles labeled with name + event count + operations.
111
+ Stage → Family edges show which stage contributes to which family.
112
+ Deterministic: same FamilyViewDTO → same DOT string.
113
+ """
114
+ lines: list[str] = []
115
+ lines.append(f'digraph "family_view_{view.structure_id}" {{')
116
+ lines.append(' graph [rankdir=LR fontname="monospace" label="Event Family View" pad="0.5" nodesep=0.6];')
117
+ lines.append(' node [fontname="monospace" fontsize=9 style=filled shape=box];')
118
+ lines.append(' edge [fontname="monospace" fontsize=8];')
119
+ lines.append("")
120
+
121
+ # Stage nodes (left column)
122
+ all_stages: set[str] = set()
123
+ for stats in view.stage_contributions.values():
124
+ for stat in stats:
125
+ all_stages.add(stat.stage)
126
+
127
+ lines.append(" // Stage nodes")
128
+ for stage in sorted(all_stages):
129
+ lines.append(f' s_{stage} [label="{stage}" fillcolor="#ffffff" shape=ellipse];')
130
+ lines.append("")
131
+
132
+ # Family nodes (right column)
133
+ lines.append(" // Family nodes")
134
+ for family in view.families:
135
+ count = view.event_count_by_family.get(family, 0)
136
+ ops = view.operations_by_family.get(family, [])
137
+ ops_label = "\\n".join(ops) if ops else "(none)"
138
+ fill = _FAMILY_FILL.get(family, _DEFAULT_FILL)
139
+ label = f"{family}\\n{count} events\\n{ops_label}"
140
+ lines.append(f' f_{family} [label="{label}" fillcolor="{fill}"];')
141
+ lines.append("")
142
+
143
+ # Stage → Family edges (dashed, labeled with count)
144
+ lines.append(" // Stage → Family contribution edges")
145
+ for family in view.families:
146
+ stats = view.stage_contributions.get(family, [])
147
+ for stat in stats:
148
+ lines.append(
149
+ f' s_{stat.stage} -> f_{family}'
150
+ f' [style=dashed label="{stat.count}" color="#555555"];'
151
+ )
152
+
153
+ lines.append("}")
154
+ return "\n".join(lines)
155
+
156
+
157
+ def write_family_view_png(view: FamilyViewDTO, output_path: Path) -> bool:
158
+ """
159
+ Render FamilyViewDTO → PNG using graphviz (dot command).
160
+
161
+ DOT is internal only — not written to disk.
162
+ Returns True if PNG was written, False if graphviz is unavailable.
163
+ """
164
+ return write_png_from_dot(render_family_view(view), output_path)
@@ -0,0 +1,150 @@
1
+ """
2
+ Materialization View — stage-by-stage artifact output as deterministic DOT (→ PNG).
3
+
4
+ ISOLATION INVARIANT: Only imports from visualization.consumers. No compiler internals.
5
+
6
+ What it shows:
7
+ - One node per compilation stage
8
+ - Artifact output listed per stage
9
+ - Stage sequence edges showing compilation order
10
+ - Projection provenance: which stages wrote how many artifacts
11
+
12
+ DTO:
13
+ MaterializationViewDTO — per-stage artifact write summary
14
+
15
+ Renderer:
16
+ render_materialization_view(view) → DOT string (internal only)
17
+ write_materialization_view_png(view, output_path) → writes PNG
18
+
19
+ The DOT output is deterministic: same MaterializationViewDTO → same DOT string.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+
27
+ from ..consumers.evidence_query import EvidenceQuery
28
+ from ..consumers.evidence_projection import EvidenceProjection, StageView
29
+ from ._png_writer import write_png_from_dot
30
+
31
+
32
+ @dataclass
33
+ class MaterializationViewDTO:
34
+ """
35
+ Per-stage artifact materialization summary.
36
+
37
+ Fields:
38
+ structure_id — identifier for the compiled structure
39
+ stage_views — {stage: StageView} in stage order
40
+ stage_order — stage names in first-seen order
41
+ total_artifacts — total count of artifact_written events across all stages
42
+ """
43
+ structure_id: str
44
+ stage_views: dict[str, StageView]
45
+ stage_order: list[str]
46
+ total_artifacts: int
47
+
48
+
49
+ def build_materialization_view(query: EvidenceQuery) -> MaterializationViewDTO:
50
+ """
51
+ Build a MaterializationViewDTO from an EvidenceQuery.
52
+
53
+ Only calls EvidenceQuery and EvidenceProjection methods.
54
+ No compiler imports, no inference beyond what the consumer layer provides.
55
+ """
56
+ projection = EvidenceProjection(query)
57
+ stage_views = projection.stage_summary()
58
+ stage_order = query.stages()
59
+
60
+ total_artifacts = sum(
61
+ len(sv.written_artifacts) for sv in stage_views.values()
62
+ )
63
+
64
+ return MaterializationViewDTO(
65
+ structure_id=query.structure_id,
66
+ stage_views=stage_views,
67
+ stage_order=stage_order,
68
+ total_artifacts=total_artifacts,
69
+ )
70
+
71
+
72
+ def render_materialization_view(view: MaterializationViewDTO) -> str:
73
+ """
74
+ Render a MaterializationViewDTO as a DOT string (internal representation only).
75
+
76
+ Stages are nodes in compilation order with artifact counts labeled.
77
+ Stage sequence edges (dashed) connect stages left-to-right.
78
+ Stage nodes are shaded darker when they write more artifacts.
79
+ Deterministic: same MaterializationViewDTO → same DOT string.
80
+ """
81
+ lines: list[str] = []
82
+ lines.append(f'digraph "materialization_view_{view.structure_id}" {{')
83
+ lines.append(' graph [rankdir=LR fontname="monospace" label="Materialization View" pad="0.5" nodesep=0.8];')
84
+ lines.append(' node [fontname="monospace" fontsize=9 style=filled shape=box];')
85
+ lines.append(' edge [fontname="monospace" fontsize=8 style=dashed color="#333333" penwidth=1.5];')
86
+ lines.append("")
87
+
88
+ # Compute max artifacts for relative shading
89
+ max_artifacts = max(
90
+ (len(sv.written_artifacts) for sv in view.stage_views.values()),
91
+ default=1,
92
+ ) or 1
93
+
94
+ lines.append(" // Stage nodes")
95
+ for stage in view.stage_order:
96
+ sv = view.stage_views.get(stage)
97
+ if sv is None:
98
+ continue
99
+
100
+ artifact_count = len(sv.written_artifacts)
101
+ event_count = sv.event_count
102
+
103
+ # Greyscale fill: more artifacts → darker (from #f0f0f0 to #808080)
104
+ shade = int(0xf0 - (artifact_count / max_artifacts) * 0x70)
105
+ fill_hex = f"#{shade:02x}{shade:02x}{shade:02x}"
106
+
107
+ # Build label: stage name + counts + top artifacts (up to 5)
108
+ artifact_lines = sv.written_artifacts[:5]
109
+ if len(sv.written_artifacts) > 5:
110
+ artifact_lines = artifact_lines + [f"... +{len(sv.written_artifacts) - 5} more"]
111
+
112
+ artifact_label = "\\n".join(
113
+ _shorten_path(p) for p in artifact_lines
114
+ ) if artifact_lines else "(no artifacts)"
115
+
116
+ label = (
117
+ f"{stage}\\n"
118
+ f"{event_count} events | {artifact_count} artifacts\\n"
119
+ f"{artifact_label}"
120
+ )
121
+ lines.append(f' s_{stage} [label="{label}" fillcolor="{fill_hex}"];')
122
+
123
+ lines.append("")
124
+
125
+ # Stage sequence edges (in stage_order order)
126
+ lines.append(" // Stage sequence edges")
127
+ for i in range(len(view.stage_order) - 1):
128
+ src = view.stage_order[i]
129
+ tgt = view.stage_order[i + 1]
130
+ lines.append(f" s_{src} -> s_{tgt};")
131
+
132
+ lines.append("}")
133
+ return "\n".join(lines)
134
+
135
+
136
+ def write_materialization_view_png(view: MaterializationViewDTO, output_path: Path) -> bool:
137
+ """
138
+ Render MaterializationViewDTO → PNG using graphviz (dot command).
139
+
140
+ DOT is internal only — not written to disk.
141
+ Returns True if PNG was written, False if graphviz is unavailable.
142
+ """
143
+ return write_png_from_dot(render_materialization_view(view), output_path)
144
+
145
+
146
+ def _shorten_path(path: str, max_len: int = 50) -> str:
147
+ """Shorten a path for display, keeping the filename visible."""
148
+ if len(path) <= max_len:
149
+ return path
150
+ return "..." + path[-(max_len - 3):]
@@ -0,0 +1,158 @@
1
+ """
2
+ Structural DAG view — compilation topology as a deterministic DOT graph (→ PNG).
3
+
4
+ ISOLATION INVARIANT: Only imports from visualization.consumers. No compiler internals.
5
+
6
+ What it shows:
7
+ - Stages as graph clusters (S1 through S7)
8
+ - Events as labeled nodes within their stage cluster
9
+ - CAUSALITY edges (solid) between events
10
+ - STAGE_SEQUENCE edges (dashed) between stage boundaries
11
+
12
+ DTO:
13
+ StructuralDAGView — all data needed to render the DAG
14
+
15
+ Renderer:
16
+ render_structural_dag(view) → DOT string (internal only)
17
+ write_structural_dag_png(view, output_path) → writes PNG
18
+
19
+ DOT is internal only — not written to disk.
20
+ The PNG output is deterministic: same evidence_graph.json → same PNG.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import dataclass, field
26
+ from pathlib import Path
27
+
28
+ from ..consumers.evidence_query import EvidenceQuery, TraceEventDTO, EvidenceEdgeDTO
29
+ from ._png_writer import write_png_from_dot
30
+
31
+
32
+ @dataclass
33
+ class StructuralDAGView:
34
+ """
35
+ All data needed to render the structural compilation DAG.
36
+
37
+ Fields:
38
+ structure_id — identifier for the compiled structure
39
+ stages — stage names in first-seen order
40
+ events_by_stage — {stage: [TraceEventDTO]} in emission order
41
+ causality_edges — all CAUSALITY EvidenceEdgeDTOs
42
+ sequence_edges — all STAGE_SEQUENCE EvidenceEdgeDTOs
43
+ """
44
+ structure_id: str
45
+ stages: list[str]
46
+ events_by_stage: dict[str, list[TraceEventDTO]] = field(default_factory=dict)
47
+ causality_edges: list[EvidenceEdgeDTO] = field(default_factory=list)
48
+ sequence_edges: list[EvidenceEdgeDTO] = field(default_factory=list)
49
+
50
+
51
+ def build_structural_dag_view(query: EvidenceQuery) -> StructuralDAGView:
52
+ """
53
+ Build a StructuralDAGView from an EvidenceQuery.
54
+
55
+ Only calls EvidenceQuery methods — no compiler imports, no inference.
56
+ """
57
+ stages = query.stages()
58
+
59
+ events_by_stage: dict[str, list[TraceEventDTO]] = {
60
+ stage: sorted(query.by_stage(stage), key=lambda e: e.event_id)
61
+ for stage in stages
62
+ }
63
+
64
+ causality_edges = query.edges_by_kind("CAUSALITY")
65
+ sequence_edges = query.edges_by_kind("STAGE_SEQUENCE")
66
+
67
+ return StructuralDAGView(
68
+ structure_id=query.structure_id,
69
+ stages=stages,
70
+ events_by_stage=events_by_stage,
71
+ causality_edges=causality_edges,
72
+ sequence_edges=sequence_edges,
73
+ )
74
+
75
+
76
+ # Family → fill color (monochrome-safe greyscale shades)
77
+ _FAMILY_COLORS: dict[str, str] = {
78
+ "DISCOVERY": "#f0f0f0",
79
+ "TOPOLOGY": "#e0e0e0",
80
+ "ADDRESSING": "#d0d0d0",
81
+ "GOVERNANCE": "#c0c0c0",
82
+ "CONSTRUCTION": "#b0b0b0",
83
+ "PROJECTION": "#a0a0a0",
84
+ "MATERIALIZATION": "#909090",
85
+ "VERIFICATION": "#808080",
86
+ }
87
+ _DEFAULT_COLOR = "#f8f8f8"
88
+
89
+
90
+ def render_structural_dag(view: StructuralDAGView) -> str:
91
+ """
92
+ Render a StructuralDAGView as a DOT string.
93
+
94
+ Output is deterministic: same StructuralDAGView → same DOT string.
95
+ Stages appear as subgraph clusters. Events are labeled by operation.
96
+ CAUSALITY edges are solid. STAGE_SEQUENCE edges are dashed.
97
+ """
98
+ lines: list[str] = []
99
+ lines.append(f'digraph "structural_dag_{view.structure_id}" {{')
100
+ lines.append(' graph [rankdir=TB fontname="monospace" label="" pad="0.5"];')
101
+ lines.append(' node [fontname="monospace" fontsize=9 shape=box style=filled];')
102
+ lines.append(' edge [fontname="monospace" fontsize=8];')
103
+ lines.append("")
104
+
105
+ # One subgraph cluster per stage
106
+ for idx, stage in enumerate(view.stages):
107
+ events = view.events_by_stage.get(stage, [])
108
+ lines.append(f" subgraph cluster_{idx} {{")
109
+ lines.append(f' label="{stage}";')
110
+ lines.append(' style=rounded;')
111
+ lines.append(' color="#444444";')
112
+ lines.append("")
113
+
114
+ for ev in events:
115
+ color = _FAMILY_COLORS.get(ev.family, _DEFAULT_COLOR)
116
+ label = f"{ev.operation}\\n(#{ev.event_id})"
117
+ if ev.subject_fqdn:
118
+ # Truncate long FQDNs to keep nodes readable
119
+ fqdn = ev.subject_fqdn
120
+ if len(fqdn) > 40:
121
+ fqdn = fqdn[:37] + "..."
122
+ label += f"\\n{fqdn}"
123
+ lines.append(
124
+ f' n{ev.event_id} [label="{label}" fillcolor="{color}"];'
125
+ )
126
+
127
+ lines.append(" }")
128
+ lines.append("")
129
+
130
+ # CAUSALITY edges — solid
131
+ lines.append(" // CAUSALITY edges")
132
+ for edge in sorted(view.causality_edges, key=lambda e: (e.source_event_id, e.target_event_id)):
133
+ lines.append(
134
+ f" n{edge.source_event_id} -> n{edge.target_event_id}"
135
+ ' [style=solid color="#333333" penwidth=1.2];'
136
+ )
137
+ lines.append("")
138
+
139
+ # STAGE_SEQUENCE edges — dashed, bold
140
+ lines.append(" // STAGE_SEQUENCE edges")
141
+ for edge in sorted(view.sequence_edges, key=lambda e: e.source_event_id):
142
+ lines.append(
143
+ f" n{edge.source_event_id} -> n{edge.target_event_id}"
144
+ ' [style=dashed color="#000000" penwidth=2.0 label="STAGE_SEQ"];'
145
+ )
146
+
147
+ lines.append("}")
148
+ return "\n".join(lines)
149
+
150
+
151
+ def write_structural_dag_png(view: StructuralDAGView, output_path: Path) -> bool:
152
+ """
153
+ Render StructuralDAGView → PNG using graphviz (dot command).
154
+
155
+ DOT is internal only — not written to disk.
156
+ Returns True if PNG was written, False if graphviz is unavailable.
157
+ """
158
+ return write_png_from_dot(render_structural_dag(view), output_path)