objectiveai-cli 2.1.2

ObjectiveAI command-line interface and embeddable library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! `agents logs read all` / `agents logs read pending` backend:
//! SELECT `logs.messages` rows for a target AIH (or every child
//! AIH of a parent), JOIN through to the row's source table to
//! pull `sender_agent_instance_hierarchy` (+ `timestamp_queued`
//! for `message_queue_*` kinds), coalesce consecutive rows into
//! `ResponseItem` blocks, and yield them in index order.
//!
//! Sender + timestamp_queued live on the row's source table — the
//! three `logs.<tier>_completion_requests` tables for request +
//! assistant_response_* + tool_response* rows (all reachable by
//! `response_id`), and `message_queue` via
//! `message_queue_contents` for the five `message_queue_*` row
//! kinds. We LEFT JOIN all four sources unconditionally and let
//! the `CASE` over `m."table"` pick the right column. No
//! denormalized shadow copies on `logs.messages`.
//!
//! Block-coalesce rule: a new block starts when ANY of `(class,
//! agent_instance_hierarchy, response_id)` changes — PLUS, for
//! `ClientNotification` rows, when the `sender_agent_instance_hierarchy`
//! changes. Assistant/Tool blocks ignore sender because their
//! producer IS the agent (no separate sender exists). The three
//! request-blob classes are always single-row blocks.
//!
//! `read pending` is read-and-advance, expressed as a single
//! CTE-chained SQL statement: the SELECT returns the pending rows,
//! and a paired UPDATE bumps each affected
//! `logs.messages_queue.read_index` to `GREATEST(current,
//! max_returned)` — never downgraded.

use objectiveai_sdk::cli::command::agents::logs::read::all::{
    AssistantResponsePart, AssistantResponsePartType, ClientNotificationPart,
    ClientNotificationPartType, ResponseItem, ToolResponsePart, ToolResponsePartType,
};
use sqlx::Row as _;

use super::super::{Error, Pool};
use super::row::MessageTable;

/// One materialized `logs.messages` row plus the joined-in sender
/// (and queue parent + enqueued_at for `message_queue_*` rows).
struct MsgRow {
    /// `logs.messages."index"` — pass to `agents logs read id`
    /// for the full typed payload.
    id: i64,
    response_id: String,
    table_kind: MessageTable,
    agent_instance_hierarchy: String,
    timestamp_delivered: i64,
    /// Sender AIH. Populated for request blob rows (from
    /// `logs.<tier>_completion_requests.sender_*`) and for
    /// `message_queue_*` rows (from `message_queue.sender_*`).
    /// NULL for assistant/tool response rows — those have no
    /// distinct sender, the agent IS the producer.
    sender_agent_instance_hierarchy: Option<String>,
    /// `message_queue.id` of the consumed parent queue row.
    /// Some only for `message_queue_*` rows. Part of the
    /// `ClientNotification` block boundary tuple so each block
    /// = exactly one parent queue row.
    message_queue_id: Option<i64>,
    /// `message_queue.enqueued_at` of the consumed parent queue
    /// row. Some only for `message_queue_*` rows; lives at
    /// block level on the emitted `ClientNotification`.
    timestamp_queued: Option<i64>,
    /// `message_queue.key` of the consumed parent queue row —
    /// the idempotency token passed to
    /// `agents message --enqueue-with-key`. Some only for
    /// `message_queue_*` rows, and only when the parent row had
    /// a key set; lives at block level on the emitted
    /// `ClientNotification`.
    message_queue_key: Option<String>,
    /// `logs.assistant_response_tool_calls.function_name` for
    /// tool-call rows. Empty string for every other table.
    /// Surfaced on [`AssistantResponsePart::function_name`] so
    /// callers can dedupe tool calls by name without a round-trip
    /// through `agents logs read id`.
    function_name: String,
}

/// Coarse block-class for a `logs.message_table` value. Block
/// boundaries are drawn whenever this changes between consecutive
/// rows (or AIH / response_id / sender for ClientNotification).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BlockClass {
    AgentCompletionRequest,
    VectorCompletionRequest,
    FunctionExecutionRequest,
    ClientNotification,
    AssistantResponse,
    ToolResponse,
}

