cortexhub 0.5.3__tar.gz → 0.5.5__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.3 → cortexhub-0.5.5}/PKG-INFO +1 -1
  2. {cortexhub-0.5.3 → cortexhub-0.5.5}/pyproject.toml +1 -1
  3. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/backend/client.py +13 -0
  4. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/client.py +112 -33
  5. cortexhub-0.5.5/src/cortexhub/policy/absence.py +78 -0
  6. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/policy/effects.py +10 -0
  7. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/policy/evaluator.py +149 -20
  8. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/tool.py +10 -0
  9. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/version.py +1 -1
  10. {cortexhub-0.5.3 → cortexhub-0.5.5}/.gitignore +0 -0
  11. {cortexhub-0.5.3 → cortexhub-0.5.5}/LICENSE +0 -0
  12. {cortexhub-0.5.3 → cortexhub-0.5.5}/README.md +0 -0
  13. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/__init__.py +0 -0
  14. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/audit/__init__.py +0 -0
  15. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/audit/events.py +0 -0
  16. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/backend/__init__.py +0 -0
  17. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/config.py +0 -0
  18. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/constants.py +0 -0
  19. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/context/__init__.py +0 -0
  20. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/context/enricher.py +0 -0
  21. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/errors.py +0 -0
  22. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/__init__.py +0 -0
  23. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/injection.py +0 -0
  24. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/__init__.py +0 -0
  25. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/LICENSE +0 -0
  26. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/LICENSES_SOURCES +0 -0
  27. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/README.md +0 -0
  28. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/accuracy.json +0 -0
  29. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/attribute_ruler/patterns +0 -0
  30. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/config.cfg +0 -0
  31. {cortexhub-0.5.3 → cortexhub-0.5.5}/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.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/meta.json +0 -0
  33. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/cfg +0 -0
  34. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/model +0 -0
  35. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/moves +0 -0
  36. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/cfg +0 -0
  37. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/model +0 -0
  38. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/moves +0 -0
  39. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/senter/cfg +0 -0
  40. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/senter/model +0 -0
  41. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tagger/cfg +0 -0
  42. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tagger/model +0 -0
  43. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tok2vec/cfg +0 -0
  44. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tok2vec/model +0 -0
  45. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tokenizer +0 -0
  46. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/key2row +0 -0
  47. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/lookups.bin +0 -0
  48. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/strings.json +0 -0
  49. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/vectors +0 -0
  50. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/vectors.cfg +0 -0
  51. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/models/en_core_web_sm/meta.json +0 -0
  52. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/pii.py +0 -0
  53. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/guardrails/secrets.py +0 -0
  54. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/interceptors/__init__.py +0 -0
  55. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/interceptors/mcp.py +0 -0
  56. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/logging.py +0 -0
  57. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/policy/__init__.py +0 -0
  58. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/policy/loader.py +0 -0
  59. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/policy/models.py +0 -0
  60. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/policy/sync.py +0 -0
  61. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/signing.py +0 -0
  62. {cortexhub-0.5.3 → cortexhub-0.5.5}/src/cortexhub/telemetry/__init__.py +0 -0
  63. {cortexhub-0.5.3 → cortexhub-0.5.5}/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.3
3
+ Version: 0.5.5
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.3"
3
+ version = "0.5.5"
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.
@@ -3457,63 +3481,118 @@ class CortexHub:
3457
3481
  self,
3458
3482
  func: Any = None,
3459
3483
  *,
3484
+ classification: str | None = None,
3460
3485
  name: str | None = None,
3461
3486
  description: str | None = None,
3462
3487
  requires: list[str] | None = None,
3463
3488
  ) -> Any:
3464
- """Decorator that wraps any callable with CortexHub governance.
3489
+ """Wrap a callable with CortexHub governance.
3490
+
3491
+ ``classification`` is **required** — it's the one governance
3492
+ signal the developer declares. Combined with the agent's
3493
+ enforcement mode, it's enough to express the full posture:
3465
3494
 
