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,241 @@
1
+ """
2
+ ASSERT_CS_SURFACE_CLOSED_V0 Handler
3
+
4
+ Validates CS surface closure:
5
+ 1. All discovered CS are explicitly declared
6
+ 2. All declared CS have runtime implementations
7
+ 3. No excess declarations (declared but not discovered)
8
+ """
9
+
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+
14
+ def execute(artifacts: list[dict], compilation_context: dict) -> dict:
15
+ """
16
+ Verify CS surface is closed (declared == executable).
17
+
18
+ Args:
19
+ artifacts: All validated artifacts
20
+ compilation_context: Contains artifacts_by_fqdn, layer_resolver, assert_artifact
21
+
22
+ Returns:
23
+ {
24
+ "assert_count": int,
25
+ "violations": list[dict],
26
+ "status": "PASSED/FAILED"
27
+ }
28
+ """
29
+ violations = []
30
+
31
+ # Get layer category map from compilation context (STRUCTURE-driven)
32
+ layer_category_map = compilation_context.get("layer_category_map", {})
33
+
34
+ # Evaluate the rule FROM the artifact being asserted.
35
+ # The compiler is a generic evaluator: it reads the allowed surface and the
36
+ # scope from the current ASSERT artifact itself, never substituting another
37
+ # (e.g. platform) artifact. This keeps every surface-closure ASSERT
38
+ # authoritative — a domain ASSERT governs its own domain surface.
39
+ current_assert = compilation_context.get("current_assert_artifact")
40
+ if current_assert:
41
+ assert_fm = current_assert.get("frontmatter", {})
42
+ else:
43
+ # Defensive fallback: locate this handler's platform assert by code.
44
+ assert_fm = {}
45
+ for artifact in artifacts:
46
+ if artifact.get("frontmatter", {}).get("artifact_code") == "ASSERT_CS_SURFACE_CLOSED_V0":
47
+ assert_fm = artifact.get("frontmatter", {})
48
+ break
49
+
50
+ allowed_cs = set(assert_fm.get("allowed_capability_side_effects", []))
51
+ scope = set(assert_fm.get("scope", {}).get("applies_to", []))
52
+
53
+ def _in_scope(cs_artifact: dict) -> bool:
54
+ """A CS is governed by this ASSERT if its layer matches the ASSERT scope.
55
+
56
+ Domain scope (e.g. BLOCKCHAIN) matches the CS's layer_code directly.
57
+ PLATFORM scope matches any CS whose layer is a platform layer.
58
+ """
59
+ layer_code = cs_artifact.get("layer_code")
60
+ if layer_code in scope:
61
+ return True
62
+ if "PLATFORM" in scope and layer_category_map.get(layer_code) == "platform":
63
+ return True
64
+ return False
65
+
66
+ # Extract all discovered CS artifacts
67
+ # Note: CS artifacts may have artifact_kind="capability_side_effect" OR cs_code field
68
+ discovered_cs = set()
69
+ cs_artifacts = []
70
+
71
+ for artifact in artifacts:
72
+ frontmatter = artifact.get("frontmatter", {})
73
+
74
+ # CS identification by canonical artifact_kind (Kind Vocabulary) — the sole discriminator.
75
+ is_cs = frontmatter.get("artifact_kind") == "CAPABILITY_SIDE_EFFECT"
76
+
77
+ if is_cs:
78
+ fqdn = artifact["fqdn_id"]
79
+ discovered_cs.add(fqdn)
80
+ cs_artifacts.append(artifact)
81
+
82
+ # CHECK 1: No Undeclared CS (within this ASSERT's scope)
83
+ # Every discovered CS governed by this ASSERT must be explicitly declared in
84
+ # its allowed list. There is no intrinsic-by-existence exemption: closure is
85
+ # enforced from the artifact, for platform and domain surfaces alike.
86
+ assert_code = assert_fm.get("artifact_code", "the ASSERT artifact")
87
+ for cs_artifact in cs_artifacts:
88
+ if not _in_scope(cs_artifact):
89
+ continue
90
+ cs_fqdn = cs_artifact["fqdn_id"]
91
+ if cs_fqdn not in allowed_cs:
92
+ violations.append({
93
+ "fqdn": cs_fqdn,
94
+ "rule": "capability_side_effects::INVARIANT_CS_SURFACE_CLOSED_V1",
95
+ "message": "Undeclared CS (exists in registry but not in allowed_capability_side_effects)",
96
+ "fix": f"Add '{cs_fqdn}' to allowed_capability_side_effects in {assert_code}"
97
+ })
98
+
99
+ # CHECK 2: No Excess Declarations
100
+ # Every declared CS must be discovered. Skipped only for a PLATFORM-scoped
101
+ # ASSERT during a domain build, where platform CS are legitimately absent.
102
+ is_domain_build = compilation_context.get("is_domain_build", False)
103
+ skip_excess = is_domain_build and "PLATFORM" in scope
104
+
105
+ if not skip_excess:
106
+ for allowed_fqdn in allowed_cs:
107
+ if allowed_fqdn not in discovered_cs:
108
+ violations.append({
109
+ "fqdn": allowed_fqdn,
110
+ "rule": "capability_side_effects::INVARIANT_CS_SURFACE_CLOSED_V1",
111
+ "message": "Declared CS not found (in allowed list but not discovered in registry)",
112
+ "fix": f"Remove '{allowed_fqdn}' from allowed_capability_side_effects (CS no longer exists)"
113
+ })
114
+
115
+ # CHECK 3: No Missing Implementations
116
+ # All discovered CS must have runtime implementation (either RB binding or runtime.py)
117
+
118
+ # Extract all CS bindings from RB artifacts
119
+ rb_bound_cs = _extract_rb_bindings(artifacts)
120
+
121
+ for artifact in cs_artifacts:
122
+ if not _in_scope(artifact):
123
+ continue
124
+ fqdn = artifact["fqdn_id"]
125
+ # The CS code (identity) is carried by the artifact, not by a legacy cs_code machine-block
126
+ # field; it equals the artifact_code. Used only for RB-binding / runtime resolution below.
127
+ cs_code = artifact.get("artifact_code")
128
+
129
+ # Check if CS is bound in an RB artifact (domain CS pattern)
130
+ if cs_code in rb_bound_cs:
131
+ # CS is bound in RB - valid (no need to check runtime.py)
132
+ continue
133
+
134
+ # Check if runtime implementation exists (platform CS pattern)
135
+ runtime_exists, runtime_path = _check_runtime_exists(cs_code)
136
+
137
+ if not runtime_exists:
138
+ violations.append({
139
+ "fqdn": fqdn,
140
+ "rule": "capability_side_effects::INVARIANT_CS_SURFACE_CLOSED_V1",
141
+ "message": f"Missing runtime implementation (not bound in RB and no runtime.py at {runtime_path})",
142
+ "fix": f"Either: (1) Bind CS in RB artifact, OR (2) Implement runtime.py at {runtime_path}"
143
+ })
144
+
145
+ # Return result
146
+ if violations:
147
+ # Add debug info about discovered CS
148
+ debug_info = {
149
+ "discovered_cs_count": len(discovered_cs),
150
+ "discovered_cs_fqdns": sorted(list(discovered_cs)),
151
+ "allowed_cs_count": len(allowed_cs),
152
+ "allowed_cs_fqdns": sorted(list(allowed_cs)),
153
+ "rb_bound_cs_count": len(rb_bound_cs),
154
+ "violation_breakdown": {}
155
+ }
156
+
157
+ # Breakdown violations by type
158
+ for v in violations:
159
+ violation_type = v["message"].split("(")[0].strip()
160
+ debug_info["violation_breakdown"].setdefault(violation_type, 0)
161
+ debug_info["violation_breakdown"][violation_type] += 1
162
+
163
+ return {
164
+ "assert_count": len(cs_artifacts),
165
+ "violations": violations,
166
+ "status": "FAILED",
167
+ "debug": debug_info
168
+ }
169
+
170
+ return {
171
+ "assert_count": len(cs_artifacts),
172
+ "violations": [],
173
+ "status": "PASSED"
174
+ }
175
+
176
+
177
+ def _extract_rb_bindings(artifacts: list[dict]) -> set[str]:
178
+ """
179
+ Extract all CS bindings from RB artifacts.
180
+
181
+ Returns:
182
+ Set of CS codes that are bound in RB artifacts
183
+ """
184
+ rb_bound_cs = set()
185
+
186
+ for artifact in artifacts:
187
+ # Check if this is an RB artifact
188
+ # Use artifact_type (normalized) instead of artifact_kind
189
+ artifact_type = artifact.get("artifact_type")
190
+
191
+ if artifact_type != "RB":
192
+ continue
193
+
194
+ # Extract bindings from RB artifact
195
+ frontmatter = artifact.get("frontmatter", {})
196
+ core = frontmatter.get("core", {})
197
+ bindings = core.get("bindings", {})
198
+
199
+ # Add all bound CS codes
200
+ # CS artifacts are identified by FQDN or code pattern: namespace::CS_*_V0 or CS_*_V0
201
+ for bound_key in bindings.keys():
202
+ if not isinstance(bound_key, str):
203
+ continue
204
+
205
+ # Extract CS code from FQDN (namespace::CS_X_V0 -> CS_X_V0)
206
+ if "::" in bound_key:
207
+ # FQDN format - extract the code part
208
+ cs_code_part = bound_key.split("::")[-1]
209
+ if cs_code_part.startswith("CS_"):
210
+ rb_bound_cs.add(cs_code_part)
211
+ elif bound_key.startswith("CS_"):
212
+ # Short code format
213
+ rb_bound_cs.add(bound_key)
214
+
215
+ return rb_bound_cs
216
+
217
+
218
+ def _get_side_effects_implementation_root() -> Path:
219
+ """
220
+ Get side effects implementation root using LayerResolver (STRUCTURE_DISCOVERY_V0).
221
+
222
+ REUSABLE_SIDE_EFFECTS registry_module resolves to pgs_side_effects/registry/.
223
+ Implementation lives at the sibling path: pgs_side_effects/implementation/side_effects/.
224
+ """
225
+ from compiler.governance_engine.platform_root import cs_implementation_root
226
+ return cs_implementation_root()
227
+
228
+
229
+ def _check_runtime_exists(cs_code: str) -> tuple[bool, Path]:
230
+ """
231
+ Check if runtime implementation exists for CS.
232
+
233
+ Expected pattern:
234
+ CS_X_V0 → pgs_side_effects/implementation/side_effects/{persistent,internal,external}/CS_X_V0/runtime.py
235
+
236
+ Returns:
237
+ (exists: bool, expected_path: Path)
238
+ """
239
+ # PGC flat layout: capability_side_effects/implementation/CS_X/runtime.py
240
+ runtime_path = _get_side_effects_implementation_root() / cs_code / "runtime.py"
241
+ return runtime_path.exists(), runtime_path
@@ -0,0 +1,35 @@
1
+ """
2
+ ASSERT_CS_TRACEABLE_V0 Handler
3
+
4
+ Parity stub for INVARIANT_CS_TRACEABLE_V0.
5
+
6
+ CS traceability (every CS execution recorded in the execution trace) is enforced at
7
+ runtime by the execution engine. Compile-time static analysis cannot verify executor
8
+ behavior. This handler exists to satisfy 1:1 INVARIANT/ASSERT parity.
9
+
10
+ CONSTITUTIONAL: Pure rule checker — no side effects
11
+ """
12
+
13
+
14
+ def execute(artifacts: list[dict], compilation_context: dict) -> dict:
15
+ """
16
+ Parity stub — enforcement delegated to runtime execution engine.
17
+
18
+ Args:
19
+ artifacts: All validated artifacts
20
+ compilation_context: Compilation context (unused)
21
+
22
+ Returns:
23
+ {
24
+ "assert_count": int,
25
+ "violations": list[dict],
26
+ "status": "PASSED"
27
+ }
28
+ """
29
+ cs_count = sum(1 for a in artifacts if a.get("artifact_type") == "CS")
30
+
31
+ return {
32
+ "assert_count": cs_count,
33
+ "violations": [],
34
+ "status": "PASSED",
35
+ }
@@ -0,0 +1,167 @@
1
+ """
2
+ ASSERT_CT_OUTPUT_CONTRACT_MATCH_V0 Handler
3
+
4
+ Validates CT output keys match CC contract declarations.
5
+ """
6
+
7
+ import ast
8
+ import re
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from compiler.governance_engine.structure.resolution.layer_resolver import LayerResolver
13
+ from compiler.governance_engine.structure.resolution.path_registry import bootstrap
14
+
15
+
16
+ def execute(artifacts: list[dict], compilation_context: dict) -> dict:
17
+ """
18
+ Verify CT outputs match CC contracts.
19
+
20
+ Args:
21
+ artifacts: All validated artifacts
22
+ compilation_context: Contains artifacts_by_fqdn mapping
23
+
24
+ Returns:
25
+ {
26
+ "assert_count": int,
27
+ "violations": list[dict]
28
+ }
29
+ """
30
+ violations = []
31
+ artifacts_by_fqdn = compilation_context["artifacts_by_fqdn"]
32
+
33
+ # Filter to CT artifacts only
34
+ ct_artifacts = [
35
+ a for a in artifacts
36
+ if a.get("frontmatter", {}).get("artifact_kind") == "CT"
37
+ ]
38
+
39
+ for ct_artifact in ct_artifacts:
40
+ fqdn = ct_artifact["fqdn_id"]
41
+ frontmatter = ct_artifact.get("frontmatter", {})
42
+ governed_by_list = frontmatter.get("governed_by", [])
43
+
44
+ # CT must have governed_by
45
+ if not governed_by_list:
46
+ violations.append({
47
+ "fqdn": fqdn,
48
+ "rule": "capability_transforms::INVARIANT_CT_OUTPUT_CONTRACT_MATCH_V0",
49
+ "message": "CT artifact missing governed_by field",
50
+ "fix": "Add governed_by field specifying the governing CC FQDN"
51
+ })
52
+ continue
53
+
54
+ # Extract CC FQDN (first governed_by)
55
+ cc_fqdn = governed_by_list[0]
56
+ if cc_fqdn not in artifacts_by_fqdn:
57
+ violations.append({
58
+ "fqdn": fqdn,
59
+ "rule": "capability_transforms::INVARIANT_CT_OUTPUT_CONTRACT_MATCH_V0",
60
+ "message": f"Governing CC artifact not found in compilation graph: {cc_fqdn}",
61
+ "fix": f"Ensure CC artifact '{cc_fqdn}' exists and is included in build"
62
+ })
63
+ continue
64
+
65
+ # Load CC artifact
66
+ cc_artifact = artifacts_by_fqdn[cc_fqdn]
67
+ cc_frontmatter = cc_artifact.get("frontmatter", {})
68
+ cc_output = cc_frontmatter.get("output", {})
69
+
70
+ if not cc_output:
71
+ # CC has no output declaration - skip check
72
+ continue
73
+
74
+ # Expected output keys from CC
75
+ expected_keys = set(cc_output.keys())
76
+
77
+ # Find CT implementation file
78
+ artifact_code = frontmatter.get("artifact_code")
79
+ ct_impl_path = _find_ct_implementation(artifact_code)
80
+
81
+ if not ct_impl_path or not ct_impl_path.exists():
82
+ violations.append({
83
+ "fqdn": fqdn,
84
+ "rule": "capability_transforms::INVARIANT_CT_OUTPUT_CONTRACT_MATCH_V0",
85
+ "message": f"CT implementation file not found for {artifact_code}",
86
+ "fix": f"Create implementation file for CT '{artifact_code}' in transforms layer atoms/ or molecules/"
87
+ })
88
+ continue
89
+
90
+ # Parse return keys from implementation
91
+ actual_keys = _extract_return_keys(ct_impl_path)
92
+
93
+ if actual_keys is None:
94
+ violations.append({
95
+ "fqdn": fqdn,
96
+ "rule": "capability_transforms::INVARIANT_CT_OUTPUT_CONTRACT_MATCH_V0",
97
+ "message": f"No return statement found in CT implementation {ct_impl_path.name}",
98
+ "fix": "Add return statement with dict output in execute() function"
99
+ })
100
+ continue
101
+
102
+ # Check for mismatch
103
+ missing_keys = expected_keys - actual_keys
104
+ extra_keys = actual_keys - expected_keys
105
+
106
+ if missing_keys or extra_keys:
107
+ msg_parts = []
108
+ if missing_keys:
109
+ msg_parts.append(f"missing keys: {sorted(missing_keys)}")
110
+ if extra_keys:
111
+ msg_parts.append(f"extra keys: {sorted(extra_keys)}")
112
+
113
+ violations.append({
114
+ "fqdn": fqdn,
115
+ "rule": "capability_transforms::INVARIANT_CT_OUTPUT_CONTRACT_MATCH_V0",
116
+ "message": f"CT output doesn't match CC contract ({', '.join(msg_parts)})",
117
+ "fix": f"Update CT implementation to return exact keys from CC '{cc_fqdn}' output contract: {sorted(expected_keys)}"
118
+ })
119
+
120
+ if violations:
121
+ return {
122
+ "assert_count": len(ct_artifacts),
123
+ "violations": violations,
124
+ "status": "FAILED"
125
+ }
126
+
127
+ return {
128
+ "assert_count": len(ct_artifacts),
129
+ "violations": [],
130
+ "status": "PASSED"
131
+ }
132
+
133
+
134
+ def _find_ct_implementation(artifact_code: str) -> Path | None:
135
+ """Find CT implementation file (flat PGC layout: capability_transforms/implementation/ct_x.py)."""
136
+ from compiler.governance_engine.platform_root import ct_implementation_root
137
+ impl_path = ct_implementation_root() / f"{artifact_code.lower()}.py"
138
+ return impl_path if impl_path.exists() else None
139
+
140
+
141
+ def _extract_return_keys(impl_path: Path) -> set[str] | None:
142
+ """Extract keys from return dict in execute() function."""
143
+ try:
144
+ source = impl_path.read_text(encoding="utf-8")
145
+ tree = ast.parse(source)
146
+
147
+ # Find execute() function
148
+ for node in ast.walk(tree):
149
+ if isinstance(node, ast.FunctionDef) and node.name == "execute":
150
+ # Find all return statements
151
+ return_keys = set()
152
+
153
+ for sub_node in ast.walk(node):
154
+ if isinstance(sub_node, ast.Return) and sub_node.value:
155
+ # Return value should be dict
156
+ if isinstance(sub_node.value, ast.Dict):
157
+ for key in sub_node.value.keys:
158
+ if isinstance(key, ast.Constant):
159
+ return_keys.add(key.value)
160
+
161
+ if return_keys:
162
+ return return_keys
163
+
164
+ return None
165
+
166
+ except Exception:
167
+ return None
@@ -0,0 +1,173 @@
1
+ """
2
+ ASSERT_CT_SURFACE_CLOSED_V0 Handler
3
+
4
+ Validates CT surface closure:
5
+ 1. All discovered CT are explicitly declared
6
+ 2. All declared CT have runtime implementations
7
+ 3. No excess declarations (declared but not discovered)
8
+ """
9
+
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ # Import LayerResolver for runtime path resolution
14
+ try:
15
+ from compiler.governance_engine.structure.resolution.layer_resolver import LayerResolver
16
+ LAYER_RESOLVER_AVAILABLE = True
17
+ except ImportError:
18
+ LAYER_RESOLVER_AVAILABLE = False
19
+
20
+
21
+ def execute(artifacts: list[dict], compilation_context: dict) -> dict:
22
+ """
23
+ Verify CT surface is closed (declared == executable).
24
+
25
+ Args:
26
+ artifacts: All validated artifacts
27
+ compilation_context: Contains artifacts_by_fqdn, layer_resolver, assert_artifact
28
+
29
+ Returns:
30
+ {
31
+ "assert_count": int,
32
+ "violations": list[dict],
33
+ "status": "PASSED/FAILED"
34
+ }
35
+ """
36
+ violations = []
37
+
38
+ # Get layer category map from compilation context (STRUCTURE-driven)
39
+ layer_category_map = compilation_context.get("layer_category_map", {})
40
+
41
+ # Evaluate the rule FROM the artifact being asserted.
42
+ # The compiler is a generic evaluator: it reads the allowed surface and the
43
+ # scope from the current ASSERT artifact itself, never substituting another
44
+ # (e.g. platform) artifact. This keeps every surface-closure ASSERT
45
+ # authoritative — a domain ASSERT governs its own domain surface.
46
+ current_assert = compilation_context.get("current_assert_artifact")
47
+ if current_assert:
48
+ assert_fm = current_assert.get("frontmatter", {})
49
+ else:
50
+ # Defensive fallback: locate this handler's platform assert by code.
51
+ assert_fm = {}
52
+ for artifact in artifacts:
53
+ if artifact.get("frontmatter", {}).get("artifact_code") == "ASSERT_CT_SURFACE_CLOSED_V0":
54
+ assert_fm = artifact.get("frontmatter", {})
55
+ break
56
+
57
+ allowed_ct = set(assert_fm.get("allowed_capability_transforms", []))
58
+ scope = set(assert_fm.get("scope", {}).get("applies_to", []))
59
+
60
+ def _in_scope(ct_artifact: dict) -> bool:
61
+ """A CT is governed by this ASSERT if its layer matches the ASSERT scope.
62
+
63
+ Domain scope (e.g. BLOCKCHAIN) matches the CT's layer_code directly.
64
+ PLATFORM scope matches any CT whose layer is a platform layer.
65
+ """
66
+ layer_code = ct_artifact.get("layer_code")
67
+ if layer_code in scope:
68
+ return True
69
+ if "PLATFORM" in scope and layer_category_map.get(layer_code) == "platform":
70
+ return True
71
+ return False
72
+
73
+ # Extract all discovered CT artifacts
74
+ # Note: CT artifacts may have artifact_kind="atom"/"molecule" OR artifact_code field
75
+ discovered_ct = set()
76
+ ct_artifacts = []
77
+
78
+ for artifact in artifacts:
79
+ frontmatter = artifact.get("frontmatter", {})
80
+
81
+ # CT identification by canonical artifact_kind (Kind Vocabulary) — the sole discriminator.
82
+ is_ct = frontmatter.get("artifact_kind") == "CAPABILITY_TRANSFORM"
83
+
84
+ if is_ct:
85
+ fqdn = artifact["fqdn_id"]
86
+ discovered_ct.add(fqdn)
87
+ ct_artifacts.append(artifact)
88
+
89
+ # CHECK 1: No Undeclared CT (within this ASSERT's scope)
90
+ # Every discovered CT governed by this ASSERT must be explicitly declared in
91
+ # its allowed list. There is no intrinsic-by-existence exemption: closure is
92
+ # enforced from the artifact, for platform and domain surfaces alike.
93
+ assert_code = assert_fm.get("artifact_code", "the ASSERT artifact")
94
+ for ct_artifact in ct_artifacts:
95
+ if not _in_scope(ct_artifact):
96
+ continue
97
+ ct_fqdn = ct_artifact["fqdn_id"]
98
+ if ct_fqdn not in allowed_ct:
99
+ violations.append({
100
+ "fqdn": ct_fqdn,
101
+ "rule": "capability_transforms::INVARIANT_CT_SURFACE_CLOSED_V1",
102
+ "message": "Undeclared CT (exists in registry but not in allowed_capability_transforms)",
103
+ "fix": f"Add '{ct_fqdn}' to allowed_capability_transforms in {assert_code}"
104
+ })
105
+
106
+ # CHECK 2: No Excess Declarations
107
+ # Every declared CT must be discovered. Skipped only for a PLATFORM-scoped
108
+ # ASSERT during a domain build, where platform CT are legitimately absent.
109
+ is_domain_build = compilation_context.get("is_domain_build", False)
110
+ skip_excess = is_domain_build and "PLATFORM" in scope
111
+
112
+ if not skip_excess:
113
+ for allowed_fqdn in allowed_ct:
114
+ if allowed_fqdn not in discovered_ct:
115
+ violations.append({
116
+ "fqdn": allowed_fqdn,
117
+ "rule": "capability_transforms::INVARIANT_CT_SURFACE_CLOSED_V1",
118
+ "message": "Declared CT not found (in allowed list but not discovered in registry)",
119
+ "fix": f"Remove '{allowed_fqdn}' from allowed_capability_transforms (CT no longer exists)"
120
+ })
121
+
122
+ # CHECK 3: No Missing Implementations
123
+ # CT resolution is intrinsic (registry + code import)
124
+ # If CT was discovered, it exists in registry → valid
125
+ # No need to check for runtime.py files
126
+ # (CT are resolved via direct code import, not RB bindings)
127
+
128
+ # (Legacy artifact_code presence validation retired: identity is carried by fqdn and the kind by
129
+ # artifact_kind (Kind Vocabulary); artifact_code is no longer a machine-block field.)
130
+
131
+ # Return result
132
+ if violations:
133
+ # Add debug info about discovered CT
134
+ debug_info = {
135
+ "discovered_ct_count": len(discovered_ct),
136
+ "discovered_ct_fqdns": sorted(list(discovered_ct)),
137
+ "allowed_ct_count": len(allowed_ct),
138
+ "allowed_ct_fqdns": sorted(list(allowed_ct))
139
+ }
140
+
141
+ return {
142
+ "assert_count": len(ct_artifacts),
143
+ "violations": violations,
144
+ "status": "FAILED",
145
+ "debug": debug_info
146
+ }
147
+
148
+ return {
149
+ "assert_count": len(ct_artifacts),
150
+ "violations": [],
151
+ "status": "PASSED"
152
+ }
153
+
154
+
155
+ def _check_runtime_exists(artifact_code: str, layer_resolver) -> tuple[bool, Path]:
156
+ """
157
+ Check if runtime implementation exists for CT.
158
+
159
+ Expected pattern:
160
+ CT_X_V0 → pgs_transforms/implementation/transforms/{atoms,molecules}/ct_x_v0.py
161
+
162
+ Returns:
163
+ (exists: bool, expected_path: Path)
164
+ """
165
+ try:
166
+ # PGC flat layout: capability_transforms/implementation/ct_x.py
167
+ from compiler.governance_engine.platform_root import ct_implementation_root
168
+ runtime_path = ct_implementation_root() / f"{artifact_code.lower()}.py"
169
+ return runtime_path.exists(), runtime_path
170
+
171
+ except Exception as e:
172
+ # If layer resolution fails, assume missing
173
+ return False, Path(f"<layer_resolution_failed: {e}>")