fivefold 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. fivefold/__init__.py +4 -0
  2. fivefold/_data/db/bootstrap.sql +26 -0
  3. fivefold/_data/db/migrations/0001_schemas.sql +67 -0
  4. fivefold/_data/db/migrations/0002_gateway.sql +224 -0
  5. fivefold/_data/db/migrations/0003_gateway_record_0010.sql +91 -0
  6. fivefold/_data/db/migrations/0004_harness.sql +141 -0
  7. fivefold/_data/db/migrations/0005_sim.sql +679 -0
  8. fivefold/_data/db/migrations/0006_gateway_reads.sql +66 -0
  9. fivefold/_data/db/migrations/0007_eval.sql +33 -0
  10. fivefold/_data/db/migrations/0008_run_stop.sql +18 -0
  11. fivefold/_data/db/migrations/0009_message_copies.sql +69 -0
  12. fivefold/_data/db/migrations/0010_gateway_g1_check.sql +14 -0
  13. fivefold/_data/db/migrations/0011_model_calls.sql +37 -0
  14. fivefold/_data/db/migrations/0012_recovery_latency.sql +23 -0
  15. fivefold/_data/db/migrations/0013_split_topology.sql +33 -0
  16. fivefold/_data/db/migrations/0014_tool_call_args.sql +20 -0
  17. fivefold/_data/db/registry/0001_registry.sql +31 -0
  18. fivefold/_data/faults/expected.yaml +406 -0
  19. fivefold/_data/scenarios/dev/dev-001-single-po.yaml +45 -0
  20. fivefold/_data/scenarios/dev/dev-002-human-approval.yaml +47 -0
  21. fivefold/agents/__init__.py +7 -0
  22. fivefold/agents/branch.py +187 -0
  23. fivefold/agents/checkpoint.py +77 -0
  24. fivefold/agents/connection.py +153 -0
  25. fivefold/agents/live.py +492 -0
  26. fivefold/agents/policy.py +426 -0
  27. fivefold/agents/remote.py +333 -0
  28. fivefold/agents/replay.py +170 -0
  29. fivefold/agents/scripted.py +122 -0
  30. fivefold/agents/tools.py +229 -0
  31. fivefold/agents/worker.py +164 -0
  32. fivefold/domain/__init__.py +5 -0
  33. fivefold/domain/api.py +517 -0
  34. fivefold/domain/authority.py +149 -0
  35. fivefold/domain/contracts.py +80 -0
  36. fivefold/domain/identity.py +113 -0
  37. fivefold/domain/prices.py +178 -0
  38. fivefold/domain/report.py +92 -0
  39. fivefold/domain/rules.py +346 -0
  40. fivefold/domain/scenario.py +524 -0
  41. fivefold/evaluator/__init__.py +155 -0
  42. fivefold/evaluator/__main__.py +127 -0
  43. fivefold/evaluator/authorization.py +146 -0
  44. fivefold/evaluator/checks.py +331 -0
  45. fivefold/evaluator/evaluate.py +109 -0
  46. fivefold/evaluator/evidence.py +392 -0
  47. fivefold/evaluator/freshness.py +136 -0
  48. fivefold/evaluator/liveness.py +236 -0
  49. fivefold/evaluator/load.py +354 -0
  50. fivefold/evaluator/metrics.py +95 -0
  51. fivefold/evaluator/records.py +452 -0
  52. fivefold/evaluator/recovery.py +209 -0
  53. fivefold/evaluator/report.py +1096 -0
  54. fivefold/evaluator/result.py +344 -0
  55. fivefold/evaluator/store.py +83 -0
  56. fivefold/faults/__init__.py +5 -0
  57. fivefold/faults/catalog.py +278 -0
  58. fivefold/faults/plan.py +538 -0
  59. fivefold/gateway/__init__.py +6 -0
  60. fivefold/gateway/admin.py +179 -0
  61. fivefold/gateway/admin_api.py +398 -0
  62. fivefold/gateway/codec.py +372 -0
  63. fivefold/gateway/destination.py +64 -0
  64. fivefold/gateway/dispatcher.py +379 -0
  65. fivefold/gateway/freshness.py +83 -0
  66. fivefold/gateway/invariants.py +761 -0
  67. fivefold/gateway/memory.py +277 -0
  68. fivefold/gateway/pg_store.py +657 -0
  69. fivefold/gateway/records.py +592 -0
  70. fivefold/gateway/server.py +102 -0
  71. fivefold/gateway/sim_client.py +295 -0
  72. fivefold/gateway/state_machine.py +376 -0
  73. fivefold/gateway/steps.py +897 -0
  74. fivefold/gateway/store.py +635 -0
  75. fivefold/gateway/tools.py +424 -0
  76. fivefold/gateway/twin.py +199 -0
  77. fivefold/gateway/wire.py +138 -0
  78. fivefold/harness/__init__.py +6 -0
  79. fivefold/harness/actors.py +230 -0
  80. fivefold/harness/cells.py +303 -0
  81. fivefold/harness/clock.py +209 -0
  82. fivefold/harness/demo.py +397 -0
  83. fivefold/harness/fault_effects.py +122 -0
  84. fivefold/harness/live_options.py +159 -0
  85. fivefold/harness/log.py +540 -0
  86. fivefold/harness/mcp_link.py +409 -0
  87. fivefold/harness/migrations.py +520 -0
  88. fivefold/harness/models.py +368 -0
  89. fivefold/harness/registry.py +105 -0
  90. fivefold/harness/reports.py +100 -0
  91. fivefold/harness/rng.py +57 -0
  92. fivefold/harness/run.py +881 -0
  93. fivefold/harness/scheduler.py +441 -0
  94. fivefold/harness/sim_points.py +215 -0
  95. fivefold/harness/split/__init__.py +34 -0
  96. fivefold/harness/split/__main__.py +275 -0
  97. fivefold/harness/split/credentials.py +74 -0
  98. fivefold/harness/split/faults.py +75 -0
  99. fivefold/harness/split/gateway.py +769 -0
  100. fivefold/harness/split/hops.py +291 -0
  101. fivefold/harness/split/lifecycle.py +322 -0
  102. fivefold/harness/split/rundir.py +152 -0
  103. fivefold/harness/split/service.py +157 -0
  104. fivefold/harness/split/simulator.py +432 -0
  105. fivefold/harness/study.py +643 -0
  106. fivefold/harness/transport.py +533 -0
  107. fivefold/paths.py +24 -0
  108. fivefold/py.typed +0 -0
  109. fivefold/recorder/__init__.py +18 -0
  110. fivefold/recorder/__main__.py +308 -0
  111. fivefold/recorder/cassette.py +322 -0
  112. fivefold/recorder/playback.py +316 -0
  113. fivefold/recorder/recording.py +133 -0
  114. fivefold/sim/__init__.py +37 -0
  115. fivefold/sim/config.py +52 -0
  116. fivefold/sim/endpoint.py +176 -0
  117. fivefold/sim/ledger.py +583 -0
  118. fivefold/sim/service.py +834 -0
  119. fivefold/viewer/__init__.py +14 -0
  120. fivefold/viewer/__main__.py +75 -0
  121. fivefold/viewer/app.py +122 -0
  122. fivefold/viewer/records.py +108 -0
  123. fivefold/viewer/source.py +196 -0
  124. fivefold/viewer/timeline.py +61 -0
  125. fivefold-0.1.0.dist-info/METADATA +169 -0
  126. fivefold-0.1.0.dist-info/RECORD +128 -0
  127. fivefold-0.1.0.dist-info/WHEEL +4 -0
  128. fivefold-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,426 @@
