mahbot 0.11.3

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Tool-call and LLM request statistics, consolidated into the logs database.
//!
//! The records of two families are built here, and never written from here on the
//! performing path:
//!
//! * **Tool calls** — each [`crate::Agent`] accumulates `ToolCallRecord`s in a
//!   `std::sync::Mutex<Vec<ToolCallRecord>>` and hands them to
//!   [`crate::telemetry`] when the session finalizes; the drain task writes them
//!   through [`LogStore::flush_batch`] (defined in this module) into `tool_calls`.
//! * **LLM requests / failures** — per-operation `llm_requests` rows via
//!   [`record_llm_operation`] / [`record_llm_operation_meta`] and grouped
//!   `llm_failures` rows via [`LlmOperationCtx`], fed by the retry pipeline.
//!
//! A record is built where its facts are — including the instant it describes —
//! and handed to [`crate::telemetry`], whose one drain task calls the `LogStore`
//! methods below; a failure there is noted by that task and is never fatal.
//!
//! All tables (and their indexes) are created by the logs store's baseline
//! schema catalog entry (in the append-only catalog) — the sole creator of this
//! schema. Consumers access the store through [`crate::logs::LOG_STORE`].

use crate::db::{self};
use anyhow::Result;

/// Which surface performed a recorded tool call: an agent's own run, or a
/// command-line operation the product carried out for its owner.
///
/// Kept as its own `tool_calls.source` column rather than inferred from
/// `agent_id`/`role`: those two are a naming convention (a custom role could be
/// named `cli`), while `source` is the explicit provenance marker a reader or a
/// later consumer can rely on.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum CallSource {
    Agent,
    CommandLine,
}

impl CallSource {
    /// The `tool_calls.source` value. `cli` is the machine-readable marker that
    /// makes a change a script made distinguishable from one the assistant
    /// made — the two rows are otherwise identical.
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Agent => "agent",
            Self::CommandLine => "cli",
        }
    }
}

/// Maximum length of serialized arguments stored in per-call stats.
/// Longer arguments are truncated at a UTF-8-safe boundary.
const MAX_STATS_ARG_LENGTH: usize = 500;

/// The `arguments` text one tool call is recorded with: the arguments serialized, then capped to
/// [`MAX_STATS_ARG_LENGTH`]. It records what it is handed — the caller asks the tool first
/// ([`crate::Tool::recorded_arguments`]).
pub(crate) fn recorded_arguments(args: &serde_json::Value) -> String {
    let serialized = serde_json::to_string(args).expect("Value is always serializable");
    crate::util::truncate_bytes(&serialized, MAX_STATS_ARG_LENGTH).to_string()
}

impl crate::logs::LogStore {
    /// Write a batch of per-call tool records for a single flush.
    ///
    /// `recorded_at` is the instant the batch describes — stamped where the batch
    /// was produced, not when it is written.
    pub(crate) async fn flush_batch(
        &self,
        agent_id: &str,
        role: &str,
        workspace: &str,
        source: CallSource,
        recorded_at: &str,
        stats: &[crate::ToolCallRecord],
    ) -> Result<()> {
        if stats.is_empty() {
            return Ok(());
        }

        let tx = self.conn.begin_tx().await?;
        for record in stats {
            tx.execute(
                "INSERT INTO tool_calls \
                 (agent_id, role, source, tool_name, arguments, duration_ms, success, error_message, workspace, recorded_at) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
                db::params![
                    agent_id,
                    role,
                    source.as_str(),
                    record.tool_name.clone(),
                    record.arguments.clone(),
                    record.duration_ms,
                    i64::from(record.success),
                    record.error_message.clone(),
                    workspace.to_string(),
                    recorded_at,
                ],
            )
            .await?;
        }
        tx.commit().await?;
        Ok(())
    }