3466
- Basic usage — wraps any function::
3495
+ * ``"read"`` — inspects data, no side effects.
3496
+ * ``"write"`` — creates or modifies state, reversible.
3497
+ * ``"destructive"`` — irreversible: deletes, refunds,
3498
+ terminates. In Enforce mode,
3499
+ destructive tools without an explicit
3500
+ policy deny by default. In Observe
3501
+ mode, they run but their dry-run
3502
+ evaluation is recorded.
3467
3503
 
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)
3504
+ Minimal usage::
3472
3505
 
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::
3506
+ @cx.tool(classification="read")
3507
+ def get_my_reservation() -> dict: ...
3477
3508
 
3478
- @cx.tool
3479
- def lookup_patient(patient_id: str) -> dict:
3480
- \"\"\"Look up a patient record.\"\"\"
3481
- ...
3509
+ @cx.tool(classification="write")
3510
+ def modify_reservation(...): ...
3482
3511
 
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
- ...
3512
+ @cx.tool(classification="destructive")
3513
+ def delete_reservation(...): ...
3487
3514
 
3488
- With name/description overrides::
3515
+ Prerequisite tools (must have executed this session first)::
3489
3516
 
3490
- @cx.tool(name="prescribe", description="Prescribe medication to a patient")
3517
+ @cx.tool(classification="read")
3518
+ def lookup_patient(...): ...
3519
+
3520
+ @cx.tool(classification="write", requires=["lookup_patient"])
3491
3521
  def prescribe_medication(...): ...
3492
3522
 
3493
3523
  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.
3524
+ classification: **Required.** ``"read"`` | ``"write"`` |
3525
+ ``"destructive"``. Drives the default-deny
3526
+ posture on destructive actions and the
3527
+ Tool Inventory badges.
3528
+ name: Override the tool name used in policies
3529
+ and telemetry. Defaults to function name.
3530
+ description: Override the description (defaults to
3531
+ docstring).
3532
+ requires: Tool names that must have been called
3533
+ successfully earlier in this session.
3534
+ Exposed to policies as
3535
+ ``context.run.called_tools``.
3501
3536
 
3502
3537
  Returns:
3503
- GovernedTool — callable, duck-type compatible with LangGraph
3504
- ToolNode and LangChain bind_tools. Zero framework imports.
3538
+ GovernedTool — duck-type compatible with LangGraph
3539
+ ToolNode and LangChain bind_tools.
3540
+
3541
+ Raises:
3542
+ ValueError: If ``classification`` is missing or invalid.
3543
+ Raised at import time so the error surfaces
3544
+ before first call.
3505
3545
  """
3506
3546
  from cortexhub.tool import GovernedTool
3507
3547
 
3508
3548
  def decorator(fn: Any) -> "GovernedTool":
3509
- return GovernedTool(fn, cx=self, name=name, description=description, requires=requires)
3549
+ self._validate_tool_classification(
3550
+ fn_name=getattr(fn, "__name__", "<anonymous>"),
3551
+ classification=classification,
3552
+ )
3553
+ return GovernedTool(
3554
+ fn,
3555
+ cx=self,
3556
+ name=name,
3557
+ description=description,
3558
+ requires=requires,
3559
+ classification=classification,
3560
+ )
3510
3561
 
3511
3562
  if func is not None:
3512
- # Called as @cx.tool (no parentheses)
3513
- return decorator(func)
3514
- # Called as @cx.tool(...) — return the decorator
3563
+ raise ValueError(
3564
+ f"@cx.tool requires a classification. Change "
3565
+ f"``@cx.tool`` above '{getattr(func, '__name__', 'tool')}' "
3566
+ f"to ``@cx.tool(classification=\"read\" | \"write\" | "
3567
+ f"\"destructive\")``. See cx.tool docstring for guidance."
3568
+ )
3515
3569
  return decorator
3516
3570
 
3571
+ def _validate_tool_classification(
3572
+ self,
3573
+ *,
3574
+ fn_name: str,
3575
+ classification: str | None,
3576
+ ) -> None:
3577
+ """Fail fast on missing/invalid classification — at import time,
3578
+ so a bad deploy never reaches first call. Error messages name
3579
+ the offending function so the fix is one line, no stack-diving."""
3580
+ if classification is None:
3581
+ raise ValueError(
3582
+ f"@cx.tool on '{fn_name}' is missing ``classification=``. "
3583
+ "Declare one of ``\"read\"`` (inspects data, no side "
3584
+ "effects), ``\"write\"`` (mutates, reversible), or "
3585
+ "``\"destructive\"`` (irreversible: deletes, refunds, "
3586
+ "terminates). The platform uses this for enforcement "
3587
+ "decisions and Tool Inventory badges; it is not optional."
3588
+ )
3589
+ if classification not in _VALID_CLASSIFICATIONS:
3590
+ raise ValueError(
3591
+ f"@cx.tool on '{fn_name}' has classification "
3592
+ f"{classification!r}; must be one of "
3593
+ f"{sorted(_VALID_CLASSIFICATIONS)!r}."
3594
+ )
3595
+
3517
3596
  def enforce(self, tool_name: str, args: dict[str, Any]) -> None:
3518
3597
  """Policy gate for code you don't own (third-party calls, APIs, DB writes).
