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,537 @@
1
+ """
2
+ S5 CONSTRUCT — Build intermediate representations on graph nodes.
3
+
4
+ Input: State from S4 (governed graph)
5
+ Output: State with IR populated on CT, CS, and CC nodes
6
+
7
+ Builds:
8
+ - CT nodes: ct_ir (atom_stream, inputs, outputs, handler_refs)
9
+ - CS nodes: cs_ir (handler_ref, operations metadata)
10
+ - CC nodes: cc_projection (pipeline step signatures)
11
+ - WF nodes: enriched node fqdn_ids
12
+ """
13
+
14
+ from typing import Any
15
+
16
+ from compiler.graph.types import NodeKind
17
+ from compiler.graph.node import Node
18
+ from compiler.graph.graph import Graph, GraphBuilder
19
+ from compiler.graph.hashing import compute_topology_hash
20
+ from compiler.graph.state import State
21
+ from compiler.graph.trace import TraceEvent
22
+ from compiler.graph.evidence import EventFamily
23
+ from compiler.atoms.errors import CompilerError
24
+ from compiler.atoms.error_codes import ErrorCode
25
+
26
+ from types import MappingProxyType
27
+
28
+
29
+ def s5_construct(state: State) -> State:
30
+ """
31
+ S5 CONSTRUCT: Build IR on CT, CS, CC, and WF nodes.
32
+
33
+ Pure function: State → State.
34
+ """
35
+ state = state.with_stage("S5_CONSTRUCT")
36
+ errors: list[CompilerError] = []
37
+ trace: list[TraceEvent] = []
38
+ graph = state.graph
39
+
40
+ builder = GraphBuilder.from_graph(graph)
41
+
42
+ # Build indices for cross-node lookups
43
+ ct_index: dict[str, Node] = {} # artifact_code → node
44
+ cs_index: dict[str, Node] = {}
45
+ code_to_fqdn: dict[str, str] = {}
46
+
47
+ for node in graph.nodes.values():
48
+ code_to_fqdn[node.artifact_code] = node.fqdn
49
+ if node.kind == NodeKind.CT:
50
+ ct_index[node.artifact_code] = node
51
+ elif node.kind == NodeKind.CS:
52
+ cs_index[node.artifact_code] = node
53
+
54
+ # --- Build CT-IR ---
55
+ for fqdn, node in graph.nodes.items():
56
+ if node.kind != NodeKind.CT:
57
+ continue
58
+
59
+ ct_ir, ct_errors = _build_ct_ir(node, ct_index)
60
+ errors.extend(ct_errors)
61
+
62
+ if ct_ir is not None:
63
+ builder.replace_node(fqdn, ir=MappingProxyType(ct_ir))
64
+ trace.append(TraceEvent.create(
65
+ stage="S5_CONSTRUCT",
66
+ operation="ct_ir_built",
67
+ subject_fqdn=fqdn,
68
+ detail={"atom_stream_length": len(ct_ir.get("atom_stream", []))},
69
+ family=EventFamily.CONSTRUCTION.value,
70
+ ))
71
+
72
+ # --- Build CS-IR ---
73
+ for fqdn, node in graph.nodes.items():
74
+ if node.kind != NodeKind.CS:
75
+ continue
76
+
77
+ cs_ir, cs_errors = _build_cs_ir(node)
78
+ errors.extend(cs_errors)
79
+
80
+ if cs_ir is not None:
81
+ builder.replace_node(fqdn, ir=MappingProxyType(cs_ir))
82
+ trace.append(TraceEvent.create(
83
+ stage="S5_CONSTRUCT",
84
+ operation="cs_ir_built",
85
+ subject_fqdn=fqdn,
86
+ family=EventFamily.CONSTRUCTION.value,
87
+ ))
88
+
89
+ # --- Build CC projection ---
90
+ for fqdn, node in graph.nodes.items():
91
+ if node.kind != NodeKind.CC:
92
+ continue
93
+
94
+ cc_proj, cc_errors = _build_cc_projection(node, ct_index, cs_index)
95
+ errors.extend(cc_errors)
96
+
97
+ if cc_proj is not None:
98
+ builder.replace_node(fqdn, ir=MappingProxyType(cc_proj))
99
+ trace.append(TraceEvent.create(
100
+ stage="S5_CONSTRUCT",
101
+ operation="cc_projection_built",
102
+ subject_fqdn=fqdn,
103
+ detail={"pipeline_steps": len(cc_proj.get("cc_projection", {}).get("steps", []))},
104
+ family=EventFamily.CONSTRUCTION.value,
105
+ ))
106
+
107
+ # --- Enrich WF nodes ---
108
+ for fqdn, node in graph.nodes.items():
109
+ if node.kind != NodeKind.WF:
110
+ continue
111
+
112
+ wf_errors = _enrich_wf_nodes(node, code_to_fqdn, builder)
113
+ errors.extend(wf_errors)
114
+
115
+ if errors:
116
+ state = state.with_errors(*errors)
117
+
118
+ # Topology hash is computed here, where the graph is final: S5 is the last stage that
119
+ # adds nodes or edges, and the hash covers node identity + typed edges (not addresses,
120
+ # which are already sealed by S3's address_hash).
121
+ builder.set_topology_hash(compute_topology_hash(builder.build()))
122
+ new_graph = builder.build() # rebuilt so the graph carries the hash just set
123
+ state = state.with_graph(new_graph)
124
+
125
+ ir_count = sum(1 for n in new_graph.nodes.values() if n.ir is not None)
126
+ state = state.with_metadata("ir_count", ir_count)
127
+ state = state.with_metadata("topology_hash", new_graph.topology_hash)
128
+
129
+ trace.append(TraceEvent.create(
130
+ stage="S5_CONSTRUCT",
131
+ operation="construction_complete",
132
+ detail={"ir_count": ir_count},
133
+ family=EventFamily.CONSTRUCTION.value,
134
+ ))
135
+ if trace:
136
+ state = state.with_trace_events(*trace)
137
+
138
+ return state
139
+
140
+
141
+ def _build_ct_ir(
142
+ node: Node, ct_index: dict[str, Node],
143
+ ) -> tuple[dict[str, Any] | None, list[CompilerError]]:
144
+ """Build CT-IR for a CT node."""
145
+ errors: list[CompilerError] = []
146
+ machine = node.frontmatter.get("machine", {})
147
+ core = node.frontmatter.get("core", {})
148
+
149
+ if not isinstance(machine, dict):
150
+ return None, errors
151
+
152
+ ct_kind = machine.get("ct_kind")
153
+ if not ct_kind:
154
+ errors.append(CompilerError(
155
+ code=ErrorCode.E205_CT_VALIDATION_FAILED,
156
+ message="CT missing ct_kind in machine section",
157
+ phase="S5_CONSTRUCT",
158
+ fqdn_id=node.fqdn,
159
+ ))
160
+ return None, errors
161
+
162
+ atom_stream: list[dict] = []
163
+ ct_ir_outputs: dict[str, Any] = {}
164
+
165
+ if ct_kind == "atom":
166
+ implementation = machine.get("implementation", {})
167
+ if not implementation:
168
+ errors.append(CompilerError(
169
+ code=ErrorCode.E205_CT_VALIDATION_FAILED,
170
+ message="Atom CT missing implementation",
171
+ phase="S5_CONSTRUCT",
172
+ fqdn_id=node.fqdn,
173
+ ))
174
+ return None, errors
175
+
176
+ impl_module = implementation.get("module", "")
177
+ impl_callable = implementation.get("callable", "")
178
+ if not impl_module or not impl_callable:
179
+ errors.append(CompilerError(
180
+ code=ErrorCode.E205_CT_VALIDATION_FAILED,
181
+ message="Atom CT implementation missing module or callable",
182
+ phase="S5_CONSTRUCT",
183
+ fqdn_id=node.fqdn,
184
+ ))
185
+ return None, errors
186
+
187
+ result_symbol = "__atom_result__"
188
+ atom_stream = [{
189
+ "atom": node.fqdn,
190
+ "handler_ref": {
191
+ "module": impl_module,
192
+ "callable": impl_callable,
193
+ },
194
+ "out": result_symbol,
195
+ "args": {
196
+ key: f"$.inputs.{key}"
197
+ for key in (core.get("inputs", {}) if isinstance(core, dict) else {}).keys()
198
+ },
199
+ }]
200
+
201
+ core_outputs = core.get("outputs", {}) if isinstance(core, dict) else {}
202
+ for output_name in core_outputs.keys():
203
+ ct_ir_outputs[output_name] = {"from": result_symbol}
204
+
205
+ elif ct_kind == "molecule":
206
+ steps = machine.get("steps", [])
207
+ if not steps:
208
+ errors.append(CompilerError(
209
+ code=ErrorCode.E205_CT_VALIDATION_FAILED,
210
+ message="Molecule CT missing steps",
211
+ phase="S5_CONSTRUCT",
212
+ fqdn_id=node.fqdn,
213
+ ))
214
+ return None, errors
215
+
216
+ for step in steps:
217
+ step_kind = step.get("kind")
218
+
219
+ if step_kind == "atom":
220
+ atom_code = step.get("atom")
221
+ atom_node = ct_index.get(atom_code)
222
+ if not atom_node:
223
+ errors.append(CompilerError(
224
+ code=ErrorCode.E201_MISSING_REFERENCE,
225
+ message=f"Unresolved atom reference: {atom_code}",
226
+ phase="S5_CONSTRUCT",
227
+ fqdn_id=node.fqdn,
228
+ ))
229
+ continue
230
+
231
+ atom_machine = atom_node.frontmatter.get("machine", {})
232
+ atom_impl = atom_machine.get("implementation", {}) if isinstance(atom_machine, dict) else {}
233
+ atom_core = atom_node.frontmatter.get("core", {})
234
+
235
+ if not atom_impl.get("module") or not atom_impl.get("callable"):
236
+ errors.append(CompilerError(
237
+ code=ErrorCode.E205_CT_VALIDATION_FAILED,
238
+ message=f"Atom '{atom_code}' has no implementation — cannot embed handler_ref",
239
+ phase="S5_CONSTRUCT",
240
+ fqdn_id=node.fqdn,
241
+ ))
242
+ continue
243
+
244
+ transformed = {
245
+ "atom": atom_node.fqdn,
246
+ "out": step.get("as"),
247
+ "args": step.get("with", {}),
248
+ "handler_ref": {
249
+ "module": atom_impl["module"],
250
+ "callable": atom_impl["callable"],
251
+ },
252
+ "input_types": _extract_input_types(
253
+ atom_core.get("inputs", {}) if isinstance(atom_core, dict) else {}
254
+ ),
255
+ }
256
+ atom_stream.append(transformed)
257
+
258
+ elif step_kind == "molecule":
259
+ mol_code = step.get("molecule")
260
+ mol_node = ct_index.get(mol_code)
261
+ if not mol_node:
262
+ errors.append(CompilerError(
263
+ code=ErrorCode.E201_MISSING_REFERENCE,
264
+ message=f"Unresolved molecule reference: {mol_code}",
265
+ phase="S5_CONSTRUCT",
266
+ fqdn_id=node.fqdn,
267
+ ))
268
+ continue
269
+
270
+ mol_core = mol_node.frontmatter.get("core", {})
271
+ transformed = {
272
+ "atom": mol_node.fqdn,
273
+ "out": step.get("as"),
274
+ "args": step.get("with", {}),
275
+ "input_types": _extract_input_types(
276
+ mol_core.get("inputs", {}) if isinstance(mol_core, dict) else {}
277
+ ),
278
+ }
279
+ atom_stream.append(transformed)
280
+
281
+ elif step_kind == "loop":
282
+ mol_code = step.get("molecule")
283
+ mol_node = ct_index.get(mol_code)
284
+ if not mol_node:
285
+ errors.append(CompilerError(
286
+ code=ErrorCode.E201_MISSING_REFERENCE,
287
+ message=f"Unresolved molecule reference: {mol_code}",
288
+ phase="S5_CONSTRUCT",
289
+ fqdn_id=node.fqdn,
290
+ ))
291
+ continue
292
+
293
+ mol_core = mol_node.frontmatter.get("core", {})
294
+ loop_spec = {
295
+ "over": step.get("over"),
296
+ "iterator": step.get("iterator"),
297
+ "accumulator": step.get("accumulator", {}),
298
+ "inputs": step.get("inputs", {}),
299
+ "update_accumulator": step.get("update_accumulator", {}),
300
+ }
301
+ transformed = {
302
+ "atom": mol_node.fqdn,
303
+ "out": step.get("as"),
304
+ "loop": loop_spec,
305
+ "input_types": _extract_input_types(
306
+ mol_core.get("inputs", {}) if isinstance(mol_core, dict) else {}
307
+ ),
308
+ }
309
+ atom_stream.append(transformed)
310
+
311
+ else:
312
+ atom_stream.append(step)
313
+
314
+ # Transform emit → outputs
315
+ emit_config = machine.get("emit", {})
316
+ for output_name, from_symbol in (emit_config.items() if isinstance(emit_config, dict) else []):
317
+ ct_ir_outputs[output_name] = {"from": from_symbol}
318
+
319
+ else:
320
+ errors.append(CompilerError(
321
+ code=ErrorCode.E205_CT_VALIDATION_FAILED,
322
+ message=f"Unknown ct_kind: {ct_kind}",
323
+ phase="S5_CONSTRUCT",
324
+ fqdn_id=node.fqdn,
325
+ ))
326
+ return None, errors
327
+
328
+ ct_ir = {
329
+ "artifact_code": node.artifact_code,
330
+ "ct_fqdn": node.fqdn,
331
+ "atom_stream": atom_stream,
332
+ "ct_composition_version": "V0",
333
+ "inputs": dict(core.get("inputs", {})) if isinstance(core, dict) else {},
334
+ "outputs": ct_ir_outputs,
335
+ }
336
+
337
+ return ct_ir, errors
338
+
339
+
340
+ def _build_cs_ir(node: Node) -> tuple[dict[str, Any] | None, list[CompilerError]]:
341
+ """Build CS-IR for a CS node."""
342
+ errors: list[CompilerError] = []
343
+ implementation = node.frontmatter.get("implementation")
344
+
345
+ if not implementation or not implementation.get("module") or not implementation.get("callable"):
346
+ errors.append(CompilerError(
347
+ code=ErrorCode.E205_CT_VALIDATION_FAILED,
348
+ message="CS missing implementation — cannot emit cs_ir",
349
+ phase="S5_CONSTRUCT",
350
+ fqdn_id=node.fqdn,
351
+ ))
352
+ return None, errors
353
+
354
+ core = node.frontmatter.get("core", {})
355
+ policy_ops = core.get("policy", {}).get("operations", []) if isinstance(core, dict) else []
356
+ operations = core.get("operations", {}) if isinstance(core, dict) else {}
357
+
358
+ cs_ir = {
359
+ "handler_ref": {
360
+ "module": implementation["module"],
361
+ "callable": implementation["callable"],
362
+ },
363
+ "cs_metadata": {
364
+ "capability": {
365
+ "supported_operation_specs": list(policy_ops),
366
+ },
367
+ "operations": {
368
+ "operations": dict(operations) if operations else {},
369
+ },
370
+ },
371
+ }
372
+
373
+ return cs_ir, errors
374
+
375
+
376
+ def _build_cc_projection(
377
+ node: Node,
378
+ ct_index: dict[str, Node],
379
+ cs_index: dict[str, Node],
380
+ ) -> tuple[dict[str, Any] | None, list[CompilerError]]:
381
+ """Build CC pipeline projection for a CC node."""
382
+ errors: list[CompilerError] = []
383
+ core = node.frontmatter.get("core", {})
384
+ pipeline = core.get("pipeline", []) if isinstance(core, dict) else []
385
+
386
+ _MAX_SIG = 5
387
+ _MAX_BIND = 5
388
+
389
+ steps: list[dict] = []
390
+ seen_fqdns: set[str] = set()
391
+
392
+ for step in pipeline:
393
+ if not isinstance(step, dict):
394
+ continue
395
+
396
+ t = step.get("transform")
397
+ s = step.get("side_effect")
398
+ ref_fqdn = t or s
399
+ if not ref_fqdn or ref_fqdn in seen_fqdns:
400
+ continue
401
+ seen_fqdns.add(ref_fqdn)
402
+
403
+ code = ref_fqdn.split("::")[-1] if "::" in ref_fqdn else ref_fqdn
404
+ kind = "CT" if t else "CS"
405
+
406
+ if kind == "CT":
407
+ ref_node = ct_index.get(code)
408
+ if not ref_node:
409
+ continue
410
+ ref_core = ref_node.frontmatter.get("core", {})
411
+ ref_core = ref_core if isinstance(ref_core, dict) else {}
412
+ inputs_sig = list(ref_core.get("inputs", {}).keys())
413
+ outputs_sig = list(ref_core.get("outputs", {}).keys())
414
+
415
+ raw_bindings = step.get("inputs", {})
416
+ bindings: dict[str, str] = {}
417
+ for k, v in (raw_bindings.items() if isinstance(raw_bindings, dict) else []):
418
+ normalized = _normalize_binding(v)
419
+ if normalized is not None:
420
+ bindings[k] = normalized
421
+ if len(bindings) >= _MAX_BIND:
422
+ break
423
+
424
+ entry: dict = {
425
+ "id": code,
426
+ "fqdn": ref_fqdn,
427
+ "kind": "CT",
428
+ "inputs": inputs_sig[:_MAX_SIG],
429
+ "outputs": outputs_sig[:_MAX_SIG],
430
+ "bindings": bindings,
431
+ }
432
+ if len(inputs_sig) > _MAX_SIG:
433
+ entry["inputs_truncated"] = True
434
+ if len(outputs_sig) > _MAX_SIG:
435
+ entry["outputs_truncated"] = True
436
+
437
+ else: # CS
438
+ ref_node = cs_index.get(code)
439
+ if not ref_node:
440
+ continue
441
+ ref_core = ref_node.frontmatter.get("core", {})
442
+ ref_core = ref_core if isinstance(ref_core, dict) else {}
443
+ policy_ops = ref_core.get("policy", {}).get("operations", [])
444
+ ops_sig = list(policy_ops) if isinstance(policy_ops, list) else list(policy_ops.keys())
445
+
446
+ entry = {
447
+ "id": code,
448
+ "fqdn": ref_fqdn,
449
+ "kind": "CS",
450
+ "ops": ops_sig[:_MAX_SIG],
451
+ "outputs": ["result_status"],
452
+ }
453
+ if len(ops_sig) > _MAX_SIG:
454
+ entry["ops_truncated"] = True
455
+
456
+ steps.append(entry)
457
+
458
+ return {"cc_projection": {"steps": steps}}, errors
459
+
460
+
461
+ def _enrich_wf_nodes(
462
+ node: Node,
463
+ code_to_fqdn: dict[str, str],
464
+ builder: GraphBuilder,
465
+ ) -> list[CompilerError]:
466
+ """Enrich WF frontmatter nodes with fqdn_id resolution."""
467
+ errors: list[CompilerError] = []
468
+ wf_nodes = node.frontmatter.get("core", {}).get("nodes", {})
469
+
470
+ if not isinstance(wf_nodes, dict):
471
+ return errors
472
+
473
+ # Build enriched frontmatter with fqdn_ids resolved
474
+ enriched_nodes = {}
475
+ for node_key, wf_node in wf_nodes.items():
476
+ if not isinstance(wf_node, dict):
477
+ enriched_nodes[node_key] = wf_node
478
+ continue
479
+
480
+ node_type = wf_node.get("type")
481
+ if node_type not in ("CC", "IN"):
482
+ enriched_nodes[node_key] = dict(wf_node)
483
+ continue
484
+
485
+ ref_code = wf_node.get("code") or wf_node.get("fqdn_id")
486
+ if not ref_code:
487
+ enriched_nodes[node_key] = dict(wf_node)
488
+ continue
489
+
490
+ enriched = dict(wf_node)
491
+ if "::" in ref_code:
492
+ enriched["fqdn_id"] = ref_code
493
+ elif ref_code in code_to_fqdn:
494
+ enriched["fqdn_id"] = code_to_fqdn[ref_code]
495
+ else:
496
+ errors.append(CompilerError(
497
+ code=ErrorCode.E201_MISSING_REFERENCE,
498
+ message=f"WF node '{node_key}' references '{ref_code}' — no matching artifact",
499
+ phase="S5_CONSTRUCT",
500
+ fqdn_id=node.fqdn,
501
+ ))
502
+
503
+ enriched_nodes[node_key] = enriched
504
+
505
+ # Update the frontmatter with enriched nodes
506
+ fm = dict(node.frontmatter)
507
+ core = dict(fm.get("core", {}))
508
+ core["nodes"] = enriched_nodes
509
+ fm["core"] = core
510
+ builder.replace_node(node.fqdn, frontmatter=MappingProxyType(fm))
511
+
512
+ return errors
513
+
514
+
515
+ def _extract_input_types(core_inputs: Any) -> dict[str, str]:
516
+ """Extract input types from core.inputs spec."""
517
+ input_types: dict[str, str] = {}
518
+ if isinstance(core_inputs, dict):
519
+ for key, spec in core_inputs.items():
520
+ if isinstance(spec, dict) and "type" in spec:
521
+ input_types[key] = spec["type"]
522
+ return input_types
523
+
524
+
525
+ def _normalize_binding(value: object) -> str | None:
526
+ """Normalize a CC pipeline binding value for projection display."""
527
+ if not isinstance(value, str):
528
+ return None
529
+ if len(value) > 80:
530
+ return None
531
+ if value.startswith("$.results."):
532
+ return value[len("$.results."):]
533
+ if value.startswith("$.inputs."):
534
+ return "in." + value[len("$.inputs."):]
535
+ if value.startswith("$."):
536
+ return value
537
+ return None
@@ -0,0 +1,94 @@
1
+ """
2
+ S6 PROJECT — Generate projections from Graph.
3
+
4
+ Input: State from S5 (graph with IR populated on CT/CS/CC/WF nodes)
5
+ Output: State with named projections populated
6
+
7
+ Orchestrates projection generators. Each projection is a deterministic
8
+ derivation of the Graph — the sole semantic authority. No projection
9
+ derives from another projection.
10
+
11
+ Current projections:
12
+ - canonical: human/governance/tooling authority (protocol_snapshot/)
13
+ - vocabulary: per-structure address space realization (semantic_vocabulary/)
14
+ - tokenized: machine/silicon/runtime topology (tokenized_snapshot/)
15
+ - evidence: dual-form observability/replay substrate (evidence_snapshot/)
16
+ """
17
+
18
+ from compiler.graph.state import State
19
+ from compiler.graph.trace import TraceEvent
20
+ from compiler.atoms.errors import CompilerError
21
+ from compiler.projections import ProjectionType
22
+ from compiler.projections.canonical import project_canonical
23
+ from compiler.projections.vocabulary import project_vocabulary
24
+ from compiler.projections.tokenized import project_tokenized
25
+ from compiler.projections.evidence import project_evidence
26
+ from compiler.projections.dispatch import project_dispatch
27
+ from compiler.projections.handlers import project_handlers
28
+
29
+
30
+ def s6_project(state: State) -> State:
31
+ """
32
+ S6 PROJECT: Generate projections from Graph.
33
+
34
+ Pure function: State → State.
35
+ """
36
+ state = state.with_stage("S6_PROJECT")
37
+ errors: list[CompilerError] = []
38
+ trace: list[TraceEvent] = []
39
+
40
+ # --- Canonical projection (protocol_snapshot/) ---
41
+ canonical_projection, canonical_trace = project_canonical(state.graph)
42
+ trace.extend(canonical_trace)
43
+
44
+ # --- Vocabulary projection (semantic_vocabulary/) ---
45
+ vocabulary_projection, voc_trace = project_vocabulary(state.graph)
46
+ trace.extend(voc_trace)
47
+
48
+ # --- Tokenized projection (tokenized_snapshot/) ---
49
+ tokenized_projection, tok_trace = project_tokenized(state.graph)
50
+ trace.extend(tok_trace)
51
+
52
+ # --- Evidence projection (evidence_snapshot/) ---
53
+ evidence_projection, evi_trace = project_evidence(state.graph)
54
+ trace.extend(evi_trace)
55
+
56
+ # --- Dispatch projection (tokenized_snapshot/ — routing tables) ---
57
+ dispatch_projection, dis_trace = project_dispatch(state.graph)
58
+ trace.extend(dis_trace)
59
+
60
+ # --- Handlers projection (tokenized_snapshot/ — implementation dispatch) ---
61
+ handlers_projection, han_trace = project_handlers(state.graph)
62
+ trace.extend(han_trace)
63
+
64
+ projections = {
65
+ ProjectionType.CANONICAL.value: canonical_projection,
66
+ ProjectionType.VOCABULARY.value: vocabulary_projection,
67
+ ProjectionType.TOKENIZED.value: tokenized_projection,
68
+ ProjectionType.EVIDENCE.value: evidence_projection,
69
+ ProjectionType.DISPATCH.value: dispatch_projection,
70
+ ProjectionType.HANDLERS.value: handlers_projection,
71
+ }
72
+
73
+ state = state.with_projections(projections)
74
+
75
+ if errors:
76
+ state = state.with_errors(*errors)
77
+ if trace:
78
+ state = state.with_trace_events(*trace)
79
+
80
+ state = state.with_metadata("projected_count", len(canonical_projection.content))
81
+ state = state.with_metadata("vocabulary_address_count", len(vocabulary_projection.content.get("forward", {})))
82
+ state = state.with_metadata("tokenized_node_count", len(tokenized_projection.content.get("nodes", [])))
83
+ state = state.with_metadata("tokenized_edge_count", len(tokenized_projection.content.get("edges", [])))
84
+ state = state.with_metadata("evidence_node_count", len(evidence_projection.content.get("nodes", [])))
85
+ state = state.with_metadata("evidence_edge_count", len(evidence_projection.content.get("edges", [])))
86
+ state = state.with_metadata("evidence_event_count", len(evidence_projection.content.get("event_catalog", [])))
87
+ state = state.with_metadata("dispatch_routing_count", len(dispatch_projection.content.get("routing", {})))
88
+ state = state.with_metadata("dispatch_pipeline_count", len(dispatch_projection.content.get("pipeline", {})))
89
+ state = state.with_metadata("dispatch_entry_count", len(dispatch_projection.content.get("entry", {})))
90
+ state = state.with_metadata("handlers_ct_count", len(handlers_projection.content.get("ct", {})))
91
+ state = state.with_metadata("handlers_cs_count", len(handlers_projection.content.get("cs", {})))
92
+ state = state.with_metadata("handlers_rb_policy_count", len(handlers_projection.content.get("rb_policy", {})))
93
+
94
+ return state