File size: 34,905 Bytes
f726fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Narrow, auditable adapter for the API reliability recovery slice."""

from __future__ import annotations

import copy
import hashlib
import json
from typing import Any

try:
    from .recovery_policy import (
        FAILURE_SIGNALS,
        OPERATION_CLASSES,
        RECOVERY_PROFILES,
        RECOVERY_RULE_CELLS,
        required_recovery_profile,
    )
except ImportError:  # Direct CLI execution from the case directory.
    from recovery_policy import (  # type: ignore
        FAILURE_SIGNALS,
        OPERATION_CLASSES,
        RECOVERY_PROFILES,
        RECOVERY_RULE_CELLS,
        required_recovery_profile,
    )


ROLE = "api_reliability_operator"
REFERENCE_NOW = "2026-05-20T12:00:00Z"
LIMIT_SCHEMA = {"type": "integer", "minimum": 1, "maximum": 100, "default": 25}
OFFSET_SCHEMA = {"type": "integer", "minimum": 0, "maximum": 1_000_000, "default": 0}

PUBLIC_TOOLS = [
    {
        "name": "list_service_integrations",
        "description": "List provider integrations with bounded business filters.",
        "input_schema": {
            "type": "object",
            "properties": {
                "provider_type": {"type": "string"},
                "status": {"type": "string"},
                "limit": LIMIT_SCHEMA,
                "offset": OFFSET_SCHEMA,
            },
            "required": [],
            "additionalProperties": False,
        },
    },
    {
        "name": "list_api_credentials",
        "description": "List credentials by integration, lifecycle state, and operation scope.",
        "input_schema": {
            "type": "object",
            "properties": {
                "integration_id": {"type": "string"},
                "status": {"type": "string"},
                "scope_contains": {"type": "string"},
                "limit": LIMIT_SCHEMA,
                "offset": OFFSET_SCHEMA,
            },
            "required": [],
            "additionalProperties": False,
        },
    },
    {
        "name": "list_retry_budgets",
        "description": "List retry-budget windows and their current capacity.",
        "input_schema": {
            "type": "object",
            "properties": {
                "integration_id": {"type": "string"},
                "status": {"type": "string"},
                "window_minutes": {"type": "integer", "minimum": 1, "maximum": 1440},
                "limit": LIMIT_SCHEMA,
                "offset": OFFSET_SCHEMA,
            },
            "required": [],
            "additionalProperties": False,
        },
    },
    {
        "name": "inspect_rate_limit_status",
        "description": "Inspect rate capacity for one integration and optional operation.",
        "input_schema": {
            "type": "object",
            "properties": {
                "integration_id": {"type": "string"},
                "operation": {"type": "string"},
                "requested_units": {"type": "integer", "minimum": 1, "maximum": 100, "default": 1},
            },
            "required": ["integration_id"],
            "additionalProperties": False,
        },
    },
    {
        "name": "list_fault_policies",
        "description": "List observed fault conditions for an integration operation.",
        "input_schema": {
            "type": "object",
            "properties": {
                "integration_id": {"type": "string"},
                "enabled": {"type": "boolean"},
                "operation": {"type": "string"},
                "limit": LIMIT_SCHEMA,
                "offset": OFFSET_SCHEMA,
            },
            "required": [],
            "additionalProperties": False,
        },
    },
    {
        "name": "search_recovery_evidence",
        "description": "Search archived successful recovery evidence by observed failure signal and operation class.",
        "input_schema": {
            "type": "object",
            "properties": {
                "failure_signal": {"type": "string", "enum": list(FAILURE_SIGNALS)},
                "operation_class": {"type": "string", "enum": list(OPERATION_CLASSES)},
                "limit": {"type": "integer", "minimum": 1, "maximum": 16, "default": 16},
                "offset": {"type": "integer", "minimum": 0, "maximum": 16, "default": 0},
            },
            "required": [],
            "additionalProperties": False,
        },
    },
    {
        "name": "search_audit_events",
        "description": "Search bounded call and recovery audit history.",
        "input_schema": {
            "type": "object",
            "properties": {
                "integration_id": {"type": "string"},
                "related_call_id": {"type": "string"},
                "limit": LIMIT_SCHEMA,
                "offset": OFFSET_SCHEMA,
            },
            "required": [],
            "additionalProperties": False,
        },
    },
    {
        "name": "execute_api_call",
        "description": "Execute one metered provider request with an explicit idempotency key.",
        "input_schema": {
            "type": "object",
            "properties": {
                "integration_id": {"type": "string"},
                "credential_id": {"type": "string"},
                "operation": {"type": "string"},
                "request_fingerprint": {"type": "string"},
                "idempotency_key": {"type": "string"},
                "retry_budget_id": {"type": "string"},
                "rate_limit_bucket_id": {"type": "string"},
                "fault_policy_id": {"type": "string"},
            },
            "required": ["integration_id", "credential_id", "operation", "request_fingerprint", "idempotency_key"],
            "additionalProperties": False,
        },
    },
    {
        "name": "retry_api_call",
        "description": "Retry one source call using explicit current credential, retry-budget, and rate-bucket bindings.",
        "input_schema": {
            "type": "object",
            "properties": {
                "call_id": {"type": "string"},
                "credential_id": {"type": "string"},
                "retry_budget_id": {"type": "string"},
                "rate_limit_bucket_id": {"type": "string"},
                "recovery_profile_id": {"type": "string", "enum": list(RECOVERY_PROFILES)},
                "incident_id": {"type": "string"},
            },
            "required": [
                "call_id",
                "credential_id",
                "retry_budget_id",
                "rate_limit_bucket_id",
                "recovery_profile_id",
            ],
            "additionalProperties": False,
        },
    },
]

TOOL_SCHEMAS = {item["name"]: item["input_schema"] for item in PUBLIC_TOOLS}
ALLOWED_TOOLS = frozenset(TOOL_SCHEMAS)
PAGED_READ_TOOLS = {
    "list_service_integrations",
    "list_api_credentials",
    "list_retry_budgets",
    "list_fault_policies",
    "search_audit_events",
}
WRITE_COST = {"execute_api_call": 8, "retry_api_call": 10}
RETRYABLE_STATUSES = {"transient_error", "rate_limited", "timeout", "queued"}


def _canonical(value: Any) -> str:
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)


def _matches_type(value: Any, expected: str) -> bool:
    if expected == "boolean":
        return isinstance(value, bool)
    if expected == "integer":
        return isinstance(value, int) and not isinstance(value, bool)
    if expected == "number":
        return isinstance(value, (int, float)) and not isinstance(value, bool)
    if expected == "string":
        return isinstance(value, str)
    return True


def _validate_arguments(tool: str, arguments: Any) -> str | None:
    if not isinstance(arguments, dict):
        return "arguments must be an object"
    schema = TOOL_SCHEMAS[tool]
    properties = schema["properties"]
    unknown = sorted(set(arguments) - set(properties))
    if unknown:
        return f"unsupported argument(s): {', '.join(unknown)}"
    missing = [name for name in schema.get("required", []) if name not in arguments]
    if missing:
        return f"missing required argument(s): {', '.join(missing)}"
    for name, value in arguments.items():
        field = properties[name]
        if not _matches_type(value, field["type"]):
            return f"{name} must be {field['type']}"
        if field["type"] == "string" and not value.strip():
            return f"{name} must be non-empty"
        if "enum" in field and value not in field["enum"]:
            return f"{name} must be one of: {', '.join(str(item) for item in field['enum'])}"
        if "minimum" in field and value < field["minimum"]:
            return f"{name} must be at least {field['minimum']}"
        if "maximum" in field and value > field["maximum"]:
            return f"{name} must be at most {field['maximum']}"
    return None


def _bounded_work_value(arguments: Any, name: str, default: int, minimum: int, maximum: int) -> int:
    if not isinstance(arguments, dict):
        return default
    value = arguments.get(name, default)
    if not isinstance(value, int) or isinstance(value, bool) or not minimum <= value <= maximum:
        return default
    return value


def _sanitize_raw_result(tool: str, result: Any) -> dict[str, Any]:
    if not isinstance(result, dict) or not isinstance(result.get("content"), dict):
        return {
            "type": "tool_result",
            "tool": tool,
            "content": {"status": "error", "data": {}, "message": "UPSTREAM_TOOL_ERROR: invalid raw response"},
        }
    content = result["content"]
    if content.get("status") != "error":
        return result
    message = str(content.get("message") or "UPSTREAM_TOOL_ERROR: raw tool failed")
    if message.startswith("TOOL_EXECUTION_ERROR") or "traceback" in message.lower():
        message = "UPSTREAM_TOOL_ERROR: raw tool execution failed"
    return {
        "type": "tool_result",
        "tool": tool,
        "content": {"status": "error", "data": {}, "message": message},
    }


class ApiReliabilityAdapter:
    """Enforces role, schema, quota, idempotency, and retry conservation."""



    def close(self) -> None:
        self.server.cleanup_runtime()

    def public_tool_schemas(self, actor: str = ROLE) -> list[dict[str, Any]]:
        return copy.deepcopy(PUBLIC_TOOLS) if actor == ROLE else []

    def _cost(self, tool: str, arguments: Any) -> int:
        if tool == "search_recovery_evidence":
            return 16 + _bounded_work_value(arguments, "limit", 16, 1, 16)
        if tool in PAGED_READ_TOOLS:
            return 2 + _bounded_work_value(arguments, "limit", 25, 1, 100)
        if tool == "inspect_rate_limit_status":
            return 3
        return WRITE_COST[tool]

    def _search_recovery_evidence(self, arguments: dict[str, Any]) -> dict[str, Any]:
        rows = RECOVERY_RULE_CELLS
        failure_signal = arguments.get("failure_signal")
        operation_class = arguments.get("operation_class")
        if failure_signal:
            rows = [row for row in rows if row["failure_signal"] == failure_signal]
        if operation_class:
            rows = [row for row in rows if row["operation_class"] == operation_class]
        offset = int(arguments.get("offset", 0))
        limit = int(arguments.get("limit", 16))
        page = rows[offset : offset + limit]
        return self._success(
            "search_recovery_evidence",
            {
                "total_count": len(rows),
                "offset": offset,
                "limit": limit,
                "evidence": copy.deepcopy(page),
            },
            "Archived recovery evidence searched",
        )

    def _error(self, tool: str, code: str, message: str, cost: int = 0) -> dict[str, Any]:
        return {
            "type": "tool_result",
            "tool": tool,
            "content": {"status": "error", "data": {}, "message": f"{code}: {message}"},
            "budget": {"charged": cost, "remaining": self.remaining},
        }

    def _success(self, tool: str, data: dict[str, Any], message: str) -> dict[str, Any]:
        return {
            "type": "tool_result",
            "tool": tool,
            "content": {"status": "success", "data": data, "message": message},
        }

    def _record_receipt(
        self,
        tool: str,
        arguments: dict[str, Any],
        status: str,
        cost: int,
        before_hash: str,
    ) -> int:
        receipt = {
            "index": len(self.receipts) + 1,
            "task_id": self.active_task_id,
            "tool": tool,
            "actor": ROLE,
            "arguments": copy.deepcopy(arguments),
            "status": status,
            "cost": cost,
            "before_hash": before_hash,
            "after_business_hash": self.business_hash(),
        }
        self.receipts.append(receipt)
        return receipt["index"]

    def _finish(
        self,
        tool: str,
        arguments: dict[str, Any],
        result: dict[str, Any],
        cost: int,
        before_hash: str,
    ) -> dict[str, Any]:
        index = self._record_receipt(
            tool,
            arguments,
            result.get("content", {}).get("status", "error"),
            cost,
            before_hash,
        )
        result["budget"] = {"charged": cost, "remaining": self.remaining}
        result["receipt_index"] = index
        return result

    def _restore_database(self, database: dict[str, Any], counters: dict[str, Any]) -> None:
        self.manager.db._data = copy.deepcopy(database)
        for entity_type in database:
            self.manager.db._flush(entity_type)
        self.manager._counters = copy.deepcopy(counters)

    def _idempotency_guard(self, arguments: dict[str, Any]) -> dict[str, Any] | None:
        matches = self.manager.query_entities(
            "idempotency_key",
            lambda row: row.get("integration_id") == arguments["integration_id"]
            and row.get("operation") == arguments["operation"]
            and row.get("key") == arguments["idempotency_key"],
        )
        if not matches:
            return None
        key = matches[0]
        if key.get("request_fingerprint") != arguments["request_fingerprint"]:
            return self._error("execute_api_call", "IDEMPOTENCY_CONFLICT", "the key is bound to a different request fingerprint")
        associated = self.manager.get_entity(
            "api_call_attempt", key.get("associated_call_id", ""), id_field="call_id"
        )
        if key.get("status") == "consumed" and associated and associated.get("side_effect_committed"):
            return self._success(
                "execute_api_call",
                {
                    "call_id": associated["call_id"],
                    "status": associated.get("status"),
                    "side_effect_committed": True,
                    "idempotency_id": key.get("idempotency_id"),
                    "idempotent_replay": True,
                },
                "Existing committed result returned without another provider call",
            )
        if key.get("status") == "consumed":
            return self._error(
                "execute_api_call",
                "IDEMPOTENCY_ALREADY_CONSUMED",
                "the original call must be recovered through its retry path",
            )
        if key.get("status") == "conflicted":
            return self._error("execute_api_call", "IDEMPOTENCY_CONFLICT", "the key is already conflicted")
        return None

    def _execute_context_guard(self, arguments: dict[str, Any]) -> dict[str, Any] | None:
        integration = self.manager.get_entity(
            "service_integration", arguments["integration_id"], id_field="integration_id"
        )
        if integration is None:
            return self._error("execute_api_call", "INTEGRATION_NOT_FOUND", "integration does not exist")
        if integration.get("status") == "paused":
            return self._error("execute_api_call", "INTEGRATION_PAUSED", "integration is paused")
        credential = self.manager.get_entity(
            "api_credential", arguments["credential_id"], id_field="credential_id"
        )
        if credential is None:
            return self._error("execute_api_call", "CREDENTIAL_NOT_FOUND", "credential does not exist")
        if credential.get("integration_id") != arguments["integration_id"]:
            return self._error("execute_api_call", "ENTITY_SCOPE_MISMATCH", "credential belongs to another integration")
        if credential.get("status") not in {"active", "rotating"}:
            return self._error("execute_api_call", "CREDENTIAL_NOT_USABLE", "credential is not currently usable")
        if arguments["operation"] not in (credential.get("scope") or []):
            return self._error("execute_api_call", "SCOPE_NOT_ALLOWED", "credential scope excludes the operation")
        return None

    def _retry_guard(self, arguments: dict[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
        source = self.manager.get_entity("api_call_attempt", arguments["call_id"], id_field="call_id")
        if source is None:
            return None, self._error("retry_api_call", "CALL_NOT_FOUND", "source call does not exist")
        if source.get("status") not in RETRYABLE_STATUSES:
            return None, self._error("retry_api_call", "CALL_NOT_RETRYABLE", "source call status is not retryable")
        if int(source.get("retry_attempt") or 0) >= int(source.get("max_retry_attempts") or 0):
            return None, self._error("retry_api_call", "RETRY_LIMIT_REACHED", "source call has no retry attempts remaining")

        prior = self.manager.query_entities(
            "api_call_attempt",
            lambda row: row.get("duplicate_of_call_id") == source.get("call_id")
            and row.get("side_effect_committed") is True,
        )
        if prior:
            prior.sort(key=lambda row: row.get("call_id") or "")
            return source, self._success(
                "retry_api_call",
                {
                    "source_call_id": source["call_id"],
                    "retry_call_id": prior[0]["call_id"],
                    "status": prior[0].get("status"),
                    "side_effect_committed": True,
                    "idempotent_replay": True,
                },
                "Existing committed recovery returned without another provider call",
            )

        if arguments["recovery_profile_id"] != required_recovery_profile(source):
            return None, self._error(
                "retry_api_call",
                "RECOVERY_PROFILE_MISMATCH",
                "the selected recovery profile is not valid for the observed failure and operation class",
            )

        credential = self.manager.get_entity("api_credential", arguments["credential_id"], id_field="credential_id")
        if credential is None:
            return None, self._error("retry_api_call", "CREDENTIAL_NOT_FOUND", "credential does not exist")
        if credential.get("integration_id") != source.get("integration_id"):
            return None, self._error("retry_api_call", "ENTITY_SCOPE_MISMATCH", "credential belongs to another integration")
        if credential.get("status") not in {"active", "rotating"}:
            return None, self._error("retry_api_call", "CREDENTIAL_NOT_USABLE", "credential is not currently usable")
        if source.get("operation") not in (credential.get("scope") or []):
            return None, self._error("retry_api_call", "SCOPE_NOT_ALLOWED", "credential scope excludes the source operation")

        budget = self.manager.get_entity("retry_budget", arguments["retry_budget_id"], id_field="budget_id")
        if budget is None:
            return None, self._error("retry_api_call", "BUDGET_NOT_FOUND", "retry budget does not exist")
        if budget.get("integration_id") != source.get("integration_id"):
            return None, self._error("retry_api_call", "ENTITY_SCOPE_MISMATCH", "retry budget belongs to another integration")
        available = int(budget.get("max_attempts") or 0) - int(budget.get("used_attempts") or 0) - int(budget.get("reserved_attempts") or 0)
        if budget.get("status") != "open" or available < 1:
            return None, self._error("retry_api_call", "RETRY_BUDGET_EXHAUSTED", "retry budget lacks capacity")

        bucket = self.manager.get_entity("rate_limit_bucket", arguments["rate_limit_bucket_id"], id_field="bucket_id")
        if bucket is None:
            return None, self._error("retry_api_call", "RATE_BUCKET_NOT_FOUND", "rate bucket does not exist")
        if bucket.get("integration_id") != source.get("integration_id") or bucket.get("operation") != source.get("operation"):
            return None, self._error("retry_api_call", "ENTITY_SCOPE_MISMATCH", "rate bucket does not match source integration and operation")
        if bucket.get("status") == "disabled" or int(bucket.get("remaining") or 0) < 1:
            return None, self._error("retry_api_call", "RATE_LIMIT_EXCEEDED", "rate bucket lacks capacity")
        incident_id = arguments.get("incident_id")
        if incident_id:
            incident = self.manager.get_entity("incident_window", incident_id, id_field="incident_id")
            if incident is None:
                return None, self._error("retry_api_call", "INCIDENT_NOT_FOUND", "incident does not exist")
            if incident.get("integration_id") != source.get("integration_id"):
                return None, self._error("retry_api_call", "INCIDENT_SCOPE_MISMATCH", "incident belongs to another integration")
        return source, None

    def _execute_retry(self, source: dict[str, Any], arguments: dict[str, Any]) -> dict[str, Any]:
        credential = self.manager.get_entity("api_credential", arguments["credential_id"], id_field="credential_id")
        budget = self.manager.get_entity("retry_budget", arguments["retry_budget_id"], id_field="budget_id")
        bucket = self.manager.get_entity("rate_limit_bucket", arguments["rate_limit_bucket_id"], id_field="bucket_id")
        assert credential is not None and budget is not None and bucket is not None

        raw_snapshot = self.manager.snapshot()
        try:
            budget["used_attempts"] = int(budget.get("used_attempts") or 0) + 1
            available = int(budget.get("max_attempts") or 0) - budget["used_attempts"] - int(budget.get("reserved_attempts") or 0)
            if available <= 0:
                budget["status"] = "exhausted"
            budget["updated_at"] = REFERENCE_NOW
            self.manager.add_entity("retry_budget", budget, id_field="budget_id")

            bucket["remaining"] = int(bucket.get("remaining") or 0) - 1
            if bucket["remaining"] == 0:
                bucket["status"] = "exhausted"
            bucket["updated_at"] = REFERENCE_NOW
            self.manager.add_entity("rate_limit_bucket", bucket, id_field="bucket_id")

            digest = hashlib.sha256(
                f"{source['call_id']}|{len(self.manager.list_entities('api_call_attempt'))}".encode("utf-8")
            ).hexdigest()[:12]
            retry_call_id = f"adapter-retry-{digest}"
            retry_call = copy.deepcopy(source)
            retry_call.update(
                {
                    "call_id": retry_call_id,
                    "credential_id": credential["credential_id"],
                    "retry_budget_id": budget["budget_id"],
                    "rate_limit_bucket_id": bucket["bucket_id"],
                    "recovery_profile_id": arguments["recovery_profile_id"],
                    "retry_attempt": int(source.get("retry_attempt") or 0) + 1,
                    "status": "success",
                    "http_status": 200,
                    "error_code": None,
                    "created_at": REFERENCE_NOW,
                    "completed_at": REFERENCE_NOW,
                    "updated_at": REFERENCE_NOW,
                    "side_effect_committed": True,
                    "duplicate_of_call_id": source["call_id"],
                    "incident_id": arguments.get("incident_id"),
                }
            )
            self.manager.add_entity("api_call_attempt", retry_call, id_field="call_id")

            audit_digest = hashlib.sha256(f"{retry_call_id}|audit".encode("utf-8")).hexdigest()[:12]
            audit_id = f"adapter-audit-{audit_digest}"
            self.manager.add_entity(
                "audit_event",
                {
                    "audit_id": audit_id,
                    "entity_type": "ApiCallAttempt",
                    "entity_id": retry_call_id,
                    "integration_id": source.get("integration_id"),
                    "actor": ROLE,
                    "action": "api_call_retried",
                    "outcome": "success",
                    "reason": "Bounded adapter retry",
                    "related_call_id": retry_call_id,
                    "incident_id": arguments.get("incident_id"),
                    "created_at": REFERENCE_NOW,
                    "metadata": {
                        "source_call_id": source["call_id"],
                        "operation": source.get("operation"),
                        "request_fingerprint": source.get("request_hash"),
                        "recovery_profile_id": arguments["recovery_profile_id"],
                    },
                },
                id_field="audit_id",
            )
        except Exception:
            self._restore_database(raw_snapshot["database"], raw_snapshot.get("counters", {}))
            return self._error("retry_api_call", "ATOMIC_RETRY_FAILED", "retry transaction was rolled back")

        return self._success(
            "retry_api_call",
            {
                "source_call_id": source["call_id"],
                "retry_call_id": retry_call_id,
                "status": "success",
                "retry_attempt": retry_call["retry_attempt"],
                "side_effect_committed": True,
                "credential_id": credential["credential_id"],
                "retry_budget_id": budget["budget_id"],
                "rate_limit_bucket_id": bucket["bucket_id"],
                "recovery_profile_id": arguments["recovery_profile_id"],
                "rate_limit_remaining": bucket["remaining"],
                "retry_budget_available": available,
                "audit_id": audit_id,
            },
            "Retry call executed",
        )

    def dispatch(self, tool: str, arguments: Any, actor: str = ROLE) -> dict[str, Any]:
        if actor != ROLE:
            return self._error(tool, "ROLE_FORBIDDEN", "actor is not an API reliability operator")
        if tool not in ALLOWED_TOOLS:
            return self._error(tool, "TOOL_FORBIDDEN", "tool is outside the reliability recovery slice")
        cost = self._cost(tool, arguments)
        if self.remaining < cost:
            return self._error(tool, "WORK_QUOTA_EXHAUSTED", "insufficient API-work quota")
        validation_error = _validate_arguments(tool, arguments)
        if validation_error is not None:
            self.remaining -= cost
            return self._error(tool, "INVALID_ARGUMENTS", validation_error, cost)

        before_hash = self.business_hash()
        self.remaining -= cost
        if tool == "execute_api_call":
            guarded = self._execute_context_guard(arguments)
            if guarded is None:
                guarded = self._idempotency_guard(arguments)
            if guarded is not None:
                return self._finish(tool, arguments, guarded, cost, before_hash)
            raw_snapshot = self.manager.snapshot()
            result = _sanitize_raw_result(tool, self.server.call_tool(tool, state_manager=self.manager, **arguments))
            if result["content"]["status"] == "error" and self.business_hash() != before_hash:
                self._restore_database(raw_snapshot["database"], raw_snapshot.get("counters", {}))
                result = self._error(tool, "ATOMIC_CALL_FAILED", "failed provider call mutation was rolled back")
            return self._finish(tool, arguments, result, cost, before_hash)
        if tool == "retry_api_call":
            source, guarded = self._retry_guard(arguments)
            result = guarded if guarded is not None else self._execute_retry(source, arguments)
            return self._finish(tool, arguments, result, cost, before_hash)
        if tool == "search_recovery_evidence":
            return self._finish(
                tool,
                arguments,
                self._search_recovery_evidence(arguments),
                cost,
                before_hash,
            )

        result = _sanitize_raw_result(tool, self.server.call_tool(tool, state_manager=self.manager, **arguments))
        return self._finish(tool, arguments, result, cost, before_hash)

    def snapshot(self) -> dict[str, Any]:
        return {
            "raw": copy.deepcopy(self.manager.snapshot()),
            "remaining": self.remaining,
            "receipts": copy.deepcopy(self.receipts),
            "applied_boundary_events": sorted(self.applied_boundary_events),
            "active_task_id": self.active_task_id,
        }

    def restore(self, snapshot: dict[str, Any]) -> None:
        self._restore_database(snapshot["raw"]["database"], snapshot["raw"].get("counters", {}))
        self.remaining = int(snapshot["remaining"])
        self.receipts = copy.deepcopy(snapshot["receipts"])
        self.applied_boundary_events = set(snapshot.get("applied_boundary_events", []))
        self.active_task_id = snapshot.get("active_task_id")

    def semantic_hash(self) -> str:
        payload = {
            "database": self.manager.snapshot()["database"],
            "remaining": self.remaining,
            "receipts": self.receipts,
            "boundary_events": sorted(self.applied_boundary_events),
            "active_task_id": self.active_task_id,
        }
        return hashlib.sha256(_canonical(payload).encode("utf-8")).hexdigest()

    def business_hash(self) -> str:
        return hashlib.sha256(
            _canonical(self.manager.snapshot()["database"]).encode("utf-8")
        ).hexdigest()

    def activate_task(self, task_id: str, allowance: int = 56) -> dict[str, Any]:
        if not isinstance(task_id, str) or not task_id:
            raise ValueError("task_id must be non-empty")
        self.active_task_id = task_id
        self.initial_budget = int(allowance)
        self.remaining = int(allowance)
        return {"task_id": task_id, "allowance": self.remaining, "world_reset": False}

    def business_events(self, since_receipt: int = 0) -> list[dict[str, Any]]:
        return copy.deepcopy([item for item in self.receipts if item["index"] > since_receipt])

    def apply_credential_rate_drift(
        self,
        event_id: str,
        credential_ids: list[str],
        bucket_ids: list[str],
    ) -> dict[str, Any]:
        if event_id in self.applied_boundary_events:
            return {"status": "success", "event_id": event_id, "idempotent": True, "changed": []}
        changed: list[str] = []
        for credential_id in credential_ids:
            credential = self.manager.get_entity("api_credential", credential_id, id_field="credential_id")
            if credential and credential.get("status") in {"active", "rotating"}:
                credential["status"] = "revoked"
                credential["updated_at"] = REFERENCE_NOW
                self.manager.add_entity("api_credential", credential, id_field="credential_id")
                changed.append(credential_id)
        for bucket_id in bucket_ids:
            bucket = self.manager.get_entity("rate_limit_bucket", bucket_id, id_field="bucket_id")
            if bucket and bucket.get("status") != "disabled":
                bucket["status"] = "disabled"
                bucket["updated_at"] = REFERENCE_NOW
                self.manager.add_entity("rate_limit_bucket", bucket, id_field="bucket_id")
                changed.append(bucket_id)
        self.applied_boundary_events.add(event_id)
        return {"status": "success", "event_id": event_id, "idempotent": False, "changed": changed}

    def grade_targets(self, targets: list[dict[str, str]]) -> dict[str, Any]:
        rows = []
        for target in targets:
            source_id = target["call_id"]
            recoveries = self.manager.query_entities(
                "api_call_attempt",
                lambda row: row.get("duplicate_of_call_id") == source_id
                and row.get("status") == "success"
                and row.get("side_effect_committed") is True,
            )
            source = self.manager.get_entity("api_call_attempt", source_id, id_field="call_id")
            committed = len(recoveries) == 1
            recovery = recoveries[0] if committed else None
            capacity_conserved = False
            recovery_policy_satisfied = False
            audit_complete = False
            if recovery:
                bucket = self.manager.get_entity("rate_limit_bucket", recovery.get("rate_limit_bucket_id", ""), id_field="bucket_id")
                budget = self.manager.get_entity("retry_budget", recovery.get("retry_budget_id", ""), id_field="budget_id")
                capacity_conserved = bool(
                    bucket
                    and budget
                    and bucket.get("integration_id") == target["integration_id"]
                    and bucket.get("operation") == target["operation"]
                    and budget.get("integration_id") == target["integration_id"]
                )
                recovery_policy_satisfied = (
                    recovery.get("recovery_profile_id") == target.get("recovery_profile_id")
                )
                audits = self.manager.query_entities(
                    "audit_event", lambda row: row.get("related_call_id") == recovery.get("call_id")
                )
                audit_complete = bool(audits)
            milestones = {
                "source_bound": bool(source and source.get("integration_id") == target["integration_id"] and source.get("operation") == target["operation"]),
                "capacity_conserved": capacity_conserved,
                "recovery_policy_satisfied": recovery_policy_satisfied,
                "single_recovery_committed": committed,
                "audit_lineage_complete": audit_complete,
            }
            score = (
                2.5 * milestones["source_bound"]
                + 5.0 * milestones["capacity_conserved"]
                + 7.5 * milestones["recovery_policy_satisfied"]
                + 7.5 * milestones["single_recovery_committed"]
                + 2.5 * milestones["audit_lineage_complete"]
            )
            rows.append({"call_id": source_id, "score": score, "milestones": milestones})
        return {"score": sum(row["score"] for row in rows), "complete_artifacts": sum(row["score"] == 25.0 for row in rows), "targets": rows}