    /// Persist one per-operation LLM request stat to the dedicated
    /// `llm_requests` table. Metadata only — no request inputs/outputs.
    pub(crate) async fn record_llm_request(&self, rec: &LlmRequestRecord) -> Result<()> {
        self.conn
            .execute(
                "INSERT INTO llm_requests \
                 (recorded_at, purpose, agent_id, role, workspace, ticket_id, model, routing, \
                  input_tokens, output_tokens, cached_input_tokens, cache_miss_tokens, \
                  cost, cost_details, upstream_provider, system_fingerprint, \
                  duration_ms, retry_attempts, finish_reason, failure_class, success) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, \
                         ?17, ?18, ?19, ?20, ?21)",
                db::params![
                    rec.recorded_at.clone(),
                    rec.purpose,
                    rec.agent_id.clone(),
                    rec.role.clone(),
                    rec.workspace.clone(),
                    rec.ticket_id.clone(),
                    rec.model.clone(),
                    rec.routing.clone(),
                    rec.input_tokens.map(i64::try_from).transpose()?,
                    rec.output_tokens.map(i64::try_from).transpose()?,
                    rec.cached_input_tokens.map(i64::try_from).transpose()?,
                    rec.cache_miss_tokens.map(i64::try_from).transpose()?,
                    rec.cost,
                    rec.cost_details.clone(),
                    rec.upstream_provider.clone(),
                    rec.system_fingerprint.clone(),
                    i64::try_from(rec.duration_ms)?,
                    i64::from(rec.retry_attempts),
                    rec.finish_reason.clone(),
                    rec.failure_class.clone(),
                    i64::from(rec.success),
                ],
            )
            .await?;
        Ok(())
    }

    pub(crate) async fn record_llm_failure_row(&self, rec: &LlmFailureRow) -> Result<()> {
        self.conn
            .execute(
                "INSERT INTO llm_failures \
                 (operation_id, recorded_at, purpose, agent_id, role, workspace, ticket_id, \
                  model, routing, attempt, attempt_duration_ms, failure_class, finish_reason, \
                  retry_after_ms, error_chain) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
                db::params![
                    rec.operation_id.clone(),
                    rec.recorded_at.clone(),
                    rec.purpose,
                    rec.agent_id.clone(),
                    rec.role.clone(),
                    rec.workspace.clone(),
                    rec.ticket_id.clone(),
                    rec.model.clone(),
                    rec.routing.clone(),
                    i64::from(rec.attempt),
                    rec.attempt_duration_ms.map(i64::try_from).transpose()?,
                    rec.failure_class.clone(),
                    rec.finish_reason.clone(),
                    rec.retry_after_ms.map(i64::try_from).transpose()?,
                    rec.error_chain.clone(),
                ],
            )
            .await?;
        Ok(())
    }
}

/// One per-operation LLM request stat row (the `llm_requests` table).
///
/// One row per completed LLM operation (agent iteration, extraction,
/// summarization, consolidation) — retry attempts are aggregated into
/// [`LlmRequestRecord::retry_attempts`]. Metadata only: no request inputs or outputs.
#[derive(Debug, Clone)]
pub(crate) struct LlmRequestRecord {
    pub purpose: &'static str,
    pub agent_id: String,
    pub role: String,
    pub workspace: String,
    pub ticket_id: Option<String>,
    pub model: String,
    /// The provider the call was pinned to; `default` when unset.
    /// Requested-vs-actual: the serving upstream is [`LlmRequestRecord::upstream_provider`].
    pub routing: String,
    pub input_tokens: Option<u64>,
    pub output_tokens: Option<u64>,
    pub cached_input_tokens: Option<u64>,
    pub cache_miss_tokens: Option<u64>,
    /// Billed cost from `usage.cost` — the invoice amount; NULL on failures.
    pub cost: Option<f64>,
    /// Raw `usage.cost_details` JSON from the provider (reference only).
    pub cost_details: Option<String>,
    /// Serving upstream — top-level OpenRouter `provider` field (undocumented in
    /// the API reference); NULL when the provider omits it.
    pub upstream_provider: Option<String>,
    /// Provider `system_fingerprint`; NULL when the provider omits it.
    pub system_fingerprint: Option<String>,
    pub duration_ms: u64,
    /// Total HTTP attempts made by the operation (1 = no retries).
    pub retry_attempts: u32,
    pub finish_reason: Option<String>,
    pub failure_class: Option<String>,
    pub success: bool,
    pub recorded_at: String,
}

