khive-runtime 0.20.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
Documentation
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! Canonical typed runtime projection and per-operation failure construction.
//!
//! Ordinary typed projections retain their structured evidence. Search-read
//! context deliberately exposes only closed classifications and safe context. The shared entry builder applies the
//! response boundary's nesting and domain-result retention rules afterwards.

use khive_storage::{StorageCapability, StorageError};
use serde_json::{json, Value};

use crate::{DomainDisposition, RuntimeError};

/// Project typed evidence, with explicit privacy narrowing for search-read context.
///
/// `disposition` describes the enclosing operation. Named runtime refusals keep
/// their existing wire override. This function moves an obligation's result
/// without cloning or recursively serializing it; callers apply their own depth
/// limits before any recursive operation on the returned value.
pub fn runtime_error_value(error: RuntimeError, disposition: DomainDisposition) -> Value {
    let disposition = if disposition == DomainDisposition::Committed {
        disposition
    } else {
        error.batch_write_disposition().unwrap_or(disposition)
    };
    runtime_error_value_inner(error, disposition)
}

/// Original input to the shared per-operation failure builder.
pub enum FailureEntrySource {
    /// A typed runtime failure and the original dispatch boundary's outcome.
    Runtime {
        error: RuntimeError,
        boundary: DomainDisposition,
    },
    /// An error payload whose disposition is supplied by its caller.
    Value {
        error: Value,
        disposition: DomainDisposition,
    },
}

/// An owned normalized failure, consumable as an error or a per-operation entry.
pub struct FailureEntryParts {
    error: Value,
    disposition: DomainDisposition,
}

impl FailureEntryParts {
    /// Return the normalized error without constructing an outer entry.
    pub fn into_error(self) -> Value {
        self.error
    }

    /// Move the normalized error into its per-operation response entry.
    pub fn into_entry(self, tool: impl Into<String>) -> Value {
        let mut entry = serde_json::Map::new();
        entry.insert("ok".into(), Value::Bool(false));
        entry.insert("tool".into(), Value::String(tool.into()));
        entry.insert(
            "domain_disposition".into(),
            json!(self.disposition.as_str()),
        );
        entry.insert("error".into(), self.error);
        Value::Object(entry)
    }
}

/// Read the outcome named by a canonical error payload, defaulting to uncertainty.
///
/// This reads an existing payload; it does not establish write provenance.
pub fn failure_error_disposition(error: &Value) -> DomainDisposition {
    match error.get("domain_disposition").and_then(Value::as_str) {
        Some("committed") => DomainDisposition::Committed,
        Some("not_committed") => DomainDisposition::NotCommitted,
        _ => DomainDisposition::Unknown,
    }
}

/// Build the canonical failure parts shared by request executors.
///
/// Runtime input uses the public typed projection once. Both final disposition
/// fields use its result. A domain result survives only when both the original
/// boundary and projection are committed. The boundary's depth handling runs
/// first, preserving its existing code and message replacement even when the
/// projection subsequently removes the result. Value input always uses its
/// caller's explicit disposition, ignoring any competing JSON claim.
pub fn failure_entry_parts(source: FailureEntrySource) -> FailureEntryParts {
    use crate::daemon::{drop_error_detail_iteratively, error_detail_value_within_limit};

    let (error, boundary, disposition) = match source {
        FailureEntrySource::Runtime { error, boundary } => {
            let projected = runtime_error_value(error, boundary);
            let disposition = failure_error_disposition(&projected);
            (projected, boundary, disposition)
        }
        FailureEntrySource::Value { error, disposition } => (error, disposition, disposition),
    };
    let mut error = match error {
        Value::Object(map) => map,
        Value::String(message) => serde_json::Map::from_iter([
            ("kind".into(), json!("runtime_error")),
            ("message".into(), Value::String(message)),
        ]),
        other => {
            drop_error_detail_iteratively(other);
            serde_json::Map::from_iter([
                ("kind".into(), json!("runtime_error")),
                ("message".into(), json!("operation failed")),
            ])
        }
    };
    let committed = |value: DomainDisposition| value == DomainDisposition::Committed;
    if let Some(result) = error.remove("domain_result") {
        if !committed(boundary) {
            drop_error_detail_iteratively(result);
        } else if !error_detail_value_within_limit(&result) {
            drop_error_detail_iteratively(result);
            error.insert("code".into(), json!("result_too_deep"));
            error.insert(
                "message".into(),
                json!("committed domain result omitted because it exceeds the nesting depth limit"),
            );
        } else if !committed(disposition) {
            drop_error_detail_iteratively(result);
        } else {
            error.insert("domain_result".into(), result);
        }
    }
    error.insert("domain_disposition".into(), json!(disposition.as_str()));
    FailureEntryParts {
        error: Value::Object(error),
        disposition,
    }
}

