cortexhub 0.5.4__tar.gz → 0.5.6__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 (63) hide show
  1. {cortexhub-0.5.4 → cortexhub-0.5.6}/PKG-INFO +1 -1
  2. {cortexhub-0.5.4 → cortexhub-0.5.6}/pyproject.toml +1 -1
  3. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/backend/client.py +13 -0
  4. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/client.py +168 -33
  5. cortexhub-0.5.6/src/cortexhub/policy/absence.py +78 -0
  6. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/policy/effects.py +10 -0
  7. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/policy/evaluator.py +106 -34
  8. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/tool.py +10 -0
  9. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/version.py +1 -1
  10. {cortexhub-0.5.4 → cortexhub-0.5.6}/.gitignore +0 -0
  11. {cortexhub-0.5.4 → cortexhub-0.5.6}/LICENSE +0 -0
  12. {cortexhub-0.5.4 → cortexhub-0.5.6}/README.md +0 -0
  13. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/__init__.py +0 -0
  14. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/audit/__init__.py +0 -0
  15. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/audit/events.py +0 -0
  16. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/backend/__init__.py +0 -0
  17. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/config.py +0 -0
  18. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/constants.py +0 -0
  19. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/context/__init__.py +0 -0
  20. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/context/enricher.py +0 -0
  21. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/errors.py +0 -0
  22. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/__init__.py +0 -0
  23. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/injection.py +0 -0
  24. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/__init__.py +0 -0
  25. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/LICENSE +0 -0
  26. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/LICENSES_SOURCES +0 -0
  27. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/README.md +0 -0
  28. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/accuracy.json +0 -0
  29. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/attribute_ruler/patterns +0 -0
  30. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/config.cfg +0 -0
  31. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/lemmatizer/lookups/lookups.bin +0 -0
  32. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/meta.json +0 -0
  33. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/cfg +0 -0
  34. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/model +0 -0
  35. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/moves +0 -0
  36. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/cfg +0 -0
  37. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/model +0 -0
  38. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/moves +0 -0
  39. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/senter/cfg +0 -0
  40. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/senter/model +0 -0
  41. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tagger/cfg +0 -0
  42. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tagger/model +0 -0
  43. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tok2vec/cfg +0 -0
  44. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tok2vec/model +0 -0
  45. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tokenizer +0 -0
  46. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/key2row +0 -0
  47. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/lookups.bin +0 -0
  48. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/strings.json +0 -0
  49. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/vectors +0 -0
  50. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/vectors.cfg +0 -0
  51. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/models/en_core_web_sm/meta.json +0 -0
  52. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/pii.py +0 -0
  53. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/guardrails/secrets.py +0 -0
  54. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/interceptors/__init__.py +0 -0
  55. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/interceptors/mcp.py +0 -0
  56. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/logging.py +0 -0
  57. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/policy/__init__.py +0 -0
  58. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/policy/loader.py +0 -0
  59. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/policy/models.py +0 -0
  60. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/policy/sync.py +0 -0
  61. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/signing.py +0 -0
  62. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/telemetry/__init__.py +0 -0
  63. {cortexhub-0.5.4 → cortexhub-0.5.6}/src/cortexhub/telemetry/otel.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cortexhub
3
- Version: 0.5.4
3
+ Version: 0.5.6
4
4
  Summary: CortexHub Python SDK — Runtime governance for AI systems. One decorator, any tool, any framework.
5
5
  Project-URL: Homepage, https://cortexhub.ai
6
6
  Project-URL: Documentation, https://docs.cortexhub.ai
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cortexhub"
3
- version = "0.5.4"
3
+ version = "0.5.6"
4
4
  description = "CortexHub Python SDK — Runtime governance for AI systems. One decorator, any tool, any framework."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10,<3.13"
@@ -94,6 +94,14 @@ class PolicyBundle:
94
94
  guardrail_version: str = "0"
95
95
  privacy_mode: str = "on"
96
96
 
97
+ # Enforcement mode on the governed agent — ``observe`` or
98
+ # ``enforce``. Read by the SDK evaluator to decide whether to
99
+ # apply the Observe dry-run overlay (permit decisions that
100
+ # would have blocked in Enforce mode). Shipped fresh on every
101
+ # ``/policies/bundle`` sync. Defaults to ``observe`` for back-
102
+ # compat with pre-0.5.5 control planes.
103
+ enforcement_mode: str = "observe"
104
+
97
105
 