/// One per-attempt LLM failure row (the `llm_failures` table).
///
/// One row per FAILED attempt of an LLM operation — including intermediate
/// failures of operations that later succeeded and the terminal exhausted
/// attempt. Grouped per operation via [`LlmFailureRow::operation_id`].
#[derive(Debug, Clone)]
pub(crate) struct LlmFailureRow {
    /// Groups the attempts of one LLM operation (generated at operation start).
    pub operation_id: String,
    pub purpose: &'static str,
    pub agent_id: String,
    pub role: String,
    pub workspace: String,
    pub ticket_id: Option<String>,
    pub model: String,
    /// The provider the call was pinned to; `default` when unset.
    pub routing: String,
    /// 1-based sequential failure index within the operation, as counted by
    /// the loop that recorded it.
    pub attempt: u32,
    /// Elapsed time of the failed attempt; NULL where not tracked.
    pub attempt_duration_ms: Option<u64>,
    pub failure_class: String,
    pub finish_reason: Option<String>,
    pub retry_after_ms: Option<u64>,
    pub error_chain: String,
    pub recorded_at: String,
}

/// The request fields the durable `llm_requests` row actually reads — the
/// minimal carrier for calls made outside the `ChatRequest` retry pipeline
/// (e.g. raw-HTTP media transcription), where synthesizing a full request
/// envelope would be a misleading data shape.
pub(crate) struct LlmCallMeta {
    pub meta: crate::ChatRequestMeta,
    pub model: String,
    /// The provider the call was pinned to; `None` = the router decides.
    pub provider: Option<String>,
}

/// Per-operation context for `llm_failures` persistence: an operation id
/// generated at operation start plus the request identity, so every failed
/// attempt of one operation shares the id and groups back without heuristics.
pub(crate) struct LlmOperationCtx {
    pub operation_id: String,
    pub call: LlmCallMeta,
}

impl LlmCallMeta {
    /// The provider column of both telemetry rows: the pinned slug, or `default` when the router
    /// decides. One accessor so the two row builders cannot drift.
    #[must_use]
    fn routing(&self) -> String {
        self.provider
            .clone()
            .unwrap_or_else(|| "default".to_string())
    }

    /// Extract the request fields the durable rows read from a `ChatRequest`.
    /// `None` when the request carries no metadata — the same gating as the
    /// `llm_requests` rows (context-free calls are never logged).
    pub(crate) fn from_request(request: &crate::ChatRequest) -> Option<Self> {
        let meta = request.meta.as_ref()?;
        Some(Self {
            meta: meta.clone(),
            model: request.model.clone(),
            provider: request.provider.clone(),
        })
    }
}

impl LlmOperationCtx {
    /// Derive the context from a `ChatRequest`; see
    /// [`LlmCallMeta::from_request`] for the metadata gating.
    #[must_use]
    pub(crate) fn from_request(request: &crate::ChatRequest) -> Option<Self> {
        let call = LlmCallMeta::from_request(request)?;
        Some(Self {
            operation_id: crate::generate_id(),
            call,
        })
    }

    /// Record the provider that actually serves the in-flight operation after a mid-run switch, so
    /// later `llm_failures` rows and the final `llm_requests` row name it (the one place this
    /// invariant is written; see [`crate::providers::selection`]).
    pub(crate) fn set_provider(&mut self, provider: Option<String>) {
        self.call.provider = provider;
    }
}

