The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: bind hosted discussion attachment tasks to source events
Teknium676238c81b82
diff --git a/gateway/hosted_room_discussion.py b/gateway/hosted_room_discussion.pyindex 03c46780a20..6d7e3529fcc 100644--- a/gateway/hosted_room_discussion.py+++ b/gateway/hosted_room_discussion.py@@ -187,10 +187,26 @@ def _all_failure_reasons() -> frozenset[str]:def validate_user_payload(value: Any) -> dict[str, Any]:"""Validate and normalize the exact ``message.user`` Discussion payload."""- payload = _exact_fields(value, label="user payload", required=_USER_PAYLOAD_FIELDS)- return {- "text": _text(payload["text"], label="user payload text", max_bytes=MAX_USER_TEXT_BYTES),- "thread_id": _identifier(payload["thread_id"], label="thread_id")}+ payload = _exact_fields(value, label="user payload", required=_USER_PAYLOAD_FIELDS, optional={"attachments"})+ normalized: dict[str, Any] = {"thread_id": _identifier(payload["thread_id"], label="thread_id")}+ if "attachments" in payload:+ normalized["attachments"] = _message_manifest(payload["attachments"])+ text = payload["text"]+ if not isinstance(text, str) or len(text.encode("utf-8")) > MAX_USER_TEXT_BYTES:+ raise DiscussionValidationError("user payload text must be a bounded string")+ if not text.strip() and not normalized.get("attachments"):+ raise DiscussionValidationError("user payload must contain text or attachments")+ normalized["text"] = text.strip()+ return normalized+++def _message_manifest(value: Any) -> list[dict[str, Any]]:+ from gateway.hosted_room_attachments import validate_manifest++ try:+ return validate_manifest(value)+ except ValueError as exc:+ raise DiscussionValidationError(str(exc)) from excdef _validate_member_target(value: Any, *, profile: str, known_profiles: set[str], index: int) -> dict[str, Any]:@@ -356,7 +372,19 @@ def _validate_user_event(kind: str, payload: Payload, actor: Payload, room: Discdef _validate_member_message(kind: str, payload: Payload, actor: Payload, room: DiscussionRoom) -> Payload:- _exact_fields(payload, label="message.member payload", required=_MEMBER_MESSAGE_FIELDS)+ _exact_fields(payload, label="message.member payload", required=_MEMBER_MESSAGE_FIELDS,+ optional={"attachments", "recipient_member_ids"})+ payload = dict(payload)+ if "attachments" in payload:+ payload["attachments"] = _message_manifest(payload["attachments"])+ if "recipient_member_ids" in payload:+ recipients = payload["recipient_member_ids"]+ if not isinstance(recipients, list) or not recipients:+ raise DiscussionValidationError("recipient_member_ids must be a non-empty list")+ recipients = [_member_by_id(room, recipient).member_id for recipient in recipients]+ if len(set(recipients)) != len(recipients):+ raise DiscussionValidationError("recipient_member_ids must be unique")+ payload["recipient_member_ids"] = recipients_validate_turn_coordinates(payload, room)if not isinstance(text := payload.get("text"), str) or not text.strip() or is_pass_text(text):raise DiscussionValidationError("message.member text must be a non-pass string")@@ -475,7 +503,12 @@ def _derive_member_watermarks(events: Sequence[_ValidatedEvent]) -> dict[tuple[sif message is None or any(message.payload.get(f) != event.payload.get(f) for f in ("task_id", "member_id", "thread_id")):raise DiscussionValidationError("turn.settled references no matching member message")- watermark = max(watermark, message.seq)+ discussion_seq = next((candidate.seq for candidate in events+ if candidate.event_id == event.payload["discussion_event_id"]), None)+ if discussion_seq is None:+ raise DiscussionValidationError("turn.settled references no matching user discussion")+ if watermark >= discussion_seq:+ watermark = max(watermark, message.seq)watermarks[key] = max(watermarks.get(key, 0), watermark)return watermarks@@ -541,20 +574,26 @@ def _build_prompt(def _make_task_plan(*, room: DiscussionRoom, discussion_event: _ValidatedEvent, member: DiscussionMember, member_index: int,round_index: int, seen_through_seq: int, prompt: str,- input_context: Mapping[str, Any] | None = None) -> DiscussionTaskPlan:+ input_context: Mapping[str, Any] | None = None,+ attachments: Sequence[Mapping[str, Any]] = ()) -> DiscussionTaskPlan:turn_id = f"d{discussion_event.seq}.r{round_index}.p{member_index}.s{seen_through_seq}.m{_member_digest(member)}"+ if attachments:+ attachments = driver.validate_bound_task_manifest(list(attachments))seed = compact_json({"discussion_event_id": discussion_event.event_id, "member_id": member.member_id, "member_index": member_index,"prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(), "room_id": room.room_id,"round_index": round_index, "seen_through_seq": seen_through_seq, "source_event_seq": discussion_event.seq,"thread_id": discussion_event.payload["thread_id"],- **({"input_context": input_context} if input_context is not None else {})})+ **({"input_context": input_context} if input_context is not None else {}),+ **({"attachments": attachments} if attachments else {})})identity = driver.TaskIdentity(room_id=room.room_id, task_id=f"dtask:{hashlib.sha256(seed.encode('utf-8')).hexdigest()[:48]}",thread_id=str(discussion_event.payload["thread_id"]), turn_id=turn_id)payload = {"target_member_id": member.member_id, "target_profile": member.profile, "prompt": prompt,"source_event_seq": discussion_event.seq}+ if attachments:+ payload["attachments"] = list(attachments)if input_context is not None:payload["input_context"] = dict(input_context)return DiscussionTaskPlan(@@ -607,6 +646,36 @@ def _effective_watermarks(return watermarks+def _event_attachments(event: _ValidatedEvent, member: DiscussionMember) -> list[dict[str, Any]]:+ if event.kind == "message.member":+ if event.payload["member_id"] == member.member_id:+ return []+ recipients = event.payload.get("recipient_member_ids")+ if recipients is not None and member.member_id not in recipients:+ return []+ return [{**attachment, "event_id": event.event_id} for attachment in event.payload.get("attachments", [])]+++def _bounded_task_delta(messages: Sequence[_ValidatedEvent], *, watermark: int,+ member: DiscussionMember) -> tuple[list[_ValidatedEvent], list[dict[str, Any]]]:+ from gateway.hosted_room_attachments import MAX_TASK_ATTACHMENTS, MAX_TASK_ATTACHMENT_BYTES++ selected: list[_ValidatedEvent] = []+ attachments: list[dict[str, Any]] = []+ size = 0+ for event in messages:+ if event.seq <= watermark:+ continue+ entries = _event_attachments(event, member)+ next_size = size + sum(item["size"] for item in entries)+ if len(attachments) + len(entries) > MAX_TASK_ATTACHMENTS or next_size > MAX_TASK_ATTACHMENT_BYTES:+ break # Each validated message fits; consume only whole event prefixes.+ selected.append(event)+ attachments.extend(entries)+ size = next_size+ return selected, attachments++def plan_next_task(room_value: Any, events: Sequence[Mapping[str, Any]], *, local_profiles: Iterable[str],initial_watermarks: Mapping[tuple[str, str], int] | None = None,@@ -627,7 +696,6 @@ def plan_next_task((int(event.payload["round_index"]), str(event.payload["member_id"])) for event in validatedif event.kind in _TERMINAL_EVENT_KINDS and event.payload.get("discussion_event_id") == discussion.event_id}watermarks = _effective_watermarks(validated, initial_watermarks)- seen_through_seq = max(event.seq for event in thread_messages)for round_index in range(MAX_DISCUSSION_ROUNDS):# The user's message selects the first round, with no mention meaning# everyone. Later rounds are opt-in: only a peer explicitly cited by a@@ -638,20 +706,19 @@ def plan_next_task(resolve_mentions((str(discussion.payload["text"]),), room.members) if round_index == 0else _unaddressed_member_mentions(discussion_messages, room))for member_index, member in enumerate(_rotate(responders, round_index)):- if (round_index, member.member_id) in terminals:- continuewatermark = watermarks.get((thread_id, member.member_id), 0)- if not any(watermark < event.seq <= seen_through_seq for event in thread_messages):+ delta, attachments = _bounded_task_delta(thread_messages, watermark=watermark, member=member)+ if not delta or ((round_index, member.member_id) in terminals and not attachments):continue+ seen_through_seq = delta[-1].seqprompt = _build_prompt(room=room, member=member, messages=thread_messages, watermark=watermark,seen_through_seq=seen_through_seq)return decide("task", "member_turn", task=_make_task_plan(room=room, discussion_event=discussion, member=member, member_index=member_index,- round_index=round_index, seen_through_seq=seen_through_seq, prompt=prompt,- input_context=(validate_task_input({"watermark": watermark, "event_seqs": [- event.seq for event in thread_messages if watermark < event.seq <= seen_through_seq]})- if freeze_input_context else None)))+ round_index=round_index, seen_through_seq=seen_through_seq, prompt=prompt, attachments=attachments,+ input_context=(validate_task_input({"watermark": watermark, "event_seqs": [event.seq for event in delta]})+ if freeze_input_context or attachments else None)))if not any(int(event.payload["round_index"]) == round_index for event in member_messages):return decide("settled", "silent_round")if round_index == MAX_DISCUSSION_ROUNDS - 1:@@ -705,10 +772,17 @@ def reconstruct_task_plan(and event.payload.get("thread_id") == identity.thread_id}if any(seq not in message_seqs for seq in input_context["event_seqs"]):raise DiscussionReconstructionError("task input message is missing")+ attachments: list[dict[str, Any]] = []+ if "attachments" in payload:+ if input_context is None:+ raise DiscussionReconstructionError("attachment task requires frozen input_context")+ by_seq = {event.seq: event for event in validated}+ attachments = [item for seq in input_context["event_seqs"]+ for item in _event_attachments(by_seq[seq], member)]reconstructed = _make_task_plan(room=room, discussion_event=discussion, member=member, member_index=int(match.group("position")),round_index=int(match.group("round")), seen_through_seq=int(match.group("seen")), prompt=prompt,- input_context=input_context)+ input_context=input_context, attachments=attachments)if reconstructed.identity != identity or dict(reconstructed.payload) != dict(payload):raise DiscussionReconstructionError("driver task failed deterministic reconstruction")return reconstructed@@ -790,7 +864,7 @@ def plan_publication(if status == "deferred":_bounded_int(execution_generation, message="deferred publication requires an execution generation", low=1)newer_same_thread = any(- event.kind == "message.user" and event.seq > task.seen_through_seq+ event.kind == "message.user" and event.seq > int(task.payload["source_event_seq"])and event.payload.get("thread_id") == task.identity.thread_id for event in validated)effective_status: TerminalKind = ("cancelled" if newer_same_thread and status != "deferred" else status)digest = task.identity.task_id.removeprefix("dtask:")diff --git a/gateway/hosted_room_driver.py b/gateway/hosted_room_driver.pyindex da14eff9e0f..50e73e52da1 100644--- a/gateway/hosted_room_driver.py+++ b/gateway/hosted_room_driver.py@@ -13,6 +13,7 @@ import jsonimport mathimport sqlite3from contextlib import closing+from collections.abc import Mappingfrom dataclasses import dataclassfrom functools import partialfrom typing import Any, Callable, Literal, get_args@@ -35,7 +36,7 @@ TASK_STATUSES = frozenset(get_args(TaskStatus))TERMINAL_STATUSES = frozenset({"settled", "failed", "cancelled"})_TASK_PAYLOAD_REQUIRED_FIELDS = frozenset({"target_profile", "prompt", "source_event_seq"})-_TASK_PAYLOAD_OPTIONAL_FIELDS = frozenset({"target_member_id", "input_context"})+_TASK_PAYLOAD_OPTIONAL_FIELDS = frozenset({"target_member_id", "input_context", "attachments"})_LEASE_COLUMNS = frozenset({"room_id", "gateway_id", "authority_epoch", "process_generation", "lease_generation", "expires_at", "acquired_at","updated_at", "released_at"})@@ -142,6 +143,23 @@ def _lease_window(ttl_seconds: Any, clock: Clock) -> tuple[float, float]:return now, now + ttl+def validate_bound_task_manifest(value: Any) -> list[dict[str, Any]]:+ """Validate store metadata plus the exact source event for each task input."""+ from gateway.hosted_room_attachments import validate_task_manifest++ if not isinstance(value, list) or not value:+ raise DriverValidationError("attachments must be a non-empty list")+ if any(not isinstance(item, Mapping) or "event_id" not in item for item in value):+ raise DriverValidationError("task attachment requires event_id")+ event_ids = [_identifier(item["event_id"], label="attachment event_id") for item in value]+ try:+ manifest = validate_task_manifest([+ {key: val for key, val in item.items() if key != "event_id"} for item in value])+ except ValueError as exc:+ raise DriverValidationError(str(exc)) from exc+ return [{**item, "event_id": event_id} for item, event_id in zip(manifest, event_ids)]++def _task_payload(value: Any) -> tuple[dict[str, Any], str, str]:if not isinstance(value, dict):raise DriverValidationError("payload must be an object")@@ -165,6 +183,8 @@ def _task_payload(value: Any) -> tuple[dict[str, Any], str, str]:raise DriverValidationError(str(exc)) from excif "target_member_id" in value:normalized["target_member_id"] = _identifier(value["target_member_id"], label="target_member_id")+ if "attachments" in value:+ normalized["attachments"] = validate_bound_task_manifest(value["attachments"])encoded = compact_json(normalized)return normalized, encoded, hashlib.sha256(encoded.encode("utf-8")).hexdigest()diff --git a/tests/gateway/test_hosted_discussion_manifests.py b/tests/gateway/test_hosted_discussion_manifests.pynew file mode 100644index 00000000000..6db9a7edcfa--- /dev/null+++ b/tests/gateway/test_hosted_discussion_manifests.py@@ -0,0 +1,100 @@+"""Exact event-bound media survives deterministic planning and reconstruction."""+from copy import deepcopy++import pytest++from gateway import hosted_room_discussion as discussion+from gateway import hosted_room_driver as driver+from gateway import hosted_rooms+from gateway.hosted_room_attachments import HostedRoomAttachmentStore+++ROOM = {"room_id": "room", "name": "Files", "authority_gateway_id": "gw", "authority_epoch": 1,+ "members": [{"member_id": name, "profile": name, "handle": name, "display_name": name}+ for name in ("alice", "bob", "carol")]}+PROFILES = ("alice", "bob", "carol")+++def attachment(n):+ return {"attachment_id": f"att_{n:032x}", "kind": "file", "name": "notes.txt",+ "size": 1, "mime": "text/plain"}+++def event(seq, *, attachments=(), text="@alice", kind="message.user", payload=None, actor=None):+ return {"room_id": "room", "seq": seq, "event_id": f"event-{seq}", "kind": kind,+ "authority_epoch": 1, "actor": actor or {"kind": "user", "id": "user"},+ "payload": payload or {"text": text, "thread_id": "thread", "attachments": list(attachments)}}+++def plan(events, **kwargs):+ return discussion.plan_next_task(ROOM, events, local_profiles=PROFILES, **kwargs).task+++def test_bound_manifest_reconstructs_frozen_input_and_rejects_forgery(tmp_path):+ db = tmp_path / "state.db"+ hosted_rooms.create_room(db, **{key: val for key, val in ROOM.items() if key != "authority_epoch"})+ store = HostedRoomAttachmentStore(db)+ meta = store.put(room_id="room", upload_id="upload", kind="file", name="notes.txt", mime="text/plain", data=b"x")+ meta = {key: meta[key] for key in ("attachment_id", "kind", "name", "size", "mime")}+ store.commit_message_with_receipt(room_id="room", event_id="event-1", manifest=[meta],+ recipient_member_ids=list(PROFILES), viewer_access=True, hold_until_event=True)+ raw = event(1, attachments=[meta], text="")+ hosted_rooms.append_event(db, **{key: val for key, val in raw.items() if key != "seq"}, authority_gateway_id="gw")+ events = hosted_rooms.read_events(db, room_id="room", since_seq=0)["events"]+ task = plan(events, freeze_input_context=True)+ expected = [{**meta, "event_id": "event-1"}]+ assert task.payload["attachments"] == expected+ normalized, _, digest = driver._task_payload(dict(task.payload))+ assert normalized == task.payload+ driver.admit_task(db, task.identity, payload=normalized, clock=lambda: 10)+ saved = driver.get_task(db, task.identity)+ assert saved["payload"] == normalized+ events.append(event(2, attachments=[attachment(2)]))+ assert discussion.reconstruct_task_plan(ROOM, events, saved, local_profiles=PROFILES) == task+ for change in ({"event_id": "event-2"}, {"name": "different.txt"}):+ forged = deepcopy(saved)+ forged["payload"]["attachments"][0].update(change)+ assert driver._task_payload(forged["payload"])[2] != digest+ with pytest.raises(discussion.DiscussionReconstructionError):+ discussion.reconstruct_task_plan(ROOM, events, forged, local_profiles=PROFILES)+ for invalid in ([], [{**expected[0], "size": True}], [{**expected[0], "path": "/private"}],+ [{k: v for k, v in expected[0].items() if k != "event_id"}]):+ with pytest.raises(driver.DriverValidationError):+ driver._task_payload({**normalized, "attachments": invalid})+++def test_member_recipients_and_bounded_batches_preserve_unconsumed_files():+ events = [event(i, attachments=[attachment(i * 10 + n) for n in range(8)], text="@alice")+ for i in range(1, 4)]+ first = plan(events, freeze_input_context=True)+ assert first.seen_through_seq == 2+ assert len(first.payload["attachments"]) == 16+ publication = discussion.plan_publication(ROOM, events, first, status="settled",+ result={"text": "Review @bob"}, local_profiles=PROFILES)+ assert publication.terminal_kind == "turn.settled"+ for effect in publication.events:+ raw = {**effect.append_kwargs("room"), "seq": len(events) + 1}+ if raw["kind"] == "message.member":+ raw["payload"] = {**raw["payload"], "attachments": [attachment(99)],+ "recipient_member_ids": ["bob"]}+ events.append(raw)+ second = plan(events, freeze_input_context=True)+ assert second.member.member_id == "alice"+ assert second.payload["attachments"] == [{**attachment(30 + n), "event_id": "event-3"} for n in range(8)]+ assert discussion.reconstruct_task_plan(ROOM, events,+ {"identity": first.identity, "payload": first.payload}, local_profiles=PROFILES) == first+ # Bob receives the peer share; Carol and the producer do not.+ for target in PROFILES:+ tailored = deepcopy(events)+ tailored[2]["payload"]["text"] = f"@{target}"+ candidate = plan(tailored, initial_watermarks={("thread", target): 3}, freeze_input_context=True)+ if target == "alice":+ continue # already terminal and no unconsumed eligible attachment+ assert candidate is not None+ assert candidate.payload.get("attachments", []) == (+ [{**attachment(99), "event_id": "dmessage:" + first.identity.task_id.removeprefix("dtask:")}]+ if target == "bob" else [])+ invalid = deepcopy(events)+ invalid[3]["payload"]["recipient_member_ids"] = ["outsider"]+ with pytest.raises(discussion.DiscussionValidationError):+ plan(invalid)diff --git a/tests/gateway/test_hosted_room_discussion.py b/tests/gateway/test_hosted_room_discussion.pyindex 2f7cfd3bf65..dcc8be29c3c 100644--- a/tests/gateway/test_hosted_room_discussion.py+++ b/tests/gateway/test_hosted_room_discussion.py@@ -664,8 +664,8 @@ def test_prompt_delta_is_bounded_to_24_message_lines(assert "Message 29." in task.payload["prompt"]-def test_attachment_payload_is_rejected_by_local_text_only_boundary():- with pytest.raises(discussion.DiscussionValidationError, match="unknown fields"):+def test_incomplete_attachment_metadata_is_rejected():+ with pytest.raises(discussion.DiscussionValidationError, match="missing fields"):discussion.validate_user_payload({"text": "Review.","thread_id": "thread-1",