98
106
  @dataclass
99
107
  class SDKConfig:
@@ -358,6 +366,11 @@ class BackendClient:
358
366
  default_behavior=policies_data.get("default_behavior", "allow_and_log"),
359
367
  guardrail_version=policies_data.get("guardrail_version", "0"),
360
368
  privacy_mode=_privacy,
369
+ enforcement_mode=(
370
+ policies_data.get("enforcement_mode")
371
+ or data.get("enforcement_mode")
372
+ or "observe"
373
+ ),
361
374
  )
362
375
  logger.debug("Validate response privacy_mode", privacy_mode=_privacy)
363
376
 
@@ -83,6 +83,19 @@ from cortexhub.version import __version__
83
83
 
84
84
  logger = structlog.get_logger(__name__)
85
85
 
86
+ # Tool classification — the one governance signal the developer is
87
+ # required to declare. Describes what kind of action the tool performs
88
+ # (read / write / destructive). Combined with the agent's enforcement
89
+ # mode (``observe`` / ``enforce``), this drives the whole platform's
90
+ # default-deny posture on destructive tools and the Tool Inventory
91
+ # badges. Required on every ``@cx.tool``.
92
+ #
93
+ # We deliberately do NOT model a ``risk`` dimension. Classification +
94
+ # explicit policies is enough to express every governance posture the
95
+ # product supports. Adding a risk lever would create overlapping
96
+ # defaults that make policy authoring harder without adding capability.
97
+ _VALID_CLASSIFICATIONS: set[str] = {"read", "write", "destructive"}
98
+
86
99
 
87
100
  def _flatten_exception_for_log(exc: BaseException) -> str:
88
101
  """Readable one-line-ish message; expands ExceptionGroup on 3.11+ (e.g. MCP httpx TaskGroup)."""
@@ -1322,6 +1335,7 @@ class CortexHub:
1322
1335
  parameters_schema: dict[str, Any] | None = None,
1323
1336
  principal: Principal | dict[str, str] | None = None,
1324
1337
  resource_type: str = "Tool",
1338
+ classification: str | None = None,
1325
1339
  ) -> Any:
1326
1340
  """Execute a tool with full governance pipeline.
1327
1341
 
@@ -1449,6 +1463,16 @@ class CortexHub:
1449
1463
  span.set_attribute("cortexhub.tool.name", tool_name)
1450
1464
  span.set_attribute("cortexhub.tool.framework", framework)
1451
1465
  span.set_attribute("cortexhub.tool.governed", _this_tool_governed)
1466
+ # Classification declared on the @cx.tool decorator.
1467
+ # Emitted on every tool.invoke so the backend's ToolInventory
1468
+ # row can be populated / refreshed on first invocation. The
1469
+ # decorator validates this is set + valid, so it's always
1470
+ # present on SDK-originated spans.
1471
+ if classification:
1472
+ span.set_attribute("cortexhub.tool.classification", classification)
1473
+ span.set_attribute(
1474
+ "cortexhub.tool.classification_source", "sdk_decorator"
1475
+ )
1452
1476
  # Per-tool governance mode — matches the MCP gateway emitter.
1453
1477
  # The ingest path uses this to decide whether to write an
1454
1478
  # EnforcementDecisionDocument.
@@ -1743,6 +1767,18 @@ class CortexHub:
1743
1767
  )
1744
1768
  span.set_attribute("cortexhub.policy.decision", decision.effect.value)
1745
1769
 
1770
+ # Observe-mode dry-run audit. When the evaluator
1771
+ # rewrote a blocking decision to PERMIT under
1772
+ # Observe, would_have_effect carries the original
1773
+ # outcome. Surface it on the span so the Decisions
1774
+ # page can show "permitted this time, but your
1775
+ # policy would have denied under Enforce".
1776
+ if decision and getattr(decision, "would_have_effect", None):
1777
+ span.set_attribute(
1778
+ "cortexhub.policy.would_have_effect",
1779
+ decision.would_have_effect,
1780
+ )
1781
+
1746
1782
  # MODIFY and DEFER must not silently fall through to
1747
1783
  # ``call_original()``. The in‑process closure already
1748
1784
  # captured the original args, so we can't safely rewrite
@@ -1898,6 +1934,20 @@ class CortexHub:
1898
1934
  _this_tool_governed_a = bool(
1899
1935
  _tool_policies_a and isinstance(_tool_policies_a, dict) and tool_name in _tool_policies_a
1900
1936
  )
1937
+ # Async interceptor path (e.g. MCP client wrapper) doesn't
1938
+ # receive a ``classification`` kwarg — the caller is a runtime
1939
+ # interceptor, not a decorator. Look up the classification from
1940
+ # the bundle's ``tool_classifications`` map instead so the span
1941
+ # still carries the same attribute the sync path emits. Fall
1942
+ # back to ``None`` (attribute omitted) if unknown.
1943
+ _classification_a: str | None = None
1944
+ _tool_classifications_a = (
1945
+ getattr(_tp_a, "tool_classifications", None) if _tp_a else None
1946
+ )
1947
+ if isinstance(_tool_classifications_a, dict):
1948
+ _cls_entry = _tool_classifications_a.get(tool_name)
1949
+ if isinstance(_cls_entry, dict):
1950
+ _classification_a = _cls_entry.get("bucket")
1901
1951
 
1902
1952
  # Step 3: Create tool.invoke span
1903
1953
  with self._tracer.start_as_current_span(
@@ -1909,6 +1959,24 @@ class CortexHub:
1909
1959
  span.set_attribute("cortexhub.tool.name", tool_name)
1910
1960
  span.set_attribute("cortexhub.tool.framework", framework)
1911
1961
  span.set_attribute("cortexhub.tool.governed", _this_tool_governed_a)
1962
+ # Parity with the sync path: emit the tool classification
1963
+ # (looked up from the bundle on the async/interceptor path
1964
+ # because the caller is a runtime interceptor, not a
1965
+ # decorator) and its source on every span. Without this,
1966
+ # async-executed tools were silently missing the data the
1967
+ # backend uses to populate ``ToolInventory`` and the Type
1968
+ # badge in the UI.
1969
+ if _classification_a:
1970
+ span.set_attribute(
1971
+ "cortexhub.tool.classification", _classification_a
1972
+ )
1973
+ # On this path the classification came from the bundle
1974
+ # (i.e. whatever was decided on the server — connector
1975
+ # classifier, operator override, or an earlier SDK
1976
+ # span). Label the source accordingly.
1977
+ span.set_attribute(
1978
+ "cortexhub.tool.classification_source", "policy_bundle"
1979
+ )
1912
1980
  # Per-tool governance mode + default decision — see the sync
1913
1981
  # path for the full rationale. Keeps both execution paths
1914
1982
  # emitting the same shape so the ingest pipeline is path-agnostic.
@@ -2166,6 +2234,18 @@ class CortexHub:
2166
2234
  )
2167
2235
  span.set_attribute("cortexhub.policy.decision", decision.effect.value)
2168
2236
 
2237
+ # Observe-mode dry-run audit. When the evaluator
2238
+ # rewrote a blocking decision to PERMIT under
2239
+ # Observe, would_have_effect carries the original
2240
+ # outcome. Surface it on the span so the Decisions
2241
+ # page can show "permitted this time, but your
2242
+ # policy would have denied under Enforce".
2243
+ if decision and getattr(decision, "would_have_effect", None):
2244
+ span.set_attribute(
2245
+ "cortexhub.policy.would_have_effect",
2246
+ decision.would_have_effect,
2247
+ )
2248
+
2169
2249
  # MODIFY / DEFER handling — see the sync path for rationale.
2170
2250
  if decision and decision.effect in (Effect.MODIFY, Effect.DEFER):
2171
2251
  span.add_event(
@@ -3457,63 +3537,118 @@ class CortexHub:
3457
3537
  self,
3458
3538
  func: Any = None,
3459
3539
  *,
3540
+ classification: str | None = None,
3460
3541
  name: str | None = None,
3461
3542
  description: str | None = None,
3462
3543
  requires: list[str] | None = None,
3463
3544
  ) -> Any:
3464
- """Decorator that wraps any callable with CortexHub governance.
3545
+ """Wrap a callable with CortexHub governance.
3465
3546
 
3466
- Basic usage — wraps any function::
3547
+ ``classification`` is **required** — it's the one governance
3548
+ signal the developer declares. Combined with the agent's
3549
+ enforcement mode, it's enough to express the full posture:
3467
3550
 
3468
- @cx.tool
3469
- def prescribe_medication(patient_id: str, medication: str, dosage: str) -> str:
3470
- \"\"\"Prescribe medication to a patient.\"\"\"
3471
- return db.prescribe(patient_id, medication, dosage)
3551
+ * ``"read"`` — inspects data, no side effects.
3552
+ * ``"write"`` — creates or modifies state, reversible.
3553
+ * ``"destructive"`` — irreversible: deletes, refunds,
3554
+ terminates. In Enforce mode,
3555
+ destructive tools without an explicit
3556
+ policy deny by default. In Observe
3557
+ mode, they run but their dry-run
3558
+ evaluation is recorded.
3472
3559
 
3473
- With prerequisite tools — the named tools must have executed successfully
3474
- in the current session before this tool is allowed to run. If they
3475
- haven't, a ``PolicyViolationError`` is raised immediately with clear
3476
- feedback so the LLM can self-correct::
3560
+ Minimal usage::
3477
3561
 
3478
- @cx.tool
3479
- def lookup_patient(patient_id: str) -> dict:
3480
- \"\"\"Look up a patient record.\"\"\"
3481
- ...
3562
+ @cx.tool(classification="read")
3563
+ def get_my_reservation() -> dict: ...
3482
3564
 
3483
- @cx.tool(requires=["lookup_patient"])
3484
- def prescribe_medication(patient_id: str, medication: str, dosage: str) -> str:
3485
- \"\"\"Prescribe medication — requires lookup_patient first.\"\"\"
3486
- ...
3565
+ @cx.tool(classification="write")
3566
+ def modify_reservation(...): ...
3487
3567
 
3488
- With name/description overrides::
3568
+ @cx.tool(classification="destructive")
3569
+ def delete_reservation(...): ...
3489
3570
 
3490
- @cx.tool(name="prescribe", description="Prescribe medication to a patient")
3571
+ Prerequisite tools (must have executed this session first)::
3572
+
3573
+ @cx.tool(classification="read")
3574
+ def lookup_patient(...): ...
3575
+
3576
+ @cx.tool(classification="write", requires=["lookup_patient"])
3491
3577
  def prescribe_medication(...): ...
3492
3578
 
3493
3579
  Args:
3494
- name: Override the tool name used in policies and telemetry.
3495
- description: Override the description (defaults to the docstring).
3496
- requires: List of tool names that must have been called successfully
3497
- in the current session before this tool can execute.
3498
- Also exposed to policies as ``context.run.called_tools``
3499
- so operators can enforce the same rules from the
3500
- control plane without changing code.
3580
+ classification: **Required.** ``"read"`` | ``"write"`` |
3581
+ ``"destructive"``. Drives the default-deny
3582
+ posture on destructive actions and the
3583
+ Tool Inventory badges.
3584
+ name: Override the tool name used in policies
3585
+ and telemetry. Defaults to function name.
3586
+ description: Override the description (defaults to
3587
+ docstring).
3588
+ requires: Tool names that must have been called
3589
+ successfully earlier in this session.
3590
+ Exposed to policies as
3591
+ ``context.run.called_tools``.
3501
3592
 
3502
3593
  Returns:
3503
- GovernedTool — callable, duck-type compatible with LangGraph
3504
- ToolNode and LangChain bind_tools. Zero framework imports.
3594
+ GovernedTool — duck-type compatible with LangGraph
3595
+ ToolNode and LangChain bind_tools.
3596
+
3597
+ Raises:
3598
+ ValueError: If ``classification`` is missing or invalid.
3599
+ Raised at import time so the error surfaces
3600
+ before first call.
3505
3601
  """
