pgs-runtime 0.3.1__tar.gz → 0.5.0__tar.gz

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 (33) hide show
  1. {pgs_runtime-0.3.1/pgs_runtime.egg-info → pgs_runtime-0.5.0}/PKG-INFO +2 -2
  2. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/README.md +1 -1
  3. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/cli.py +74 -3
  4. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/conformance.py +19 -2
  5. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/dispatcher.py +35 -4
  6. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/evidence.py +3 -3
  7. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/loader.py +28 -16
  8. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/scheduler.py +19 -7
  9. pgs_runtime-0.5.0/pgs_runtime/trace_viz.py +276 -0
  10. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0/pgs_runtime.egg-info}/PKG-INFO +2 -2
  11. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime.egg-info/SOURCES.txt +1 -0
  12. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pyproject.toml +1 -1
  13. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/LICENSE +0 -0
  14. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/MANIFEST.in +0 -0
  15. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/NOTICE +0 -0
  16. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/__init__.py +0 -0
  17. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/ct_errors.py +0 -0
  18. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/ct_execute.py +0 -0
  19. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/ct_executor.py +0 -0
  20. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/examine/__init__.py +0 -0
  21. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/examine/classifier.py +0 -0
  22. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/examine/cli.py +0 -0
  23. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/examine/conformance_test.py +0 -0
  24. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/examine/hint_engine.py +0 -0
  25. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/examine/locator.py +0 -0
  26. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/examine/parser.py +0 -0
  27. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/examine/reporter.py +0 -0
  28. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/memory.py +0 -0
  29. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime/server.py +0 -0
  30. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime.egg-info/dependency_links.txt +0 -0
  31. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime.egg-info/entry_points.txt +0 -0
  32. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/pgs_runtime.egg-info/top_level.txt +0 -0
  33. {pgs_runtime-0.3.1 → pgs_runtime-0.5.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pgs_runtime
3
- Version: 0.3.1
3
+ Version: 0.5.0
4
4
  Summary: PGS runtime for Protocol-Governed Systems
5
5
  Author: Bachi
6
6
  License-Expression: Apache-2.0
@@ -29,7 +29,7 @@ It does not discover behavior. It does not interpret intent. It does not contain
29
29
 
30
30
  Behavior is declared in protocol, executed by runtime, implemented in capabilities, and observed via traces and state.
31
31
 
32
- > **New to PGS?** This is one of eight repositories in the Protocol-Governed Systems ecosystem.
32
+ > **New to PGS?** This is one of the repositories in the Protocol-Governed Systems ecosystem.
33
33
  > For orientation, architecture overview, and end-to-end execution, start at [pgs_workspace](https://github.com/bachipeachy/pgs_workspace).
34
34
 
35
35
  ---
@@ -7,7 +7,7 @@ It does not discover behavior. It does not interpret intent. It does not contain
7
7
 
8
8
  Behavior is declared in protocol, executed by runtime, implemented in capabilities, and observed via traces and state.
9
9
 
10
- > **New to PGS?** This is one of eight repositories in the Protocol-Governed Systems ecosystem.
10
+ > **New to PGS?** This is one of the repositories in the Protocol-Governed Systems ecosystem.
11
11
  > For orientation, architecture overview, and end-to-end execution, start at [pgs_workspace](https://github.com/bachipeachy/pgs_workspace).
12
12
 
13
13
  ---
@@ -2,16 +2,18 @@
2
2
  cli.py — Token-native CLI entry point for the pgs_runtime.
3
3
 
4
4
  Commands:
5
- run — Execute a workflow against the tokenized snapshot.
6
- examine — Analyze a completed trace file and print a diagnostic report.
5
+ run — Execute a workflow against the tokenized snapshot.
6
+ examine — Analyze a completed trace file and print a diagnostic report.
7
+ behavior-logic — Render execution-path PNG from a completed trace file.
7
8
 
8
9
  Execution path (run):
9
10
  1. Load tokenized snapshot for the domain via loader.load_domain()
10
11
  — verifies topology hash against trust attestation; fails hard on mismatch
11
12
  2. Generate deterministic trace ID from (domain, wf_fqdn, payload)
12
- 3. Open TraceWriter at traces/<domain>/<trace_id>/
13
+ 3. Open TraceWriter at traces/<domain>/<wf_code>/<trace_id>/
13
14
  4. Drive workflow topology via scheduler.run_wf()
14
15
  5. Print result summary; exit 1 on non-SUCCESS
16
+ 6. If --behavior-logic: invoke evidence projection (trace_viz) to render PNG
15
17
 
16
18
  All runtime behavior comes from the compiled tokenized_snapshot.
17
19
  The CLI does not implement any domain logic.
@@ -69,6 +71,14 @@ def _build_parser() -> argparse.ArgumentParser:
69
71
  "tokenized_snapshot/ and traces/ live here",
70
72
  )
71
73
 
74
+ # ── run: optional behavior-logic flag ────────────────────────
75
+ run_p.add_argument(
76
+ "--behavior-logic",
77
+ action="store_true",
78
+ dest="behavior_logic",
79
+ help="Render execution-path PNG after run (requires graphviz)",
80
+ )
81
+
72
82
  # ── examine ───────────────────────────────────────────────────
73
83
  ex_p = subs.add_parser("examine", help="Analyze a completed trace file")
74
84
  ex_p.add_argument(
@@ -77,6 +87,22 @@ def _build_parser() -> argparse.ArgumentParser:
77
87
  help="Path to a completed .jsonl trace file",
78
88
  )
79
89
 
90
+ # ── behavior-logic ────────────────────────────────────────────
91
+ bl_p = subs.add_parser(
92
+ "behavior-logic",
93
+ help="Render execution-path PNG from a completed trace file",
94
+ )
95
+ bl_p.add_argument(
96
+ "trace_file",
97
+ metavar="FILE",
98
+ help="Path to a completed .jsonl trace file",
99
+ )
100
+ bl_p.add_argument(
101
+ "--workspace",
102
+ metavar="PATH",
103
+ help="Absolute path to pgs_workspace root (or set PGS_WORKSPACE)",
104
+ )
105
+
80
106
  return parser
81
107
 
82
108
 
@@ -161,6 +187,12 @@ def _handle_run(args: argparse.Namespace) -> None:
161
187
 
162
188
  duration_ms = int((time.monotonic() - t0) * 1000)
163
189
 
190
+ # Evidence projection: render execution-path PNG if requested
191
+ trace_path = trace_dir / f"{trace_id}.jsonl"
192
+ png_path = None
193
+ if args.behavior_logic:
194
+ png_path = _render_behavior_logic(workspace, trace_path)
195
+
164
196
  print("=" * 60)
165
197
  print("[pgs_runtime] Workflow Complete")
166
198
  print("=" * 60)
@@ -170,12 +202,39 @@ def _handle_run(args: argparse.Namespace) -> None:
170
202
  print(f"Duration: {duration_ms}ms")
171
203
  if surface:
172
204
  print(f"Output: {json.dumps(surface, separators=(',', ':'))}")
205
+ if png_path:
206
+ print(f"Graph: {png_path}")
207
+ elif args.behavior_logic:
208
+ print("Graph: (graphviz not available — PNG skipped)")
173
209
  print("=" * 60)
174
210
 
175
211
  if result_status not in ("SUCCESS", "ALREADY_EXISTS"):
176
212
  sys.exit(1)
177
213
 
178
214
 
215
+ def _handle_behavior_logic(args: argparse.Namespace) -> None:
216
+ trace_path = Path(args.trace_file)
217
+ if not trace_path.exists():
218
+ _fatal(f"Trace file not found: {args.trace_file}")
219
+
220
+ workspace_str = args.workspace or os.environ.get("PGS_WORKSPACE")
221
+ if not workspace_str:
222
+ _fatal("--workspace PATH or PGS_WORKSPACE is required")
223
+ workspace = Path(workspace_str)
224
+ if not workspace.is_absolute():
225
+ _fatal(f"--workspace must be an absolute path, got: {workspace_str}")
226
+
227
+ png_path = _render_behavior_logic(workspace, trace_path)
228
+ if png_path:
229
+ print(f"[pgs_runtime] Execution path PNG: {png_path}")
230
+ else:
231
+ print(
232
+ "[pgs_runtime] Behavior logic render skipped — graphviz (dot) not available.",
233
+ file=sys.stderr,
234
+ )
235
+ sys.exit(1)
236
+
237
+
179
238
  def _handle_examine(args: argparse.Namespace) -> None:
180
239
  trace_path = Path(args.trace_file)
181
240
  if not trace_path.exists():
@@ -205,6 +264,16 @@ def _handle_examine(args: argparse.Namespace) -> None:
205
264
  # Utilities
206
265
  # ---------------------------------------------------------------------------
207
266
 
267
+ def _render_behavior_logic(workspace: Path, trace_path: Path) -> "Path | None":
268
+ """Invoke evidence projection to render execution-path PNG. Best-effort."""
269
+ from pgs_runtime.trace_viz import render_trace_png
270
+ try:
271
+ return render_trace_png(workspace, trace_path)
272
+ except (FileNotFoundError, ValueError) as exc:
273
+ print(f"[pgs_runtime] Behavior logic render error: {exc}", file=sys.stderr)
274
+ return None
275
+
276
+
208
277
  def _load_payload(payload_path: str | None) -> dict:
209
278
  if not payload_path:
210
279
  return {}
@@ -234,6 +303,8 @@ def main() -> None:
234
303
  _handle_run(args)
235
304
  elif args.command == "examine":
236
305
  _handle_examine(args)
306
+ elif args.command == "behavior-logic":
307
+ _handle_behavior_logic(args)
237
308
 
238
309
 
239
310
  if __name__ == "__main__":
@@ -198,10 +198,22 @@ def run(snapshot_root: Path) -> ConformanceResult:
198
198
  expected = artifact.get("expected", {})
199
199
  assertions = artifact.get("assertions", {})
200
200
 
201
+ expected_outcome = artifact.get("expected_outcome", "SUCCESS")
202
+
201
203
  try:
202
204
  vars_result = executor.execute(ct_ir=ct_ir, inputs=inputs)
203
205
  actual = _resolve_outputs(ct_ir, vars_result)
204
206
 
207
+ if expected_outcome == "VIOLATION":
208
+ # CT completed without error but a VIOLATION was expected.
209
+ result.failed += 1
210
+ result.cases.append(CaseResult(
211
+ fqdn=fqdn,
212
+ passed=False,
213
+ error="expected CTExecutionError (VIOLATION) but CT completed without raising",
214
+ ))
215
+ continue
216
+
205
217
  # Structural assertions validate non-deterministic fields by shape/type/size.
206
218
  # Fields covered by assertions are excluded from exact-match comparison.
207
219
  assertion_error = _assert_structural(actual, assertions) if assertions else None
@@ -226,7 +238,12 @@ def run(snapshot_root: Path) -> ConformanceResult:
226
238
  result.cases.append(CaseResult(fqdn=fqdn, passed=True))
227
239
 
228
240
  except CTExecutionError as e:
229
- result.failed += 1
230
- result.cases.append(CaseResult(fqdn=fqdn, passed=False, error=str(e)))
241
+ if expected_outcome == "VIOLATION":
242
+ # CT raised as expected — PASS.
243
+ result.passed += 1
244
+ result.cases.append(CaseResult(fqdn=fqdn, passed=True))
245
+ else:
246
+ result.failed += 1
247
+ result.cases.append(CaseResult(fqdn=fqdn, passed=False, error=str(e)))
231
248
 
232
249
  return result
@@ -86,6 +86,10 @@ def execute_cc(
86
86
  surface: dict[str, Any] = {}
87
87
  result_status = "SUCCESS"
88
88
 
89
+ # Build a workflow executor closure for CS types that need nested WF invocation.
90
+ # Injected unconditionally — CSs that don't need it ignore it.
91
+ wf_executor = _make_workflow_executor(pkg, writer, data_root)
92
+
89
93
  for step in steps:
90
94
  step_addr: int = step["addr"]
91
95
  op: str | None = step.get("op")
@@ -104,7 +108,7 @@ def execute_cc(
104
108
  else:
105
109
  # CS step — controlled side effect via declared handler
106
110
  result_status, raw_result = _execute_cs_step(
107
- step_addr, op, resolved_inputs, rb_addr, pkg, data_root
111
+ step_addr, op, resolved_inputs, rb_addr, pkg, data_root, wf_executor
108
112
  )
109
113
 
110
114
  # Apply outputs mapping: {cc_field: "$.capability_result.<ct_field>"} → surface fragment
@@ -177,6 +181,29 @@ def _execute_ct_step(
177
181
  return "VIOLATION", {}
178
182
 
179
183
 
184
+ def _make_workflow_executor(
185
+ pkg: RuntimePackage,
186
+ writer: TraceWriter,
187
+ data_root: str,
188
+ ):
189
+ """
190
+ Build a workflow executor callable for injection into CS config.
191
+
192
+ The returned callable lets CS implementations invoke sub-workflows without
193
+ importing the scheduler directly (avoids circular imports at module load time).
194
+
195
+ Interface: executor(wf_fqdn: str, payload: dict) -> (result_status: str, surface: dict)
196
+ """
197
+ def executor(wf_fqdn_or_addr, payload: dict) -> tuple[str, dict]:
198
+ from pgs_runtime.scheduler import run_wf # lazy import — avoids circular dependency
199
+ # Compiler tokenizes nested dict string values to int addresses.
200
+ # CS_WORKFLOW_LOOP_V0 receives int addrs from the compiled mapping; resolve to FQDN here.
201
+ if isinstance(wf_fqdn_or_addr, int):
202
+ wf_fqdn_or_addr = pkg.vocab.fqdn(wf_fqdn_or_addr)
203
+ return run_wf(wf_fqdn_or_addr, payload, pkg, writer, data_root)
204
+ return executor
205
+
206
+
180
207
  def _execute_cs_step(
181
208
  cs_addr: int,
182
209
  op: str,
@@ -184,6 +211,7 @@ def _execute_cs_step(
184
211
  rb_addr: int,
185
212
  pkg: RuntimePackage,
186
213
  data_root: str,
214
+ wf_executor=None,
187
215
  ) -> tuple[str, dict[str, Any]]:
188
216
  """
189
217
  Execute a CS (side effect) step.
@@ -202,11 +230,14 @@ def _execute_cs_step(
202
230
  # Resolve per-RB policy config for this CS
203
231
  rb_cs_map = pkg.handlers.rb_policy.get(rb_addr, {})
204
232
  policy_entry = rb_cs_map.get(cs_addr, {})
205
- # Compiler emits either "policy" or "config" as the key name depending on
206
- # the structure; accept both to remain forward/backward compatible.
207
- policy_raw = policy_entry.get("policy") or policy_entry.get("config") or {}
233
+ policy_raw = policy_entry.get("policy") or {}
208
234
  policy = _expand_policy(policy_raw, data_root)
209
235
 
236
+ # Inject workflow executor for CS types that need nested WF invocation.
237
+ # Injected unconditionally — CSs that don't use it ignore the key.
238
+ if wf_executor is not None:
239
+ policy = {**policy, "workflow_executor": wf_executor}
240
+
210
241
  # Instantiate CS runtime
211
242
  handler_ref = cs_entry["handler_ref"]
212
243
  cs_metadata = cs_entry.get("cs_metadata", {})
@@ -15,12 +15,12 @@ Each execution event is a self-contained JSON line with:
15
15
  - ts_ns — monotonic nanosecond timestamp
16
16
 
17
17
  The trace file is written to:
18
- <traces_root>/<domain>/<subdomain>/<trace_id>/<trace_id>.jsonl
18
+ <traces_root>/<domain>/<wf_code>/<trace_id>/<trace_id>.jsonl
19
19
 
20
20
  subdomain is not known to this module — caller passes the full trace dir path.
21
21
 
22
- Projection (human-readable reports, visualizations) belongs in tooling/compiler,
23
- not here. The runtime produces .jsonl only.
22
+ This module produces the raw JSONL evidence only. Evidence projection
23
+ (execution-path PNG overlay) is handled separately in trace_viz.py.
24
24
  """
25
25
 
26
26
  from __future__ import annotations
@@ -44,10 +44,10 @@ class DispatchTable:
44
44
  """
45
45
  Integer-keyed routing substrate from dispatch.json.
46
46
 
47
- routing: {wf_addr: {cc_addr: {condition_addr: next_cc_addr}}}
47
+ routing: {wf_addr: {cc_addr: {condition_addr: {"addr": next_cc_addr, "key": node_key}}}}
48
48
  pipeline: {cc_addr: [step, ...]}
49
- entry: {wf_addr: {"start": cc_addr, "rb": rb_addr, "in": in_addr}}
50
- bindings: {wf_addr: {cc_addr: {input_name: path_or_literal}}}
49
+ entry: {wf_addr: {"start": cc_addr, "start_key": node_key, "rb": rb_addr, "in": in_addr}}
50
+ bindings: {wf_addr: {node_key: {input_name: path_or_literal}}}
51
51
 
52
52
  Each pipeline step is a named-field execution instruction record:
53
53
  {
@@ -59,14 +59,19 @@ class DispatchTable:
59
59
  "step_id": str, # symbolic step name for $.results.<step_id>.<field> references
60
60
  }
61
61
 
62
+ Routing values carry both the next CC address and the target node_key so that
63
+ the scheduler can disambiguate distinct WF usages of the same shared CC
64
+ (e.g. four denial audit nodes that all bind to CC_RECORD_DENIED_ACTION_V0).
65
+
66
+ Bindings are keyed by node_key (not CC address) for the same reason.
67
+
62
68
  All semantics are compiler-materialized. The dispatcher is a blind executor.
63
- All dict keys are ints. All address values are ints.
64
69
  The nested dicts are plain Python dicts (not frozen) — callers must not mutate.
65
70
  """
66
- routing: dict[int, dict[int, dict[int, int]]]
71
+ routing: dict[int, dict[int, dict[int, Any]]]
67
72
  pipeline: dict[int, list[dict]]
68
- entry: dict[int, dict[str, int]]
69
- bindings: dict[int, dict[int, dict[str, Any]]]
73
+ entry: dict[int, dict[str, Any]]
74
+ bindings: dict[int, dict[str, dict[str, Any]]]
70
75
 
71
76
 
72
77
  @dataclass(frozen=True)
@@ -209,14 +214,16 @@ def _build_dispatch(raw: dict) -> DispatchTable:
209
214
  """
210
215
  Parse dispatch.json into integer-keyed DispatchTable.
211
216
 
212
- JSON keys are strings (JSON spec). Addresses are hex-string or int values.
213
- All converted to int on load.
217
+ JSON keys are strings (JSON spec). Addresses are int values.
218
+ Outer WF and CC keys are converted to int. Routing values are
219
+ {"addr": int, "key": str} dicts — preserved as-is. Bindings keys
220
+ are node_key strings — preserved as-is (not int-converted).
214
221
  """
215
- routing: dict[int, dict[int, dict[int, int]]] = {}
222
+ routing: dict[int, dict[int, dict[int, Any]]] = {}
216
223
  for wf_key, cc_map in raw.get("routing", {}).items():
217
224
  wf_addr = int(wf_key)
218
225
  routing[wf_addr] = {
219
- int(cc_key): {int(cond): int(tgt) for cond, tgt in cond_map.items()}
226
+ int(cc_key): {int(cond): tgt for cond, tgt in cond_map.items()}
220
227
  for cc_key, cond_map in cc_map.items()
221
228
  }
222
229
 
@@ -225,15 +232,20 @@ def _build_dispatch(raw: dict) -> DispatchTable:
225
232
  cc_addr = int(cc_key)
226
233
  pipeline[cc_addr] = steps # list of named-field step dicts
227
234
 
228
- entry: dict[int, dict[str, int]] = {}
235
+ entry: dict[int, dict[str, Any]] = {}
229
236
  for wf_key, e in raw.get("entry", {}).items():
230
237
  wf_addr = int(wf_key)
231
- entry[wf_addr] = {k: int(v) for k, v in e.items()}
238
+ # int-convert only numeric values (start, rb, in); leave start_key as str
239
+ entry[wf_addr] = {
240
+ k: (int(v) if isinstance(v, (int, float)) else v)
241
+ for k, v in e.items()
242
+ }
232
243
 
233
- bindings: dict[int, dict[int, dict[str, Any]]] = {}
234
- for wf_key, cc_map in raw.get("bindings", {}).items():
244
+ bindings: dict[int, dict[str, dict[str, Any]]] = {}
245
+ for wf_key, node_map in raw.get("bindings", {}).items():
235
246
  wf_addr = int(wf_key)
236
- bindings[wf_addr] = {int(cc_key): inp for cc_key, inp in cc_map.items()}
247
+ # node_map keys are node_key strings (e.g. "CC_NORMALIZE_AGENT_REQUEST_V0")
248
+ bindings[wf_addr] = {node_key: inp for node_key, inp in node_map.items()}
237
249
 
238
250
  return DispatchTable(
239
251
  routing = routing,
@@ -20,8 +20,8 @@ Topology traversal rules:
20
20
 
21
21
  Boundary nodes (IN_, EXIT_):
22
22
  Nodes without a pipeline entry (not in dispatch.pipeline) are boundary nodes.
23
- IN_ nodes perform admission gating; for v0.3.0, prior to admission_snapshot
24
- integration, they pass through as ACK. The routing table routes ACK forward.
23
+ IN_ nodes perform admission gating; prior to admission_snapshot integration,
24
+ they pass through as ACK. The routing table routes ACK forward.
25
25
  EXIT_ nodes (no routing) terminate the loop naturally.
26
26
 
27
27
  Bindings path grammar (WF-level, compiler-emitted):
@@ -90,6 +90,7 @@ def run_wf(
90
90
 
91
91
  rb_addr = entry["rb"]
92
92
  current_addr: int | None = entry["start"]
93
+ current_node_key: str = entry.get("start_key", "")
93
94
 
94
95
  ctx = ExecutionContext(payload)
95
96
  writer.wf_start(payload)
@@ -107,11 +108,14 @@ def run_wf(
107
108
  hops += 1
108
109
 
109
110
  if current_addr in pkg.dispatch.pipeline:
110
- # CC node — resolve WF-level bindings and execute
111
+ # CC node — resolve WF-level bindings and execute.
112
+ # Bindings are keyed by node_key (not CC addr) so that distinct WF
113
+ # usages of the same CC (e.g. four denial audit nodes) each carry
114
+ # their own literal inputs (e.g. different denial_reason values).
111
115
  wf_bindings = (
112
116
  pkg.dispatch.bindings
113
117
  .get(wf_addr, {})
114
- .get(current_addr, {})
118
+ .get(current_node_key, {})
115
119
  )
116
120
  cc_inputs = ctx.resolve_inputs(wf_bindings)
117
121
 
@@ -122,13 +126,21 @@ def run_wf(
122
126
 
123
127
  else:
124
128
  # Boundary node (IN_, EXIT_) — no pipeline
125
- # v0.3.0: admission_snapshot not yet integrated; IN_ nodes pass as ACK
129
+ # admission_snapshot not yet integrated; IN_ nodes pass as ACK
126
130
  result_status = "ACK"
127
131
 
128
- # Resolve result_status → condition address and route to next node
132
+ # Resolve result_status → condition address and route to next node.
133
+ # Routing values are {"addr": int, "key": str} — addr is the next CC address,
134
+ # key is the next node_key for bindings disambiguation.
129
135
  condition_addr = _condition_addr(result_status, pkg)
130
136
  routing = pkg.dispatch.routing.get(wf_addr, {}).get(current_addr, {})
131
- current_addr = routing.get(condition_addr) # None → terminal
137
+ next_entry = routing.get(condition_addr) # None → terminal
138
+ if isinstance(next_entry, dict):
139
+ current_addr = next_entry.get("addr")
140
+ current_node_key = next_entry.get("key", "")
141
+ else:
142
+ current_addr = next_entry # bare int (legacy) or None
143
+ current_node_key = ""
132
144
 
133
145
  writer.wf_complete(result_status)
134
146
  return result_status, surface
@@ -0,0 +1,276 @@
1
+ """
2
+ trace_viz.py — Evidence projection: execution path behavior logic.
3
+
4
+ Reads a completed trace (.jsonl) and the compiled workflow graph (.graph.json)
5
+ from the protocol snapshot behavior_logic directory, then generates a PNG with
6
+ the actual execution path overlaid in red on the static compiled graph.
7
+
8
+ This is Evidence Projection — not a runtime execution feature:
9
+
10
+ topology (graph.json)
11
+ +
12
+ evidence (trace.jsonl)
13
+ ───────────────────────
14
+ → execution path PNG
15
+
16
+ Inputs (both already materialized, read-only):
17
+ protocol_snapshot/behavior_logic/<WF_CODE>/<WF_CODE>.graph.json
18
+ traces/<domain>/<wf_code>/<trace_id>/<trace_id>.jsonl
19
+
20
+ Output:
21
+ traces/<domain>/<wf_code>/<trace_id>/<trace_id>.png
22
+
23
+ Architectural invariant:
24
+ This module reads ONLY from:
25
+ - protocol_snapshot/behavior_logic/ (compiled graph artifacts)
26
+ - the caller-supplied trace .jsonl (execution evidence)
27
+ It does NOT walk protocol_snapshot/artifacts/ or any other canonical
28
+ protocol location. Behavior logic overlay is read-only — no protocol interpretation.
29
+
30
+ Uses graphviz (dot) — returns None silently if dot is not available.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import json
36
+ import subprocess
37
+ from pathlib import Path
38
+ from typing import Optional
39
+
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # Public API
43
+ # ---------------------------------------------------------------------------
44
+
45
+ def render_trace_png(
46
+ workspace: Path,
47
+ trace_path: Path,
48
+ ) -> Optional[Path]:
49
+ """
50
+ Generate execution-path overlay PNG for a completed trace.
51
+
52
+ Reads CC_COMPLETE events from trace_path to reconstruct the actual
53
+ execution path, then overlays it (red) on the compiled workflow graph.
54
+
55
+ Args:
56
+ workspace: Absolute path to pgs_workspace root.
57
+ trace_path: Path to the completed .jsonl trace file.
58
+
59
+ Returns:
60
+ Path to the generated PNG, or None if graphviz is unavailable.
61
+
62
+ Raises:
63
+ FileNotFoundError: trace_path or graph.json does not exist.
64
+ ValueError: Trace is empty or missing WF_START event.
65
+ """
66
+ if not trace_path.exists():
67
+ raise FileNotFoundError(f"Trace file not found: {trace_path}")
68
+
69
+ # Parse trace events
70
+ events: list[dict] = []
71
+ for line in trace_path.read_text(encoding="utf-8").splitlines():
72
+ line = line.strip()
73
+ if line:
74
+ events.append(json.loads(line))
75
+
76
+ if not events:
77
+ raise ValueError(f"Trace file is empty: {trace_path}")
78
+
79
+ # Extract WF code from WF_START event
80
+ wf_start = next((e for e in events if e["event_type"] == "WF_START"), None)
81
+ if wf_start is None:
82
+ raise ValueError(f"No WF_START event found in: {trace_path}")
83
+
84
+ wf_fqdn = wf_start["detail"]["wf_fqdn"]
85
+ wf_code = wf_fqdn.split("::")[-1] # e.g. "WF_REGISTER_ACTOR_UNVERIFIED_V0"
86
+
87
+ # Load compiled graph from protocol_snapshot/behavior_logic/
88
+ graph_path = (
89
+ workspace
90
+ / "protocol_snapshot"
91
+ / "behavior_logic"
92
+ / wf_code
93
+ / f"{wf_code}.graph.json"
94
+ )
95
+ if not graph_path.exists():
96
+ raise FileNotFoundError(
97
+ f"Compiled graph not found: {graph_path}\n"
98
+ f"Re-run the compiler to regenerate behavior_logic artifacts."
99
+ )
100
+
101
+ graph = json.loads(graph_path.read_text(encoding="utf-8"))
102
+
103
+ # Reconstruct actual execution path from trace events + graph edges
104
+ path = _extract_execution_path(events, graph)
105
+
106
+ # Build visited node and taken edge sets
107
+ visited_nodes: set[str] = set()
108
+ taken_edges: set[tuple[str, str, str]] = set() # (from_node, to_node, condition)
109
+ for from_node, condition, to_node in path:
110
+ visited_nodes.add(from_node)
111
+ visited_nodes.add(to_node)
112
+ taken_edges.add((from_node, to_node, condition))
113
+
114
+ # Generate DOT source with execution-path overlay
115
+ dot_content = _generate_dot(graph, visited_nodes, taken_edges)
116
+
117
+ # Render: write DOT, invoke graphviz, clean up DOT
118
+ png_path = trace_path.with_suffix(".png")
119
+ dot_path = trace_path.with_suffix(".dot")
120
+ dot_path.write_text(dot_content, encoding="utf-8")
121
+
122
+ try:
123
+ subprocess.run(
124
+ ["dot", "-Tpng", str(dot_path), "-o", str(png_path)],
125
+ check=True,
126
+ capture_output=True,
127
+ )
128
+ dot_path.unlink()
129
+ return png_path
130
+ except (subprocess.CalledProcessError, FileNotFoundError):
131
+ dot_path.unlink(missing_ok=True)
132
+ return None
133
+
134
+
135
+ # ---------------------------------------------------------------------------
136
+ # Path reconstruction
137
+ # ---------------------------------------------------------------------------
138
+
139
+ def _extract_execution_path(
140
+ events: list[dict],
141
+ graph: dict,
142
+ ) -> list[tuple[str, str, str]]:
143
+ """
144
+ Reconstruct [(from_node, condition, to_node), ...] from trace events.
145
+
146
+ Uses CC_COMPLETE events (in emission order) and graph edges to walk
147
+ the actual execution path. IN_ boundary nodes always yield ACK in
148
+ the current runtime (admission_snapshot not yet integrated).
149
+
150
+ Args:
151
+ events: Parsed JSONL trace events.
152
+ graph: Compiled graph dict (from graph.json).
153
+
154
+ Returns:
155
+ Ordered list of (from_node_id, condition, to_node_id) tuples.
156
+ """
157
+ entry_node: str = graph["entry"] # e.g. "IN_ACTOR_REGISTERED_V0"
158
+
159
+ # (from_node, condition) → to_node
160
+ edge_map: dict[tuple[str, str], str] = {
161
+ (e["from"], e["condition"]): e["to"]
162
+ for e in graph["edges"]
163
+ }
164
+
165
+ # Filter to top-level workflow CC events only.
166
+ # Sub-workflows emit CC_COMPLETE events with the same wf_addr as the
167
+ # top-level workflow (the runtime reuses the same address), so wf_addr
168
+ # filtering is insufficient. Instead, restrict to CCs that are declared
169
+ # nodes in the top-level graph — sub-workflow CCs won't appear there.
170
+ graph_cc_nodes: set[str] = {
171
+ n["id"] for n in graph["nodes"] if n["type"] == "CC"
172
+ }
173
+ cc_completions = [
174
+ e for e in events
175
+ if e["event_type"] == "CC_COMPLETE"
176
+ and e["detail"]["cc_fqdn"].split("::")[-1] in graph_cc_nodes
177
+ ]
178
+
179
+ if not cc_completions:
180
+ # No CC nodes executed — IN_ gated as NACK and routed to EXIT
181
+ to_node = edge_map.get((entry_node, "NACK"), "EXIT")
182
+ return [(entry_node, "NACK", to_node)]
183
+
184
+ path: list[tuple[str, str, str]] = []
185
+
186
+ # IN_ → first CC: always ACK (admission passes through in current runtime)
187
+ first_cc_code = cc_completions[0]["detail"]["cc_fqdn"].split("::")[-1]
188
+ path.append((entry_node, "ACK", first_cc_code))
189
+
190
+ # CC → CC (or EXIT) — follow result_status routing
191
+ for cc_event in cc_completions:
192
+ cc_code = cc_event["detail"]["cc_fqdn"].split("::")[-1]
193
+ result_status = cc_event["result_status"]
194
+ to_node = edge_map.get((cc_code, result_status))
195
+ if to_node is None:
196
+ break # no further routing — terminal
197
+ path.append((cc_code, result_status, to_node))
198
+
199
+ return path
200
+
201
+
202
+ # ---------------------------------------------------------------------------
203
+ # DOT generation
204
+ # ---------------------------------------------------------------------------
205
+
206
+ def _generate_dot(
207
+ graph: dict,
208
+ visited_nodes: set[str],
209
+ taken_edges: set[tuple[str, str, str]],
210
+ ) -> str:
211
+ """
212
+ Generate Graphviz DOT with actual execution path highlighted in red.
213
+
214
+ Visited nodes: red border + solid red fill.
215
+ Taken edges: red, bold, red label.
216
+ Unvisited: standard fill, grey border, grey edges.
217
+ """
218
+ lines = [
219
+ f'digraph "{graph["wf_id"]}" {{',
220
+ " rankdir=LR;",
221
+ ' node [fontname="Arial"];',
222
+ "",
223
+ ]
224
+
225
+ # --- Nodes ---
226
+ for node in graph["nodes"]:
227
+ node_id = node["id"]
228
+ node_type = node["type"]
229
+ visited = node_id in visited_nodes
230
+
231
+ if node_type == "IN":
232
+ fill = "tomato" if visited else "lightblue"
233
+ shape = "ellipse"
234
+ elif node_type == "CC":
235
+ fill = "tomato" if visited else "lightgreen"
236
+ shape = "box"
237
+ elif node_type == "EXIT":
238
+ fill = "tomato" if visited else "lightcoral"
239
+ shape = "ellipse"
240
+ else:
241
+ fill = "white"
242
+ shape = "box"
243
+
244
+ if visited:
245
+ lines.append(
246
+ f' "{node_id}" [label="{node_id}", shape={shape},'
247
+ f" style=filled, fillcolor={fill}, color=red, penwidth=2.5];"
248
+ )
249
+ else:
250
+ lines.append(
251
+ f' "{node_id}" [label="{node_id}", shape={shape},'
252
+ f" style=filled, fillcolor={fill}, color=gray];"
253
+ )
254
+
255
+ lines.append("")
256
+
257
+ # --- Edges ---
258
+ for edge in graph["edges"]:
259
+ from_id = edge["from"]
260
+ to_id = edge["to"]
261
+ condition = edge["condition"]
262
+ taken = (from_id, to_id, condition) in taken_edges
263
+
264
+ if taken:
265
+ lines.append(
266
+ f' "{from_id}" -> "{to_id}"'
267
+ f' [label="{condition}", color=red, penwidth=2.5, fontcolor=red];'
268
+ )
269
+ else:
270
+ lines.append(
271
+ f' "{from_id}" -> "{to_id}"'
272
+ f' [label="{condition}", color=gray, fontcolor=gray];'
273
+ )
274
+
275
+ lines.append("}")
276
+ return "\n".join(lines)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pgs_runtime
3
- Version: 0.3.1
3
+ Version: 0.5.0
4
4
  Summary: PGS runtime for Protocol-Governed Systems
5
5
  Author: Bachi
6
6
  License-Expression: Apache-2.0
@@ -29,7 +29,7 @@ It does not discover behavior. It does not interpret intent. It does not contain
29
29
 
30
30
  Behavior is declared in protocol, executed by runtime, implemented in capabilities, and observed via traces and state.
31
31
 
32
- > **New to PGS?** This is one of eight repositories in the Protocol-Governed Systems ecosystem.
32
+ > **New to PGS?** This is one of the repositories in the Protocol-Governed Systems ecosystem.
33
33
  > For orientation, architecture overview, and end-to-end execution, start at [pgs_workspace](https://github.com/bachipeachy/pgs_workspace).
34
34
 
35
35
  ---
@@ -15,6 +15,7 @@ pgs_runtime/loader.py
15
15
  pgs_runtime/memory.py
16
16
  pgs_runtime/scheduler.py
17
17
  pgs_runtime/server.py
18
+ pgs_runtime/trace_viz.py
18
19
  pgs_runtime.egg-info/PKG-INFO
19
20
  pgs_runtime.egg-info/SOURCES.txt
20
21
  pgs_runtime.egg-info/dependency_links.txt
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pgs_runtime"
7
- version = "0.3.1"
7
+ version = "0.5.0"
8
8
  description = "PGS runtime for Protocol-Governed Systems"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
File without changes
File without changes
File without changes
File without changes