// Choose operation-local proof once. Recursive projection must not promote an
// inner batch proof past an enclosing context with earlier or unknown effects.
fn runtime_error_value_inner(error: RuntimeError, disposition: DomainDisposition) -> Value {
    // These named outcomes carry their own domain proof. Do not infer general
    // write disposition from a conflict or unavailable variant.
    let sqlite_write_failure = match error.refusal_source() {
        RuntimeError::Storage(error) => error.sqlite_write_failure(),
        _ => None,
    };
    let outcome_has_precedence = error.writer_task_failure_context().is_some_and(|context| {
        context.task_terminated
            || context.request_state == khive_storage::WriterTaskRequestState::SideEffectsUnknown
    });
    let receipt_projection = crate::visibility_receipts::receipt_error_projection(&error);
    let named_disposition = match &error {
        _ if receipt_projection.is_some_and(|(_, replay)| replay) => Some("not_committed"),
        // An immutable-stream policy refusal is a definite no-write. It is matched by the
        // shared predicate rather than by a reason string so the two consumers of that
        // predicate and this projection cannot drift into disagreeing about it.
        error if error.is_stream_policy_refusal() => Some("not_committed"),
        // A refusal that wrote a receipt is a definite no-write of the thing it
        // refused: the receipt exists precisely to record that nothing ran.
        RuntimeError::RefusedWithReceipt(_) => Some("not_committed"),
        RuntimeError::Khive(k) => match (k.kind(), k.details().and_then(|d| d.get("reason"))) {
            (
                khive_types::ErrorKind::Internal,
                Some("post_commit_degraded" | "embedding_input_truncated"),
            ) => Some("committed"),
            // These keyed conflicts certify that this request wrote no domain record.
            (
                khive_types::ErrorKind::Conflict,
                Some("key_conflict" | "fence_conflict" | "idempotency_key_conflict"),
            ) => Some("not_committed"),
            (khive_types::ErrorKind::Unavailable, Some("key_holder_unresolved")) => Some("unknown"),
            // ADR-174 A1.1: a stream member refusal carries
            // `domain_disposition: not_committed` wherever it surfaces. In
            // per-member mode it is the member's own value and the runtime
            // writes the field itself; in atomic mode the refusal is raised
            // as the call's error, where without these rows the boundary's
            // `unknown` would stand and the caller could not tell a batch
            // that wrote nothing from one whose outcome is unestablished.
            (khive_types::ErrorKind::Conflict, Some("seq_conflict")) => Some("not_committed"),
            (khive_types::ErrorKind::Conflict, Some("unknown_op")) => Some("not_committed"),
            (khive_types::ErrorKind::Conflict, Some("version_conflict" | "identity_conflict")) => {
                Some("not_committed")
            }
            (khive_types::ErrorKind::Conflict, Some("expired" | "live_until_unreadable")) => {
                Some("not_committed")
            }
            (khive_types::ErrorKind::NotFound, Some("stream_write_not_found")) => {
                Some("not_committed")
            }
            // An exact keyed replay whose holder was hard-deleted before its
            // provenance read: the attempt's unit rolled back on the key claim.
            (khive_types::ErrorKind::NotFound, Some("keyed_replay_holder_missing")) => {
                Some("not_committed")
            }
            (
                khive_types::ErrorKind::InvalidInput,
                Some("member_unavailable" | "sequence_exhausted"),
            ) => Some("not_committed"),
            _ => None,
        },
        _ => None,
    };
    // The refusal text is the same Display string every consumer already
    // matches on; the receipt fields ride beside it.
    let denial_message =
        matches!(error, RuntimeError::PermissionDenied { .. }).then(|| error.to_string());
    let payload = match error {
        RuntimeError::SearchRead { context } => {
            let message = context.to_string();
            let backend = context.backend().as_str().to_owned();
            let substrate = context.substrate().as_str();
            let cause_class = context.source().audit_error_class().as_str();
            let retryable = context.source().retryable_failure_context().is_some();
            // Only the canonical source kind and typed outcome survive. Never
            // copy arbitrary source messages, details, codes or retry values.
            let source = runtime_error_value_inner(context.into_source(), disposition);
            let kind = source["kind"]
                .as_str()
                .expect("canonical error kind is a string");
            assert!(
                matches!(
                    kind,
                    "runtime_error"
                        | "obligation"
                        | "internal"
                        | "remote_fetch_error"
                        | "not_found"
                        | "storage"
                        | "unavailable"
                        | "invalid_input"
                        | "unauthorized"
                        | "conflict"
                ),
                "canonical error kind must have an explicit privacy classification"
            );
            let mut value = json!({
                "kind": kind,
                "code": "search_read_failed",
                "message": message,
                "cause_class": cause_class,
                "domain_disposition": failure_error_disposition(&source).as_str(),
                "search_context": {"backend": backend, "substrate": substrate},
            });
            if retryable {
                value["retryable"] = json!(true);
            }
            return value;
        }
        RuntimeError::CanonicalUnsupportedOperation {
            op_index,
            operation,
        } => {
            return json!({
                "kind": "runtime_error",
                "code": "invalid_input",
                "reason": "KnownUnimplemented",
                "operation": operation,
                "op_index": op_index,
                "message": format!("canonical operation {op_index}: {operation} is KnownUnimplemented for canonical apply"),
                "domain_disposition": "not_committed",
                "retryable": false,
            });
        }
        RuntimeError::CanonicalAdmission { op_index, source } => {
            // Preparation precedes all domain DML. Keep the original typed
            // refusal (including secret detector/permission receipt) and add
            // only the constituent's index; never stringify captured input.
            let mut value = runtime_error_value_inner(*source, DomainDisposition::NotCommitted);
            value["op_index"] = json!(op_index);
            value["domain_disposition"] = json!("not_committed");
            value["retryable"] = json!(false);
            return value;
        }
        RuntimeError::LintFix { source, detail } => {
            let mut value = runtime_error_value_inner(*source, DomainDisposition::Unknown);
            let object = value
                .as_object_mut()
                .expect("runtime error projection is an object");
            let details = object.entry("details").or_insert_with(|| json!({}));
            if !details.is_object() {
                *details = json!({});
            }
            details["lint_fix"] = json!(detail);
            // Earlier actions may already have committed. A named refusal of
            // the last action cannot certify the whole call as not committed.
            value["domain_disposition"] = json!("unknown");
            value["retryable"] = json!(false);
            return value;
        }

        RuntimeError::WithResolution { context } => {
            let crate::error::ResolutionFailureContext { source, resolution } = context;
            let mut value = runtime_error_value_inner(*source, disposition);
            let details = value
                .as_object_mut()
                .expect("runtime error projection is an object")
                .entry("details")
                .or_insert_with(|| json!({}));
            if !details.is_object() {
                *details = json!({});
            }
            details["resolution"] = json!(resolution);
            return value;
        }
        RuntimeError::BatchWrite { context } => {
            let crate::error::BatchWriteContext {
                source, admission, ..
            } = *context;
            let mut value = runtime_error_value_inner(*source, disposition);
            if let Some(report) = admission {
                if report.validation_complete {
                    if let Some(first) = report.refused.first() {
                        if !value["details"].is_object() {
                            value["details"] = json!({});
                        }
                        value["details"]["index"] = json!(first.index.to_string());
                        value["details"]["field"] = json!(first.field);
                        value["details"]["reason"] = json!(first.reason);
                    }
                } else {
                    value["unchecked_indices"] = json!(report.unchecked_indices);
                }
                value["refused"] = json!(report.refused);
                value["validation_complete"] = json!(report.validation_complete);
            }
            value["domain_disposition"] = json!(disposition.as_str());
            return value;
        }
        RuntimeError::RefusedWithEvents { context } => {
            let crate::error::RefusalEventContext { source, recordings } = context;
            // Project the source first so named dispositions, code/details,
            // detector location and refusal text retain their original meaning.
            let mut value = runtime_error_value_inner(*source, disposition);
            if !recordings.is_empty() {
                value["refusal_recorded"] = json!(recordings.iter().all(|recording| {
                    matches!(recording, crate::RefusalEventRecording::Recorded { .. })
                }));
                value["refusal_events"] = json!(recordings);
            }
            return value;
        }
        RuntimeError::PermissionDenied {
            verb,
            reason,
            receipt,
        } => json!({
            "kind": "runtime_error",
            "code": "permission_denied",
            "message": denial_message.unwrap_or_default(),
            "verb": verb,
            "reason": reason,
            "audit_event_id": receipt.audit_event_id.map(|id| id.to_string()),
            "audit_outcome": receipt.audit_outcome.wire_code(),
        }),
        RuntimeError::SecretDetected(matched) => {
            let message = RuntimeError::SecretDetected(matched.clone()).to_string();
            json!({
                "kind": "runtime_error",
                "code": "secret_detected",
                "detector": matched.detector,
                "location": matched.location,
                "message": message,
            })
        }
        RuntimeError::RefusedWithReceipt(refusal) => {
            let crate::error::ReceiptRefusal {
                code,
                message,
                receipt_id,
                reason,
                detail,
            } = *refusal;
            // Surface evidence first, contract fields last: a detail member that
            // happens to share a name with a contract field cannot shadow it.
            let mut error = match detail {
                Value::Object(members) => members,
                _ => serde_json::Map::new(),
            };
            error.insert("kind".into(), json!("runtime_error"));
            error.insert("code".into(), json!(code));
            error.insert("message".into(), json!(message));
            error.insert("receipt_id".into(), json!(receipt_id));
            error.insert("reason".into(), json!(reason));
            Value::Object(error)
        }
        RuntimeError::AuditObligation {
            failure,
            domain_result,
        } => {
            let mut error = serde_json::Map::from_iter([
                ("kind".into(), json!("obligation")),
                ("code".into(), json!(failure.wire_code())),
                ("message".into(), json!(failure.to_string())),
            ]);
            error.insert("domain_result".into(), domain_result);
            Value::Object(error)
        }
        RuntimeError::Khive(k) => {
            let mut value = serde_json::to_value(&k)
                .unwrap_or_else(|_| json!({"kind": "internal", "message": k.to_string()}));
            if k.kind() == khive_types::ErrorKind::InvalidInput
                && k.details().and_then(|d| d.get("reason")) == Some("external_id_unverifiable")
            {
                value["code"] = json!("external_id_unverifiable");
            }
            value
        }
        RuntimeError::RemoteFetchError { remote, message } => json!({
            "kind": "remote_fetch_error",
            "remote": remote,
            "message": message,
        }),
        missing @ RuntimeError::NotFound(_) => json!({
            "kind": "not_found",
            "code": null,
            "details": null,
            "message": missing.to_string(),
        }),
        other @ (RuntimeError::Storage(_)
        | RuntimeError::Query(_)
        | RuntimeError::InvalidInput(_)
        | RuntimeError::UnknownVerb(_)
        | RuntimeError::Unconfigured(_)
        | RuntimeError::UnknownModel(_)
        | RuntimeError::Embedding(_)
        | RuntimeError::Ambiguous(_)
        | RuntimeError::Fusion(_)
        | RuntimeError::UnknownFusionStrategy(_)
        | RuntimeError::Internal(_)
        | RuntimeError::IncompatibleEventStore(_)
        | RuntimeError::GuardedWriteFailed(_)
        | RuntimeError::MissingPackDependency(_)
        | RuntimeError::MissingPackDependencies(_)
        | RuntimeError::CircularPackDependency(_)
        | RuntimeError::PackRedeclared { .. }
        | RuntimeError::VerbCollision { .. }
        | RuntimeError::ReservedEnvelopeParam { .. }
        | RuntimeError::GateUnavailable { .. }
        | RuntimeError::NamespaceMismatch { .. }
        | RuntimeError::AmbiguousPrefix { .. }
        | RuntimeError::CrossBackendMergeUnsupported { .. }
        | RuntimeError::UnknownRemote { .. }
        | RuntimeError::RemoteCacheMissing { .. }
        | RuntimeError::AmbiguousId { .. }
        | RuntimeError::CrossNamespaceWrite { .. }
        | RuntimeError::WriteBudgetExceeded { .. }
        | RuntimeError::DeadlineExceeded { .. }
        | RuntimeError::AttachmentCutoverRequired { .. }) => {
            if let Some(capacity) = sqlite_capacity_failure(&other) {
                let mut value = capacity.into_value(other.to_string());
                if let Some(context) = other.writer_task_failure_context() {
                    value["request_state"] = json!(context.request_state.to_string());
                    value["task_terminated"] = json!(context.task_terminated);
                }
                value
            } else if let Some(context) = other.writer_task_failure_context() {
                json!({"kind":"storage", "code":context.stage, "stage":context.stage,
                    "message":other.to_string(), "retryable":context.retryable,
                    "request_state":context.request_state.to_string(), "task_terminated":context.task_terminated})
            } else if let Some(context) = other.retryable_failure_context() {
                let timeout_ms = u64::try_from(context.timeout.as_millis()).unwrap_or(u64::MAX);
                let mut value = json!({"kind":"unavailable", "code":context.stage, "stage":context.stage,
                    "message":other.to_string(), "retryable":true, "timeout_ms":timeout_ms,
                    "capability":context.capability.map(storage_capability_wire_name),
                    "operation":context.operation, "scope":context.scope, "retry_after_ms":context.retry_after_ms});
                if let Some(pool_identity) = context.pool_identity {
                    value["pool_identity"] = json!(pool_identity);
                }
                value
            } else {
                json!({"kind":"runtime_error", "message":other.to_string()})
            }
        }
    };
    let mut value = payload;
    if let Some(failure) = sqlite_write_failure {
        // Capacity refusal retains its existing caller-visible precedence.
        if !outcome_has_precedence
            && !failure.settlement_unknown
            && failure.primary_code != rusqlite::ffi::SQLITE_FULL
        {
            value["code"] = json!(failure.stage.as_str());
            value["stage"] = json!(failure.stage.as_str());
            if value["kind"] == "runtime_error" {
                value["kind"] = json!("storage");
            }
        }
        value["sqlite_write_stage"] = json!(failure.stage.as_str());
        value["sqlite_primary_code"] = json!(failure.primary_code);
        value["sqlite_extended_code"] = json!(failure.extended_code);
    }
    if let Some((retryable, _)) = receipt_projection {
        value["retryable"] = json!(retryable);
    }
    value["domain_disposition"] = json!(disposition.as_str());
    if let Some(named) = named_disposition {
        value["domain_disposition"] = json!(named);
    }
    value
}