3506
3602
  from cortexhub.tool import GovernedTool
3507
3603
 
3508
3604
  def decorator(fn: Any) -> "GovernedTool":
3509
- return GovernedTool(fn, cx=self, name=name, description=description, requires=requires)
3605
+ self._validate_tool_classification(
3606
+ fn_name=getattr(fn, "__name__", "<anonymous>"),
3607
+ classification=classification,
3608
+ )
3609
+ return GovernedTool(
3610
+ fn,
3611
+ cx=self,
3612
+ name=name,
3613
+ description=description,
3614
+ requires=requires,
3615
+ classification=classification,
3616
+ )
3510
3617
 
3511
3618
  if func is not None:
3512
- # Called as @cx.tool (no parentheses)
3513
- return decorator(func)
3514
- # Called as @cx.tool(...) — return the decorator
3619
+ raise ValueError(
3620
+ f"@cx.tool requires a classification. Change "
3621
+ f"``@cx.tool`` above '{getattr(func, '__name__', 'tool')}' "
3622
+ f"to ``@cx.tool(classification=\"read\" | \"write\" | "
3623
+ f"\"destructive\")``. See cx.tool docstring for guidance."
3624
+ )
3515
3625
  return decorator
3516
3626
 
3627
+ def _validate_tool_classification(
3628
+ self,
3629
+ *,
3630
+ fn_name: str,
3631
+ classification: str | None,
3632
+ ) -> None:
3633
+ """Fail fast on missing/invalid classification — at import time,
3634
+ so a bad deploy never reaches first call. Error messages name
3635
+ the offending function so the fix is one line, no stack-diving."""
3636
+ if classification is None:
3637
+ raise ValueError(
3638
+ f"@cx.tool on '{fn_name}' is missing ``classification=``. "
3639
+ "Declare one of ``\"read\"`` (inspects data, no side "
3640
+ "effects), ``\"write\"`` (mutates, reversible), or "
3641
+ "``\"destructive\"`` (irreversible: deletes, refunds, "
3642
+ "terminates). The platform uses this for enforcement "
3643
+ "decisions and Tool Inventory badges; it is not optional."
3644
+ )
3645
+ if classification not in _VALID_CLASSIFICATIONS:
3646
+ raise ValueError(
3647
+ f"@cx.tool on '{fn_name}' has classification "
3648
+ f"{classification!r}; must be one of "
3649
+ f"{sorted(_VALID_CLASSIFICATIONS)!r}."
3650
+ )
3651
+
3517
3652
  def enforce(self, tool_name: str, args: dict[str, Any]) -> None:
