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
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
"""Target-scoped API recovery with exact accounting and replay-checked state."""

from __future__ import annotations

from copy import deepcopy
import json
from typing import Any, Mapping

import jsonschema

from . import adapter as _adapter
from . import recovery_policy as _policy
from . import stream_runtime as _stream
from .snapshot import validate_snapshot
from .spec import (
    BUSINESS_BUDGET, DRIFT_EVENT_ID, EXACT_IDENTITY_READ_COST, EXACT_RULE_READ_COST,
    INITIAL_BUDGET, RATE_READ_COST, RETRY_COST, SNAPSHOT_SCHEMA, TARGETS,
    TOOL_BY_NAME, provider_tools,
)

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

def _is_int(value: Any) -> bool:
    return type(value) is int

def _source_cell(source: Mapping[str, Any]) -> tuple[str, str]:
    return (
        _policy.failure_signal_for(dict(source)),
        _policy.operation_class_for(str(source.get("operation") or "")),
    )

class ApiReliabilityWorld(_stream.PersistentApiReliabilityAdapter):
    """One released world; capability evidence and business state persist together."""

    def __init__(self, budget: int = INITIAL_BUDGET, *, snapshot: dict[str, Any] | None = None) -> None:
        self.capability_observations: list[dict[str, Any]] = []
        super().__init__(budget=budget)
        if snapshot is not None:
            self.restore(snapshot)

    def snapshot(self) -> dict[str, Any]:
        value = super().snapshot()
        value["schema"] = SNAPSHOT_SCHEMA
        value["capability_observations"] = deepcopy(self.capability_observations)
        return value

    def activate_task(self, task_id: str, allowance: int = BUSINESS_BUDGET, *,
                      apply_boundary_drift: bool = True) -> dict[str, Any]:
        if task_id != "T09" or apply_boundary_drift:
            return super().activate_task(task_id, allowance=allowance)
        # A researcher-only counterfactual uses the same activation without drift.
        already_applied = DRIFT_EVENT_ID in self.applied_boundary_events
        self.applied_boundary_events.add(DRIFT_EVENT_ID)
        try:
            receipt = super().activate_task(task_id, allowance=allowance)
        finally:
            if not already_applied:
                self.applied_boundary_events.remove(DRIFT_EVENT_ID)
        receipt["boundary_event_applied"] = False
        return receipt

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

    def _cost(self, tool: str, arguments: Any) -> int:
        if tool in {"list_api_credentials", "list_retry_budgets"}:
            return EXACT_IDENTITY_READ_COST
        if tool == "inspect_rate_limit_status":
            return RATE_READ_COST
        if tool == "search_recovery_evidence":
            return EXACT_RULE_READ_COST
        if tool in {"list_service_integrations", "list_fault_policies", "search_audit_events"}:
            return 4
        return super()._cost(tool, arguments)

    def _observation_is_visible(self, observation: Mapping[str, Any]) -> bool:
        if self.active_task_id is None:
            return False
        targets = TARGETS[self.active_task_id]
        kind = observation.get("kind")
        if kind in {"credential", "retry_budget"}:
            return any(
                target["integration_id"] == observation.get("integration_id")
                for target in targets
            )
        if kind == "rate_bucket":
            return any(
                target["integration_id"] == observation.get("integration_id")
                and target["operation"] == observation.get("operation")
                for target in targets
            )
        if kind == "recovery_profile":
            return any(
                target["failure_signal"] == observation.get("failure_signal")
                and target["operation_class"] == observation.get("operation_class")
                for target in targets
            )
        return False

    def _scope_matches_active_target(
        self, tool: str, arguments: Mapping[str, Any]
    ) -> bool:
        if self.active_task_id is None:
            return False
        targets = TARGETS[self.active_task_id]
        if tool == "list_api_credentials":
            return any(
                target["integration_id"] == arguments.get("integration_id")
                and target["operation"] == arguments.get("scope_contains")
                for target in targets
            )
        if tool == "list_retry_budgets":
            return any(
                target["integration_id"] == arguments.get("integration_id")
                for target in targets
            )
        if tool == "inspect_rate_limit_status":
            return any(
                target["integration_id"] == arguments.get("integration_id")
                and target["operation"] == arguments.get("operation")
                for target in targets
            )
        if tool == "search_recovery_evidence":
            return any(
                target["failure_signal"] == arguments.get("failure_signal")
                and target["operation_class"] == arguments.get("operation_class")
                for target in targets
            )
        return True

    def _append_observation(self, observation: dict[str, Any]) -> None:
        if not self._observation_is_visible(observation):
            return
        self.capability_observations.append(
            {
                **deepcopy(observation),
                "task_id": self.active_task_id,
            }
        )

    def _record_public_observations(self, result: Mapping[str, Any]) -> None:
        content = result.get("content")
        if not isinstance(content, Mapping) or content.get("status") != "success":
            return
        data = content.get("data")
        receipt_index = result.get("receipt_index")
        if not isinstance(data, Mapping) or not _is_int(receipt_index):
            return
        tool = result.get("tool")

        if tool == "list_api_credentials":
            for row in data.get("items", []):
                if not isinstance(row, Mapping):
                    continue
                self._append_observation(
                    {
                        "kind": "credential",
                        "credential_id": row.get("credential_id"),
                        "integration_id": row.get("integration_id"),
                        "operations": deepcopy(row.get("scope")),
                        "receipt_index": receipt_index,
                    }
                )
        elif tool == "list_retry_budgets":
            for row in data.get("items", []):
                if not isinstance(row, Mapping):
                    continue
                self._append_observation(
                    {
                        "kind": "retry_budget",
                        "retry_budget_id": row.get("budget_id"),
                        "integration_id": row.get("integration_id"),
                        "receipt_index": receipt_index,
                    }
                )
        elif tool == "inspect_rate_limit_status":
            for row in data.get("buckets", []):
                if not isinstance(row, Mapping):
                    continue
                self._append_observation(
                    {
                        "kind": "rate_bucket",
                        "rate_limit_bucket_id": row.get("bucket_id"),
                        "integration_id": row.get("integration_id"),
                        "operation": row.get("operation"),
                        "receipt_index": receipt_index,
                    }
                )
        elif tool == "search_recovery_evidence":
            for row in data.get("evidence", []):
                if not isinstance(row, Mapping):
                    continue
                self._append_observation(
                    {
                        "kind": "recovery_profile",
                        "recovery_profile_id": row.get("recovery_profile_id"),
                        "failure_signal": row.get("failure_signal"),
                        "operation_class": row.get("operation_class"),
                        "receipt_index": receipt_index,
                    }
                )

    def _has_credential(self, source: Mapping[str, Any], capability_id: str) -> bool:
        return any(
            row.get("kind") == "credential"
            and row.get("credential_id") == capability_id
            and row.get("integration_id") == source.get("integration_id")
            and source.get("operation") in row.get("operations", [])
            for row in self.capability_observations
        )

    def _has_retry_budget(self, source: Mapping[str, Any], capability_id: str) -> bool:
        return any(
            row.get("kind") == "retry_budget"
            and row.get("retry_budget_id") == capability_id
            and row.get("integration_id") == source.get("integration_id")
            for row in self.capability_observations
        )

    def _has_rate_bucket(self, source: Mapping[str, Any], capability_id: str) -> bool:
        return any(
            row.get("kind") == "rate_bucket"
            and row.get("rate_limit_bucket_id") == capability_id
            and row.get("integration_id") == source.get("integration_id")
            and row.get("operation") == source.get("operation")
            for row in self.capability_observations
        )

    def _has_recovery_profile(
        self, source: Mapping[str, Any], capability_id: str
    ) -> bool:
        failure_signal, operation_class = _source_cell(source)
        return any(
            row.get("kind") == "recovery_profile"
            and row.get("recovery_profile_id") == capability_id
            and row.get("failure_signal") == failure_signal
            and row.get("operation_class") == operation_class
            for row in self.capability_observations
        )

    def _provenance_error(
        self,
        arguments: dict[str, Any],
        code: str,
        message: str,
    ) -> dict[str, Any]:
        cost = self._cost("retry_api_call", arguments)
        before = self.business_hash()
        self.remaining -= cost
        result = self._error("retry_api_call", code, message, cost)
        return self._finish("retry_api_call", arguments, result, cost, before)

    @classmethod
    def _replay_snapshot(cls, snapshot: Mapping[str, Any]) -> "ApiReliabilityWorld":
        replay = cls()
        receipts = list(snapshot["receipts"])
        cursor = 0

        while cursor < len(receipts) and receipts[cursor]["task_id"] is None:
            receipt = receipts[cursor]
            replay.dispatch(receipt["tool"], deepcopy(receipt["arguments"]), receipt["actor"])
            cursor += 1

        for task_id in snapshot["activated_tasks"]:
            replay.activate_task(task_id)
            while cursor < len(receipts) and receipts[cursor]["task_id"] == task_id:
                receipt = receipts[cursor]
                replay.dispatch(
                    receipt["tool"], deepcopy(receipt["arguments"]), receipt["actor"]
                )
                cursor += 1
        if cursor != len(receipts):
            raise ValueError("API Reliability v8 receipt ledger cannot be replayed")
        return replay

    def _dispatch_business(
        self,
        tool: str,
        arguments: Mapping[str, Any],
        actor: str = _adapter.ROLE,
    ) -> dict[str, Any]:
        if (
            tool == "retry_api_call"
            and isinstance(arguments, Mapping)
            and "incident_id" in arguments
            and actor == _adapter.ROLE
            and self.active_task_id is not None
        ):
            cost = self._cost(tool, arguments)
            if self.remaining < cost:
                return self._error(
                    tool, "WORK_QUOTA_EXHAUSTED", "insufficient API-work quota"
                )
            before = self.business_hash()
            self.remaining -= cost
            result = self._error(
                tool,
                "INVALID_ARGUMENTS",
                "unsupported argument(s): incident_id",
                cost,
            )
            return self._finish(tool, dict(arguments), result, cost, before)
        return super().dispatch(tool, arguments, actor)

    def _dispatch_observed(
        self,
        tool: str,
        arguments: Mapping[str, Any],
        actor: str = _adapter.ROLE,
    ) -> dict[str, Any]:
        if tool == "retry_api_call" and actor == _adapter.ROLE:
            if self.remaining < self._cost(tool, arguments):
                return self._dispatch_business(tool, arguments, actor)
            if (
                isinstance(arguments, dict)
                and "incident_id" not in arguments
                and _adapter._validate_arguments(tool, arguments) is None
            ):
                source = self.manager.get_entity(
                    "api_call_attempt", arguments["call_id"], id_field="call_id"
                )
                if source is not None:
                    checks = (
                        (
                            self._has_credential(source, arguments["credential_id"]),
                            "UNOBSERVED_CREDENTIAL",
                            "credential was not returned by a public capability read for this source scope",
                        ),
                        (
                            self._has_retry_budget(source, arguments["retry_budget_id"]),
                            "UNOBSERVED_RETRY_BUDGET",
                            "retry budget was not returned by a public capability read for this source scope",
                        ),
                        (
                            self._has_rate_bucket(
                                source, arguments["rate_limit_bucket_id"]
                            ),
                            "UNOBSERVED_RATE_BUCKET",
                            "rate bucket was not returned by a public capability read for this source scope",
                        ),
                        (
                            self._has_recovery_profile(
                                source, arguments["recovery_profile_id"]
                            ),
                            "UNOBSERVED_RECOVERY_PROFILE",
                            "recovery profile was not observed for the exact failure and operation cell",
                        ),
                    )
                    for observed, code, message in checks:
                        if not observed:
                            return self._provenance_error(dict(arguments), code, message)

        result = self._dispatch_business(tool, arguments, actor)
        if actor == _adapter.ROLE:
            self._record_public_observations(result)
        return result

    def _scoped_error(
        self,
        tool: str,
        arguments: dict[str, Any],
        code: str,
        message: str,
    ) -> dict[str, Any]:
        cost = self._cost(tool, arguments)
        if self.remaining < cost:
            return self._dispatch_observed(tool, arguments, _adapter.ROLE)
        before = self.business_hash()
        self.remaining -= cost
        result = self._error(tool, code, message, cost)
        return self._finish(tool, arguments, result, cost, before)

    def dispatch(
        self,
        tool: str,
        arguments: Mapping[str, Any],
        actor: str = _adapter.ROLE,
    ) -> dict[str, Any]:
        if actor != _adapter.ROLE:
            return self._dispatch_observed(tool, arguments, actor)
        if tool not in TOOL_BY_NAME:
            if tool in _adapter.ALLOWED_TOOLS:
                prepared = dict(arguments) if isinstance(arguments, Mapping) else {}
                return self._scoped_error(
                    tool,
                    prepared,
                    "TOOL_FORBIDDEN",
                    "tool is outside the target-scoped API recovery surface",
                )
            return self._dispatch_observed(tool, arguments, actor)
        if not isinstance(arguments, Mapping):
            return self._dispatch_observed(tool, arguments, actor)

        prepared = dict(arguments)
        if tool in {
            "list_api_credentials",
            "list_retry_budgets",
            "search_recovery_evidence",
        }:
            prepared.setdefault("limit", 1)
        try:
            jsonschema.validate(prepared, TOOL_BY_NAME[tool]["input_schema"])
        except jsonschema.ValidationError:
            return self._scoped_error(
                tool,
                prepared,
                "INVALID_ARGUMENTS",
                "arguments do not match the target-scoped public schema",
            )

        if tool in {
            "list_api_credentials",
            "list_retry_budgets",
            "inspect_rate_limit_status",
            "search_recovery_evidence",
        } and not self._scope_matches_active_target(tool, prepared):
            return self._scoped_error(
                tool,
                prepared,
                "TARGET_SCOPE_REQUIRED",
                "capability discovery must match one exact target in the active task",
            )
        return self._dispatch_observed(tool, prepared, actor)

    def restore(self, snapshot: dict[str, Any]) -> None:
        validate_snapshot(snapshot)
        replay = self._replay_snapshot(snapshot)
        canonical = replay.snapshot()
        if _canonical(canonical) != _canonical(snapshot):
            raise ValueError("API Reliability v8 snapshot differs from canonical public replay")
        inherited = deepcopy(canonical)
        observations = inherited.pop("capability_observations")
        inherited["schema"] = _stream.SNAPSHOT_SCHEMA
        super().restore(inherited)
        self.capability_observations = observations
        if _canonical(self.snapshot()) != _canonical(canonical):
            raise ValueError("API Reliability v8 snapshot did not round trip exactly")

    def grade(self, task_id: str | None = None) -> dict[str, Any]:
        diagnostic = super().grade(task_id)
        rows = []
        for row in diagnostic["targets"]:
            item = deepcopy(row)
            item["diagnostic_milestone_score"] = item["score"]
            complete = all(bool(value) for value in item["milestones"].values())
            item["score"] = 25.0 if complete else 0.0
            item["complete"] = complete
            rows.append(item)
        complete_artifacts = sum(int(row["complete"]) for row in rows)
        return {
            "task_id": diagnostic["task_id"],
            "score": 25.0 * complete_artifacts,
            "complete_artifacts": complete_artifacts,
            "completed_artifacts": complete_artifacts,
            "remaining_budget": self.remaining,
            "work_units_used": self.initial_budget - self.remaining,
            "targets": rows,
        }