enum SqliteCapacityFailure {
    Refused {
        volume: String,
        available_bytes: u64,
        reserve_bytes: u64,
        required_headroom_bytes: u64,
    },
    Unavailable {
        phase: khive_storage::CapacityUnavailablePhase,
    },
    NativeFull {
        primary_code: i32,
        extended_code: i32,
    },
}

impl SqliteCapacityFailure {
    fn into_value(self, message: String) -> Value {
        match self {
            Self::Refused {
                volume,
                available_bytes,
                reserve_bytes,
                required_headroom_bytes,
            } => json!({
                "kind": "storage",
                "code": "sqlite_capacity_refused",
                "stage": "sqlite_capacity_refused",
                "message": message,
                "retryable": false,
                "capability": "sql",
                "volume": volume,
                "available_bytes": available_bytes,
                "reserve_bytes": reserve_bytes,
                "required_headroom_bytes": required_headroom_bytes,
            }),
            Self::Unavailable { phase } => json!({
                "kind": "storage",
                "code": "sqlite_capacity_unavailable",
                "stage": "sqlite_capacity_unavailable",
                "message": message,
                "retryable": phase == khive_storage::CapacityUnavailablePhase::LockContended,
                "capability": "sql",
                "phase": phase.as_str(),
            }),
            Self::NativeFull {
                primary_code,
                extended_code,
            } => json!({
                "kind": "storage",
                "code": "sqlite_disk_full",
                "stage": "sqlite_disk_full",
                "message": message,
                "retryable": false,
                "capability": "sql",
                "sqlite_primary_code": primary_code,
                "sqlite_extended_code": extended_code,
            }),
        }
    }
}