3518
3653
  """Policy gate for code you don't own (third-party calls, APIs, DB writes).
3519
3654
 
@@ -0,0 +1,78 @@
1
+ """Shared policy-absence resolver — Observe / Enforce posture.
2
+
3
+ Mirror of ``backend/app/services/governance_resolver.py``. Kept in
4
+ lock-step: a parity test asserts byte-identical output across every
5
+ (mode, classification) combination. If you change one file without
6
+ the other, CI goes red.
7
+
8
+ See the backend file for the full contract and rationale. Summary:
9
+
10
+ * Observe mode → permit everything (dry-run policies upstream).
11
+ * Enforce mode + destructive + no policy → deny.
12
+ * Enforce mode + read/write/unknown + no policy → permit.
13
+ * Error paths deny before this runs — safety, not posture.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+ from typing import Literal
20
+
21
+
22
+ Effect = Literal["permit", "deny"]
23
+ DecisionReason = Literal[
24
+ "observe_mode_permit",
25
+ "enforce_mode_destructive_hard_gate",
26
+ "enforce_mode_permit",
27
+ ]
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class PolicyAbsenceDecision:
32
+ effect: Effect
33
+ reason: DecisionReason
34
+ reasoning: str
35
+
36
+
37
+ def resolve_policy_absence_decision(
38
+ *,
39
+ enforcement_mode: str | None,
40
+ effective_classification: str | None,
41
+ tool_name: str,
42
+ ) -> PolicyAbsenceDecision:
43
+ """Same contract as the backend helper. Keep the two in sync."""
44
+ mode = "enforce" if enforcement_mode == "enforce" else "observe"
45
+ classification = effective_classification or "write"
46
+
47
+ if mode == "observe":
48
+ return PolicyAbsenceDecision(
49
+ effect="permit",
50
+ reason="observe_mode_permit",
51
+ reasoning=(
52
+ f"Tool '{tool_name}' ran in Observe mode. Policies "
53
+ "are evaluated as dry-runs only; nothing is blocked. "
54
+ "Switch the agent to Enforce mode to act on policies."
55
+ ),
56
+ )
57
+
58
+ if classification == "destructive":
59
+ return PolicyAbsenceDecision(
60
+ effect="deny",
61
+ reason="enforce_mode_destructive_hard_gate",
62
+ reasoning=(
63
+ f"Tool '{tool_name}' is classified as destructive and has "
64
+ "no active policy. In Enforce mode, destructive actions "
65
+ "require an explicit policy (permit, step_up, or modify) "
66
+ "before they run."
67
+ ),
68
+ )
69
+
70
+ return PolicyAbsenceDecision(
71
+ effect="permit",
72
+ reason="enforce_mode_permit",
73
+ reasoning=(
74
+ f"Tool '{tool_name}' has no active policy and is classified "
75
+ f"as {classification}; permitted under Enforce mode. Author "
76
+ "a policy to tighten, or rely on the default permit-and-log."
77
+ ),
78
+ )
@@ -32,6 +32,14 @@ class Decision(BaseModel):
32
32
  policy_timeout_behavior: str | None = None