3519
3598
 
@@ -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,73 @@ 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)."""
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
+
120
165
  tool_name = getattr(request.action, "name", None) or request.resource.id
121
- if self.default_behavior == "allow_and_log":
166
+ absence = resolve_policy_absence_decision(
167
+ enforcement_mode=self._enforcement_mode(),
168
+ effective_classification=self._tool_classification(tool_name),
169
+ tool_name=tool_name,
170
+ )
171
+ if absence.effect == "permit":
122
172
  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",
173
+ absence.reasoning,
174
+ policy_id="ungoverned",
137
175
  policy_decisions=[],
138
176
  )
139
177
  return Decision.deny(
140
- "Invalid default behavior configuration",
141
- policy_id="error",
178
+ absence.reasoning,
179
+ policy_id="hard_gate",
142
180
  policy_decisions=[],
143
181
  )
144
182
 
183
+ def _enforcement_mode(self) -> str | None:
184
+ """Pull the agent's ``enforcement_mode`` from the bundle.
185
+
186
+ Shipped on every ``/policies/bundle`` sync (see backend
187
+ ``PolicyBundleResponse.enforcement_mode``). The SDK's
188
+ ``backend.client.PolicyBundle`` dataclass exposes it as a
189
+ direct attribute. Back-compat: when the attribute is missing
190
+ (pre-0.5.5 bundle cached locally) or the value is empty, the
191
+ resolver treats it as Observe.
192
+ """
193
+ mode = getattr(self.policy_bundle, "enforcement_mode", None)
194
+ if isinstance(mode, str) and mode:
195
+ return mode
196
+ # Back-compat fallback: some ``PolicyBundle`` variants keep
197
+ # the mode in ``metadata`` — check there too.
198
+ meta = getattr(self.policy_bundle, "metadata", None)
199
+ if isinstance(meta, dict):
200
+ fallback = meta.get("enforcement_mode")
201
+ if isinstance(fallback, str) and fallback:
202
+ return fallback
203
+ return None
204
+
205
+ def _tool_classification(self, tool_name: str) -> str | None:
206
+ classifications = (
207
+ getattr(self.policy_bundle, "tool_classifications", None) or {}
208
+ )
209
+ bundle_cls = (
210
+ classifications.get(tool_name)
211
+ if isinstance(classifications, dict)
212
+ else None
213
+ )
214
+ return bundle_cls.get("bucket") if isinstance(bundle_cls, dict) else None
215
+
145
216
  def _evaluate_cedar(self, request: AuthorizationRequest) -> Decision:
146
217
  """Evaluate using the bundled in-process policy engine.