fn sqlite_capacity_failure(error: &RuntimeError) -> Option<SqliteCapacityFailure> {
    match error {
        RuntimeError::Storage(storage) => sqlite_capacity_failure_from_storage(storage),
        _ => None,
    }
}

fn sqlite_capacity_failure_from_storage(error: &StorageError) -> Option<SqliteCapacityFailure> {
    match error {
        StorageError::CapacityFloor {
            capability: StorageCapability::Sql,
            volume,
            available_bytes,
            floor_bytes,
            required_headroom_bytes,
        } => Some(SqliteCapacityFailure::Refused {
            volume: volume.clone(),
            available_bytes: *available_bytes,
            reserve_bytes: *floor_bytes,
            required_headroom_bytes: *required_headroom_bytes,
        }),
        StorageError::CapacityUnavailable {
            capability: StorageCapability::Sql,
            phase,
            ..
        } => Some(SqliteCapacityFailure::Unavailable { phase: *phase }),
        StorageError::WriterTaskTerminated {
            sqlite_full_codes: Some((primary_code, extended_code)),
            ..
        } if *primary_code == rusqlite::ffi::SQLITE_FULL
            && *extended_code >= 0
            && (*extended_code & 0xff) == *primary_code =>
        {
            Some(SqliteCapacityFailure::NativeFull {
                primary_code: *primary_code,
                extended_code: *extended_code,
            })
        }
        StorageError::SqliteWrite { failure, .. }
            if failure.primary_code == rusqlite::ffi::SQLITE_FULL =>
        {
            Some(SqliteCapacityFailure::NativeFull {
                primary_code: failure.primary_code,
                extended_code: failure.extended_code,
            })
        }
        StorageError::WriterTaskRequestFailed { source, .. }
        | StorageError::SqliteWrite { source, .. } => sqlite_capacity_failure_from_storage(source),
        StorageError::Driver { source, .. } => {
            if let Some(sqlite) = source.downcast_ref::<khive_db::SqliteError>() {
                sqlite_capacity_failure_from_sqlite(sqlite)
            } else {
                native_sqlite_full(source.as_ref())
            }
        }
        _ => None,
    }
}