/// Build an [`LlmRequestRecord`] from explicit metadata (see
/// [`record_llm_operation_meta`]).
fn llm_request_record_meta(
    call: &LlmCallMeta,
    duration_ms: u64,
    attempts: u32,
    response: Option<&crate::ChatResponse>,
    finish_reason: Option<&str>,
    failure_class: Option<&'static str>,
) -> LlmRequestRecord {
    let usage = response.and_then(|r| r.usage.as_ref());
    LlmRequestRecord {
        purpose: call.meta.purpose,
        agent_id: call.meta.agent_id.clone(),
        role: call.meta.role.clone(),
        workspace: call.meta.workspace.clone(),
        ticket_id: call.meta.ticket_id.clone(),
        model: call.model.clone(),
        routing: call.routing(),
        input_tokens: usage.and_then(|u| u.input_tokens),
        output_tokens: usage.and_then(|u| u.output_tokens),
        cached_input_tokens: usage.and_then(|u| u.cached_input_tokens),
        cache_miss_tokens: usage.and_then(|u| u.cache_miss_tokens),
        cost: usage.and_then(|u| u.cost),
        cost_details: usage
            .and_then(|u| u.cost_details.as_ref())
            .map(serde_json::Value::to_string),
        upstream_provider: response.and_then(|r| r.upstream_provider.clone()),
        system_fingerprint: response.and_then(|r| r.system_fingerprint.clone()),
        duration_ms,
        retry_attempts: attempts,
        finish_reason: finish_reason.map(str::to_string),
        failure_class: failure_class.map(str::to_string),
        success: failure_class.is_none(),
        recorded_at: crate::db::now(),
    }
}

/// Emit one per-operation LLM request stat row (best-effort, fail-open).
///
/// Skips when the request carries no metadata (context-free calls — test
/// doubles, ad-hoc requests).
///
/// Failure-path semantics: `upstream_provider` / `system_fingerprint` /
/// `cost` / `cost_details` are only populated from a successful response
/// envelope — failed requests have no response, so those columns stay NULL.
fn record_llm_operation(
    request: &crate::ChatRequest,
    duration_ms: u64,
    attempts: u32,
    response: Option<&crate::ChatResponse>,
    finish_reason: Option<&str>,
    failure_class: Option<&'static str>,
) {
    let Some(call) = LlmCallMeta::from_request(request) else {
        return;
    };
    record_llm_operation_meta(
        &call,
        duration_ms,
        attempts,
        response,
        finish_reason,
        failure_class,
    );
}

/// Emit one per-operation LLM request stat row from explicit metadata.
/// [`record_llm_operation`] delegates here after extracting metadata from a
/// `ChatRequest`; direct callers are for calls made outside the `ChatRequest`
/// retry pipeline (e.g. raw-HTTP media transcription), which carry no response
/// envelope. `attempts` is supplied by the caller: the transcription paths
/// always pass 1 (a single-shot fail-open call never retries). The row is handed
/// to [`crate::telemetry`]: a write failure is noted by the drain task and never propagates.
pub(crate) fn record_llm_operation_meta(
    call: &LlmCallMeta,
    duration_ms: u64,
    attempts: u32,
    response: Option<&crate::ChatResponse>,
    finish_reason: Option<&str>,
    failure_class: Option<&'static str>,
) {
    crate::telemetry::enqueue(crate::telemetry::TelemetryRecord::LlmRequest(
        llm_request_record_meta(
            call,
            duration_ms,
            attempts,
            response,
            finish_reason,
            failure_class,
        ),
    ));
}

/// What happened on one failed attempt, beyond the operation identity —
/// bundles the per-attempt fields so the row builder stays readable.
struct LlmAttemptOutcome {
    attempt: u32,
    attempt_duration_ms: Option<u64>,
    failure_class: String,
    finish_reason: Option<String>,
    retry_after_ms: Option<u64>,
    error_chain: String,
}