147
218
 
@@ -200,8 +271,44 @@ class PolicyEvaluator:
200
271
  schema = None
201
272
  policy_map = self.policy_bundle.metadata.get("policy_map", {}) if self.policy_bundle else {}
202
273
 
274
+ # Cedar ``context`` parity contract with the backend evaluator
275
+ # (``backend/app/services/studio/studio_governance.py::_cedar_allows``).
276
+ # Both runtimes must populate the same top-level keys so a
277
+ # single compiled policy evaluates to the same decision on both.
278
+ # When you change either side, update the other and the parity
279
+ # test (``tests/test_cedar_context_parity.py``).
280
+ #
281
+ # ``args``
282
+ # Tool arguments with every string value lowercased. String
283
+ # comparisons in compiled policies are case-insensitive (the
284
+ # compiler lowercases string literals at emit time), so we
285
+ # lowercase on the value side here to meet at the same casing.
286
+ # Non-string values (numbers, bools, nested objects) pass
287
+ # through untouched. Keys are preserved so
288
+ # ``context.args.<field>`` references still resolve.
289
+ #
290
+ # ``runtime``
291
+ # ``{"framework": "sdk"}``. Lets a policy author gate on the
292
+ # execution mode (e.g. ``context.runtime.framework == "sdk"``).
293
+ # The backend gateway path sets ``"studio"`` here.
294
+ #
295
+ # ``gateway``
296
+ # Empty dict on the SDK path. The MCP gateway populates it
297
+ # with request metadata (session id, declared intent, etc.).
298
+ # Injecting an empty record means Cedar policies that
299
+ # reference ``context.gateway.<field>`` evaluate to a missing
300
+ # attribute cleanly instead of raising a Cedar error. Any
301
+ # such policy was authored for the gateway runtime; on the
302
+ # SDK path it'll produce a non-match naturally, and the
303
+ # ``has context.gateway.<field>`` guard the UI generates
304
+ # short-circuits.
203
305
  context_args = request.context.get("args") if isinstance(request.context, dict) else {}
204
- cedar_context = {"args": self._json_safe(context_args) if context_args is not None else {}}
306
+ normalised_args = self._lowercase_strings(context_args) if context_args is not None else {}
307
+ cedar_context = {
308
+ "args": self._json_safe(normalised_args),
309
+ "runtime": {"framework": "sdk"},
310
+ "gateway": {},
311
+ }
205
312
 
206
313
  cedar_request = {
207
314
  "principal": f'{principal_type}::"{principal_id}"',
@@ -346,6 +453,28 @@ class PolicyEvaluator:
346
453
  policy_decisions=policy_decisions,
347
454
  )
348
455
 
456
+ def _lowercase_strings(self, value: Any) -> Any:
457
+ """Return a deep copy with every string *value* lowercased.
458
+
459
+ Powers the case-insensitive string comparison contract shared
460
+ with the backend (see ``studio_governance._cedar_allows`` for
461
+ the mirror). Non-strings pass through untouched; nested dicts
462
+ and lists recurse. Keys are preserved as-is — they're field
463
+ names that compiled Cedar references (``context.args.foo``)
464
+ and lowercasing them breaks lookup.
465
+
466
+ Keep this function and the backend's helper in lock-step. The
467
+ two are the contract that makes case-insensitive matching work
468
+ across both runtimes.
469
+ """
470
+ if isinstance(value, str):
471
+ return value.lower()
472
+ if isinstance(value, dict):
473
+ return {k: self._lowercase_strings(v) for k, v in value.items()}
474
+ if isinstance(value, list):
475
+ return [self._lowercase_strings(i) for i in value]
476
+ return value
477
+
349
478
  def _json_safe(self, value: Any) -> Any:
350
479
  if value is None:
351
480
  return 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.5"
16
16
 
17
17
 
18
18
  def _resolve_version() -> str:
File without changes
File without changes
File without changes