fn block_class(t: MessageTable) -> BlockClass {
    match t {
        MessageTable::AgentCompletionRequest => BlockClass::AgentCompletionRequest,
        MessageTable::VectorCompletionRequest => BlockClass::VectorCompletionRequest,
        MessageTable::FunctionExecutionRequest => BlockClass::FunctionExecutionRequest,
        MessageTable::MessageQueueText
        | MessageTable::MessageQueueImage
        | MessageTable::MessageQueueAudio
        | MessageTable::MessageQueueVideo
        | MessageTable::MessageQueueFile => BlockClass::ClientNotification,
        MessageTable::ToolResponse
        | MessageTable::ToolResponseContentText
        | MessageTable::ToolResponseContentImage
        | MessageTable::ToolResponseContentAudio
        | MessageTable::ToolResponseContentVideo
        | MessageTable::ToolResponseContentFile => BlockClass::ToolResponse,
        MessageTable::AssistantResponseRefusal
        | MessageTable::AssistantResponseReasoning
        | MessageTable::AssistantResponseToolCalls
        | MessageTable::AssistantResponseContentText
        | MessageTable::AssistantResponseContentImage
        | MessageTable::AssistantResponseContentAudio
        | MessageTable::AssistantResponseContentVideo
        | MessageTable::AssistantResponseContentFile => BlockClass::AssistantResponse,
    }
}

fn client_notification_kind(t: MessageTable) -> Option<ClientNotificationPartType> {
    match t {
        MessageTable::MessageQueueText => Some(ClientNotificationPartType::Text),
        MessageTable::MessageQueueImage => Some(ClientNotificationPartType::Image),
        MessageTable::MessageQueueAudio => Some(ClientNotificationPartType::Audio),
        MessageTable::MessageQueueVideo => Some(ClientNotificationPartType::Video),
        MessageTable::MessageQueueFile => Some(ClientNotificationPartType::File),
        _ => None,
    }
}

fn assistant_response_kind(t: MessageTable) -> Option<AssistantResponsePartType> {
    match t {
        MessageTable::AssistantResponseRefusal => Some(AssistantResponsePartType::Refusal),
        MessageTable::AssistantResponseReasoning => Some(AssistantResponsePartType::Reasoning),
        MessageTable::AssistantResponseToolCalls => Some(AssistantResponsePartType::ToolCall),
        MessageTable::AssistantResponseContentText => Some(AssistantResponsePartType::Text),
        MessageTable::AssistantResponseContentImage => Some(AssistantResponsePartType::Image),
        MessageTable::AssistantResponseContentAudio => Some(AssistantResponsePartType::Audio),
        MessageTable::AssistantResponseContentVideo => Some(AssistantResponsePartType::Video),
        MessageTable::AssistantResponseContentFile => Some(AssistantResponsePartType::File),
        _ => None,
    }
}

fn tool_response_kind(t: MessageTable) -> Option<ToolResponsePartType> {
    match t {
        MessageTable::ToolResponse => Some(ToolResponsePartType::Container),
        MessageTable::ToolResponseContentText => Some(ToolResponsePartType::Text),
        MessageTable::ToolResponseContentImage => Some(ToolResponsePartType::Image),
        MessageTable::ToolResponseContentAudio => Some(ToolResponsePartType::Audio),
        MessageTable::ToolResponseContentVideo => Some(ToolResponsePartType::Video),
        MessageTable::ToolResponseContentFile => Some(ToolResponsePartType::File),
        _ => None,
    }
}

/// Shared SELECT clause for `read_all` / `read_pending`. JOINs
/// the four sender source tables LEFT-style; CASE-picks the
/// right sender column based on `m."table"`. `timestamp_queued`
/// comes from the queue JOIN (Some only for `message_queue_*`
/// kinds).
const SELECT_SHAPE: &str = "SELECT \
    m.\"index\" AS id, \
    m.response_id, \
    m.\"table\" AS table_kind, \
    m.agent_instance_hierarchy, \
    m.\"timestamp\" AS timestamp_delivered, \
    CASE m.\"table\" \
        WHEN 'message_queue_text'  THEN mq.sender_agent_instance_hierarchy \
        WHEN 'message_queue_image' THEN mq.sender_agent_instance_hierarchy \
        WHEN 'message_queue_audio' THEN mq.sender_agent_instance_hierarchy \
        WHEN 'message_queue_video' THEN mq.sender_agent_instance_hierarchy \
        WHEN 'message_queue_file'  THEN mq.sender_agent_instance_hierarchy \
        WHEN 'agent_completion_request'    THEN acr.sender_agent_instance_hierarchy \
        WHEN 'vector_completion_request'   THEN vcr.sender_agent_instance_hierarchy \
        WHEN 'function_execution_request'  THEN fer.sender_agent_instance_hierarchy \
        ELSE NULL \
    END AS sender_agent_instance_hierarchy, \
    mq.id AS message_queue_id, \
    mq.enqueued_at AS timestamp_queued, \
    mq.key AS message_queue_key, \
    COALESCE(atc.function_name, '') AS function_name";