33
33
  modified_args: dict[str, object] | None = None
34
34
 
35
+ # Observe-mode dry-run: the effect this decision *would* have been
36
+ # in Enforce mode. Populated by the evaluator's mode overlay when
37
+ # Observe rewrote a blocking outcome to PERMIT for audit-only
38
+ # purposes. Written to the span attribute
39
+ # ``cortexhub.policy.would_have_effect`` so operators can evaluate
40
+ # their policy set against real traffic before flipping Enforce.
41
+ would_have_effect: str | None = None
42
+
35
43
  def is_permitted(self) -> bool:
36
44
  return self.effect == Effect.PERMIT
37
45
 
@@ -55,6 +63,7 @@ class Decision(BaseModel):
55
63
  policy_name: str | None = None,
56
64
  policy_effect: str | None = None,
57
65
  policy_decisions: list[dict[str, str | None]] | None = None,
66
+ would_have_effect: str | None = None,
58
67
  ) -> "Decision":
59
68
  return cls(
60
69
  effect=Effect.PERMIT,
@@ -63,6 +72,7 @@ class Decision(BaseModel):
63
72
  policy_name=policy_name,
64
73
  policy_effect=policy_effect,
65
74
  policy_decisions=policy_decisions,
75
+ would_have_effect=would_have_effect,
66
76
  )
67
77
 
68
78
  @classmethod
@@ -25,7 +25,7 @@ except Exception as exc:
25
25
  policies_dir="backend",
26
26
  ) from exc
27
27
 
28
- from cortexhub.policy.effects import Decision
28
+ from cortexhub.policy.effects import Decision, Effect
29
29
  from cortexhub.policy.loader import PolicyBundle
30
30
  from cortexhub.policy.models import AuthorizationRequest
31
31
 
@@ -80,6 +80,36 @@ class PolicyEvaluator:
80
80
  try:
81
81
  decision = self._evaluate_cedar(request)
82
82
 
83
+ # Observe-mode dry-run overlay.
84
+ #
85
+ # In Observe mode, agents are watching — nothing is blocked
86
+ # at the point of execution. But we still want the audit
87
+ # signal: "this tool call *would* have been denied by
88
+ # policy X if we were enforcing." We rewrite the decision
89
+ # so ``effect`` is PERMIT (tool runs) while
90
+ # ``would_have_effect`` and ``would_have_policy_id`` carry
91
+ # what Enforce mode would have produced. The tool-span
92
+ # emitter writes these onto the audit trail.
93
+ #
94
+ # ``_evaluate_cedar`` itself is mode-agnostic — it always
95
+ # computes the real Enforce-mode decision. This layer is
96
+ # the ONE place the SDK reasons about mode, which keeps
97
+ # the implementation auditable and makes dry-run correct
98
+ # by construction.
99
+ if self._enforcement_mode() != "enforce" and decision.effect != Effect.PERMIT:
100
+ decision = Decision.permit(
101
+ reasoning=(
102
+ f"Observe mode dry-run — policy would have "
103
+ f"{decision.effect.value} "
104
+ f"({decision.reasoning})"
105
+ ),
106
+ policy_id=decision.policy_id,
107
+ policy_name=decision.policy_name,
108
+ policy_effect=decision.policy_effect,
109
+ policy_decisions=decision.policy_decisions,
110
+ would_have_effect=decision.effect.value,
111
+ )
112
+
83
113
  latency_ms = (time.perf_counter() - start_time) * 1000
