-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
993 lines (878 loc) · 41.8 KB
/
Copy pathclient.py
File metadata and controls
993 lines (878 loc) · 41.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
"""CodeRifts HTTP client — REST parity with the TypeScript SDK (ID75).
Canonical Decision Spec v2 tools remain ``preflight_change_set`` /
``verify_receipt`` / ``get_decision_details``. Additional methods map 1:1 to
the TypeScript ``CodeRifts`` class REST (and two client-side helpers).
Offline Ed25519 verification is intentionally not in this package.
"""
import math
from typing import Any, Callable, Dict, List, Mapping, Optional, Union
import requests
from .exceptions import ApiError, AuthError, CodeRiftsError, RateLimitError
from .decision import (
UNREADABLE_DECISION,
has_explicit_execution_action,
read_decision,
)
from .types import (
EXECUTION_GRANT_V2_REQUEST_FIELDS,
ExecutionGrantV2Request,
PreflightChangeSetContext,
PreflightMode,
StateChallenge,
)
DEFAULT_BASE_URL = "https://app.coderifts.com/api/v1"
# ── advisory prose (rendered from execution_action, never from ``decision``) ──
#: Control-input → summary sentence. Keys are the closed ExecutionAction set.
_ACTION_SUMMARY = {
"CONTINUE": "Execution action: CONTINUE — this change may proceed.",
"CONTINUE_WITH_MONITORING": (
"Execution action: CONTINUE_WITH_MONITORING — this change may proceed "
"only with monitoring wired."
),
"REQUEST_APPROVAL": (
"Execution action: REQUEST_APPROVAL — manual approval is required "
"before this change may proceed."
),
"STOP": "Execution action: STOP — this change must not proceed.",
}
#: Rendered whenever read_decision falls closed. Never says "safe to proceed".
_UNREADABLE_SUMMARY = (
"Execution action is unrecognised or absent ({}) — treat as STOP; "
"this change must not proceed."
).format(UNREADABLE_DECISION)
#: Rendered as the first unblock step when read_decision falls closed.
_UNREADABLE_UNBLOCK = (
"Execution action is unrecognised or absent ({}) — treat as STOP. "
"Re-read a response that carries execution_action, and resolve the "
"findings below before proceeding."
).format(UNREADABLE_DECISION)
#: Execution actions that genuinely need no unblock steps.
_NO_UNBLOCK_ACTIONS = frozenset({"CONTINUE", "CONTINUE_WITH_MONITORING"})
DEFAULT_TIMEOUT = 30
SDK_VERSION = "3.6.0"
# ID104 — verification expiry leeway (ms). Server applies this; the SDK is an HTTP client.
# `exp + leeway < now` → VERIFIED_EXPIRED. 0s when intended context declares destructive
# AND environment production. IntentContext has `environment` but no `destructive` /
# `operation_class` — never guess from operation labels.
CLOCK_SKEW_LEEWAY_MS = 30_000
_PREFLIGHT_MODES = frozenset({"analyze", "authorize"})
# Re-export: existing imports of PreflightChangeSetContext from this module stay valid.
__all__ = ["CodeRifts", "PreflightChangeSetContext", "PreflightMode", "_Response"]
class _Response:
"""Dot-access wrapper around a dict response.
Nested dicts are also wrapped. Lists and scalars are returned as-is.
Use ``to_dict()`` for the raw payload, or ``in`` / ``[]`` for key access.
"""
def __init__(self, data: dict):
self._data = data
def __getattr__(self, name: str):
try:
value = self._data[name]
except KeyError:
raise AttributeError("Response has no attribute {!r}".format(name))
if isinstance(value, dict):
return _Response(value)
return value
def __repr__(self) -> str:
return "Response({})".format(self._data)
def __contains__(self, key):
return key in self._data
def __getitem__(self, key):
return self._data[key]
def to_dict(self) -> dict:
"""Return the raw response dict."""
return self._data
def _assert_request_mode(artifacts, derivation, context):
"""Fail fast on the two mutually exclusive /v1/preflight request modes.
Python cannot express this as a type-level union the way the TypeScript SDK does
(``CallerArtifactsRequest | ServerDerivedRequest``), so the same rule is enforced at
runtime here and mirrored in the TypedDicts and docstrings.
The SERVER remains the authority: this guard exists to fail fast with a readable message
naming the rule, not to duplicate policy. Every condition below is one the API already
rejects; the messages quote the server's own reason so the two never diverge in meaning.
mode A artifacts=[...] derivation absent
mode B derivation="server" artifacts absent, context needs
repository + base + head
:raises ValueError: naming which rule was broken.
"""
if derivation is not None and derivation != "server":
raise ValueError(
'derivation must be "server" when set (got {!r}); omit it to supply '
"artifacts[] yourself".format(derivation)
)
if derivation is None:
if not artifacts:
raise ValueError(
"artifacts[] is required when derivation is not set — supply the complete "
'base->head change set, or pass derivation="server" to have the server list it'
)
return
# derivation == "server"
if artifacts:
raise ValueError(
'derivation="server" forbids caller-supplied artifacts[] — one source of truth '
"per request (the server lists the change-set via the SCM provider)"
)
ctx = context or {}
missing = [k for k in ("repository", "base", "head") if not str(ctx.get(k) or "").strip()]
if missing:
raise ValueError(
'derivation="server" requires context.{} — the server returns 400 '
"derivation_requires_base_head without base AND head, and 400 INVALID_INPUT "
"without a parseable owner/repo".format(", context.".join(missing))
)
class CodeRifts:
"""CodeRifts API client (REST parity with ``@coderifts/sdk`` 3.3.0).
Args:
api_key: Your CodeRifts API key (starts with ``cr_live_`` or ``cr_test_``).
base_url: Override the default API base URL
(``https://app.coderifts.com/api/v1``).
timeout: Request timeout in seconds.
"""
def __init__(
self,
api_key: str,
base_url: str = DEFAULT_BASE_URL,
timeout: int = DEFAULT_TIMEOUT,
):
if not api_key:
raise AuthError("API key is required")
self._api_key = api_key
self._base_url = base_url.rstrip("/")
self._timeout = timeout
self._session = requests.Session()
self._session.headers.update(
{
"Authorization": "Bearer {}".format(api_key),
"Content-Type": "application/json",
"User-Agent": "coderifts-python-sdk/{}".format(SDK_VERSION),
}
)
# ── internal ──────────────────────────────────────────────
def _request(self, method: str, path: str, **kwargs) -> dict:
url = "{}{}".format(self._base_url, path)
try:
resp = self._session.request(
method, url, timeout=self._timeout, **kwargs
)
except requests.exceptions.Timeout:
raise CodeRiftsError("Request timed out", "timeout_error")
except requests.exceptions.ConnectionError:
raise CodeRiftsError("Connection failed", "connection_error")
if resp.status_code == 401:
raise AuthError()
if resp.status_code == 429:
raise RateLimitError()
if resp.status_code >= 400:
try:
body = resp.json()
msg = body.get("error", body.get("message", resp.text))
except Exception:
msg = resp.text
raise ApiError(str(msg), status_code=resp.status_code)
try:
return resp.json()
except Exception:
return {"raw": resp.text}
def _post(self, path: str, body: dict, headers: Optional[Dict[str, str]] = None) -> _Response:
if headers:
data = self._request("POST", path, json=body, headers=headers)
else:
data = self._request("POST", path, json=body)
return _Response(data)
def _get(self, path: str, params: Optional[Dict[str, Any]] = None) -> _Response:
data = self._request("GET", path, params=params or None)
return _Response(data)
# ── public methods ────────────────────────────────────────
def preflight_change_set(
self,
artifacts: Optional[List[Dict[str, Any]]] = None,
*,
preflight_mode: PreflightMode,
derivation: Optional[str] = None,
context: Optional[PreflightChangeSetContext] = None,
include_execution_grant: Optional[bool] = None,
state_nonce: Optional[str] = None,
grant_version: Optional[str] = None,
execution_grant_binding: Optional[ExecutionGrantV2Request] = None,
previous_receipt: Optional[str] = None,
idempotency_key: Optional[str] = None,
scm_token: Optional[str] = None,
) -> _Response:
"""Preflight a complete base→head change set of contract artifacts.
Maps to ``POST /api/v1/preflight``.
**Required** top-level ``preflight_mode`` (Decision Spec v2): ``'analyze'``
or ``'authorize'``. The server returns HTTP 400 if it is omitted. Prefer
:meth:`analyze_change_set` / :meth:`authorize_change_set` so the two
meanings cannot be mixed via a silent default.
**What to branch on**
* ``execution_action`` — the proceed signal (e.g. ``CONTINUE``). Use this
for automated go / no-go control flow (authorize responses).
* ``decision`` — the governance explanation label (e.g. ``ALLOW``,
``WARN``, ``REQUIRE_APPROVAL``, ``BLOCK``). Use this for logging and
human-facing copy, not as the sole gate.
* On analyze responses, branch on ``analysis_outcome`` / risk fields —
analyze is informational, not permission.
Unrecognised ``execution_action`` values are not permission — treat as
STOP (fail closed).
Observed v2 fields (authorize) include ``execution_action``,
``receipt_kind`` (``operation_authorization`` | ``NONE``),
``chain_receipt``, optional ``execution_grant`` (when opted in),
``blast_radius`` (ID27 counts), ``decision_result``, ``control_envelope``.
Analyze responses carry ``analysis_outcome``, ``receipt_kind: NONE``,
``may_execute: false`` — not permission. Nested objects wrap.
Args:
artifacts: Non-empty list of artifact dicts. Each entry must include
at least ``id``, ``type``, ``before``, and ``after`` (spec
strings or equivalent payload fields accepted by the API).
preflight_mode: Required keyword-only. ``'analyze'`` (risk-only) or
``'authorize'`` (operation-bound; may mint a receipt). Top-level
on the request body — not nested under ``context``.
context: Optional :class:`PreflightChangeSetContext`. Documented
fields: ``operation``, ``environment``, ``repository``,
``branch``, ``pull_request``, ``policy_profile``, ``base``,
``head`` (PR/commit SHAs), ``platform`` (``github`` / ``gitlab`` /
``bitbucket``). Extra keys the API accepts are still
forwarded. For ``authorize``, the server requires a non-empty
``context.operation``.
scm_token: Per-request SCM token for GitLab/Bitbucket Compare
derivation. Sent ONLY as the ``X-Coderifts-Scm-Token`` header
(never in the JSON body, never stored on the client).
include_execution_grant: Opt-in execution grant on authorize.
Default omitted. WHICH grant the server mints when
``grant_version`` is also omitted is the server's default at
request time — pin ``grant_version`` explicitly to control
this. ``'v2'`` requests ``cr.exec.v2``. The Python client does
not verify grants offline (no Ed25519 dependency); use the
app/SDK-TS kernel.
grant_version: ``'v1'`` / ``'v2'`` selects the grant envelope.
Omitted — this SDK sends no version field. The server's default
at request time is what is issued; the response (and any
deprecation / sunset headers) is the statement that cannot go
stale. Pin explicitly to control this.
execution_grant_binding: The v2 identity the grant should bind, as
:class:`~coderifts.types.ExecutionGrantV2Request`:
``executor_id`` / ``adapter_id`` / ``target_uri`` /
``tenant_id`` / ``expected_state_token``. Only meaningful with
``grant_version='v2'``; sent at the request's TOP LEVEL, which
is where the server reads it.
MEASURED, and worth knowing before omitting it: the server does
NOT refuse a v2 request that names no identity. It falls back to
``context.<same name>``, then to its own defaults
(``executor_id='local'``, ``adapter_id='fs'``,
``tenant_id='default'``, and a ``target_uri`` derived from the
repository and head sha). A grant bound to those defaults is a
weaker statement than one bound to an identity you stated.
NOT exposed, because a client cannot supply them: the remaining
:class:`~coderifts.types.ExecutionGrantV2` fields (``kid``,
``grant_id``, ``receipt_hash``, ``after_payload_hash``,
``nonce_hash``, ``policy_hash``, ``audience_hash``) are minted
during issuance. A parameter the server ignores would read like
a binding that took effect.
previous_receipt: Optional prior chain receipt to link (TS
``previous_receipt``).
idempotency_key: Optional client idempotency key (TS
``idempotency_key``).
Returns:
Response wrapper over the full JSON body.
"""
if preflight_mode not in _PREFLIGHT_MODES:
raise ValueError(
"preflight_mode must be 'analyze' or 'authorize' "
"(got {!r}); prefer analyze_change_set / authorize_change_set".format(
preflight_mode
)
)
_assert_request_mode(artifacts, derivation, context)
body: Dict[str, Any] = {"preflight_mode": preflight_mode}
if derivation is not None:
body["derivation"] = derivation
else:
body["artifacts"] = artifacts
if context is not None:
body["context"] = context
if include_execution_grant is not None:
body["include_execution_grant"] = include_execution_grant
if state_nonce is not None:
body["state_nonce"] = state_nonce
if grant_version is not None:
body["grant_version"] = grant_version
if execution_grant_binding:
# TOP LEVEL, not nested under context — measured against
# coderifts-app src/change-set.js:1265-1285, which reads these from
# the body's top level and treats `context.<name>` only as a
# fallback.
#
# Only the fields the server actually reads are forwarded. An
# unknown key would travel, be ignored, and read to the caller like
# a binding that took effect.
for _field in EXECUTION_GRANT_V2_REQUEST_FIELDS:
_value = execution_grant_binding.get(_field)
if _value is not None:
body[_field] = _value
if previous_receipt is not None:
body["previous_receipt"] = previous_receipt
if idempotency_key is not None:
body["idempotency_key"] = idempotency_key
extra_headers = None
if isinstance(scm_token, str) and scm_token.strip():
extra_headers = {"X-Coderifts-Scm-Token": scm_token.strip()}
if extra_headers:
return self._post("/preflight", body, headers=extra_headers)
return self._post("/preflight", body)
def analyze_change_set(
self,
artifacts: Optional[List[Dict[str, Any]]] = None,
*,
derivation: Optional[str] = None,
state_nonce: Optional[str] = None,
context: Optional[PreflightChangeSetContext] = None,
previous_receipt: Optional[str] = None,
idempotency_key: Optional[str] = None,
scm_token: Optional[str] = None,
) -> _Response:
"""Risk-only preflight (``preflight_mode='analyze'``).
Informational — not permission; does not mint an operation-bound receipt.
Delegates to :meth:`preflight_change_set`.
"""
return self.preflight_change_set(
artifacts,
preflight_mode="analyze",
derivation=derivation,
state_nonce=state_nonce,
context=context,
previous_receipt=previous_receipt,
idempotency_key=idempotency_key,
scm_token=scm_token,
)
def authorize_change_set(
self,
artifacts: Optional[List[Dict[str, Any]]] = None,
*,
derivation: Optional[str] = None,
state_nonce: Optional[str] = None,
context: Optional[PreflightChangeSetContext] = None,
include_execution_grant: Optional[bool] = None,
grant_version: Optional[str] = None,
execution_grant_binding: Optional[ExecutionGrantV2Request] = None,
resolve_state_challenge: Optional[Callable[[], StateChallenge]] = None,
previous_receipt: Optional[str] = None,
idempotency_key: Optional[str] = None,
scm_token: Optional[str] = None,
) -> _Response:
"""Operation-bound authorize preflight (``preflight_mode='authorize'``).
Requires a non-empty ``context.operation`` (e.g. ``merge``, ``deploy``,
``tool_call``) — the server returns HTTP 400 otherwise. May mint a
signed receipt. Delegates to :meth:`preflight_change_set`.
Branch on ``execution_action`` (``CONTINUE`` | ``CONTINUE_WITH_MONITORING``
| ``REQUEST_APPROVAL`` | ``STOP``). Unrecognised → STOP.
**This SDK never mints an execution grant.** The SERVER mints; this library
requests one (``include_execution_grant=True``) and carries what comes back. A grant
minted locally would be signed by the caller and would therefore attest only that the
caller authorised itself — worthless to any verifier, which checks the issuer key. If
you are looking for a "sign a grant" call here, its absence is the design.
Args:
grant_version: ``"v2"`` selects the ATOMIC-profile grant. Omitted —
this SDK sends no version field. The server's default at request
time is what is issued; pin explicitly to control this.
execution_grant_binding: The v2 identity the grant should bind. Forwarded at the
request's top level; unknown keys are dropped rather than sent.
resolve_state_challenge: Zero-argument callable returning
``{"state_nonce": ..., "expected_state_token": ...}`` (both optional). Both
halves come from the EXECUTOR — the component that will consume the nonce and
observe the state. This SDK does not generate either: a nonce invented here
would bind the grant to a state no executor is holding. Called exactly once,
so one call cannot mix a nonce from one resolution with a token from another.
Mutually exclusive with ``state_nonce``.
"""
# ── the state challenge ─────────────────────────────────────────────────────────
binding = dict(execution_grant_binding) if execution_grant_binding else None
if resolve_state_challenge is not None:
if state_nonce is not None:
raise ValueError(
"pass either state_nonce or resolve_state_challenge, not both — "
"two sources for one nonce is how they diverge"
)
challenge = resolve_state_challenge() or {}
state_nonce = challenge.get("state_nonce")
token = challenge.get("expected_state_token")
if token is not None:
binding = dict(binding or {})
# An expected_state_token already in the binding is NOT overwritten silently:
# the caller stated it twice and the two may disagree.
if binding.get("expected_state_token") not in (None, token):
raise ValueError(
"expected_state_token differs between execution_grant_binding and "
"resolve_state_challenge — the grant would be bound to one of them "
"and this SDK will not choose"
)
binding["expected_state_token"] = token
return self.preflight_change_set(
artifacts,
preflight_mode="authorize",
derivation=derivation,
state_nonce=state_nonce,
context=context,
include_execution_grant=include_execution_grant,
grant_version=grant_version,
execution_grant_binding=binding,
previous_receipt=previous_receipt,
idempotency_key=idempotency_key,
scm_token=scm_token,
)
def verify_receipt(
self,
token: str,
operation: Optional[str] = None,
environment: Optional[str] = None,
target_id: Optional[str] = None,
fingerprint: Optional[str] = None,
audience: Optional[str] = None,
repository: Optional[str] = None,
branch: Optional[str] = None,
pull_request: Optional[Union[str, int]] = None,
base: Optional[str] = None,
head: Optional[str] = None,
indices: Optional[Dict[str, Any]] = None,
decision_result: Optional[Dict[str, Any]] = None,
) -> _Response:
"""Verify a signed chain-receipt and optionally evaluate authorization.
Maps to ``POST /api/v1/verify-receipt``.
**A valid signature is not authorization.** ``valid`` / ``status`` speak
to cryptographic authenticity (and lifecycle flags reflected in
``status``). Expiry uses 30s clock-skew leeway
(``CLOCK_SKEW_LEEWAY_MS``); 0s for destructive operations in production
when the intended context declares them. The SDK does not compare expiry
locally — the server does. Whether the receipt currently authorizes a
stated intent is a separate question.
**What to branch on**
* ``valid`` — whether the token is a well-formed, verifiable receipt.
* ``currently_authorized`` — **boolean or null**. ``True`` means
authorized for the supplied intent; ``False`` means not authorized;
``null`` means authorization could not be evaluated (for example when
only a token was sent). Treat null as neither authorized nor
unauthorized — that distinction is why this endpoint exists.
* When intent context is supplied, ``authz_status`` / ``authz_reason``
(and when a full evaluation succeeds, ``authz_state``) refine the
authorization outcome.
With only ``token``, observed fields include ``valid``, ``reason``,
``status``, ``payload``, ``currently_authorized``, ``authz_note``, and
``correlation_id``. Adding intent context can add ``authz_status`` and
``authz_reason``.
Args:
token: The chain-receipt token string (e.g. from
``preflight_change_set`` → ``chain_receipt`` or
``decision_result.receipt.token``).
operation: Optional intent field (e.g. ``merge``).
environment: Optional intent field (e.g. ``staging``).
target_id: Optional target binding (e.g. artifact digest).
fingerprint: Optional change / verdict fingerprint.
audience: Optional audience claim.
repository: Optional repository scope for authorization binding.
branch: Optional branch scope for authorization binding.
pull_request: Optional pull-request identifier (``str`` or ``int``)
for authorization binding.
base: Optional intended base commit/ref SHA (signed-wins vs the
envelope).
head: Optional intended head commit/ref SHA (signed-wins vs the
envelope).
indices: Optional dict of lifecycle indices used in authorization
evaluation (server requires an object).
decision_result: Optional body-hash-bound decision envelope from a
prior preflight or lookup; required for full scope evaluation.
Returns:
Response wrapper over the full JSON body.
"""
body: Dict[str, Any] = {"token": token}
if operation is not None:
body["operation"] = operation
if environment is not None:
body["environment"] = environment
if target_id is not None:
body["target_id"] = target_id
if fingerprint is not None:
body["fingerprint"] = fingerprint
if audience is not None:
body["audience"] = audience
if repository is not None:
body["repository"] = repository
if branch is not None:
body["branch"] = branch
if pull_request is not None:
body["pull_request"] = pull_request
if base is not None:
body["base"] = base
if head is not None:
body["head"] = head
if indices is not None:
body["indices"] = indices
if decision_result is not None:
body["decision_result"] = decision_result
return self._post("/verify-receipt", body)
def get_decision_details(
self,
decision_id: Optional[str] = None,
fingerprint: Optional[str] = None,
) -> _Response:
"""Look up a previously stored governance decision.
Maps to ``POST /api/v1/decisions/lookup``.
Provide **either** ``decision_id`` **or** ``fingerprint`` (or both). An
empty body is rejected by the API with ``INVALID_INPUT``.
**What to branch on**
* ``execution_action`` — the proceed signal from the stored decision.
* ``decision`` — the explanation label for that decision.
Observed fields on a successful lookup include ``decision``,
``execution_action``, ``risk_score``, ``safe_for_agent``,
``breaking_changes`` (integer), ``patterns``, ``decision_result``,
``control_envelope``, ``verdict_fingerprint``, ``required_action_core``,
``meta``, and ``correlation_id``.
Args:
decision_id: Stored decision id (e.g. ``dec_...`` from
``decision_result.decision_id``).
fingerprint: Verdict / change fingerprint (e.g. ``sha256:...``).
Returns:
Response wrapper over the full JSON body.
"""
body: Dict[str, Any] = {}
if decision_id is not None:
body["decision_id"] = decision_id
if fingerprint is not None:
body["fingerprint"] = fingerprint
return self._post("/decisions/lookup", body)
# ── additional REST (TS CodeRifts class parity) ───────────
def preflight_check(
self,
tool_name: str,
old_spec: str,
new_spec: str,
) -> _Response:
"""Single-tool agent preflight (TS ``preflightCheck``).
Maps to ``POST /api/v1/agent/preflight``. Legacy single-spec surface —
prefer :meth:`preflight_change_set` for Decision Spec v2.
Branch on ``execution_action`` via
:func:`~coderifts.decision.read_decision` — measured live, this endpoint
emits it top-level.
3.5.0 — BREAKING, deliberate. ``safe`` is a permission and is now
GRANTED, not merely un-refused: it is true only when the response
carried an explicit ``CONTINUE``. An absent, unknown or unrecognised
action reads as ``STOP`` and ``safe`` is ``False``. The pre-3.5.0
mapper manufactured an ``ALLOW`` from an omitted field, so a server
that said nothing produced ``safe=True``. ``decision`` is now passed
through exactly as received — the SDK computes no decision of its own.
"""
raw = self._request(
"POST",
"/agent/preflight",
json={
"tool_name": tool_name,
"old_spec": old_spec,
"new_spec": new_spec,
},
)
read = read_decision(raw)
body = dict(raw)
body["omega_api"] = raw.get("omega_api", 0)
body["safe"] = (
read.execution_action == "CONTINUE"
and has_explicit_execution_action(raw)
)
body.setdefault("reflex_triggers", raw.get("reflex_triggers") or [])
body.setdefault("affected_tools", raw.get("affected_tools") or [])
return _Response(body)
def diff(
self,
before: str,
after: str,
branch_name: Optional[str] = None,
config: Optional[Dict[str, Any]] = None,
) -> _Response:
"""Full OpenAPI spec diff (TS ``diff``).
Maps to ``POST /api/v1/diff``.
Branch on ``execution_action`` via
:func:`~coderifts.decision.read_decision` — measured live, this endpoint
emits it top-level. Unrecognised or absent → STOP.
"""
body: Dict[str, Any] = {"before": before, "after": after}
if branch_name is not None:
body["branch_name"] = branch_name
if config is not None:
body["config"] = config
return self._post("/diff", body)
def score_mcp(self, manifest: Dict[str, Any]) -> _Response:
"""Score an MCP manifest for agent safety (TS ``scoreMcp``).
Maps to ``POST /api/v1/agent-readiness-score`` with ``spec_type='mcp'``
(same body the TypeScript client sends).
"""
return self._post(
"/agent-readiness-score",
{"spec": manifest, "spec_type": "mcp"},
)
def get_ledger(
self,
repo: Optional[str] = None,
decision: Optional[str] = None,
from_: Optional[str] = None,
to: Optional[str] = None,
limit: Optional[int] = None,
) -> _Response:
"""Query compliance ledger entries (TS ``getLedger``).
Maps to ``GET /api/v1/ledger``. Python parameter ``from_`` is sent as
the query string key ``from`` (``from`` is a reserved word).
"""
params: Dict[str, Any] = {}
if repo is not None:
params["repo"] = repo
if decision is not None:
params["decision"] = decision
if from_ is not None:
params["from"] = from_
if to is not None:
params["to"] = to
if limit is not None:
params["limit"] = limit
return self._get("/ledger", params=params or None)
def simulate_policy(
self,
policy_yaml: str,
old_spec: str,
new_spec: str,
) -> _Response:
"""Test a YAML policy against two OpenAPI specs (TS ``simulatePolicy``).
Maps to ``POST /api/v1/policy-simulator``.
Branch on ``effective_action``. Unrecognised values are not permission
— treat as STOP.
"""
return self._post(
"/policy-simulator",
{
"policy_yaml": policy_yaml,
"old_spec": old_spec,
"new_spec": new_spec,
},
)
def explain_decision(
self,
omega_api: float,
decision: str,
reflex_triggers: Optional[List[Dict[str, Any]]] = None,
omega_components: Optional[Dict[str, Any]] = None,
*,
execution_action: Optional[str] = None,
response: Any = None,
) -> _Response:
"""Human-readable explanation of a decision (TS ``explainDecision``).
Computed client-side — no HTTP call, no invented endpoint.
**Advisory prose, not a gate.** For control flow call
:func:`~coderifts.decision.read_decision` on the response yourself; this
method only renders a summary.
The control input is ``execution_action``, resolved through
``read_decision``: pass ``response=`` (a full API payload — preferred) or
``execution_action=``. ``decision`` is rendered in the prose because it
explains *why*, and never selects a branch. When no readable execution
action is supplied the summary says the action is unrecognised and must
be treated as STOP — it never reports a change as safe to proceed.
Args:
omega_api: Ω_API score, rendered in the summary.
decision: Governance label for the prose (e.g. ``ALLOW``). Not a gate.
reflex_triggers: Triggered reflex rules; only the count is rendered.
omega_components: Numeric components to describe.
execution_action: Keyword-only control input.
response: Keyword-only full response payload; takes precedence over
``execution_action``.
Returns:
Response wrapper with ``summary``, ``components``,
``execution_action`` (the resolved control input) and ``reason``.
"""
components = []
if omega_components:
for name, value in omega_components.items():
if isinstance(value, (int, float)) and not isinstance(value, bool):
components.append(
{
"name": name,
"value": value,
"description": _describe_component(name, float(value)),
}
)
triggers = reflex_triggers or []
read = read_decision(
response if response is not None else {"execution_action": execution_action}
)
summary = "Decision: {} (Ω_API = {}).".format(decision, omega_api)
if triggers:
summary += " {} reflex rule(s) triggered.".format(len(triggers))
if read.unreadable:
summary += " " + _UNREADABLE_SUMMARY
else:
summary += " " + _ACTION_SUMMARY[read.execution_action]
return _Response(
{
"summary": summary,
"components": components,
"execution_action": read.execution_action,
"reason": read.reason,
}
)
def how_to_unblock(
self,
decision: str,
breaking_changes: Optional[List[Dict[str, Any]]] = None,
detected_patterns: Optional[List[Any]] = None,
reflex_triggers: Optional[List[Dict[str, Any]]] = None,
*,
execution_action: Optional[str] = None,
response: Any = None,
) -> _Response:
"""Actionable steps to resolve a halted change (TS ``howToUnblock``).
Computed client-side — no HTTP call, no invented endpoint.
``detected_patterns`` is accepted for signature parity with TypeScript
(the TS client currently does not render it).
**Advisory prose, not a gate.** For control flow call
:func:`~coderifts.decision.read_decision` on the response yourself.
The control input is ``execution_action``, resolved through
``read_decision``: pass ``response=`` (a full API payload — preferred) or
``execution_action=``. ``decision`` is rendered in the prose only.
"No unblock needed" is emitted **only** for a readable ``CONTINUE`` /
``CONTINUE_WITH_MONITORING``; an unrecognised or absent action is
treated as STOP and still yields steps.
Args:
decision: Governance label for the prose. Not a gate.
breaking_changes: Breaking changes to render as the first fix step.
detected_patterns: Signature parity only; unused.
reflex_triggers: Reflex rules to render as steps.
execution_action: Keyword-only control input.
response: Keyword-only full response payload; takes precedence over
``execution_action``.
Returns:
Response wrapper with ``actions``, ``execution_action`` and ``reason``.
"""
del detected_patterns # signature parity; unused in the TS client too
read = read_decision(
response if response is not None else {"execution_action": execution_action}
)
actions: List[Dict[str, Any]] = []
step = 1
if not read.unreadable and read.execution_action in _NO_UNBLOCK_ACTIONS:
actions.append(
{
"step": step,
"description": (
'Execution action is "{}" (decision: "{}") '
"— no unblock needed."
).format(read.execution_action, decision),
}
)
return _Response(
{
"actions": actions,
"execution_action": read.execution_action,
"reason": read.reason,
}
)
if read.unreadable:
actions.append({"step": step, "description": _UNREADABLE_UNBLOCK})
step += 1
elif read.execution_action == "REQUEST_APPROVAL":
actions.append(
{"step": step, "description": _ACTION_SUMMARY["REQUEST_APPROVAL"]}
)
step += 1
bcs = breaking_changes or []
if bcs:
example = "\n".join(
"# {} at {}: {}".format(
bc.get("type", ""), bc.get("path", ""), bc.get("description", "")
)
for bc in bcs[:3]
)
actions.append(
{
"step": step,
"description": "Fix {} breaking change(s) in your spec.".format(
len(bcs)
),
"code_example": example,
}
)
step += 1
for trigger in reflex_triggers or []:
actions.append(
{
"step": step,
"description": "Resolve reflex rule: {}".format(
trigger.get("rule", "")
),
}
)
step += 1
actions.append(
{
"step": step,
"description": (
"Request a manual override via POST /api/v1/ledger/:id/override "
"if this is an emergency."
),
}
)
return _Response(
{
"actions": actions,
"execution_action": read.execution_action,
"reason": read.reason,
}
)
def _describe_component(name: str, value: float) -> str:
descriptions = {
"S_contract": "Contract severity score — measures how severe the breaking changes are",
"P_break": "Break probability — likelihood that downstream consumers will break",
"S_blast_eff": "Blast radius — how many consumers are affected",
"S_agent": "Agent safety score — risk to AI agent tool invocations",
"S_runtime": "Runtime impact — risk of runtime failures",
"ECI": "Ecosystem coupling index — how tightly coupled the API is",
"M_eff": "Migration effort — estimated effort to migrate consumers",
"D_contract": "Contract distance — semantic distance between old and new contracts",
"confidence_score": "Confidence in the analysis result",
}
return descriptions.get(name, "{} = {}".format(name, value))
def _is_finite_number(value: object) -> bool:
"""Match JS ``Number.isFinite``: real int/float only, not bool, not coerced strings."""
if isinstance(value, bool) or not isinstance(value, (int, float)):
return False
return math.isfinite(value)
def expiry_leeway_ms(context: Optional[Mapping[str, Any]] = None) -> int:
"""Return verification expiry leeway in milliseconds.
0 only when intended context declares destructive AND production. Measured
IntentContext has ``environment`` but no ``destructive`` / ``operation_class``.
"""
if declares_destructive_production(context):
return 0
return CLOCK_SKEW_LEEWAY_MS
def declares_destructive_production(context: Optional[Mapping[str, Any]] = None) -> bool:
"""True only when intended context DECLARES destructive AND production.
No such destructive field exists on IntentContext — always False.
"""
if not isinstance(context, Mapping):
return False
if context.get("environment") != "production":
return False
return False
def is_receipt_expired(
expires_at_ms: object,
now_ms: object,
context: Optional[Mapping[str, Any]] = None,
) -> bool:
"""``exp + leeway < now`` → expired (verification verdict only).
Non-finite timestamps cannot be judged (same as JS ``Number.isFinite`` miss).
"""
if not _is_finite_number(expires_at_ms) or not _is_finite_number(now_ms):
return False
return (float(expires_at_ms) + expiry_leeway_ms(context)) < float(now_ms)
def is_issued_in_future(
issued_at_ms: object,
now_ms: object,
context: Optional[Mapping[str, Any]] = None,
) -> bool:
"""Future-dated iat (`ts`): same 30s leeway on the other side. No nbf."""
if not _is_finite_number(issued_at_ms) or not _is_finite_number(now_ms):
return False
return float(issued_at_ms) > (float(now_ms) + expiry_leeway_ms(context))