Skip to content

Commit d85dcf0

Browse files
authored
Merge pull request #10065 from loopx-project/codex/identify-inbox-content-conflicts
Identify the captured message behind a Lark history content conflict
2 parents 20be612 + 1b3010f commit d85dcf0

3 files changed

Lines changed: 74 additions & 4 deletions

File tree

‎loopx/extensions/lark/README.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,52 @@ payload. Inbox and cursor directories are restricted to the owner, and their
205205
state files are written with mode `0600`. Product-specific URL classification
206206
and field-enrichment policy remain with the consuming product or private skill.
207207

208+
### Check the current source of a captured message
209+
210+
A forward history window follows message creation time. An author can edit a
211+
message from an earlier window without adding a new inbox item. When a page
212+
returns the same message again with different normalized text, execution keeps
213+
the original snapshot and holds the cursor. The failure receipt reports
214+
`group_history_inbox_readback_failed`. Its optional
215+
`readback.conflicting_message_ref` identifies the first content conflict on
216+
that route. A missing file or a different stored route still requires a local
217+
inbox integrity check.
218+
219+
To resolve the reference locally, set `INBOX_DIR` to the route's configured
220+
inbox and `CONFLICTING_MESSAGE_REF` to the value in the receipt.
221+
222+
```sh
223+
MESSAGE_ID=$(python3 - "$INBOX_DIR" "$CONFLICTING_MESSAGE_REF" <<'PYREF'
224+
import hashlib
225+
from pathlib import Path
226+
import sys
227+
228+
directory, reference = sys.argv[1:]
229+
matches = [
230+
p.stem for p in Path(directory).glob("om_*.json")
231+
if "sha256:" + hashlib.sha256(p.stem.encode()).hexdigest()[:24] == reference
232+
]
233+
if len(matches) != 1:
234+
raise SystemExit("Expected one matching message in the configured route inbox")
235+
print(matches[0])
236+
PYREF
237+
)
238+
```
239+
240+
Read the current message using the configured Bot profile. If you already have
241+
the source message ID, this is the only command needed.
242+
243+
```sh
244+
lark-cli --profile "$PROFILE" im +messages-mget --as bot \
245+
--message-ids "$MESSAGE_ID" --no-reactions --format json
246+
```
247+
248+
Check the Bot readback's message and chat IDs against the source route before
249+
using its content. The provider's `updated` flag and `update_time` describe
250+
the source as observed. A text difference alone cannot establish who edited it.
251+
The read-only lookup preserves earlier acknowledgements and effects. A retry
252+
can advance the held page once its contents verify against the retained inbox.
253+
208254
The cursor binding includes the route key, Bot profile, chat, inbox config,
209255
resolved inbox destination, and capture scope. If any of those inputs changes,
210256
catch-up fails closed with `Lark group-history cursor source binding changed`

‎loopx/extensions/lark/group_history.py‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from typing import Any
1818
from urllib.parse import urlsplit, urlunsplit
1919

20+
from ..external_connector_runtime import external_event_ref
2021
from .event_collector import _executable_prefix, load_lark_event_collector_config
2122
from .event_collector_runtime import (
2223
_is_profile_self_message,
@@ -387,6 +388,10 @@ def _page_digest(events: Sequence[Mapping[str, Any]], page_token: str | None) ->
387388
return hashlib.sha256("\0".join(values).encode()).hexdigest()[:16]
388389

389390

391+
class _InboxContentConflict(ValueError):
392+
"""The retained message and route match, but their captured text differs."""
393+
394+
390395
def _verify_inbox_events(
391396
route: Mapping[str, Any], events: Sequence[Mapping[str, Any]]
392397
) -> int:
@@ -403,9 +408,11 @@ def _verify_inbox_events(
403408
not isinstance(payload, Mapping)
404409
or payload.get("message_id") != event["message_id"]
405410
or payload.get("route_key") != route["route_key"]
406-
or payload.get("content") != expected_content
411+
or not isinstance(payload.get("content"), str)
407412
):
408413
raise ValueError("Lark group-history inbox readback mismatch")
414+
if payload["content"] != expected_content:
415+
raise _InboxContentConflict(external_event_ref(str(event["message_id"])))
409416
verified += 1
410417
return verified
411418

@@ -589,13 +596,16 @@ def catch_up_lark_group_history(
589596

590597
try:
591598
verified_count = _verify_inbox_events(route, events)
592-
except ValueError:
593-
return _failed_receipt(
599+
except ValueError as error:
600+
failure = _failed_receipt(
594601
route_key=route_key,
595602
status="group_history_inbox_readback_failed",
596603
external_read_performed=True,
597604
inbox_state_mutated=bool(ingest["write_performed"]),
598605
)
606+
if isinstance(error, _InboxContentConflict):
607+
failure["readback"]["conflicting_message_ref"] = str(error)
608+
return failure
599609
updated = {
600610
**state,
601611
"next_page_token": next_page_token,

‎tests/extensions/test_lark_group_history.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import hashlib
34
import json
45
import subprocess
56
from collections.abc import Sequence
@@ -930,8 +931,9 @@ def test_cursor_fails_closed_when_provider_binding_changes(tmp_path: Path) -> No
930931
_catch_up(project, config, PageRunner([]), execute=True)
931932

932933

934+
@pytest.mark.parametrize("stored_route", ["requirements-a", "other-route"])
933935
def test_cursor_does_not_advance_when_duplicate_content_readback_differs(
934-
tmp_path: Path,
936+
tmp_path: Path, stored_route: str,
935937
) -> None:
936938
project, config = _project(tmp_path)
937939
ingest_routed_lark_event_inbox(
@@ -949,6 +951,10 @@ def test_cursor_does_not_advance_when_duplicate_content_readback_differs(
949951
],
950952
execute=True,
951953
)
954+
snapshot = project / ".loopx/inbox/requirements-a/om_edited.json"
955+
original = json.loads(snapshot.read_text())
956+
original["route_key"] = stored_route
957+
snapshot.write_text(json.dumps(original))
952958
runner = PageRunner(
953959
[
954960
{
@@ -966,6 +972,14 @@ def test_cursor_does_not_advance_when_duplicate_content_readback_differs(
966972
assert receipt["status"] == "group_history_inbox_readback_failed"
967973
assert receipt["cursor_state_mutated"] is False
968974
assert receipt["readback"]["verified"] is False # type: ignore[index]
975+
if stored_route == "requirements-a":
976+
digest = hashlib.sha256(b"om_edited").hexdigest()[:24]
977+
assert receipt["readback"]["conflicting_message_ref"] == f"sha256:{digest}"
978+
else:
979+
assert "conflicting_message_ref" not in receipt["readback"]
980+
assert json.loads(snapshot.read_text()) == original
981+
public = json.dumps(receipt)
982+
assert all(value not in public for value in ("om_edited", "old content", "new content"))
969983
assert not (project / ".loopx" / "inbox" / ".history").exists()
970984

971985

0 commit comments

Comments
 (0)