const FROM_JOINS: &str = "FROM logs.messages m \
    LEFT JOIN message_queue_contents mqc \
        ON m.row_index = mqc.id \
        AND m.\"table\" IN ( \
            'message_queue_text', 'message_queue_image', 'message_queue_audio', \
            'message_queue_video', 'message_queue_file' \
        ) \
    LEFT JOIN message_queue mq ON mqc.message_queue_id = mq.id \
    LEFT JOIN logs.agent_completion_requests acr \
        ON m.response_id = acr.response_id \
        AND m.\"table\" = 'agent_completion_request' \
    LEFT JOIN logs.vector_completion_requests vcr \
        ON m.response_id = vcr.response_id \
        AND m.\"table\" = 'vector_completion_request' \
    LEFT JOIN logs.function_execution_requests fer \
        ON m.response_id = fer.response_id \
        AND m.\"table\" = 'function_execution_request' \
    LEFT JOIN logs.assistant_response_tool_calls atc \
        ON m.response_id = atc.response_id \
        AND m.row_index = atc.\"index\" \
        AND m.row_sub_index = atc.tool_call_index \
        AND m.\"table\" = 'assistant_response_tool_calls'";

fn row_into_msg(r: &sqlx::postgres::PgRow) -> Result<MsgRow, Error> {
    Ok(MsgRow {
        id: r.try_get("id")?,
        response_id: r.try_get("response_id")?,
        table_kind: r.try_get("table_kind")?,
        agent_instance_hierarchy: r.try_get("agent_instance_hierarchy")?,
        timestamp_delivered: r.try_get("timestamp_delivered")?,
        sender_agent_instance_hierarchy: r.try_get("sender_agent_instance_hierarchy")?,
        message_queue_id: r.try_get("message_queue_id")?,
        timestamp_queued: r.try_get("timestamp_queued")?,
        message_queue_key: r.try_get("message_queue_key")?,
        function_name: r.try_get("function_name")?,
    })
}