84
114
  policy_label = decision.policy_name or decision.policy_id or "default"
85
115
  _cedar_debug = os.getenv("CORTEXHUB_CEDAR_DEBUG", "").lower() in ("1", "true", "yes")
@@ -116,32 +146,78 @@ class PolicyEvaluator:
116
146
  return Decision.deny(f"Policy evaluation error: {e}")
117
147
 
118
148
  def _default_behavior_decision(self, request: AuthorizationRequest) -> Decision:
119
- """Return decision when no policies apply (tool not in bundle or engine NoDecision)."""
120
- tool_name = getattr(request.action, "name", None) or request.resource.id
121
- if self.default_behavior == "allow_and_log":
149
+ """Decide the outcome when no active policy matched this tool call.
150
+
151
+ Routes through ``resolve_policy_absence_decision`` — the same
152
+ helper the backend uses — so SDK, Studio, and MCP gateway all
153
+ produce identical outcomes for the same request.
154
+
155
+ Semantics (0.5.5):
156
+ * Observe mode: permit. Agent is watching, not enforcing.
157
+ * Enforce mode + destructive tool: deny (hard gate).
158
+ * Enforce mode + everything else: permit.
159
+
160
+ Error paths (engine unavailable, Cedar raised) deny before we
161
+ reach this function — see the outer ``evaluate`` try/except.
162
+ """
163
+ from cortexhub.policy.absence import resolve_policy_absence_decision
164
+
165
+ # For ``tool.invoke`` the action name is the verb ("tool.invoke")
166
+ # and the *tool identity* is on the resource (e.g. "delete_user").
167
+ # ``tool_classifications`` is keyed by the resource id in the
168
+ # bundle, so prefer resource.id and only fall back to the action
169
+ # for non-tool.invoke actions (reserved for future action types).
170
+ tool_name = request.resource.id or getattr(request.action, "name", None) or "unknown"
171
+ absence = resolve_policy_absence_decision(
172
+ enforcement_mode=self._enforcement_mode(),
173
+ effective_classification=self._tool_classification(tool_name),
174
+ tool_name=tool_name,
175
+ )
176
+ if absence.effect == "permit":
122
177
  return Decision.permit(
123
- f"Tool '{tool_name}' permitted by default behavior",
124
- policy_id="default",
125
- policy_decisions=[],
126
- )
127
- if self.default_behavior == "deny_and_log":
128
- return Decision.deny(
129
- f"Tool '{tool_name}' denied by default behavior (no matching policy)",
130
- policy_id="default",
131
- policy_decisions=[],
132
- )
133
- if self.default_behavior == "escalate":
134
- return Decision.step_up(
135
- f"Tool '{tool_name}' requires approval (unknown tool)",
136
- policy_id="default",
178
+ absence.reasoning,
179
+ policy_id="ungoverned",
137
180
  policy_decisions=[],
138
181
  )
139
182
  return Decision.deny(
140
- "Invalid default behavior configuration",
141
- policy_id="error",
183
+ absence.reasoning,
184
+ policy_id="hard_gate",
142
185
  policy_decisions=[],
143
186
  )
144
187
 
188
+ def _enforcement_mode(self) -> str | None:
189
+ """Pull the agent's ``enforcement_mode`` from the bundle.
190
+
191
+ Shipped on every ``/policies/bundle`` sync (see backend
192
+ ``PolicyBundleResponse.enforcement_mode``). The SDK's
193
+ ``backend.client.PolicyBundle`` dataclass exposes it as a
194
+ direct attribute. Back-compat: when the attribute is missing
195
+ (pre-0.5.5 bundle cached locally) or the value is empty, the
196
+ resolver treats it as Observe.
197
+ """
198
+ mode = getattr(self.policy_bundle, "enforcement_mode", None)
199
+ if isinstance(mode, str) and mode:
200
+ return mode
201
+ # Back-compat fallback: some ``PolicyBundle`` variants keep
202
+ # the mode in ``metadata`` — check there too.
203
+ meta = getattr(self.policy_bundle, "metadata", None)
204
+ if isinstance(meta, dict):
205
+ fallback = meta.get("enforcement_mode")
206
+ if isinstance(fallback, str) and fallback:
207
+ return fallback
208
+ return None
209
+
210
+ def _tool_classification(self, tool_name: str) -> str | None:
211
+ classifications = (
212
+ getattr(self.policy_bundle, "tool_classifications", None) or {}
213
+ )
214
+ bundle_cls = (
215
+ classifications.get(tool_name)
216
+ if isinstance(classifications, dict)
217
+ else None
218
+ )
219
+ return bundle_cls.get("bucket") if isinstance(bundle_cls, dict) else None
220
+
145
221
  def _evaluate_cedar(self, request: AuthorizationRequest) -> Decision:
146
222
  """Evaluate using the bundled in-process policy engine.
147
223
 
@@ -178,23 +254,19 @@ class PolicyEvaluator:
178
254
  entry = candidate
179
255
 
180
256
  if tool_policies or bucket_policies:
181
- # Per-tool / bucket mode — evaluate the resolved entry, or fall
182
- # through to ungoverned if nothing matched.
183
- if entry is None:
184
- return Decision.permit(
185
- f"No active policy for tool '{tool_name}' (ungoverned)",
186
- policy_id="ungoverned",
187
- policy_decisions=[],
188
- )
257
+ # Per-tool / bucket mode — evaluate the resolved entry, or
258
+ # route through the shared absence resolver if nothing
259
+ # matched. Before 0.5.5+fix, this branch returned an
260
+ # unconditional ``permit`` which meant Enforce + destructive
261
+ # + no-policy-for-this-tool got a silent permit on the SDK
262
+ # while the gateway denied — a CVE-class divergence. Route
263
+ # through ``_default_behavior_decision`` so both runtimes
264
+ # honour the hard gate identically.
265
+ if entry is None or not (entry.get("cedar") or ""):
266
+ return self._default_behavior_decision(request)
189
267
  cedar = entry.get("cedar") or ""
190
268
  schema = entry.get("schema") if isinstance(entry.get("schema"), dict) else None
191
269
  policy_map = entry.get("policy_metadata") or {}
192
- if not cedar:
193
- return Decision.permit(
194
- f"No active policy for tool '{tool_name}' (ungoverned)",
195
- policy_id="ungoverned",
196
- policy_decisions=[],
197
- )
198
270
  else:
199
271
  cedar = self.policy_bundle.policies
200
272
  schema = None
@@ -101,6 +101,7 @@ class GovernedTool:
101
101
  name: str | None = None,
102
102
  description: str | None = None,
103
103
  requires: list[str] | None = None,
104
+ classification: str | None = None,
104
105
  ) -> None:
105
106
  self._fn = fn
106
107
  self._cx = cx
@@ -110,6 +111,13 @@ class GovernedTool:
110
111
  # this tool is allowed to execute.
111
112
  self.requires: list[str] = requires or []
112
113
 
114
+ # Classification — the developer's declaration of what the tool
115
+ # does. Validated by ``CortexHub.tool`` before we get here, so
116
+ # it's always one of ``read`` / ``write`` / ``destructive``.
117
+ # Rides on every ``tool.invoke`` span so the backend's
118
+ # ``ToolInventory`` row picks it up on first invocation.
119
+ self.classification = classification
120
+
113
121
  # Public attributes — duck-type LangChain/LangGraph tool interface
114
122
  self.name = name or fn.__name__
115
123
  self.description = description or (inspect.cleandoc(fn.__doc__ or "")).strip()
@@ -191,6 +199,7 @@ class GovernedTool:
191
199
  if self.args_schema is not None
192
200
  else None
193
201
  ),
202
+ classification=self.classification,
194
203
  )
195
204
  # Record successful execution so subsequent tools can use this as evidence
196
205
  self._cx._register_tool_called(self.name)
@@ -214,6 +223,7 @@ class GovernedTool:
214
223
  if self.args_schema is not None
215
224
  else None
216
225
  ),
226
+ classification=self.classification,
217
227
  )
218
228
  # If the underlying function is async, execute_governed_tool returns
219
229
  # a coroutine from the lambda; await it here.
@@ -12,7 +12,7 @@ incorrectly in those environments.
12
12
 
13
13
  from importlib.metadata import PackageNotFoundError, version
14
14
 
15
- __fallback_version__ = "0.5.3"
15
+ __fallback_version__ = "0.5.6"
16
16
 
17
17
 
18
18
  def _resolve_version() -> str:
File without changes
File without changes
File without changes