Skip to content

Commit 14a63dd

Browse files
hhyykkcodexloopx-agent
authored
fix(steward): recover Lark return receipts after runtime rollback (#9786)
* fix(steward): recover Lark return receipts after runtime rollback Signed-off-by: Codex <codex@openai.com> * fix(steward): show legacy admissions in return reconciliation Signed-off-by: Codex <codex@openai.com> * fix(steward): recover verified returns before dispatch Signed-off-by: Codex <codex@openai.com> * test(digests): register the Steward return recovery consumer Signed-off-by: Codex <codex@openai.com> --------- Signed-off-by: Codex <codex@openai.com> Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Co-authored-by: Codex <codex@openai.com> Co-authored-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 9f43e59 commit 14a63dd

28 files changed

Lines changed: 1686 additions & 191 deletions

‎docs/reference/protocols/manager-evidence-and-continuity-v0.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,32 @@ origin correlation. A delivered request remains deduplicated after worker
620620
acknowledgment and service restart. Full three-Goal live acceptance remains open.
621621

622622

623+
### Worker results returned to Lark
624+
625+
Each newly published result stores `provider_delivery_id`, derived from its
626+
immutable request ID and result key. The Lark inbox return uses it when
627+
building its provider idempotency key, including the per-part keys for a split
628+
post. Replaying a historical result without this field retains its original
629+
key and allows verification against its saved receipt. Keep the matching
630+
reader available for in-flight deliveries during a rollback.
631+
632+
The return verifies the selected chat and placement as well as the content.
633+
For a source-thread reply, an explicit parent must match the captured source
634+
message, and an explicit root must agree with its thread root. A readback
635+
that omits those IDs can establish thread membership through the native
636+
thread metadata and root readback. An unavailable locator or insufficient
637+
verification evidence must not be recorded as delivered.
638+
639+
For a single text return, the Lark sender checks the Core dispatch checkpoint
640+
just before its POST and again before retrying a lost response with the same
641+
provider key. Exact dispatch requires the current revision, matching admission
642+
token and a clock inside the half-open admission interval. A provider receipt
643+
from an already dispatched request can still be recorded after the interval
644+
when the checkpoint remains current. A provider exception after dispatch with
645+
no locator leaves the effect unverified. A known refusal before any write can
646+
be retried through a fresh admission. An expired legacy-format exact admission
647+
with no locator remains ambiguous after restart.
648+
623649
### Lark receipt feedback
624650

625651
After a routed manager message is durably captured, the synchronous ingress

‎loopx/capabilities/manager_context/README.md‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1022,6 +1022,90 @@ Replies are immutable and additive, separate from private decision reasons and
10221022
Core progress. Query `manager-inbox status` or `loopx_manager_read view=handoffs`
10231023
for delivery diagnostics. These queries are not required from the user.
10241024

1025+
### Restore a Steward return after a runtime rollback
1026+
1027+
For an ordinary Lark Steward return with a captured Lark source and no attached
1028+
files, publishing a new result first opens a private recovery record. Each
1029+
delivery transition commits there before updating the runtime's Inbox receipt.
1030+
The record binds the request and result key to the original publication and
1031+
route. It retains the verified provider receipt and locator when available.
1032+
Replaying the publication reuses the existing record.
1033+
1034+
The local service uses `$XDG_STATE_HOME/loopx/return-witnesses`. The fallback
1035+
is `%LOCALAPPDATA%/loopx/return-witnesses` on Windows and
1036+
`~/.local/state/loopx/return-witnesses` elsewhere. Set `LOOPX_RETURN_WITNESS_DIR`
1037+
to an absolute private directory on storage retained across restoration of the
1038+
runtime. The publishing and sending processes must resolve the same store.
1039+
Access to the private records includes access to provider locators. Keep the
1040+
store through the lifetime of all restorable runtime backups and pending
1041+
returns. Removing an enrolled record leaves the return pending reconciliation.
1042+
1043+
After restoring a runtime, the return pump checks the current authority and
1044+
original publication before repairing the Inbox receipt. A verified receipt
1045+
can restore the recorded delivery. A saved locator can be read back. A
1046+
confirmed zero-effect refusal can proceed through normal admission with the
1047+
original key. Ambiguous writes, conflicting revisions and missing evidence
1048+
remain visible through the reconciliation query. An enrolled return whose
1049+
recovery store was unavailable becomes eligible for another check after five
1050+
minutes. Historical queued Lark results without enrollment or a provider locator
1051+
require operator review.
1052+
Historical verified deliveries and recoverable locators retain their existing
1053+
read paths.
1054+
1055+
The single-text recovery tests exercise a restart on one host with the
1056+
independent store intact. Reverting both stores can erase the evidence of a
1057+
remote write. Keep prior-version senders stopped during a rollback. Verification
1058+
of a full-state backup creates an inert inspection copy.
1059+
1060+
### Take over a return before its first provider write
1061+
1062+
An enrolled ordinary Lark return can use a sender that checkpoints before its
1063+
first possible provider effect. Core records that protocol with the exact
1064+
admission in the detached recovery record. The sender checkpoints before a
1065+
single provider call or before the part-delivery flow can send a part or a
1066+
stall notice.
1067+
1068+
When a worker exits during admission or preview, a qualified worker can take
1069+
over at the 60-second deadline. Core rechecks the original result and grant,
1070+
verifies the untouched admission in the retained record, and issues a new
1071+
token and revision. Delayed callbacks using the original generation are
1072+
rejected. A worker without that protocol leaves the reservation available for
1073+
a qualified worker.
1074+
1075+
Admissions without a recorded protocol and dispatched attempts without a
1076+
locator stay unverified. A saved locator follows the existing readback path.
1077+
This recovery covers the ordinary external route. Steward-bound providers and
1078+
attachment uploads have separate delivery paths.
1079+
1080+
### Find returns that still need reconciliation
1081+
1082+
From the local owner CLI, run the following with the registered receiving Goal
1083+
and Agent. Use the escalation age agreed for that route. Omitting it leaves
1084+
the escalation decision unknown.
1085+
1086+
```sh
1087+
loopx manager-inbox reconciliation --goal-id research --agent-id worker --escalate-after-seconds 3600
1088+
```
1089+
1090+
The report counts unresolved return effects across the current receiver's
1091+
Inbox before paging. Each row identifies a request and result key. A row
1092+
marked `automatic_check` is still eligible for the delivery pump to inspect.
1093+
A row marked `manual` needs operator review. For a valid provider attempt
1094+
the report includes the intent and receipt digests and whether a locator
1095+
exists. The provider locator and message body stay in private storage.
1096+
1097+
`unverified_since` records the first possible dispatch or observed uncertainty
1098+
in the current unresolved episode. Historical cases can have an unknown start.
1099+
`age_seconds` is also unknown if the observation clock predates the start.
1100+
`oldest_known_age_seconds` covers dated cases. Check `unknown_age_count` and
1101+
`unreadable_requests` alongside it. The threshold marks cases due for
1102+
escalation in this report. Reading it has no delivery or notification effects.
1103+
1104+
Use `--offset` with `next_offset` to continue, or `--request-id` for one
1105+
request. Each invocation observes current local receipts. A changing inbox
1106+
can change page membership. Independent receiver records are needed to
1107+
establish what the provider actually delivered.
1108+
10251109
## Semantic delegation and peer review
10261110

10271111
Shared request/decision/result storage now lives in the

‎loopx/capabilities/manager_context/roundtrip.py‎

Lines changed: 41 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
_read_peer_return_route,
4848
_registered_chat_route,
4949
_request_lock,
50+
return_witness_directory,
5051
iter_result_paths,
5152
DELIVERY_STATUSES as DELIVERY_STATUSES,
5253
DELIVERY_ERRORS as DELIVERY_ERRORS,
@@ -630,6 +631,7 @@ def read_chat_history_selection(root, store, session_id, *, registry, selection,
630631

631632

632633
RETURN_DELIVERY_TRANSACTION = "manager_return_delivery_transaction_v0"
634+
CHECKPOINT_BEFORE_EFFECT = "checkpoint_before_effect_v1"
633635

634636

635637
def _hold_return_source_fence(root, route, effects):
@@ -695,11 +697,17 @@ def _return_transaction(host, path, phase, request):
695697
}.items():
696698
if isinstance(observed.get(field), dict):
697699
observed[field] = {key: observed[field][key] for key in keys if key in observed[field]}
700+
witness = {}
701+
if str(observed.get("entry", {}).get("source_id", "")).startswith("lark:"):
702+
try:
703+
witness["witness_directory"] = return_witness_directory(root)
704+
except (OSError, ValueError, RuntimeError):
705+
pass # The typed owner holds an enrolled return when its evidence is unavailable.
698706
result = effect_runtime_result("manager.return_delivery.transact", {
699707
"schema_version": RETURN_DELIVERY_TRANSACTION,
700708
"runtime_root": str(root), "request_id": path.parent.name,
701709
"result_key": path.stem, "phase": phase, "now": host["clock"]().isoformat(),
702-
"exact": exact, "facts": observed, **payload,
710+
"exact": exact, "facts": observed, **witness, **payload,
703711
}, retry_safe=False)
704712
if (not isinstance(result, dict) or result.get("schema_version") != RETURN_DELIVERY_TRANSACTION
705713
or result.get("action") not in {"skip", "private", "verify", "send", "reconcile_private"}
@@ -708,11 +716,12 @@ def _return_transaction(host, path, phase, request):
708716
return result
709717

710718

711-
def _return_provider(plan, source, sender, record_attempt):
719+
def _return_provider(plan, source, sender, record_attempt, checkpointed_send=None):
712720
route, session, turn = (source[key] for key in ("route", "session", "turn"))
713721
# The typed transaction owns the canonical result identity. Transports may
714722
# verify a mirror of this message, never guess its identity from its body.
715-
route = {**route, "return_message_id": plan["message_id"]}
723+
route = {**route, "return_message_id": plan["message_id"],
724+
"provider_delivery_id": plan.get("provider_delivery_id")}
716725
attachments = plan.get("attachments") or []
717726
if attachments:
718727
if getattr(sender, "supports_result_files", False) is not True:
@@ -729,7 +738,13 @@ def _return_provider(plan, source, sender, record_attempt):
729738
return {"kind": "verify_unavailable"}
730739
return {"kind": "verified", "verification": verifier(
731740
{**route, "original_publisher": plan.get("original_publisher")}, session, turn, plan["text"], attempt)}
732-
provider = getattr(sender, "send_with_attempt", None)
741+
if plan.get("dispatch_protocol") == CHECKPOINT_BEFORE_EFFECT:
742+
select = getattr(sender, "checkpointed_return_sender", None)
743+
if not callable(checkpointed_send) or not callable(select) or select(route, session) != checkpointed_send:
744+
raise ReturnTransportUnavailable("checkpointed return transport changed")
745+
provider = checkpointed_send
746+
else:
747+
provider = getattr(sender, "send_with_attempt", None)
733748
if callable(provider):
734749
sent = provider(route, session, turn, plan["text"], record_attempt)
735750
elif callable(sender):
@@ -762,23 +777,28 @@ def __init__(self, transact, checkpoint, exact, original_provider):
762777
self.transact = transact
763778
self.checkpoint = checkpoint
764779
self.exact = exact
780+
self.dispatch_started = False
765781

766782
def _save(self, phase, **payload):
767783
result = self.transact(phase, **payload)
768784
self.checkpoint.update({key: result[key] for key in ("revision", "token")})
769785
return result
770786

771787
def before_provider_send(self):
772-
# Exact returns already persisted their sending admission at prepare.
773-
if not self.exact:
774-
self._save("dispatch")
788+
self.before_provider_dispatch(None)
775789

776790
def before_provider_dispatch(self, provider):
777-
if not self.exact:
778-
result = self._save("dispatch", dispatch_provider=provider,
779-
original_dispatch_provider=self.original_provider)
780-
if result.get("dispatch_allowed") is not True:
781-
raise _PriorDispatchUnknown
791+
check_transcript = provider is not None and not self.exact
792+
dispatch: dict[str, object] = {"replay": self.dispatch_started}
793+
if check_transcript:
794+
dispatch.update(
795+
dispatch_provider=provider,
796+
original_dispatch_provider=self.original_provider,
797+
)
798+
result = self._save("dispatch", **dispatch)
799+
self.dispatch_started = True
800+
if check_transcript and result.get("dispatch_allowed") is not True:
801+
raise _PriorDispatchUnknown
782802

783803
def __call__(self, attempt):
784804
self._save("attempt", attempt=dict(attempt))
@@ -802,7 +822,14 @@ def _deliver_return(host, path, sender, frozen_route):
802822

803823
store, cancelled = host["store"], host["cancelled"]
804824
with _return_source(host, path, frozen_route) as facts:
805-
plan = _return_transaction(host, path, "prepare", {"facts": facts})
825+
select = getattr(sender, "checkpointed_return_sender", None)
826+
checkpointed_send = None
827+
if host["exact"] and not facts.get("error") and callable(select) and facts.get("session"):
828+
checkpointed_send = select(facts["route"], facts["session"])
829+
request = {"facts": facts}
830+
if callable(checkpointed_send):
831+
request["dispatch_protocol"] = CHECKPOINT_BEFORE_EFFECT
832+
plan = _return_transaction(host, path, "prepare", request)
806833
source = dict(facts)
807834
if plan.get("source_unavailable") is True:
808835
logging.getLogger(__name__).warning("Exact manager return admission unavailable")
@@ -845,7 +872,7 @@ def transact(phase, **payload):
845872
original_provider=original_message.get("return_dispatch_provider") if isinstance(original_message, dict) else None)
846873
if cancelled():
847874
return 0
848-
outcome = _return_provider(plan, source, sender, record_attempt)
875+
outcome = _return_provider(plan, source, sender, record_attempt, checkpointed_send)
849876
if outcome["kind"] == "private" and source["turn"].get("origin") == "native_loopx":
850877
outcome["original_message"] = original_message
851878
except _PriorDispatchUnknown:

‎loopx/capabilities/native_chat/transports.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,13 @@ def return_dispatch_provider(self, route: dict[str, Any], session: dict[str, Any
114114
provider = getattr(transport, "return_dispatch_provider", None)
115115
return provider(route, session) if callable(provider) else None
116116

117+
def checkpointed_return_sender(self, route: dict[str, Any], session: dict[str, Any]) -> Callable[..., Any] | None:
118+
# Ordinary returns use the default route. Steward bindings select their own provider at send time.
119+
if session.get("steward_context") is not None:
120+
return None
121+
select = getattr(self.default_return, "checkpointed_return_sender", None)
122+
return select(route, session) if callable(select) else None
123+
117124
def send_with_attempt(self, route: dict[str, Any], session: dict[str, Any], turn: dict[str, Any],
118125
text: str, record_attempt: Callable[[Mapping[str, str | None]], None]) -> dict[str, Any]:
119126
transport = self._return_transport(route, session)

‎loopx/cli_commands/manager_inbox.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ def register_manager_inbox(subparsers, add_format):
198198
"link",
199199
"report",
200200
"status",
201+
"reconciliation",
201202
"control",
202203
"configure-read-scope",
203204
"configure-delivery-scope",
@@ -267,6 +268,7 @@ def register_manager_inbox(subparsers, add_format):
267268
help="For acknowledge-return: whether this Turn used, deferred, or rejected the peer result.")
268269
parser.add_argument("--related-todo-id", action="append", default=[])
269270
parser.add_argument("--evidence-id", action="append", default=[])
271+
parser.add_argument("--escalate-after-seconds", type=int, help="For reconciliation: flag cases at or beyond this age in seconds.")
270272
parser.add_argument("--offset", type=int, default=0)
271273
parser.add_argument("--limit", type=int, default=8)
272274
parser.add_argument("--cursor", help="For read: continue with the previous request or native child result cursor.")
@@ -284,6 +286,8 @@ def handle_manager_inbox(args, registry_path, runtime_root):
284286
remainder = getattr(args, "remaining_work", None)
285287
resume = getattr(args, "resume_when", None)
286288
attention_only = getattr(args, "attention_only", False)
289+
if getattr(args, "escalate_after_seconds", None) is not None and args.manager_inbox_action != "reconciliation":
290+
raise ValueError("--escalate-after-seconds requires reconciliation")
287291
if attention_only and (args.manager_inbox_action != "read" or getattr(args, "request_id", None) is not None):
288292
raise ValueError("--attention-only requires read without --request-id")
289293
if remainder is not None or resume is not None:
@@ -555,6 +559,18 @@ def handle_manager_inbox(args, registry_path, runtime_root):
555559
args.related_todo_id,
556560
args.evidence_id,
557561
)
562+
elif args.manager_inbox_action == "reconciliation":
563+
from ..control_plane.collaboration.goal_instance_scope import (
564+
collaboration_goal_scope,
565+
)
566+
from ..control_plane.collaboration.inbox import read_inbox_transaction
567+
568+
with collaboration_goal_scope(registry_path, goal_id=args.goal_id, agents=(args.agent_id,)) as scope:
569+
result = read_inbox_transaction(runtime_root, {
570+
"operation": "reconciliation", "goal_id": args.goal_id, "agent_id": args.agent_id,
571+
"request_id": args.request_id, "offset": args.offset, "limit": args.limit,
572+
"escalate_after_seconds": args.escalate_after_seconds,
573+
}, scope=scope)
558574
elif args.manager_inbox_action == "status":
559575
from ..capabilities.manager_context.tracking import query
560576

0 commit comments

Comments
 (0)