/// Walk `rows` (already sorted by `id` ASC) and coalesce into
/// `ResponseItem`s. Pure / deterministic.
fn coalesce_into_blocks(rows: Vec<MsgRow>) -> Vec<ResponseItem> {
    let mut out: Vec<ResponseItem> = Vec::new();
    let mut cur_class: Option<BlockClass> = None;
    let mut cur_aih: String = String::new();
    let mut cur_rid: String = String::new();
    /// `Some` only for an open `ClientNotification` block; assistant /
    /// tool blocks never set this. Boundary check pulls it in.
    let mut cur_sender: Option<String> = None;
    /// `Some` only for an open `ClientNotification` block — the
    /// consumed `message_queue.id`. Forces 1:1 block-to-parent
    /// correspondence so block-level `timestamp_queued` is
    /// well-defined.
    let mut cur_mq_id: Option<i64> = None;
    /// `Some` only for an open `ClientNotification` block —
    /// `message_queue.enqueued_at`.
    let mut cur_timestamp_queued: Option<i64> = None;
    /// `Some` only for an open `ClientNotification` block AND
    /// only when the parent queue row had `--key` set —
    /// `message_queue.key`.
    let mut cur_key: Option<String> = None;
    let mut cur_notification_parts: Vec<ClientNotificationPart> = Vec::new();
    let mut cur_assistant_parts: Vec<AssistantResponsePart> = Vec::new();
    let mut cur_tool_parts: Vec<ToolResponsePart> = Vec::new();

    let flush = |class: Option<BlockClass>,
                 aih: &mut String,
                 rid: &mut String,
                 sender: &mut Option<String>,
                 mq_id: &mut Option<i64>,
                 timestamp_queued: &mut Option<i64>,
                 key: &mut Option<String>,
                 notification_parts: &mut Vec<ClientNotificationPart>,
                 assistant_parts: &mut Vec<AssistantResponsePart>,
                 tool_parts: &mut Vec<ToolResponsePart>,
                 out: &mut Vec<ResponseItem>| {
        match class {
            Some(BlockClass::ClientNotification) if !notification_parts.is_empty() => {
                out.push(ResponseItem::ClientNotification {
                    agent_instance_hierarchy: std::mem::take(aih),
                    sender_agent_instance_hierarchy: sender.take().unwrap_or_default(),
                    response_id: std::mem::take(rid),
                    timestamp_queued: timestamp_queued.take().unwrap_or_default(),
                    key: key.take(),
                    parts: std::mem::take(notification_parts),
                });
                *mq_id = None;
            }
            Some(BlockClass::AssistantResponse) if !assistant_parts.is_empty() => {
                out.push(ResponseItem::AssistantResponse {
                    agent_instance_hierarchy: std::mem::take(aih),
                    response_id: std::mem::take(rid),
                    parts: std::mem::take(assistant_parts),
                });
            }
            Some(BlockClass::ToolResponse) if !tool_parts.is_empty() => {
                out.push(ResponseItem::ToolResponse {
                    agent_instance_hierarchy: std::mem::take(aih),
                    response_id: std::mem::take(rid),
                    parts: std::mem::take(tool_parts),
                });
            }
            _ => {
                aih.clear();
                rid.clear();
                *sender = None;
                *mq_id = None;
                *timestamp_queued = None;
                *key = None;
                notification_parts.clear();
                assistant_parts.clear();
                tool_parts.clear();
            }
        }
    };

    for row in rows {
        let class = block_class(row.table_kind);

        // Single-row request classes — emit immediately, reset.
        match class {
            BlockClass::AgentCompletionRequest => {
                flush(
                    cur_class, &mut cur_aih, &mut cur_rid, &mut cur_sender,
                    &mut cur_mq_id, &mut cur_timestamp_queued, &mut cur_key,
                    &mut cur_notification_parts, &mut cur_assistant_parts,
                    &mut cur_tool_parts, &mut out,
                );
                out.push(ResponseItem::AgentCompletionRequest {
                    id: row.id,
                    agent_instance_hierarchy: row.agent_instance_hierarchy,
                    sender_agent_instance_hierarchy: row
                        .sender_agent_instance_hierarchy
                        .unwrap_or_default(),
                    timestamp_delivered: row.timestamp_delivered,
                    response_id: row.response_id,
                });
                cur_class = None;
                continue;
            }
            BlockClass::VectorCompletionRequest => {
                flush(
                    cur_class, &mut cur_aih, &mut cur_rid, &mut cur_sender,
                    &mut cur_mq_id, &mut cur_timestamp_queued, &mut cur_key,
                    &mut cur_notification_parts, &mut cur_assistant_parts,
                    &mut cur_tool_parts, &mut out,
                );
                out.push(ResponseItem::VectorCompletionRequest {
                    id: row.id,
                    agent_instance_hierarchy: row.agent_instance_hierarchy,
                    sender_agent_instance_hierarchy: row
                        .sender_agent_instance_hierarchy
                        .unwrap_or_default(),
                    timestamp_delivered: row.timestamp_delivered,
                    response_id: row.response_id,
                });
                cur_class = None;
                continue;
            }
            BlockClass::FunctionExecutionRequest => {
                flush(
                    cur_class, &mut cur_aih, &mut cur_rid, &mut cur_sender,
                    &mut cur_mq_id, &mut cur_timestamp_queued, &mut cur_key,
                    &mut cur_notification_parts, &mut cur_assistant_parts,
                    &mut cur_tool_parts, &mut out,
                );
                out.push(ResponseItem::FunctionExecutionRequest {
                    id: row.id,
                    agent_instance_hierarchy: row.agent_instance_hierarchy,
                    sender_agent_instance_hierarchy: row
                        .sender_agent_instance_hierarchy
                        .unwrap_or_default(),
                    timestamp_delivered: row.timestamp_delivered,
                    response_id: row.response_id,
                });
                cur_class = None;
                continue;
            }
            _ => {}
        }

        // Multi-row class. For ClientNotification, sender_aih
        // AND message_queue_id are part of the boundary tuple —
        // each block = one consumed parent queue row, well-defined
        // block-level `timestamp_queued`. Assistant/Tool blocks
        // ignore sender + mq_id (both are None for them anyway).
        let boundary = cur_class != Some(class)
            || cur_aih != row.agent_instance_hierarchy
            || cur_rid != row.response_id
            || (class == BlockClass::ClientNotification
                && (cur_sender.as_deref() != row.sender_agent_instance_hierarchy.as_deref()
                    || cur_mq_id != row.message_queue_id));
        if boundary {
            flush(
                cur_class, &mut cur_aih, &mut cur_rid, &mut cur_sender,
                &mut cur_mq_id, &mut cur_timestamp_queued, &mut cur_key,
                &mut cur_notification_parts, &mut cur_assistant_parts,
                &mut cur_tool_parts, &mut out,
            );
            cur_class = Some(class);
            cur_aih = row.agent_instance_hierarchy.clone();
            cur_rid = row.response_id.clone();
            if class == BlockClass::ClientNotification {
                cur_sender = row.sender_agent_instance_hierarchy.clone();
                cur_mq_id = row.message_queue_id;
                cur_timestamp_queued = row.timestamp_queued;
                cur_key = row.message_queue_key.clone();
            } else {
                cur_sender = None;
                cur_mq_id = None;
                cur_timestamp_queued = None;
                cur_key = None;
            }
        }

        match class {
            BlockClass::ClientNotification => {
                let r#type = client_notification_kind(row.table_kind)
                    .expect("class invariant: ClientNotification maps to message_queue_*");
                cur_notification_parts.push(ClientNotificationPart {
                    id: row.id,
                    timestamp_delivered: row.timestamp_delivered,
                    r#type,
                });
            }
            BlockClass::AssistantResponse => {
                let r#type = assistant_response_kind(row.table_kind)
                    .expect("class invariant: AssistantResponse maps to assistant_response_*");
                cur_assistant_parts.push(AssistantResponsePart {
                    id: row.id,
                    timestamp_delivered: row.timestamp_delivered,
                    r#type,
                    function_name: row.function_name,
                });
            }
            BlockClass::ToolResponse => {
                let r#type = tool_response_kind(row.table_kind)
                    .expect("class invariant: ToolResponse maps to tool_response*");
                cur_tool_parts.push(ToolResponsePart {
                    id: row.id,
                    timestamp_delivered: row.timestamp_delivered,
                    r#type,
                });
            }
            _ => unreachable!("request classes handled above"),
        }
    }

    flush(
        cur_class, &mut cur_aih, &mut cur_rid, &mut cur_sender,
        &mut cur_mq_id, &mut cur_timestamp_queued, &mut cur_key,
        &mut cur_notification_parts, &mut cur_assistant_parts,
        &mut cur_tool_parts, &mut out,
    );

    out
}