/// Build the failure row shared by both emit entry points below.
fn llm_failure_row(
    operation_id: &str,
    call: &LlmCallMeta,
    outcome: LlmAttemptOutcome,
) -> LlmFailureRow {
    LlmFailureRow {
        operation_id: operation_id.to_string(),
        purpose: call.meta.purpose,
        agent_id: call.meta.agent_id.clone(),
        role: call.meta.role.clone(),
        workspace: call.meta.workspace.clone(),
        ticket_id: call.meta.ticket_id.clone(),
        model: call.model.clone(),
        routing: call.routing(),
        attempt: outcome.attempt,
        attempt_duration_ms: outcome.attempt_duration_ms,
        failure_class: outcome.failure_class,
        finish_reason: outcome.finish_reason,
        retry_after_ms: outcome.retry_after_ms,
        error_chain: outcome.error_chain,
        recorded_at: crate::db::now(),
    }
}

/// Emit one per-attempt `llm_failures` row for a failed attempt inside an
/// outer retry loop. `attempt_started` is the failed attempt's launch instant
/// (`None` when the caller does not track it → NULL `attempt_duration_ms`).
/// The row is handed to [`crate::telemetry`]: a write failure is noted by the
/// drain task and never propagates.
pub(crate) fn record_llm_attempt_failure(
    ctx: &LlmOperationCtx,
    attempt: u32,
    rec: &crate::retry::RetryFailureRecord,
    attempt_started: Option<std::time::Instant>,
) {
    let outcome = LlmAttemptOutcome {
        attempt,
        attempt_duration_ms: elapsed_ms(attempt_started),
        failure_class: rec.class.label().to_string(),
        finish_reason: rec.finish_reason.clone(),
        retry_after_ms: rec.retry_after_ms,
        error_chain: rec.error_chain.clone(),
    };
    crate::telemetry::enqueue(crate::telemetry::TelemetryRecord::LlmFailure(
        llm_failure_row(&ctx.operation_id, &ctx.call, outcome),
    ));
}

/// Elapsed milliseconds since `started`, if tracked.
fn elapsed_ms(started: Option<std::time::Instant>) -> Option<u64> {
    started.and_then(|t| u64::try_from(t.elapsed().as_millis()).ok())
}

#[expect(clippy::cast_possible_truncation)]
pub(crate) fn record_llm_success(
    request: &crate::ChatRequest,
    started: std::time::Instant,
    attempt: u32,
    response: &crate::ChatResponse,
) {
    record_llm_operation(
        request,
        started.elapsed().as_millis() as u64,
        attempt,
        Some(response),
        response.finish_reason.as_deref(),
        None,
    );
}

#[expect(clippy::cast_possible_truncation)]
pub(crate) fn record_llm_failure(
    request: &crate::ChatRequest,
    started: std::time::Instant,
    exhausted: &crate::retry::RetryExhausted,
) {
    record_llm_operation(
        request,
        started.elapsed().as_millis() as u64,
        exhausted.failures.len() as u32,
        None,
        exhausted
            .failures
            .last()
            .and_then(|r| r.finish_reason.as_deref()),
        Some(exhausted.final_class.label()),
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `recorded_arguments` records the serialized arguments as produced, capped at
    /// [`MAX_STATS_ARG_LENGTH`]. What it is handed is what it writes — keeping a secret out is the
    /// recording caller's job, done where the tool declares it.
    #[test]
    fn recorded_arguments_are_recorded_as_produced_and_capped() {
        // A short argument set is recorded exactly as produced, key order and all.
        assert_eq!(
            recorded_arguments(&serde_json::json!({ "action": "search", "query": "cats" })),
            r#"{"action":"search","query":"cats"}"#
        );

        let args = serde_json::json!({
            "action": "search",
            "query": "x".repeat(MAX_STATS_ARG_LENGTH * 2),
        });
        let recorded = recorded_arguments(&args);
        assert_eq!(recorded.len(), MAX_STATS_ARG_LENGTH);
        assert!(recorded.starts_with(r#"{"action":"search","query":"xxx"#));
    }
}