Skip to content
112 changes: 49 additions & 63 deletions core/continuum-cognition/src/cognition/conversation/room_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,17 +81,41 @@ pub fn room_turn_from_event(event: &TranscriptEvent) -> Result<(uuid::Uuid, Stri
Ok((turn.sender, render_room_content(&turn.text, &turn.media)))
}

/// What kind of media an attachment is, from its declared kind (the MIME top-level type).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum MediaKind {
Image,
Audio,
Video,
Text,
File,
}

impl MediaKind {
fn of(kind: &str) -> Self {
match kind {
"image" => Self::Image,
"audio" => Self::Audio,
"video" => Self::Video,
"text" => Self::Text,
_ => Self::File, // any other declared kind is a file she can open, never free text in her prompt
}
}
}

/// A bounded notice, not a claim that the model has inspected the attachment.
/// The event retains the full references for explicit inspection/replay.
pub(crate) fn render_room_content(text: &str, media: &[crate::cognition::conversation::channel_items::MediaItemRequest]) -> String {
if media.is_empty() { return text.to_owned(); }
let mut rendered = format!("{text}\n[{} media attachment(s); contents not loaded", media.len());
for item in media.iter().take(8) {
let kind: String = item.kind.chars().filter(|c| !c.is_control()).take(24).collect();
rendered.push_str(&format!("; {kind}"));
if let Some(hash) = item.blob_hash.as_deref().filter(|h| h.starts_with("sha256:") && h.len() == 71 && h[7..].bytes().all(|b| b.is_ascii_hexdigit())) {
rendered.push_str(&format!(" {hash}"));
}
// One entry per kind with its count: bounded by the few media kinds that exist, never by a cap
// on items or characters (a typed kind from the MIME top-level type, so no free text reaches her).
let mut kinds = std::collections::BTreeMap::<MediaKind, usize>::new();
for item in media {
*kinds.entry(MediaKind::of(&item.kind)).or_default() += 1;
}
for (kind, count) in kinds {
rendered.push_str(&format!("; {count} {kind:?}"));
}
rendered.push(']');
rendered
Expand All @@ -101,7 +125,7 @@ pub(crate) fn render_room_content(text: &str, media: &[crate::cognition::convers
/// words. Short ids because that is how the board renders them; the typed event
/// retains the full ids for her hands.
pub fn render_room_work(work: &RoomWork, actor: uuid::Uuid) -> String {
let short = |id: uuid::Uuid| id.to_string()[..8].to_string();
let short = airc_core::shown_id::shown_form;
match work {
RoomWork::Reviewed { card_id, outcome, reviewer, .. } => format!(
"[board fact] review on card {}: {:?} (reviewer {})",
Expand Down Expand Up @@ -171,7 +195,7 @@ pub fn room_content_from_event(event: &TranscriptEvent) -> Result<RoomTurn, &'st
match envelope_from_event(event) {
Err(_) => return Err("envelope_decode_error"),
Ok(None) => return Err("no_continuum_body_hint"),
Ok(Some(envelope)) => chat_transcript_content(&envelope, event.peer_id.as_uuid()).ok_or("non_chat_schema")?,
Ok(Some(envelope)) => chat_transcript_content(&envelope, crate::routing::airc_realtime_wire::logical_sender(event)).ok_or("non_chat_schema")?,
}
};
// Native AIRC attachments are first-class room input too. Preserve the
Expand Down Expand Up @@ -200,11 +224,9 @@ pub fn room_content_from_event(event: &TranscriptEvent) -> Result<RoomTurn, &'st
/// (EventBridge, presence, media-control) — a non-`chat_transcript`
/// fabricates nothing.
///
/// The sender falls back to `fallback_peer` (the transport peer that
/// relayed the publish) when `inline.senderId` is absent. Both are real
/// identities — this is attribution recovery of a present-but-relayed
/// sender, NOT a fabricated default for a missing one
/// ([[fallbacks-are-illegal-fail-loud]]).
/// The sender is the caller's, resolved from the event's header by
/// [`crate::routing::airc_realtime_wire::logical_sender`]: this decoder opens the body for the
/// line's text and media only, never to attribute it.
///
/// This is the ONE decoder for the `chat_transcript` wire shape. Both the
/// persona perception path (`perceptual_from_event`) and the positron
Expand All @@ -216,13 +238,13 @@ pub fn room_content_from_event(event: &TranscriptEvent) -> Result<RoomTurn, &'st
/// through this decoder.
pub fn chat_transcript_message(
envelope: &AircRealtimeEnvelope,
fallback_peer: uuid::Uuid,
sender: uuid::Uuid,
) -> Option<(uuid::Uuid, String)> {
let turn = chat_transcript_content(envelope, fallback_peer)?;
let turn = chat_transcript_content(envelope, sender)?;
Some((turn.sender, render_room_content(&turn.text, &turn.media)))
}

fn chat_transcript_content(envelope: &AircRealtimeEnvelope, fallback_peer: uuid::Uuid) -> Option<RoomTurn> {
pub fn chat_transcript_content(envelope: &AircRealtimeEnvelope, sender: uuid::Uuid) -> Option<RoomTurn> {
let AircRealtimePayload::ExistingSchema { payload } = &envelope.payload else {
return None;
};
Expand All @@ -231,11 +253,6 @@ fn chat_transcript_content(envelope: &AircRealtimeEnvelope, fallback_peer: uuid:
}
let inline = payload.inline.as_ref()?;
let text = inline.get("text").and_then(serde_json::Value::as_str)?;
let sender = inline
.get("senderId")
.and_then(serde_json::Value::as_str)
.and_then(|s| uuid::Uuid::parse_str(s).ok())
.unwrap_or(fallback_peer);
let media = inline.get("media").map(|value| serde_json::from_value(value.clone())).transpose().ok()?.unwrap_or_default(); // boundary: AIRC transcript JSON decodes typed references; omitted media is the legacy text-only wire contract.
Some(RoomTurn { sender, text: text.to_string(), media })
}
Expand All @@ -254,7 +271,9 @@ pub struct ChatTranscriptLine<'a> {
/// caller-owned publication and a hydrated durable row all send.
pub fn chat_transcript_envelope(message_id: uuid::Uuid, line: &ChatTranscriptLine<'_>, now_ms: u64) -> serde_json::Value {
serde_json::json!({
"eventId": uuid::Uuid::new_v4().to_string(),
// The envelope is named by the stored message id, so its `continuum.event_id` header names
// the row and its publication obligation (attribution reads the header, never the body).
"eventId": message_id.to_string(),
"roomId": line.room_id.to_string(),
"sourceId": line.sender_id.to_string(),
"createdAtMs": now_ms,
Expand Down Expand Up @@ -287,12 +306,12 @@ mod tests {
// This is the seam that keeps human chat lines from being structurally
// invisible to BOTH persona perception and the positron read surface.
// A regression that renamed the `chat_transcript` schema tag or the
// inline `text`/`senderId` fields silently drops every human message
// from the room.
// inline `text` field silently drops every human message from the room;
// and the body's `senderId` must never override the header-resolved sender
// (routing on headers, never parsed bodies: Joel, 2026-11-01).
#[test]
fn chat_transcript_message_recovers_sender_and_text() {
fn chat_transcript_text_decodes_and_the_header_sender_wins() {
let sender = uuid::Uuid::from_u128(0x5e).to_string();
let relay = uuid::Uuid::from_u128(0x4e);
// Encode exactly as chat/send → airc/realtime-publish builds it.
let envelope: AircRealtimeEnvelope = serde_json::from_value(serde_json::json!({
"eventId": uuid::Uuid::from_u128(0x1).to_string(),
Expand All @@ -315,13 +334,11 @@ mod tests {
}))
.expect("chat/send envelope shape must decode into AircRealtimeEnvelope");

let header_sender = uuid::Uuid::from_u128(0x77);
let (recovered, text) =
chat_transcript_message(&envelope, relay).expect("chat_transcript must decode");
assert_eq!(
recovered.to_string(),
sender,
"logical sender, not the relay"
);
chat_transcript_message(&envelope, header_sender).expect("chat_transcript must decode");
assert_eq!(recovered, header_sender, "the header's sender; the body's senderId routes nothing");
assert_ne!(recovered.to_string(), sender);
assert_eq!(text, "is anyone there?");
}

Expand All @@ -342,37 +359,6 @@ mod tests {
assert!(rendered.len() < 1000);
}

// what this catches: attribution recovery, not fabrication. When the
// inline omits senderId, the sender falls back to the transport peer
// that relayed the publish — a real identity, never a nil/default.
#[test]
fn chat_transcript_message_falls_back_to_transport_peer() {
let relay = uuid::Uuid::from_u128(0x4e);
let envelope: AircRealtimeEnvelope = serde_json::from_value(serde_json::json!({
"eventId": uuid::Uuid::from_u128(0x1).to_string(),
"roomId": uuid::Uuid::from_u128(0x2).to_string(),
"sourceId": uuid::Uuid::from_u128(0x5e).to_string(),
"createdAtMs": 100,
"delivery": "durable",
"payload": {
"kind": "existing_schema",
"payload": {
"schema": "chat_transcript",
"inline": { "text": "hello" }
}
},
}))
.expect("envelope must decode");

let (recovered, text) =
chat_transcript_message(&envelope, relay).expect("chat_transcript must decode");
assert_eq!(
recovered, relay,
"omitted senderId recovers to the relay peer"
);
assert_eq!(text, "hello");
}

// what this catches: classification, not fallback. A non-chat_transcript
// envelope (here EventBridge) must yield None from this decoder — it is
// NOT a chat line and must never be projected as one.
Expand Down
116 changes: 106 additions & 10 deletions core/continuum-core/src/airc/inbound_attach.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,21 @@ pub async fn run_daemon_attach(
.attach(request)
.await
.map_err(|error| format!("failed to attach to airc daemon: {error}"))?;
// The room's transport is ready: publish again what this core relayed into it and has not seen
// back (#5696). This attach owns the recovery; an error ends it, and the supervisor's backoff
// retries, so a publish refused at boot recovers without another process start.
let recovered = lines
.recover_publications(channel)
.await
.map_err(|e| format!("pending publications not recovered; re-attaching to retry: {e}"))?;
if recovered > 0 {
continuum_base::probe!(
class = "airc.attach.publications_recovered",
room = %channel.as_uuid(),
recovered = recovered as u64,
"re-published lines this core relayed and had not seen back"
);
}

// WATERMARK DISCIPLINE (#261, both PR #2057 review findings): the attach
// NEVER pre-persists the room tip. The old tip-probe persisted a cursor
Expand Down Expand Up @@ -362,6 +377,44 @@ pub async fn publish_transcript_event(
// core, instead of from a per-persona subscription (which on the 5090 never
// carried other peers' durable pushes while this path did). Synchronous and
// cheap: one classification, one lock per resident, no await.
// ATTRIBUTION BEFORE ANYTHING CONSUMES THE LINE (Codex on #5696): a line claiming to speak for
// someone other than its transport author reaches perception, the store and the projection only
// when this core's publication obligation proves it; otherwise it is refused here, said, and
// dropped, never relabeled.
let delegated = match attribution_gate(event, lines).await? {
Gate::Pass { delegated } => delegated,
Gate::Refused => return Ok(()),
};
// THE STORE FIRST, ONCE (Slice P; Codex on #5696): a room line is imported, awaited, before
// anything consumes it; an error ends this attach before the watermark passes the line, and the
// re-attach replays it. A line the store already holds (a replay after a restart, a re-published
// relayed line) is not perceived or projected again. Known gap until P2 perceives from the store:
// a line imported but not yet fed when the core died is not re-fed on replay.
let decoded = envelope_from_event(event);
let chat_line = match &decoded {
Ok(None) => posted_from_message(event),
Ok(Some(envelope)) => posted_from_envelope(envelope, event).map(|mut line| {
line.retires_publication = delegated;
line
}),
Err(_) => None,
};
if let Some(line) = &chat_line {
let imported = lines
.import(line.clone())
.await
.map_err(|e| format!("inbound line not stored; re-attaching to replay it: {e}"))?;
if let continuum_mind::chat::line_store::Imported::Duplicate { arrival_seq } = imported {
continuum_base::probe!(
class = "airc.inbound.duplicate_line",
room = %event.room_id.as_uuid(),
message = %line.message_id,
arrival_seq = arrival_seq,
"a line the store already holds arrived again; not perceived or projected twice"
);
return Ok(());
}
}
let fed = crate::persona::perception_feed::feed(&conversation, EpochMs::now().millis());
if fed > 0 {
continuum_base::probe!(
Expand All @@ -376,7 +429,7 @@ pub async fn publish_transcript_event(
// review is verified (signed by its author, accepted in the room's projection,
// admitted by the room's self-review policy). It used to settle here, on any
// review-shaped event, unchecked.
let envelope = match envelope_from_event(event) {
let envelope = match decoded {
Ok(Some(envelope)) => envelope,
// Not a Continuum EventBridge envelope. Before dropping it, try
// the thin chat projection: a plain airc chat message projects
Expand All @@ -391,13 +444,7 @@ pub async fn publish_transcript_event(
// content). An event is at most one of these; anything else is not
// ours here → skip. Classification, never a fallback — a
// non-matching kind fabricates nothing.
if let Some(line) = posted_from_message(event) {
// The durable transcript FIRST, awaited (#140, Slice P): an error ends this
// attach before the watermark can pass the line, and the re-attach replays it;
// the import is idempotent by id, so the replay never doubles it.
lines.import(line.clone()).await.map_err(|e| {
format!("inbound line not stored; re-attaching to replay it: {e}")
})?;
if let Some(line) = &chat_line {
// task #84: the persona-turn / plain-airc-message stream into
// the room. This is the seam a client's live read surface
// (positron ChatViewState) is fed from — probe it so the turn
Expand Down Expand Up @@ -459,7 +506,8 @@ pub async fn publish_transcript_event(
"first capacity offer heard from a grid peer",
);
}
} else if let Some(line) = posted_from_envelope(&envelope, event) {
} else if let Some(mut line) = posted_from_envelope(&envelope, event) {
line.retires_publication = delegated;
// The same awaited, idempotent import as the plain arm (a human line was stored by
// chat/send under this id already; the import reuses its row and arrival).
lines
Expand Down Expand Up @@ -505,7 +553,7 @@ fn posted_from_envelope(
envelope: &AircRealtimeEnvelope,
event: &airc_core::TranscriptEvent,
) -> Option<PostedLine> {
let (sender_id, content) = chat_transcript_message(envelope, event.peer_id.as_uuid())?;
let (sender_id, content) = chat_transcript_message(envelope, crate::routing::airc_realtime_wire::logical_sender(event))?;
let message_id = match &envelope.payload {
crate::routing::airc_realtime::AircRealtimePayload::ExistingSchema { payload } => payload
.inline
Expand All @@ -522,6 +570,53 @@ fn posted_from_envelope(
Some(line)
}

/// Whether a line may be consumed, decided by attribution.
enum Gate {
Pass { delegated: bool },
Refused,
}

/// Attribute a line before it is consumed: no claim (or a claim naming its transport author) passes
/// as the author's own; a claim to speak for someone else passes only on an exact publication
/// obligation (`chat::publication::attribute`), read through the injected store.
async fn attribution_gate(event: &airc_core::TranscriptEvent, lines: &dyn LineImporter) -> Result<Gate, String> {
use crate::routing::airc_realtime_wire::{claimed_message, claimed_sender, envelope_from_event};
use continuum_mind::chat::publication::{attribute, publication_digest, Attribution};
use crate::routing::airc_realtime_wire::SenderClaim;
let claim = claimed_sender(event);
if claim == SenderClaim::Absent || claim == SenderClaim::Named(event.peer_id) {
return Ok(Gate::Pass { delegated: false });
}
let obligation = match claimed_message(event) {
Some(id) => lines.publication(id).await?,
None => None,
};
// The line as received, from the one chat_transcript decoder (its claimed sender, its text and
// media); a line that does not decode matches no publication.
let received = match (claimed_message(event), claim, envelope_from_event(event)) {
(Some(message), SenderClaim::Named(sender), Ok(Some(envelope))) => {
crate::cognition::conversation::room_event::chat_transcript_content(&envelope, sender.as_uuid())
.map(|turn| publication_digest(message, event.room_id, sender, &turn.text, &turn.media))
}
_ => None,
};
match attribute(event.peer_id, claim, event.room_id, obligation.as_ref(), received) {
Attribution::Author(_) => Ok(Gate::Pass { delegated: false }),
Attribution::Delegated { .. } => Ok(Gate::Pass { delegated: true }),
Attribution::Refused { claimed, reason } => {
continuum_base::probe!(
class = "airc.inbound.delegation_refused",
room = %event.room_id.as_uuid(),
transport = %event.peer_id.as_uuid(),
claimed = ?claimed.map(|c| c.as_uuid()),
reason = ?reason,
"a line claimed to speak for someone it could not prove; refused, not relabeled"
);
Ok(Gate::Refused)
}
}
}

/// The typed line of a room event, from its header (kind, ids, addressee) and its decoded text;
/// `None` when the event is not a room line.
fn posted_line(event: &airc_core::TranscriptEvent, text: String) -> Option<PostedLine> {
Expand All @@ -534,6 +629,7 @@ fn posted_line(event: &airc_core::TranscriptEvent, text: String) -> Option<Poste
direct_to: arrival.direct_to,
occurred_at_ms: event.occurred_at_ms,
text,
retires_publication: false,
})
}

Expand Down
Loading
Loading