/// Materialize every `logs.messages` row for `agent_instance_hierarchy`
/// (filtered by `after_id` / `limit`), coalesced into `ResponseItem`
/// blocks.
pub async fn read_all_for_hierarchy(
    pool: &Pool,
    agent_instance_hierarchy: &str,
    after_id: Option<i64>,
    limit: Option<i64>,
) -> Result<Vec<ResponseItem>, Error> {
    let sql = format!(
        "{select} {from} \
         WHERE m.agent_instance_hierarchy = $1 \
           AND m.\"index\" > COALESCE($2, 0) \
         ORDER BY m.\"index\" ASC \
         LIMIT $3",
        select = SELECT_SHAPE,
        from = FROM_JOINS,
    );
    let rows = sqlx::query(&sql)
        .bind(agent_instance_hierarchy)
        .bind(after_id)
        .bind(limit)
        .fetch_all(&**pool)
        .await?;

    let msg_rows: Vec<MsgRow> = rows.iter().map(row_into_msg).collect::<Result<_, _>>()?;
    Ok(coalesce_into_blocks(msg_rows))
}

/// Materialize every unread `logs.messages` row for the children
/// spawned by `parent_agent_instance_hierarchy` (per
/// `logs.messages_queue` watermarks), coalesced into `ResponseItem`
/// blocks. Bumps each affected child's `read_index` to
/// `GREATEST(current, max_returned)` atomically in the same SQL
/// statement.
pub async fn read_pending_for_parent(
    pool: &Pool,
    parent_agent_instance_hierarchy: &str,
    after_id: Option<i64>,
    limit: Option<i64>,
) -> Result<Vec<ResponseItem>, Error> {
    // CTE-chained read-and-bump:
    //   * `selected` — the rows to return; same JOIN topology as
    //     `read_all_for_hierarchy` plus a JOIN to
    //     `logs.messages_queue` for the watermark filter.
    //   * `maxes` — per-spawned max returned `id`.
    //   * `bump` — UPDATE that lifts each child's `read_index` to
    //     `GREATEST(current, max_id)`. Always runs (Postgres
    //     materializes data-modifying CTEs even when the outer
    //     SELECT doesn't reference them); when `selected` is
    //     empty, `maxes` is empty and `bump` no-ops.
    //   * Final SELECT pulls from `selected`.
    let sql = format!(
        "WITH selected AS ( \
             {select} \
             {from} \
             JOIN logs.messages_queue q \
               ON q.spawned_agent_instance_hierarchy = m.agent_instance_hierarchy \
             WHERE q.parent_agent_instance_hierarchy = $1 \
               AND m.\"index\" > GREATEST(q.read_index, COALESCE($2, 0)) \
             ORDER BY m.\"index\" ASC \
             LIMIT $3 \
         ), \
         maxes AS ( \
             SELECT agent_instance_hierarchy AS spawned, MAX(id) AS max_id \
               FROM selected \
              GROUP BY agent_instance_hierarchy \
         ), \
         bump AS ( \
             UPDATE logs.messages_queue qq \
                SET read_index = GREATEST(qq.read_index, mx.max_id) \
               FROM maxes mx \
              WHERE qq.parent_agent_instance_hierarchy = $1 \
                AND qq.spawned_agent_instance_hierarchy = mx.spawned \
             RETURNING 1 \
         ) \
         SELECT s.id, s.response_id, s.table_kind, \
                s.agent_instance_hierarchy, s.timestamp_delivered, \
                s.sender_agent_instance_hierarchy, \
                s.message_queue_id, s.timestamp_queued, \
                s.message_queue_key \
           FROM selected s \
          ORDER BY s.id ASC",
        select = SELECT_SHAPE,
        from = FROM_JOINS,
    );
    let rows = sqlx::query(&sql)
        .bind(parent_agent_instance_hierarchy)
        .bind(after_id)
        .bind(limit)
        .fetch_all(&**pool)
        .await?;

    let msg_rows: Vec<MsgRow> = rows.iter().map(row_into_msg).collect::<Result<_, _>>()?;
    Ok(coalesce_into_blocks(msg_rows))
}