1
+ """The scripted agent policy of record 0008, as a generator of tool calls.
2
+
3
+ The policy is the same in every configuration, except where 0008 says B0 differs:
4
+
5
+ 1. Read the quotes of the intent's allowed suppliers and the budget. Choose the cheapest
6
+ acceptable quote that fits the budget (with `rank` 1, the second-cheapest: F9's
7
+ `different_args` variant for the second worker).
8
+ 2. B0 only: request approval, then wait with `get_approval_status` for at most the
9
+ scenario limit or 60,000 ms, at most 3 times (0015).
10
+ 3. Submit the write once, with no optional fields. G modes cite exactly the reads of the
11
+ operation's dependencies; B0 passes the approval id and those reads' versions.
12
+ 4. Act on the result, as 0008's table says.
13
+ 5. Report. G modes first call `get_action_status` once per action with `wait_ms = 0`. If
14
+ G2 refuses the report as inconsistent, correct the named claims and resubmit, at
15
+ most twice.
16
+
17
+ `scripted_policy` returns a generator that yields `ToolCall`s and is sent each call's
18
+ result: the tool's JSON, parsed. The scripted model replays it over the conversation's
19
+ tool results to find the next call, so the policy keeps no state outside the
20
+ conversation, and a worker resumed from its checkpoint (F11) decides the same way.
21
+
22
+ An action rejected with reason `run_closed`, which another worker's report can cause
23
+ (0010), stops work on the intent, as 0008's table says since record 0011 amended it.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from collections.abc import Generator, Mapping, Sequence
29
+ from dataclasses import dataclass, field
30
+ from enum import StrEnum
31
+ from typing import Any
32
+
33
+ from fivefold.domain.rules import Operation, budget_key, inventory_key, quote_key
34
+ from fivefold.domain.scenario import Intent, PurchaseOrderAccept, ReservationAccept
35
+
36
+ WAIT_MS = 60_000
37
+ """The maximum the scripted policy asks for in each status wait (0015)."""
38
+
39
+ MAX_WAITS = 3
40
+ """Status waits per action, and approval waits per request (0008)."""
41
+
42
+ MAX_STALE_RETRIES = 2
43
+ """Re-reads after a stale-input rejection (0008)."""
44
+
45
+ MAX_REPORT_CORRECTIONS = 2
46
+ """Resubmissions after G2 refuses a report as inconsistent (0008)."""
47
+
48
+ APPROVAL_REASONS = frozenset(
49
+ {"approval_denied", "approval_revoked", "approval_expired", "approval_timeout"}
50
+ )
51
+ """Rejections that end work on an intent (0008)."""
52
+
53
+ WAITING_STATES = frozenset(
54
+ {"pending_approval", "proposed", "authorized", "dispatched", "outcome_unknown"}
55
+ )
56
+ """States the agent waits on with `get_action_status` (0008)."""
57
+
58
+ UNSETTLED_STATES = frozenset({"dispatched", "outcome_unknown"})
59
+ """States in which a write may or may not have committed: the claim is `unknown`."""
60
+
61
+ REREAD_REFUSALS = frozenset({"invalid_args", "unknown_read", "missing_basis"})
62
+ """Refusals after which the agent re-reads and tries once more (0008)."""
63
+
64
+ INPUT_CHECKS = frozenset({"stale_input", "undeclared_input", "unobserved_input"})
65
+ """A conditional write's failed checks about its inputs (0005)."""
66
+
67
+ Result = Mapping[str, Any]
68
+
69
+
70
+ class Mode(StrEnum):
71
+ """Which tool surface the agent has (0008)."""
72
+
73
+ GATEWAY = "gateway"
74
+ """G1 and G2: the gateway's tools."""
75
+
76
+ BASELINE = "baseline"
77
+ """B0: the simulator's API and the report sink."""
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class ToolCall:
82
+ """One tool call the policy makes."""
83
+
84
+ name: str
85
+ args: Mapping[str, object]
86
+
87
+
88
+ @dataclass
89
+ class _Outcome:
90
+ """Where work on one intent ended, as the claim the report will make."""
91
+
92
+ status: str
93
+ effect_ids: list[str] = field(default_factory=list)
94
+ note: str = ""
95
+ action_ids: list[str] = field(default_factory=list)
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class _Choice:
100
+ """The option chosen for an intent, and the reads it relies on."""
101
+
102
+ args: dict[str, str | int]
103
+ reads: tuple[Result, ...]
104
+
105
+
106
+ Policy = Generator[ToolCall, Result, None]
107
+ _Step = Generator[ToolCall, Result, Any]
108
+
109
+
110
+ def scripted_policy(
111
+ intents: Sequence[Intent], *, mode: Mode, rank: int = 0, max_wait_ms: int = WAIT_MS
112
+ ) -> Policy:
113
+ """The policy for one worker, with its scenario limit and option rank."""
114
+ wait_ms = min(WAIT_MS, max_wait_ms)
115
+ outcomes: dict[str, _Outcome] = {}
116
+ for intent in intents:
117
+ if mode is Mode.GATEWAY:
118
+ outcomes[intent.id] = yield from _gateway_intent(intent, rank, wait_ms)
119
+ else:
120
+ outcomes[intent.id] = yield from _baseline_intent(intent, rank, wait_ms)
121
+ if mode is Mode.GATEWAY:
122
+ for outcome in outcomes.values():
123
+ yield from _refresh(outcome)
124
+ yield from _report(outcomes)
125
+
126
+
127
+ # Reading and choosing --------------------------------------------------------------------
128
+
129
+
130
+ def _is_fact(result: Result) -> bool:
131
+ """Whether a read returned a fact: G modes give a read id, B0 an answer `fact`."""
132
+ return "read_id" in result or result.get("answer") == "fact"
133
+
134
+
135
+ def _read_and_choose(intent: Intent, rank: int) -> _Step:
136
+ """Read what the intent depends on and choose an option, or return None."""
137
+ accept = intent.accept
138
+ if isinstance(accept, ReservationAccept):
139
+ stock = yield ToolCall(
140
+ "get_inventory", {"warehouse_id": accept.warehouse_id, "sku": accept.sku}
141
+ )
142
+ if not _is_fact(stock) or int(stock["data"]["available"]) < accept.quantity:
143
+ return None
144
+ args: dict[str, str | int] = {
145
+ "warehouse_id": accept.warehouse_id,
146
+ "sku": accept.sku,
147
+ "quantity": accept.quantity,
148
+ }
149
+ return _Choice(args, (stock,))
150
+ assert isinstance(accept, PurchaseOrderAccept)
151
+ quotes: list[tuple[str, Result]] = []
152
+ for supplier_id in sorted(set(accept.suppliers)):
153
+ quote = yield ToolCall("get_quote", {"supplier_id": supplier_id, "sku": accept.sku})
154
+ if _is_fact(quote):
155
+ quotes.append((supplier_id, quote))
156
+ budget = yield ToolCall("get_budget", {"cost_center": accept.cost_center})
157
+ if not _is_fact(budget):
158
+ return None
159
+ left = int(budget["data"]["limit_minor"]) - int(budget["data"]["committed_minor"])
160
+ acceptable: list[tuple[int, str, Result]] = []
161
+ for supplier_id, quote in quotes:
162
+ data = quote["data"]
163
+ price = int(data["unit_price_minor"])
164
+ if (
165
+ data.get("status") == "active"
166
+ and price <= accept.max_unit_price_minor
167
+ and data.get("currency") == accept.currency
168
+ and accept.quantity >= int(data["min_quantity"])
169
+ and accept.quantity * price <= left
170
+ ):
171
+ acceptable.append((price, supplier_id, quote))
172
+ acceptable.sort(key=lambda option: (option[0], option[1]))
173
+ if rank >= len(acceptable):
174
+ return None
175
+ price, supplier_id, quote = acceptable[rank]
176
+ args = {
177
+ "supplier_id": supplier_id,
178
+ "sku": accept.sku,
179
+ "quantity": accept.quantity,
180
+ "unit_price_minor": price,
181
+ "currency": accept.currency,
182
+ "cost_center": accept.cost_center,
183
+ }
184
+ return _Choice(args, (quote, budget))
185
+
186
+
187
+ # G modes ---------------------------------------------------------------------------------
188
+
189
+
190
+ def _gateway_intent(intent: Intent, rank: int, wait_ms: int) -> _Step:
191
+ """Steps 1, 3 and 4 for one intent, through the gateway's tools."""
192
+ actions: list[str] = []
193
+ stale_retries = failure_retries = reread_retries = 0
194
+ while True:
195
+ choice = yield from _read_and_choose(intent, rank)
196
+ if choice is None:
197
+ return _Outcome("not_done", note="No acceptable option fits.", action_ids=actions)
198
+ cited = [read["read_id"] for read in choice.reads]
199
+ result = yield ToolCall(
200
+ str(intent.operation), {"intent_id": intent.id, **choice.args, "based_on": cited}
201
+ )
202
+ waits: dict[str, int] = {}
203
+ while True:
204
+ if result.get("result") == "refused":
205
+ reason = str(result.get("reason"))
206
+ details = result.get("details") or {}
207
+ if reason == "intent_busy":
208
+ holder = str(details["action_id"])
209
+ if holder not in actions:
210
+ actions.append(holder)
211
+ if waits.get(holder, 0) >= MAX_WAITS:
212
+ return _settled_outcome(str(details.get("state")), actions, None)
213
+ waits[holder] = waits.get(holder, 0) + 1
214
+ result = yield ToolCall(
215
+ "get_action_status", {"action_id": holder, "wait_ms": wait_ms}
216
+ )
217
+ continue
218
+ if reason == "intent_done":
219
+ holder = str(details["action_id"])
220
+ if holder not in actions:
221
+ actions.append(holder)
222
+ effect = str(details["effect_id"])
223
+ return _Outcome("done", [effect], f"Done as {effect}.", actions)
224
+ if reason in REREAD_REFUSALS and reread_retries < 1:
225
+ reread_retries += 1
226
+ break
227
+ return _Outcome("not_done", note=f"Refused: {reason}.", action_ids=actions)
228
+ action_id = str(result["action_id"])
229
+ if action_id not in actions:
230
+ actions.append(action_id)
231
+ state = str(result["state"])
232
+ if state == "confirmed":
233
+ effect = str(result["effect_id"])
234
+ return _Outcome("done", [effect], f"Done as {effect}.", actions)
235
+ if state in WAITING_STATES:
236
+ if waits.get(action_id, 0) >= MAX_WAITS:
237
+ return _settled_outcome(state, actions, None)
238
+ waits[action_id] = waits.get(action_id, 0) + 1
239
+ result = yield ToolCall(
240
+ "get_action_status", {"action_id": action_id, "wait_ms": wait_ms}
241
+ )
242
+ continue
243
+ reason = str(result.get("reason"))
244
+ if result.get("stale") or reason == "stale_input":
245
+ if stale_retries < MAX_STALE_RETRIES:
246
+ stale_retries += 1
247
+ break
248
+ return _Outcome("not_done", note="Inputs kept changing.", action_ids=actions)
249
+ if state == "rejected" and reason in APPROVAL_REASONS:
250
+ return _Outcome("not_done", note=f"Stopped: {reason}.", action_ids=actions)
251
+ if state == "failed" and failure_retries < 1:
252
+ failure_retries += 1
253
+ break
254
+ return _Outcome("not_done", note=f"Ended {state}: {reason}.", action_ids=actions)
255
+
256
+
257
+ def _settled_outcome(state: str, actions: list[str], effect: str | None) -> _Outcome:
258
+ """The claim for an action the agent stopped waiting on (0008, step 5)."""
259
+ if state == "confirmed" and effect is not None:
260
+ return _Outcome("done", [effect], f"Done as {effect}.", actions)
261
+ if state in UNSETTLED_STATES:
262
+ return _Outcome("unknown", note="The outcome is not known yet.", action_ids=actions)
263
+ return _Outcome("not_done", note=f"Stopped while {state}.", action_ids=actions)
264
+
265
+
266
+ def _refresh(outcome: _Outcome) -> _Step:
267
+ """Step 5: read each action's state once, with no wait, and settle the claim."""
268
+ if not outcome.action_ids:
269
+ return None
270
+ effects: list[str] = []
271
+ unsettled = False
272
+ for action_id in outcome.action_ids:
273
+ result = yield ToolCall("get_action_status", {"action_id": action_id, "wait_ms": 0})
274
+ state = str(result.get("state"))
275
+ if state == "confirmed":
276
+ effects.append(str(result["effect_id"]))
277
+ elif state in UNSETTLED_STATES:
278
+ unsettled = True
279
+ if effects:
280
+ outcome.status, outcome.effect_ids = "done", effects
281
+ outcome.note = f"Done as {', '.join(effects)}."
282
+ elif unsettled:
283
+ outcome.status, outcome.effect_ids = "unknown", []
284
+ outcome.note = "The outcome is not known yet."
285
+ elif outcome.status != "not_done":
286
+ outcome.status, outcome.effect_ids = "not_done", []
287
+ outcome.note = "Nothing was committed."
288
+ return None
289
+
290
+
291
+ # B0 --------------------------------------------------------------------------------------
292
+
293
+
294
+ def _scope(operation: Operation, args: Mapping[str, str | int]) -> dict[str, str | int]:
295
+ """What an approval for exactly this write covers (0002, rule 5)."""
296
+ if operation is Operation.RESERVE_INVENTORY:
297
+ return {
298
+ "warehouse_id": args["warehouse_id"],
299
+ "sku": args["sku"],
300
+ "max_quantity": args["quantity"],
301
+ }
302
+ return {
303
+ "supplier_id": args["supplier_id"],
304
+ "sku": args["sku"],
305
+ "max_quantity": args["quantity"],
306
+ "max_amount_minor": int(args["quantity"]) * int(args["unit_price_minor"]),
307
+ "currency": args["currency"],
308
+ "cost_center": args["cost_center"],
309
+ }
310
+
311
+
312
+ def _covers(scope: Mapping[str, object], wanted: Mapping[str, object]) -> bool:
313
+ """Whether an approval's scope still covers a write with scope `wanted`."""
314
+ for name, value in wanted.items():
315
+ held = scope.get(name)
316
+ if name.startswith("max_"):
317
+ if not isinstance(held, int) or not isinstance(value, int) or value > held:
318
+ return False
319
+ elif held != value:
320
+ return False
321
+ return True
322
+
323
+
324
+ def _basis(intent: Intent, choice: _Choice) -> dict[str, int]:
325
+ """The versions of the reads the write relies on: its dependencies (0004)."""
326
+ args = choice.args
327
+ if intent.operation is Operation.RESERVE_INVENTORY:
328
+ keys = [inventory_key(str(args["warehouse_id"]), str(args["sku"]))]
329
+ else:
330
+ keys = [
331
+ quote_key(str(args["supplier_id"]), str(args["sku"])),
332
+ budget_key(str(args["cost_center"])),
333
+ ]
334
+ return {key: int(read["version"]) for key, read in zip(keys, choice.reads, strict=True)}
335
+
336
+
337
+ def _baseline_intent(intent: Intent, rank: int, wait_ms: int) -> _Step:
338
+ """Steps 1 to 4 for one intent, against the simulator's API."""
339
+ approval: tuple[str, dict[str, str | int]] | None = None
340
+ stale_retries = failure_retries = 0
341
+ while True:
342
+ choice = yield from _read_and_choose(intent, rank)
343
+ if choice is None:
344
+ return _Outcome("not_done", note="No acceptable option fits.")
345
+ wanted = _scope(intent.operation, choice.args)
346
+ if approval is None or not _covers(approval[1], wanted):
347
+ answer = yield ToolCall(
348
+ "request_approval",
349
+ {"intent_id": intent.id, "operation": str(intent.operation), "scope": wanted},
350
+ )
351
+ waits = 0
352
+ while answer.get("status") == "pending" and waits < MAX_WAITS:
353
+ waits += 1
354
+ answer = yield ToolCall(
355
+ "get_approval_status",
356
+ {"approval_id": answer["approval_id"], "wait_ms": wait_ms},
357
+ )
358
+ if answer.get("status") != "approved":
359
+ status = answer.get("status", answer.get("reason"))
360
+ return _Outcome("not_done", note=f"Approval {status}.")
361
+ approval = (str(answer["approval_id"]), wanted)
362
+ result = yield ToolCall(
363
+ str(intent.operation),
364
+ {
365
+ "intent_id": intent.id,
366
+ "approval_id": approval[0],
367
+ "basis": _basis(intent, choice),
368
+ **choice.args,
369
+ },
370
+ )
371
+ kind = result.get("answer")
372
+ if kind == "committed":
373
+ effect = str(result["effect_id"])
374
+ return _Outcome("done", [effect], f"Done as {effect}.")
375
+ if kind == "in_progress":
376
+ return _Outcome("unknown", note="The write is still in progress.")
377
+ checks = {str(check.get("check")) for check in result.get("failed_checks", [])}
378
+ if checks & INPUT_CHECKS:
379
+ if stale_retries < MAX_STALE_RETRIES:
380
+ stale_retries += 1
381
+ continue
382
+ return _Outcome("not_done", note="Inputs kept changing.")
383
+ if checks:
384
+ return _Outcome("not_done", note=f"Stopped: {', '.join(sorted(checks))}.")
385
+ if failure_retries < 1:
386
+ failure_retries += 1
387
+ continue
388
+ return _Outcome("not_done", note=f"Rejected: {result.get('reason')}.")
389
+
390
+
391
+ # The report ------------------------------------------------------------------------------
392
+
393
+
394
+ def _claim(intent_id: str, outcome: _Outcome) -> dict[str, object]:
395
+ return {
396
+ "intent_id": intent_id,
397
+ "status": outcome.status,
398
+ "effect_ids": list(outcome.effect_ids) if outcome.status == "done" else [],
399
+ "note": outcome.note,
400
+ }
401
+
402
+
403
+ def _from_records(recorded: Sequence[Mapping[str, Any]]) -> _Outcome:
404
+ """The claim the gateway's records support, from a report refusal's details."""
405
+ effects = [str(e) for action in recorded for e in action.get("effect_ids", [])]
406
+ if effects:
407
+ return _Outcome("done", effects, f"Done as {', '.join(effects)}.")
408
+ if any(action.get("state") in UNSETTLED_STATES for action in recorded):
409
+ return _Outcome("unknown", note="The outcome is not known yet.")
410
+ return _Outcome("not_done", note="Nothing was committed.")
411
+
412
+
413
+ def _report(outcomes: dict[str, _Outcome]) -> _Step:
414
+ """Submit the report; correct the named claims at most twice (0008, step 5)."""
415
+ corrections = 0
416
+ while True:
417
+ claims = [_claim(intent_id, outcome) for intent_id, outcome in outcomes.items()]
418
+ result = yield ToolCall("submit_final_report", {"claims": claims})
419
+ if result.get("result") != "refused" or result.get("reason") != "report_inconsistent":
420
+ return None
421
+ if corrections >= MAX_REPORT_CORRECTIONS:
422
+ return None
423
+ corrections += 1
424
+ for conflict in (result.get("details") or {}).get("conflicts", []):
425
+ intent_id = str(conflict["intent_id"])
426
+ outcomes[intent_id] = _from_records(conflict.get("recorded", []))