fn sqlite_capacity_failure_from_sqlite(
    error: &khive_db::SqliteError,
) -> Option<SqliteCapacityFailure> {
    match error {
        khive_db::SqliteError::CapacityFloor {
            volume,
            available_bytes,
            floor_bytes,
            required_headroom_bytes,
        } => Some(SqliteCapacityFailure::Refused {
            volume: volume.clone(),
            available_bytes: *available_bytes,
            reserve_bytes: *floor_bytes,
            required_headroom_bytes: *required_headroom_bytes,
        }),
        khive_db::SqliteError::CapacityUnavailable { phase, .. } => {
            Some(SqliteCapacityFailure::Unavailable { phase: *phase })
        }
        khive_db::SqliteError::Rusqlite(sqlite)
        | khive_db::SqliteError::Write { source: sqlite, .. } => native_sqlite_full(sqlite),
        _ => None,
    }
}

fn native_sqlite_full(error: &(dyn std::error::Error + 'static)) -> Option<SqliteCapacityFailure> {
    let mut source = Some(error);
    while let Some(current) = source {
        if let Some(rusqlite::Error::SqliteFailure(code, _)) =
            current.downcast_ref::<rusqlite::Error>()
        {
            if code.code == rusqlite::ErrorCode::DiskFull {
                return Some(SqliteCapacityFailure::NativeFull {
                    primary_code: code.extended_code & 0xff,
                    extended_code: code.extended_code,
                });
            }
        }
        source = current.source();
    }
    None
}

fn storage_capability_wire_name(capability: StorageCapability) -> &'static str {
    match capability {
        StorageCapability::Sql => "sql",
        StorageCapability::Notes => "notes",
        StorageCapability::Entities => "entities",
        StorageCapability::Graph => "graph",
        StorageCapability::Events => "events",
        StorageCapability::Vectors => "vectors",
        StorageCapability::Sparse => "sparse",
        StorageCapability::Text => "text",
        StorageCapability::Blob => "blob",
        StorageCapability::Attachments => "attachments",
    }
}

#[cfg(test)]
#[path = "error_projection_tests.rs"]
mod tests;