/// Side-effect-free existence check used by
/// `agents logs read subscribe`'s wait loop. Returns `true` iff
/// `logs.messages_queue` has at least one unread row past the
/// watermark for any child of `parent_agent_instance_hierarchy`
/// whose `m."table"` falls in `kinds`. When `kinds` is `None` or
/// empty, the kind filter is dropped (existence check across all
/// kinds — equivalent to "is there anything pending at all?").
///
/// Does NOT touch `read_index`. The subscriber re-checks via
/// this on every wake-up and only calls
/// `read_pending_for_parent` (which DOES bump) once it confirms
/// a matching row exists. When a match is confirmed, the
/// subsequent `read_pending_for_parent` call returns EVERY
/// pending row regardless of kind — the kinds filter is for
/// "wake me up" gating only, not for the returned slice.
pub async fn any_pending_matching_kinds(
    pool: &Pool,
    parent_agent_instance_hierarchy: &str,
    after_id: Option<i64>,
    kinds: Option<&[MessageTable]>,
) -> Result<bool, Error> {
    let kinds_clause = match kinds {
        Some(ks) if !ks.is_empty() => {
            let list = ks
                .iter()
                .map(|k| format!("'{}'", k.schema_name()))
                .collect::<Vec<_>>()
                .join(", ");
            format!("AND m.\"table\" IN ({list})")
        }
        _ => String::new(),
    };
    let sql = format!(
        "SELECT EXISTS( \
             SELECT 1 FROM logs.messages m \
             JOIN logs.messages_queue q \
               ON q.spawned_agent_instance_hierarchy = m.agent_instance_hierarchy \
             WHERE q.parent_agent_instance_hierarchy = $1 \
               AND m.\"index\" > GREATEST(q.read_index, COALESCE($2, 0)) \
               {kinds_clause} \
         )"
    );
    let exists: bool = sqlx::query_scalar(&sql)
        .bind(parent_agent_instance_hierarchy)
        .bind(after_id)
        .fetch_one(&**pool)
        .await?;
    Ok(exists)
}