Skip to main content

khive_runtime/
error.rs

1//! Runtime error types.
2
3use std::fmt;
4use std::time::Duration;
5
6use thiserror::Error;
7use uuid::Uuid;
8
9/// Convenience alias for `Result<T, RuntimeError>`.
10pub type RuntimeResult<T> = Result<T, RuntimeError>;
11
12/// What this dispatch boundary can establish about its own domain operation.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
14#[serde(rename_all = "snake_case")]
15pub enum DomainDisposition {
16    /// The handler returned its canonical success value before a later failure.
17    Committed,
18    /// No requested domain write committed, established by pre-dispatch refusal
19    /// or an explicit handler/write proof.
20    NotCommitted,
21    /// The handler failed, so its domain effects are not established here.
22    Unknown,
23}
24
25impl DomainDisposition {
26    /// Stable wire spelling, shared by request and daemon envelopes.
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            Self::Committed => "committed",
30            Self::NotCommitted => "not_committed",
31            Self::Unknown => "unknown",
32        }
33    }
34}
35
36/// An unchanged runtime error with provenance from one dispatch boundary.
37#[derive(Debug, Error)]
38#[error("{source}")]
39pub struct DispatchError {
40    #[source]
41    source: RuntimeError,
42    disposition: DomainDisposition,
43}
44
45impl DispatchError {
46    pub(crate) fn new(source: RuntimeError, disposition: DomainDisposition) -> Self {
47        Self {
48            source,
49            disposition,
50        }
51    }
52
53    pub(crate) fn before_dispatch(source: RuntimeError) -> Self {
54        Self::new(source, DomainDisposition::NotCommitted)
55    }
56
57    pub(crate) fn after_handler(source: RuntimeError, domain_succeeded: bool) -> Self {
58        let disposition = if domain_succeeded {
59            DomainDisposition::Committed
60        } else {
61            source
62                .batch_write_disposition()
63                .unwrap_or(DomainDisposition::Unknown)
64        };
65        Self::new(source, disposition)
66    }
67
68    /// Borrow the original error without changing its classification.
69    pub fn source(&self) -> &RuntimeError {
70        &self.source
71    }
72
73    /// Read provenance belonging to this dispatch, not to a nested operation.
74    pub fn disposition(&self) -> DomainDisposition {
75        self.disposition
76    }
77
78    /// Separate the original error from its dispatch provenance.
79    pub fn into_parts(self) -> (RuntimeError, DomainDisposition) {
80        (self.source, self.disposition)
81    }
82
83    /// Compatibility path for callers that consume runtime errors directly.
84    pub fn into_source(self) -> RuntimeError {
85        self.source
86    }
87}
88
89/// Typed cause of a post-dispatch audit or durable-receipt failure.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum AuditObligationReason {
92    /// The audit batch reported one of its closed terminal outcomes.
93    Terminal(crate::audit_batch::AuditTerminalReason),
94    /// Receipt setup failed before submission produced a terminal outcome.
95    GitDigestReceiptFailure,
96}
97
98/// An obligation failure preserves its typed cause and any storage source.
99#[derive(Debug, Error)]
100#[error("{message}")]
101pub struct AuditObligationFailure {
102    /// Machine-readable terminal or receipt-setup cause.
103    pub reason: AuditObligationReason,
104    /// Domain verb whose post-dispatch obligation failed.
105    pub verb: String,
106    /// Stable caller-visible explanation; excludes the canonical domain value.
107    pub message: String,
108    #[source]
109    source: Option<khive_storage::StorageError>,
110}
111
112impl AuditObligationFailure {
113    /// Preserve a terminal audit outcome without parsing its display text.
114    pub fn new(verb: impl Into<String>, reason: crate::audit_batch::AuditTerminalReason) -> Self {
115        let verb = verb.into();
116        Self {
117            message: format!("audit obligation commit failed for verb {verb:?}: {reason:?}"),
118            verb,
119            reason: AuditObligationReason::Terminal(reason),
120            source: None,
121        }
122    }
123
124    pub(crate) fn from_store(verb: &str, source: khive_storage::StorageError) -> Self {
125        let mut failure = Self::new(verb, crate::audit_batch::AuditTerminalReason::StoreFailure);
126        failure.message = format!("audit obligation commit failed for verb {verb:?}: {source}");
127        failure.source = Some(source);
128        failure
129    }
130
131    pub(crate) fn git_digest_receipt(branch: &'static str) -> Self {
132        Self {
133            reason: AuditObligationReason::GitDigestReceiptFailure,
134            verb: "git.digest".into(),
135            message: format!(
136                "git_digest_receipt_persist_failed: {branch}; git.digest writes may have committed, but no durable success receipt was confirmed; inspect ingest state before retrying"
137            ),
138            source: None,
139        }
140    }
141
142    /// Closed wire-code mapping: a new batch terminal reason requires an arm.
143    pub const fn wire_code(&self) -> &'static str {
144        use crate::audit_batch::AuditTerminalReason;
145        match self.reason {
146            AuditObligationReason::Terminal(reason) => match reason {
147                AuditTerminalReason::PreflightRejected => "preflight_rejected",
148                AuditTerminalReason::AdmissionClosed => "admission_closed",
149                AuditTerminalReason::QueueAdmissionExhausted => "queue_admission_exhausted",
150                AuditTerminalReason::AdmissionDeadlineExpired => "admission_deadline_expired",
151                AuditTerminalReason::ResolutionDeadlineExpired => "resolution_deadline_expired",
152                AuditTerminalReason::IdentityConflict => "identity_conflict",
153                AuditTerminalReason::StoreFailure => "store_failure",
154                AuditTerminalReason::RetryExhausted => "retry_exhausted",
155                AuditTerminalReason::IdempotencyUnsupported => "idempotency_unsupported",
156                AuditTerminalReason::DriverPanicked => "driver_panicked",
157                AuditTerminalReason::DriverCancelled => "driver_cancelled",
158                AuditTerminalReason::DriverJoinLost => "driver_join_lost",
159                AuditTerminalReason::DriverExitedInconsistent => "driver_exited_inconsistent",
160                AuditTerminalReason::DriverAppendAbandoned => "driver_append_abandoned",
161                AuditTerminalReason::StoreWedged => "store_wedged",
162            },
163            AuditObligationReason::GitDigestReceiptFailure => "git_digest_receipt_failure",
164        }
165    }
166}
167
168/// Stable ADR-135 F6 stage and wire code for a finite-wait pooled writer
169/// checkout that expires before SQLite executes.
170pub const WRITER_POOL_CHECKOUT_TIMEOUT_STAGE: &str = "writer_pool_checkout_timeout";
171
172/// Stable ADR-194 WAL capacity stages, shared with the SQLite error source.
173pub use khive_db::{SQLITE_WAL_CAPACITY_REFUSED_STAGE, SQLITE_WAL_CAPACITY_UNAVAILABLE_STAGE};
174
175/// Stable wire code/stage for a bounded write-queue enqueue that never
176/// accepted the request within its configured deadline (#1382, #1643).
177pub const WRITER_QUEUE_SATURATED_STAGE: &str = "writer_queue_saturated";
178
179/// Stable wire code/stage for SQLite write-lock contention after the writer
180/// queue accepted a request but before its operation closure ran.
181pub const WRITER_TASK_BEGIN_BUSY_STAGE: &str = "writer_task_begin_busy";
182
183/// Stable wire code/stage for an ordinary writer request whose operation or
184/// COMMIT failed after the task proved its transaction was rolled back.
185pub const WRITER_TASK_REQUEST_FAILED_STAGE: &str = "writer_task_request_failed";
186
187/// Stable wire code/stage for a request reported by a permanently retired
188/// writer seam.
189pub const WRITER_TASK_TERMINATED_STAGE: &str = "writer_task_terminated";
190
191/// COMMIT was issued but its caller cannot establish the outcome (ADR-135 F6).
192pub const WRITE_OUTCOME_UNKNOWN_STAGE: &str = "write_outcome_unknown";
193/// Strict routing could not reach its writer before execution (ADR-135 F6).
194pub const WRITER_OWNER_UNAVAILABLE_STAGE: &str = "writer_owner_unavailable";
195/// Strict routing refused an attempted direct logical write (ADR-135 F6).
196pub const WRITER_ROUTE_VIOLATION_STAGE: &str = "writer_route_violation";
197
198/// Stable wire code/stage for a bounded storage-admission wait (a
199/// reader/writer handle slot or a pooled reader checkout) that elapsed
200/// before anything was acquired. The operation never started, so the
201/// failure is safe to retry.
202pub const STORAGE_ADMISSION_TIMEOUT_STAGE: &str = "storage_admission_timeout";
203
204/// Stable wire code/stage for a cached read-only transaction proactively
205/// rolled back after pinning a WAL snapshot past the configured
206/// `read_tx_max_age` bound (#1846). Always safe to retry: the eviction only
207/// ever fires on a read-only handle, so no side effect can exist for a
208/// retry to duplicate. Shared by both
209/// [`khive_storage::StorageError::ReadTransactionAgeEvicted`] (clean
210/// rollback) and
211/// [`khive_storage::StorageError::ReadTransactionAgeEvictionCleanupFailed`]
212/// (rollback denied or failed outright) — the rendered `message` field
213/// distinguishes the two; retry behavior is identical for both.
214pub const READ_TX_AGE_EVICTED_STAGE: &str = "read_tx_age_evicted";
215
216/// Stable ADR-131:251 `scope` discriminator carried on a
217/// [`WRITER_QUEUE_SATURATED_STAGE`] failure — distinguishes write-queue
218/// admission saturation from other `unavailable` failure kinds that share
219/// the same `retryable: true` shape but are not bounded by the admission
220/// deadline (e.g. [`WRITER_POOL_CHECKOUT_TIMEOUT_STAGE`], which has no
221/// ADR-131-defined scope and carries `None`).
222pub const WRITER_ADMISSION_SCOPE: &str = "writer_admission";
223
224/// Structured context for a pre-execution admission failure: a finite-wait
225/// pooled writer checkout timeout, a bounded write-queue enqueue timeout, or
226/// a bounded storage-admission wait (reader/writer handle slot or pooled
227/// reader checkout). All happen before SQLite executes the request, so all
228/// are safe to classify as retryable — the request was never accepted, let
229/// alone started.
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct AdmissionFailureContext {
232    /// Stable wire stage/code: one of [`WRITER_POOL_CHECKOUT_TIMEOUT_STAGE`],
233    /// [`WRITER_QUEUE_SATURATED_STAGE`], or
234    /// [`STORAGE_ADMISSION_TIMEOUT_STAGE`].
235    pub stage: &'static str,
236    /// The configured deadline that elapsed.
237    pub timeout: Duration,
238    /// Storage capability the request was scoped to, when known. The write
239    /// queue is process-local and unscoped by capability, so this is `None`
240    /// for [`WRITER_QUEUE_SATURATED_STAGE`].
241    pub capability: Option<khive_storage::StorageCapability>,
242    /// Storage operation name, when known.
243    pub operation: Option<String>,
244    /// Database identity supplied by the pool that refused admission, when known.
245    pub pool_identity: Option<String>,
246    /// ADR-131:251 `scope` discriminator. `Some(`[`WRITER_ADMISSION_SCOPE`]`)`
247    /// for [`WRITER_QUEUE_SATURATED_STAGE`]; `None` for
248    /// [`WRITER_POOL_CHECKOUT_TIMEOUT_STAGE`], which ADR-131 does not define a
249    /// scope for.
250    pub scope: Option<&'static str>,
251    /// ADR-131:251 `retry_after_ms` hint — set equal to the admission
252    /// deadline actually applied to the rejected operation, so a retrying
253    /// caller waits at least one full admission window before retrying.
254    /// `Some(timeout_ms)` for [`WRITER_QUEUE_SATURATED_STAGE`]; `None`
255    /// otherwise.
256    pub retry_after_ms: Option<u64>,
257}
258
259/// Structured context for a failure that is proven safe to retry.
260///
261/// This includes the two pre-admission failures above and writer-task BEGIN
262/// contention after queue acceptance but before operation execution. Callers
263/// must inspect `scope`: only `writer_admission` means the queue never
264/// accepted the operation.
265#[derive(Debug, Clone, PartialEq, Eq)]
266pub struct RetryableFailureContext {
267    /// Stable wire stage/code.
268    pub stage: &'static str,
269    /// Configured wait that ended before execution.
270    pub timeout: Duration,
271    /// Storage capability when the failure is capability-scoped.
272    pub capability: Option<khive_storage::StorageCapability>,
273    /// Storage operation when known.
274    pub operation: Option<String>,
275    /// Database identity supplied by the pool that refused admission, when known.
276    pub pool_identity: Option<String>,
277    /// Admission scope only when the queue never accepted the operation.
278    pub scope: Option<&'static str>,
279    /// Server backoff hint when a governing contract defines one.
280    pub retry_after_ms: Option<u64>,
281}
282
283/// Structured writer-request finality recovered from a storage error.
284///
285/// `request_state` answers whether effects are known absent or ambiguous;
286/// `task_terminated` separately answers whether the writer seam remains
287/// usable. `retryable` retains the source error's transient policy and must
288/// not be inferred from rollback finality alone.
289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
290pub struct WriterTaskFailureContext {
291    /// Stable MCP code/stage for the error family.
292    pub stage: &'static str,
293    /// What the writer can prove about this request's effects.
294    pub request_state: khive_storage::WriterTaskRequestState,
295    /// Whether the writer seam was permanently retired.
296    pub task_terminated: bool,
297    /// Whether the source failure is transient independently of finality.
298    pub retryable: bool,
299}
300
301impl From<AdmissionFailureContext> for RetryableFailureContext {
302    fn from(context: AdmissionFailureContext) -> Self {
303        Self {
304            stage: context.stage,
305            timeout: context.timeout,
306            capability: context.capability,
307            operation: context.operation,
308            pool_identity: context.pool_identity,
309            scope: context.scope,
310            retry_after_ms: context.retry_after_ms,
311        }
312    }
313}
314
315/// Typed disposition for a channel message whose `comm.ingest` write failed.
316///
317/// Every bucket carries the stable [`RuntimeError`] variant name that selected
318/// it. Consumers can therefore make retry/quarantine decisions and report a
319/// reason without inspecting the error's rendered text.
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub enum ChannelIngestFailureClass {
322    /// A pre-execution admission failure that is safe to retry indefinitely.
323    Retryable { reason: &'static str },
324    /// A deterministic policy refusal that should quarantine immediately.
325    Permanent { reason: &'static str },
326    /// An error with no explicit retry or permanent policy classification.
327    Unknown { reason: &'static str },
328}
329
330impl ChannelIngestFailureClass {
331    /// Stable lowercase bucket name persisted on quarantine notifications.
332    pub const fn name(self) -> &'static str {
333        match self {
334            Self::Retryable { .. } => "retryable",
335            Self::Permanent { .. } => "permanent",
336            Self::Unknown { .. } => "unknown",
337        }
338    }
339
340    /// Stable typed error-variant name; never derived from `Display` output.
341    pub const fn reason(self) -> &'static str {
342        match self {
343            Self::Retryable { reason } | Self::Permanent { reason } | Self::Unknown { reason } => {
344                reason
345            }
346        }
347    }
348}
349
350/// Structured context recovered from either a direct SQLite runtime error or
351/// a typed SQLite source preserved inside a storage-driver wrapper.
352#[derive(Debug, Clone, PartialEq, Eq)]
353pub struct WriterPoolCheckoutTimeoutContext {
354    /// Finite checkout deadline that elapsed before the pooled mutex was
355    /// acquired.
356    pub timeout: Duration,
357    /// Storage capability that wrapped the SQLite source, if one did.
358    pub capability: Option<khive_storage::StorageCapability>,
359    /// Storage operation that wrapped the SQLite source, if one did.
360    pub operation: Option<String>,
361}
362
363/// A guarded edge write (`link`/`link_many`) was refused because one or both
364/// endpoints no longer existed at write time. Names the exact endpoint(s)
365/// missing instead of a generic "source or target" message, and, for a batch
366/// write, which entry in the batch failed first.
367#[derive(Debug, Clone, PartialEq, Eq)]
368pub struct GuardedWriteFailure {
369    /// Index of the failing entry within a `link_many` batch. `None` for the
370    /// singleton `link` path, which has no batch to index into.
371    pub entry_index: Option<usize>,
372    /// The source endpoint id, present only when it is the (or one of the)
373    /// missing endpoint(s).
374    pub missing_source: Option<Uuid>,
375    /// The target endpoint id, present only when it is the (or one of the)
376    /// missing endpoint(s).
377    pub missing_target: Option<Uuid>,
378}
379
380impl fmt::Display for GuardedWriteFailure {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        let mut missing = Vec::new();
383        if let Some(source) = self.missing_source {
384            missing.push(format!("source {source}"));
385        }
386        if let Some(target) = self.missing_target {
387            missing.push(format!("target {target}"));
388        }
389        let missing = if missing.is_empty() {
390            "endpoint(s)".to_string()
391        } else {
392            missing.join(" and ")
393        };
394        match self.entry_index {
395            Some(index) => write!(
396                f,
397                "batch entry {index}: {missing} no longer exist at write time"
398            ),
399            None => write!(f, "{missing} no longer exist at write time"),
400        }
401    }
402}
403
404impl std::error::Error for GuardedWriteFailure {}
405
406/// A single missing pack dependency.
407#[derive(Debug, Clone, PartialEq, Eq)]
408pub struct MissingPackDependency {
409    pub from: String,
410    pub requires: String,
411}
412
413impl fmt::Display for MissingPackDependency {
414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415        write!(
416            f,
417            "pack '{}' requires '{}', but '{}' is not in the loaded pack set",
418            self.from, self.requires, self.requires
419        )
420    }
421}
422
423impl std::error::Error for MissingPackDependency {}
424
425/// Multiple missing pack dependencies collected into one error.
426#[derive(Debug, Clone, PartialEq, Eq)]
427pub struct MissingPackDependencies {
428    pub missing: Vec<MissingPackDependency>,
429}
430
431impl fmt::Display for MissingPackDependencies {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        let parts: Vec<String> = self.missing.iter().map(ToString::to_string).collect();
434        write!(f, "{}", parts.join("; "))
435    }
436}
437
438impl std::error::Error for MissingPackDependencies {}
439
440/// Circular pack dependency detected during topological sort.
441#[derive(Debug, Clone, PartialEq, Eq)]
442pub struct CircularPackDependency {
443    pub cycle: Vec<String>,
444}
445
446impl fmt::Display for CircularPackDependency {
447    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448        write!(
449            f,
450            "circular dependency detected among packs: {}",
451            self.cycle.join(" -> ")
452        )
453    }
454}
455
456impl std::error::Error for CircularPackDependency {}
457
458/// All errors produced by the khive-runtime layer.
459///
460/// Where the `GateDenied` audit row of a refused dispatch ended up.
461///
462/// A refusal reaches the caller whatever happens to its audit row; this value
463/// says whether the row the caller could cite exists.
464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
465pub enum DenialAuditOutcome {
466    /// The row committed, or an identical row was already present, and
467    /// `audit_event_id` on the refusal names it.
468    Committed,
469    /// The row was built and submitted but did not commit; the audit
470    /// obligation wire code says why.
471    NotCommitted(&'static str),
472    /// No event store is configured, so no row was written.
473    NoStore,
474    /// The refusal comes from a path that writes no audit row (namespace
475    /// authorization, channel policy).
476    NotAudited,
477}
478
479impl DenialAuditOutcome {
480    /// Closed wire spelling: `committed`, `not_committed:<code>`, `no_store`,
481    /// `not_audited`.
482    pub fn wire_code(&self) -> String {
483        match self {
484            Self::Committed => "committed".to_string(),
485            Self::NotCommitted(code) => format!("not_committed:{code}"),
486            Self::NoStore => "no_store".to_string(),
487            Self::NotAudited => "not_audited".to_string(),
488        }
489    }
490}
491
492/// What a refused dispatch can cite: the `GateDenied` audit row's id when
493/// one committed, and where the row ended up otherwise. Boxed on the error
494/// so a refusal does not widen every `Result<_, RuntimeError>` in the tree.
495#[derive(Debug, Clone, PartialEq, Eq)]
496pub struct DenialReceipt {
497    /// The audit row's event id when `audit_outcome` is `Committed`.
498    pub audit_event_id: Option<uuid::Uuid>,
499    /// Whether the row the caller could cite exists.
500    pub audit_outcome: DenialAuditOutcome,
501}
502
503impl DenialReceipt {
504    /// The refusal's path writes no audit row.
505    pub fn not_audited() -> Self {
506        Self {
507            audit_event_id: None,
508            audit_outcome: DenialAuditOutcome::NotAudited,
509        }
510    }
511
512    /// No event store is configured, so no row was written.
513    pub fn no_store() -> Self {
514        Self {
515            audit_event_id: None,
516            audit_outcome: DenialAuditOutcome::NoStore,
517        }
518    }
519}
520
521/// Payload of [`RuntimeError::RefusedWithReceipt`].
522#[derive(Debug, Clone)]
523pub struct ReceiptRefusal {
524    /// Wire `code`, naming which refusal surface produced this.
525    pub code: &'static str,
526    /// The refusal's own sentence, unchanged.
527    pub message: String,
528    /// Id of the durable row the refusal wrote.
529    pub receipt_id: String,
530    /// Why the call was refused, as the receipt records it.
531    pub reason: String,
532    /// Surface-specific structured evidence, an object or `Value::Null`.
533    pub detail: serde_json::Value,
534}
535
536/// Bounded failure evidence; never carries rejected input or a storage error string.
537#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
538#[serde(rename_all = "snake_case")]
539pub enum RefusalRecordingErrorClass {
540    EventStoreUnavailable,
541    EventAppendFailed,
542}
543
544impl RefusalRecordingErrorClass {
545    pub const fn as_str(self) -> &'static str {
546        match self {
547            Self::EventStoreUnavailable => "event_store_unavailable",
548            Self::EventAppendFailed => "event_append_failed",
549        }
550    }
551}
552
553/// Event evidence for one eligible existing target in a refused request.
554/// `Failed` means no confirmed event, not proof that an ambiguous append wrote nothing.
555#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
556#[serde(untagged)]
557pub enum RefusalEventRecording {
558    Recorded {
559        item_index: usize,
560        subject: Uuid,
561        event_id: Uuid,
562    },
563    Failed {
564        item_index: usize,
565        subject: Uuid,
566        error_class: RefusalRecordingErrorClass,
567    },
568}
569
570/// Value-free admission evidence for one original input position.
571#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
572pub struct BatchRefusal {
573    pub index: usize,
574    pub field: &'static str,
575    pub reason: &'static str,
576}
577
578/// Complete or explicitly interrupted record-list admission.
579#[derive(Debug)]
580pub struct BatchAdmissionReport {
581    pub refused: Vec<BatchRefusal>,
582    pub validation_complete: bool,
583    pub unchecked_indices: Vec<usize>,
584}
585
586/// Operation-local proof, independent of any separately recorded refusal events.
587#[derive(Debug)]
588pub struct BatchWriteContext {
589    pub source: Box<RuntimeError>,
590    pub disposition: DomainDisposition,
591    pub admission: Option<BatchAdmissionReport>,
592}
593
594impl fmt::Display for BatchWriteContext {
595    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
596        fmt::Display::fmt(self.source.as_ref(), formatter)
597    }
598}
599
600impl std::error::Error for BatchWriteContext {
601    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
602        Some(self.source.as_ref())
603    }
604}
605
606/// Original refusal and the independent evidence of recording it.
607///
608/// The runtime variant transparently forwards this context's error source, which
609/// deliberately exposes the contained `RuntimeError`, not its `Box` or its own
610/// underlying source. This keeps typed consumers at the original refusal first.
611#[derive(Debug)]
612pub struct RefusalEventContext {
613    pub source: Box<RuntimeError>,
614    pub recordings: Vec<RefusalEventRecording>,
615}
616
617impl std::fmt::Display for RefusalEventContext {
618    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
619        std::fmt::Display::fmt(self.source.as_ref(), formatter)
620    }
621}
622
623impl std::error::Error for RefusalEventContext {
624    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
625        Some(self.source.as_ref())
626    }
627}
628
629/// Repo-anchor facts established before a `git.digest` ingest failed.
630#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
631pub struct ResolutionFacts {
632    pub project_id: Uuid,
633    pub duplicate_anchor_ids: Vec<Uuid>,
634    pub slug_backfilled: bool,
635    pub project_created: bool,
636    pub orphaned_project_id: Option<Uuid>,
637    pub orphaned_note_count: u64,
638}
639
640/// Preserve a resolved anchor's facts while exposing the original typed error.
641#[derive(Debug)]
642pub struct ResolutionFailureContext {
643    pub source: Box<RuntimeError>,
644    pub resolution: ResolutionFacts,
645}
646
647impl std::fmt::Display for ResolutionFailureContext {
648    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
649        std::fmt::Display::fmt(self.source.as_ref(), formatter)
650    }
651}
652
653impl std::error::Error for ResolutionFailureContext {
654    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
655        Some(self.source.as_ref())
656    }
657}
658
659/// The substrate whose required search metadata could not be read.
660#[derive(Debug, Clone, Copy, PartialEq, Eq)]
661pub enum SearchReadSubstrate {
662    Entity,
663    Note,
664}
665
666impl SearchReadSubstrate {
667    pub const fn as_str(self) -> &'static str {
668        match self {
669            Self::Entity => "entity",
670            Self::Note => "note",
671        }
672    }
673}
674
675/// Search context with an intact typed cause that is never rendered publicly.
676#[derive(Debug)]
677pub struct SearchReadContext {
678    backend: crate::BackendId,
679    substrate: SearchReadSubstrate,
680    source: Box<RuntimeError>,
681}
682
683impl SearchReadContext {
684    pub fn backend(&self) -> &crate::BackendId {
685        &self.backend
686    }
687
688    pub fn substrate(&self) -> SearchReadSubstrate {
689        self.substrate
690    }
691
692    pub fn source(&self) -> &RuntimeError {
693        &self.source
694    }
695
696    pub(crate) fn into_source(self) -> RuntimeError {
697        *self.source
698    }
699}
700
701impl fmt::Display for SearchReadContext {
702    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
703        write!(
704            formatter,
705            "search metadata read failed on backend {} ({})",
706            self.backend,
707            self.substrate.as_str()
708        )
709    }
710}
711
712impl std::error::Error for SearchReadContext {
713    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
714        Some(self.source.as_ref())
715    }
716}
717
718/// Variants cover storage, query, validation, namespace isolation, and permission failures.
719/// Callers should match on `InvalidInput` for bad arguments, `NotFound` for missing records,
720/// and `NamespaceMismatch` (reported as not-found) for cross-namespace access attempts.
721#[derive(Debug, Error)]
722pub enum RuntimeError {
723    /// A required search read failed; public context excludes source contents.
724    #[error(transparent)]
725    SearchRead { context: SearchReadContext },
726    /// A decoded canonical operation has no live apply implementation.
727    #[error(
728        "canonical operation {op_index}: {operation} is KnownUnimplemented for canonical apply"
729    )]
730    CanonicalUnsupportedOperation {
731        op_index: usize,
732        operation: &'static str,
733    },
734    /// A constituent was refused before canonical writer admission. Retain
735    /// its typed source without rendering submitted or captured contents.
736    #[error("canonical operation {op_index} refused")]
737    CanonicalAdmission {
738        op_index: usize,
739        #[source]
740        source: Box<RuntimeError>,
741    },
742    /// A lint fix stopped, retaining its exact typed cause and confirmed receipts.
743    #[error("{source}")]
744    LintFix {
745        #[source]
746        source: Box<RuntimeError>,
747        detail: Box<crate::graph_lint::LintFixFailureDetail>,
748    },
749
750    /// The domain handler succeeded, but its post-dispatch obligation did not.
751    #[error("{failure}")]
752    AuditObligation {
753        /// Typed reason and source of the obligation failure.
754        #[source]
755        failure: Box<AuditObligationFailure>,
756        /// Exact canonical value held after the domain handler succeeded.
757        domain_result: serde_json::Value,
758    },
759
760    #[error("storage: {0}")]
761    Storage(#[source] khive_storage::StorageError),
762
763    #[error("query: {0}")]
764    Query(#[from] khive_query::QueryError),
765
766    #[error("not found: {0}")]
767    NotFound(String),
768
769    #[error("invalid input: {0}")]
770    InvalidInput(String),
771
772    #[error("invalid input: {0}")]
773    UnknownVerb(String),
774
775    #[error("unconfigured: {0} is not set")]
776    Unconfigured(String),
777
778    #[error("unknown embedding model: {0}")]
779    UnknownModel(String),
780
781    #[error("embedding: {0}")]
782    Embedding(#[from] lattice_embed::EmbedError),
783
784    #[error("ambiguous: {0}")]
785    Ambiguous(String),
786
787    #[error("fusion: {0}")]
788    Fusion(#[from] khive_fusion::FuseError),
789
790    /// `FusionStrategy::Custom { name, .. }` named a strategy no pack has
791    /// registered via `KhiveRuntime::register_fusion_strategy` (ADR-012).
792    /// Fails closed — never falls back to RRF or any other default.
793    #[error("unknown fusion strategy: {0}")]
794    UnknownFusionStrategy(String),
795
796    #[error("internal: {0}")]
797    Internal(String),
798
799    /// An `EventStore` was configured via `with_event_store` but does not
800    /// implement ADR-133's `preflight_event`/`append_events_idempotent`
801    /// pair (`EventStore::supports_idempotent_audit_batch` reports
802    /// `false`). Raised at `build()` time rather than left to fail every
803    /// audited dispatch silently.
804    #[error("audit batch incompatible event store: {0}")]
805    IncompatibleEventStore(String),
806
807    #[error("guarded edge write refused: {0}")]
808    GuardedWriteFailed(GuardedWriteFailure),
809
810    #[error("missing pack dependency: {0}")]
811    MissingPackDependency(MissingPackDependency),
812
813    #[error("missing pack dependencies: {0}")]
814    MissingPackDependencies(MissingPackDependencies),
815
816    #[error("{0}")]
817    CircularPackDependency(CircularPackDependency),
818
819    #[error("pack '{name}' registered twice (indices {first_idx} and {second_idx})")]
820    PackRedeclared {
821        name: String,
822        first_idx: usize,
823        second_idx: usize,
824    },
825
826    /// Two packs declared the same `Visibility::Verb` handler name.
827    /// `Visibility::Subhandler` entries are pack-prefixed and do not
828    /// participate in cross-pack collision checks.
829    #[error(
830        "verb collision: verb {verb:?} declared by both pack {first_pack:?} and pack \
831         {second_pack:?}; rename one handler or use Visibility::Subhandler for internal verbs"
832    )]
833    VerbCollision {
834        verb: String,
835        first_pack: String,
836        second_pack: String,
837    },
838
839    /// A handler advertised a parameter that request parsing owns at the envelope level.
840    #[error(
841        "pack {pack:?} handler {verb:?} declares request-envelope parameter {param:?}; rename the verb argument"
842    )]
843    ReservedEnvelopeParam {
844        pack: String,
845        verb: String,
846        param: String,
847    },
848
849    /// A handler refused the call and wrote a durable receipt naming the refusal.
850    ///
851    /// The durable id rides as its own field. Without it a consumer has to find
852    /// the id inside the refusal sentence with a regular expression, which makes
853    /// the wording of a message part of the contract and breaks silently the
854    /// first time someone rewords it. `message` keeps whatever text the refusal
855    /// already produced, so a reader that does parse it today keeps working.
856    ///
857    /// `reason` is the refusal's own explanation, the same value the receipt
858    /// stores, so a consumer keeping its own command record does not parse the
859    /// sentence for it either. `detail` carries the surface's other structured
860    /// evidence (for exec, the resolved output cap); it must be a JSON object or
861    /// null, and its members are projected beside the fields above without
862    /// overriding them.
863    ///
864    /// Boxed so the refusal's evidence does not widen every `Result` in the
865    /// runtime: the error enum is copied on each `?`, the refusal is rare.
866    #[error("{}", .0.message)]
867    RefusedWithReceipt(Box<ReceiptRefusal>),
868
869    /// Original typed refusal, with recording evidence independent of the refused write.
870    /// Construct through [`Self::with_refusal_events`] so no eligible targets means
871    /// an unchanged, unadorned refusal.
872    #[error(transparent)]
873    RefusedWithEvents { context: RefusalEventContext },
874
875    /// A batch boundary's typed admission or atomic-write settlement evidence.
876    #[error(transparent)]
877    BatchWrite { context: Box<BatchWriteContext> },
878
879    /// Preserve the original typed failure while carrying facts established
880    /// before a `git.digest` ingest failed.
881    #[error(transparent)]
882    WithResolution { context: ResolutionFailureContext },
883
884    /// Gate denied this verb invocation.
885    ///
886    /// Returned by `VerbRegistry::dispatch` when the configured `Gate` returns
887    /// `GateDecision::Deny`. The pack is never invoked. The `reason` field
888    /// carries the deny message produced by the gate implementation.
889    ///
890    /// `receipt` carries the id of the `GateDenied` audit row when one
891    /// committed, so the caller can cite the refusal, and says whether such
892    /// a row exists.
893    #[error("permission denied for verb {verb:?}: {reason}")]
894    PermissionDenied {
895        verb: String,
896        reason: String,
897        receipt: Box<DenialReceipt>,
898    },
899
900    /// The configured gate could not produce an authorization decision.
901    ///
902    /// This is distinct from [`Self::PermissionDenied`]: the pack or
903    /// intercepted operation is never invoked, but the gate did not answer
904    /// with an explicit denial.
905    #[error("gate unavailable for verb {verb:?}: {reason}")]
906    GateUnavailable { verb: String, reason: String },
907
908    /// A structured [`khive_types::KhiveError`] converted into the runtime
909    /// layer. The full structured error is preserved so callers can inspect
910    /// `kind`, `code`, `details`, and `retry_hint` without information loss.
911    #[error("{0}")]
912    Khive(khive_types::KhiveError),
913
914    /// Record exists but belongs to a different namespace than the provided token.
915    ///
916    /// Externally reported as "not found in this namespace" to avoid leaking
917    /// cross-namespace existence information (timing-oracle mitigation).
918    #[error("not found in this namespace")]
919    NamespaceMismatch { id: uuid::Uuid },
920
921    /// A short-prefix lookup matched more than one record.
922    ///
923    /// `prefix` is the 8+ hex-char prefix supplied by the caller.
924    /// `matches` holds the full UUIDs of all matching records (at most 2 are
925    /// reported to bound the scan — callers must supply the full UUID to disambiguate).
926    #[error("ambiguous prefix {prefix:?}: matches {}", format_uuid_list(matches))]
927    AmbiguousPrefix {
928        prefix: String,
929        matches: Vec<uuid::Uuid>,
930    },
931
932    /// Cross-backend `merge_entity` is unsupported in v1.
933    ///
934    /// Both entities must reside on the same backend. To merge entities on different
935    /// backends, manually export `from_id`, delete it, and re-import on `into_id`'s backend.
936    #[error(
937        "cross-backend merge is not supported: \
938         into_id {into_id} is on backend '{into_backend}', \
939         from_id {from_id} is on backend '{from_backend}'. \
940         Both entities must be on the same backend to merge."
941    )]
942    CrossBackendMergeUnsupported {
943        into_id: uuid::Uuid,
944        from_id: uuid::Uuid,
945        into_backend: String,
946        from_backend: String,
947    },
948
949    // ── Remote Resolution and Content-Hash Verification ──────────────────────
950    /// A `kg://` ref names a remote not declared in `schema.yaml`.
951    #[error("unknown remote: {name:?}")]
952    UnknownRemote { name: String },
953
954    /// A remote cache entry is absent and `--fetch` was not requested.
955    #[error("remote cache missing for remote={remote:?} namespace={namespace:?}")]
956    RemoteCacheMissing { remote: String, namespace: String },
957
958    /// A short ID matches multiple entities in the same namespace or remote cache.
959    #[error("ambiguous id {id:?}: matched {count} records")]
960    AmbiguousId { id: String, count: usize },
961
962    /// A write operation targeted a remote namespace, which is read-only.
963    #[error("cross-namespace write denied: cannot write to remote namespace {namespace:?}")]
964    CrossNamespaceWrite { namespace: String },
965
966    /// Remote cache setup or repair failed. Producers redact the source and
967    /// sanitize diagnostics before constructing this wire-visible error.
968    #[error("remote fetch error for remote={remote:?}: {message}")]
969    RemoteFetchError { remote: String, message: String },
970
971    /// A caller-supplied write budget was exceeded during a Compound apply.
972    ///
973    /// `max_new_entries` is the limit passed by the caller. `attempted_new_entries`
974    /// is `consumed + 1`, i.e. the create that would have exceeded the cap.
975    /// `None` budget never produces this error (unlimited path).
976    #[error(
977        "write budget exceeded: max_new_entries={max_new_entries}, \
978         attempted_new_entries={attempted_new_entries}"
979    )]
980    WriteBudgetExceeded {
981        max_new_entries: u64,
982        attempted_new_entries: u64,
983    },
984
985    /// Write blocked: content matches a secret pattern.
986    ///
987    /// The `SecretMatch` carries the detector name and a masked excerpt
988    /// (`first6...Nchars`). The full candidate is never stored in the error.
989    /// Store a pointer (env-var name, keychain item) rather than the raw value.
990    #[error("write blocked: {0}")]
991    SecretDetected(crate::secret_gate::SecretMatch),
992
993    /// A bounded per-operation deadline elapsed before the operation
994    /// completed (#889). The operation may still be running in the
995    /// background (this is a client-observable timeout, not a cancellation
996    /// signal to the underlying work) — callers should treat this as "no
997    /// answer within budget", not "the operation failed or was rolled back".
998    ///
999    /// Distinct from `#836`'s narrower `ann_ready_timeout_ms`, which bounds
1000    /// only a single cold-miss ANN-build wait inside the recall vector leg
1001    /// and degrades to an in-band FTS-only result. This variant bounds the
1002    /// *entire* operation end-to-end and is surfaced as a typed error so a
1003    /// caller under sustained contention gets a fast, clear answer instead
1004    /// of hanging until an upstream client-side ceiling (observed at 300s in
1005    /// production, #889) fires instead.
1006    #[error("{operation} exceeded its {budget_ms}ms deadline (elapsed {elapsed_ms}ms)")]
1007    DeadlineExceeded {
1008        operation: String,
1009        budget_ms: u64,
1010        elapsed_ms: u64,
1011    },
1012
1013    /// The database schema is below the V21 attachment cutover, so a runtime
1014    /// cannot be constructed over it yet.
1015    ///
1016    /// Bring the database forward with
1017    /// [`coordinate_attachment_cutover`](crate::coordinate_attachment_cutover)
1018    /// (or
1019    /// [`coordinate_empty_secondary_attachment_cutover`](crate::coordinate_empty_secondary_attachment_cutover)
1020    /// for a secondary store) and construct the runtime afterwards. The cutover
1021    /// state can be read beforehand, without migrating past V21, through
1022    /// `StorageBackend::attachment_cutover_status`.
1023    #[error(
1024        "database is at schema V{schema_version} and requires the V{required_version} attachment \
1025         cutover; run khive_runtime::coordinate_attachment_cutover before constructing \
1026         KhiveRuntime"
1027    )]
1028    AttachmentCutoverRequired {
1029        /// Schema version the database reports.
1030        schema_version: u32,
1031        /// First schema version that includes the attachment cutover.
1032        required_version: u32,
1033    },
1034}
1035
1036impl From<khive_storage::StorageError> for RuntimeError {
1037    fn from(error: khive_storage::StorageError) -> Self {
1038        match error {
1039            khive_storage::StorageError::SecretDetected { matched, .. } => {
1040                Self::SecretDetected(*matched)
1041            }
1042            other => Self::Storage(other),
1043        }
1044    }
1045}
1046
1047#[cfg(test)]
1048mod secret_storage_conversion_tests {
1049    use super::RuntimeError;
1050    use khive_storage::{StorageCapability, StorageError};
1051    use std::error::Error;
1052
1053    #[test]
1054    fn storage_secret_conversion_preserves_safe_match_and_runtime_refusal() {
1055        let key = format!("ghp_{}", "A".repeat(40));
1056        let storage =
1057            khive_storage::note::validate_note_key_for_store(&key, "assign_note_key_if_unset")
1058                .expect_err("storage must refuse the incoming key");
1059        let display = storage.to_string();
1060        let runtime: RuntimeError = storage.into();
1061        let RuntimeError::SecretDetected(matched) = &runtime else {
1062            panic!("typed storage secret must become the existing runtime refusal: {runtime:?}");
1063        };
1064        assert_eq!(matched.detector, "github-token");
1065        assert_eq!(matched.trigger, None);
1066        assert_eq!(matched.masked, "ghp_AA...44chars");
1067        assert_eq!(matched.location.as_deref(), Some("note.key"));
1068        assert_eq!(runtime.to_string(), display);
1069        let direct = crate::secret_gate::check_at(&key, "note", "key").unwrap_err();
1070        let RuntimeError::SecretDetected(direct_match) = direct else {
1071            panic!("runtime scanner must retain its typed refusal");
1072        };
1073        assert_eq!(matched, &direct_match);
1074        assert!(!runtime.to_string().contains(&key));
1075        assert!(!format!("{runtime:?}").contains(&key));
1076        assert!(runtime.source().is_none());
1077    }
1078
1079    #[test]
1080    fn ordinary_storage_conversion_and_direct_wrapper_keep_the_typed_source() {
1081        for converted in [false, true] {
1082            let storage = StorageError::InvalidInput {
1083                capability: StorageCapability::Notes,
1084                operation: "source-chain-fixture".into(),
1085                message: "ordinary refusal".into(),
1086            };
1087            let expected = storage.to_string();
1088            let runtime = if converted {
1089                RuntimeError::from(storage)
1090            } else {
1091                RuntimeError::Storage(storage)
1092            };
1093            assert_eq!(runtime.to_string(), format!("storage: {expected}"));
1094            let source = runtime
1095                .source()
1096                .expect("ordinary storage wrapper must retain Error::source");
1097            assert!(
1098                matches!(source.downcast_ref::<StorageError>(),
1099                Some(StorageError::InvalidInput { capability: StorageCapability::Notes, operation, message })
1100                    if operation == "source-chain-fixture" && message == "ordinary refusal"),
1101                "the source must be the original typed StorageError"
1102            );
1103        }
1104    }
1105}
1106
1107// Compatibility bridge for concrete backend callers while ADR-071's raw-SQL
1108// and backend-handle migrations remain in progress. Classification belongs to
1109// the database boundary; the runtime exposes only the storage error envelope.
1110impl From<khive_db::SqliteError> for RuntimeError {
1111    fn from(error: khive_db::SqliteError) -> Self {
1112        Self::Storage(match error {
1113            khive_db::SqliteError::RequestReadStopped(error) => error,
1114            error => error.into_storage_error(khive_storage::StorageCapability::Sql, "runtime"),
1115        })
1116    }
1117}
1118
1119impl RuntimeError {
1120    /// Attach the owning backend and substrate without exposing the cause text.
1121    pub fn with_search_read_context(
1122        self,
1123        backend: crate::BackendId,
1124        substrate: SearchReadSubstrate,
1125    ) -> Self {
1126        Self::SearchRead {
1127            context: SearchReadContext {
1128                backend,
1129                substrate,
1130                source: Box::new(self),
1131            },
1132        }
1133    }
1134
1135    /// Certify that this operation refused before attempting requested data writes.
1136    pub fn before_requested_write(self) -> Self {
1137        Self::BatchWrite {
1138            context: Box::new(BatchWriteContext {
1139                source: Box::new(self),
1140                disposition: DomainDisposition::NotCommitted,
1141                admission: None,
1142            }),
1143        }
1144    }
1145
1146    /// Attach admission evidence established before any requested data write.
1147    pub fn with_batch_admission(self, admission: BatchAdmissionReport) -> Self {
1148        Self::BatchWrite {
1149            context: Box::new(BatchWriteContext {
1150                source: Box::new(self),
1151                disposition: DomainDisposition::NotCommitted,
1152                admission: Some(admission),
1153            }),
1154        }
1155    }
1156
1157    /// Preserve a single atomic write's actual typed settlement, never its rendered text.
1158    pub fn atomic_write_failure(error: khive_storage::StorageError) -> Self {
1159        use khive_storage::{StorageError, WriterTaskRequestState};
1160        let disposition = match error.writer_request_state() {
1161            Some(request_state) => match request_state {
1162                WriterTaskRequestState::NotStarted
1163                | WriterTaskRequestState::TransactionRolledBack => DomainDisposition::NotCommitted,
1164                WriterTaskRequestState::SideEffectsUnknown => DomainDisposition::Unknown,
1165            },
1166            None => match error.without_sqlite_write_stage() {
1167                StorageError::WriterTaskBusy { .. }
1168                | StorageError::WriteQueueFull { .. }
1169                | StorageError::AdmissionTimeout { .. } => DomainDisposition::NotCommitted,
1170                _ => DomainDisposition::Unknown,
1171            },
1172        };
1173        Self::BatchWrite {
1174            context: Box::new(BatchWriteContext {
1175                source: Box::new(Self::Storage(error)),
1176                disposition,
1177                admission: None,
1178            }),
1179        }
1180    }
1181
1182    /// Read only this operation's proof, never a nested earlier action's finality.
1183    pub fn batch_write_disposition(&self) -> Option<DomainDisposition> {
1184        match self {
1185            Self::BatchWrite { context } => Some(context.disposition),
1186            Self::RefusedWithEvents { context } => context.source.batch_write_disposition(),
1187            Self::SearchRead { context } => context.source.batch_write_disposition(),
1188            _ => None,
1189        }
1190    }
1191
1192    /// Attach established repo-anchor facts without changing the source error.
1193    pub fn with_resolution(self, resolution: ResolutionFacts) -> Self {
1194        Self::WithResolution {
1195            context: ResolutionFailureContext {
1196                source: Box::new(self),
1197                resolution,
1198            },
1199        }
1200    }
1201
1202    /// Attach only evidence for established, eligible targets. Missing/new targets
1203    /// contribute no entry, and an empty batch leaves the error variant unchanged.
1204    pub fn with_refusal_events(self, mut recordings: Vec<RefusalEventRecording>) -> Self {
1205        if recordings.is_empty() {
1206            return self;
1207        }
1208        match self {
1209            Self::RefusedWithEvents { mut context } => {
1210                context.recordings.append(&mut recordings);
1211                Self::RefusedWithEvents { context }
1212            }
1213            source => Self::RefusedWithEvents {
1214                context: RefusalEventContext {
1215                    source: Box::new(source),
1216                    recordings,
1217                },
1218            },
1219        }
1220    }
1221
1222    /// Inspect the original typed error without losing its policy/retry
1223    /// classification through evidence wrappers.
1224    pub fn refusal_source(&self) -> &Self {
1225        let mut error = self;
1226        loop {
1227            error = match error {
1228                Self::RefusedWithEvents { context } => &context.source,
1229                Self::BatchWrite { context } => &context.source,
1230                Self::WithResolution { context } => context.source.as_ref(),
1231                Self::SearchRead { context } => context.source.as_ref(),
1232                Self::LintFix { source, .. } => source.as_ref(),
1233                Self::CanonicalAdmission { source, .. } => source.as_ref(),
1234                _ => return error,
1235            };
1236        }
1237    }
1238
1239    /// Whether the immutable stream record policy refused this write.
1240    ///
1241    /// Only the structured runtime marker establishes this class. Ordinary
1242    /// conflicts, caller sequence preconditions, and raw storage failures do
1243    /// not acquire a refusal classification from their rendered messages.
1244    /// These membership guards refuse before applying the requested domain write.
1245    pub fn is_stream_policy_refusal(&self) -> bool {
1246        matches!(self.refusal_source(), Self::Khive(error)
1247            if error.kind() == khive_types::ErrorKind::Conflict
1248                && error.details().and_then(|details| details.get("reason"))
1249                    == Some("stream_member"))
1250    }
1251
1252    /// A gate refusal from a path that writes no audit row.
1253    pub fn permission_denied(verb: impl Into<String>, reason: impl Into<String>) -> Self {
1254        Self::PermissionDenied {
1255            verb: verb.into(),
1256            reason: reason.into(),
1257            receipt: Box::new(DenialReceipt::not_audited()),
1258        }
1259    }
1260
1261    /// An [`Internal`](Self::Internal) error whose message is `context: source`.
1262    ///
1263    /// Storage and SQL failures that have no typed variant of their own use
1264    /// this shape, so the rendered text is defined here once.
1265    pub fn internal_with_context(context: impl fmt::Display, source: impl fmt::Display) -> Self {
1266        Self::Internal(format!("{context}: {source}"))
1267    }
1268
1269    /// Classify a failed inbound channel write without inspecting rendered
1270    /// error text.
1271    ///
1272    /// Existing typed safe-retry failures remain retryable. Secret detection is
1273    /// the first deterministic policy refusal and is permanent. `None` from
1274    /// [`Self::retryable_failure_context`] is deliberately not interpreted as
1275    /// permanent: every other variant starts in the bounded `Unknown` bucket.
1276    pub fn channel_ingest_failure_class(&self) -> ChannelIngestFailureClass {
1277        let source = self.refusal_source();
1278        let reason = source.variant_name();
1279        if source.retryable_failure_context().is_some() {
1280            ChannelIngestFailureClass::Retryable { reason }
1281        } else if matches!(source, Self::SecretDetected(_)) {
1282            ChannelIngestFailureClass::Permanent { reason }
1283        } else {
1284            ChannelIngestFailureClass::Unknown { reason }
1285        }
1286    }
1287
1288    /// Stable top-level variant name used by typed policy classifiers.
1289    fn variant_name(&self) -> &'static str {
1290        match self {
1291            Self::AuditObligation { .. } => "AuditObligation",
1292            Self::Storage(_) => "Storage",
1293            Self::Query(_) => "Query",
1294            Self::NotFound(_) => "NotFound",
1295            Self::InvalidInput(_) => "InvalidInput",
1296            Self::UnknownVerb(_) => "UnknownVerb",
1297            Self::Unconfigured(_) => "Unconfigured",
1298            Self::UnknownModel(_) => "UnknownModel",
1299            Self::Embedding(_) => "Embedding",
1300            Self::Ambiguous(_) => "Ambiguous",
1301            Self::Fusion(_) => "Fusion",
1302            Self::UnknownFusionStrategy(_) => "UnknownFusionStrategy",
1303            Self::Internal(_) => "Internal",
1304            Self::GuardedWriteFailed(_) => "GuardedWriteFailed",
1305            Self::MissingPackDependency(_) => "MissingPackDependency",
1306            Self::MissingPackDependencies(_) => "MissingPackDependencies",
1307            Self::CircularPackDependency(_) => "CircularPackDependency",
1308            Self::PackRedeclared { .. } => "PackRedeclared",
1309            Self::VerbCollision { .. } => "VerbCollision",
1310            Self::ReservedEnvelopeParam { .. } => "ReservedEnvelopeParam",
1311            Self::PermissionDenied { .. } => "PermissionDenied",
1312            Self::GateUnavailable { .. } => "GateUnavailable",
1313            Self::Khive(_) => "Khive",
1314            Self::NamespaceMismatch { .. } => "NamespaceMismatch",
1315            Self::AmbiguousPrefix { .. } => "AmbiguousPrefix",
1316            Self::CrossBackendMergeUnsupported { .. } => "CrossBackendMergeUnsupported",
1317            Self::UnknownRemote { .. } => "UnknownRemote",
1318            Self::RemoteCacheMissing { .. } => "RemoteCacheMissing",
1319            Self::AmbiguousId { .. } => "AmbiguousId",
1320            Self::CrossNamespaceWrite { .. } => "CrossNamespaceWrite",
1321            Self::RemoteFetchError { .. } => "RemoteFetchError",
1322            Self::WriteBudgetExceeded { .. } => "WriteBudgetExceeded",
1323            Self::SecretDetected(_) => "SecretDetected",
1324            Self::DeadlineExceeded { .. } => "DeadlineExceeded",
1325            Self::AttachmentCutoverRequired { .. } => "AttachmentCutoverRequired",
1326            Self::IncompatibleEventStore(_) => "IncompatibleEventStore",
1327            Self::RefusedWithReceipt { .. } => "RefusedWithReceipt",
1328            Self::RefusedWithEvents { context } => context.source.variant_name(),
1329            Self::BatchWrite { context } => context.source.variant_name(),
1330            Self::WithResolution { context } => context.source.variant_name(),
1331            Self::SearchRead { context } => context.source.variant_name(),
1332            Self::LintFix { source, .. } => source.variant_name(),
1333            Self::CanonicalAdmission { source, .. } => source.variant_name(),
1334            Self::CanonicalUnsupportedOperation { .. } => "CanonicalUnsupportedOperation",
1335        }
1336    }
1337
1338    /// Recover a finite-wait pool-checkout timeout without inspecting rendered
1339    /// error text.
1340    ///
1341    /// Store implementations retain [`khive_db::SqliteError`] as the typed
1342    /// source of `StorageError::Driver`; this method carries that structure
1343    /// through the runtime wrapper for the MCP wire serializer.
1344    pub fn writer_pool_checkout_timeout_context(&self) -> Option<WriterPoolCheckoutTimeoutContext> {
1345        let (sqlite_error, capability, operation) = match self.refusal_source() {
1346            Self::Storage(khive_storage::StorageError::Driver {
1347                capability,
1348                operation,
1349                source,
1350            }) => (
1351                source.downcast_ref::<khive_db::SqliteError>()?,
1352                Some(*capability),
1353                Some(operation.to_string()),
1354            ),
1355            _ => return None,
1356        };
1357
1358        let khive_db::SqliteError::WriterPoolCheckoutTimeout { timeout } = sqlite_error else {
1359            return None;
1360        };
1361        Some(WriterPoolCheckoutTimeoutContext {
1362            timeout: *timeout,
1363            capability,
1364            operation,
1365        })
1366    }
1367
1368    /// Recover either pre-execution write-admission failure this process can
1369    /// produce, by typed variant rather than rendered message text (#1643).
1370    /// Both are safe to classify as retryable: the request was never
1371    /// accepted, so no partial side effect can exist to roll back.
1372    pub fn admission_failure_context(&self) -> Option<AdmissionFailureContext> {
1373        let source = self.refusal_source();
1374        if let Some(context) = self.writer_pool_checkout_timeout_context() {
1375            return Some(AdmissionFailureContext {
1376                stage: WRITER_POOL_CHECKOUT_TIMEOUT_STAGE,
1377                timeout: context.timeout,
1378                capability: context.capability,
1379                operation: context.operation,
1380                pool_identity: None,
1381                scope: None,
1382                retry_after_ms: None,
1383            });
1384        }
1385        if let Self::Storage(khive_storage::StorageError::WriteQueueFull { timeout_ms }) = source {
1386            return Some(AdmissionFailureContext {
1387                stage: WRITER_QUEUE_SATURATED_STAGE,
1388                timeout: Duration::from_millis(*timeout_ms),
1389                capability: None,
1390                operation: None,
1391                pool_identity: None,
1392                scope: Some(WRITER_ADMISSION_SCOPE),
1393                retry_after_ms: Some(*timeout_ms),
1394            });
1395        }
1396        if let Self::Storage(khive_storage::StorageError::AdmissionTimeout {
1397            operation,
1398            timeout_ms,
1399            pool_identity,
1400        }) = source
1401        {
1402            return Some(AdmissionFailureContext {
1403                stage: STORAGE_ADMISSION_TIMEOUT_STAGE,
1404                timeout: Duration::from_millis(*timeout_ms),
1405                capability: None,
1406                operation: Some(operation.to_string()),
1407                pool_identity: pool_identity.clone(),
1408                scope: None,
1409                retry_after_ms: None,
1410            });
1411        }
1412        None
1413    }
1414
1415    /// Recover writer-request finality without parsing the rendered storage
1416    /// error. Ordinary proven rollbacks and terminal writer failures are
1417    /// deliberately distinct even when they carry the same request state.
1418    pub fn writer_task_failure_context(&self) -> Option<WriterTaskFailureContext> {
1419        let Self::Storage(error) = self.refusal_source() else {
1420            return None;
1421        };
1422        match error.without_sqlite_write_stage() {
1423            khive_storage::StorageError::WriteOutcomeUnknown { .. } => {
1424                Some(WriterTaskFailureContext {
1425                    stage: WRITE_OUTCOME_UNKNOWN_STAGE,
1426                    request_state: khive_storage::WriterTaskRequestState::SideEffectsUnknown,
1427                    task_terminated: false,
1428                    retryable: false,
1429                })
1430            }
1431            khive_storage::StorageError::WriterOwnerUnavailable { source, .. } => {
1432                Some(WriterTaskFailureContext {
1433                    stage: WRITER_OWNER_UNAVAILABLE_STAGE,
1434                    request_state: khive_storage::WriterTaskRequestState::NotStarted,
1435                    task_terminated: false,
1436                    retryable: source.is_retryable(),
1437                })
1438            }
1439            khive_storage::StorageError::WriterRouteViolation { .. } => {
1440                Some(WriterTaskFailureContext {
1441                    stage: WRITER_ROUTE_VIOLATION_STAGE,
1442                    request_state: khive_storage::WriterTaskRequestState::NotStarted,
1443                    task_terminated: false,
1444                    retryable: false,
1445                })
1446            }
1447            khive_storage::StorageError::WriterTaskRequestFailed {
1448                request_state,
1449                source,
1450            } => Some(WriterTaskFailureContext {
1451                stage: WRITER_TASK_REQUEST_FAILED_STAGE,
1452                request_state: *request_state,
1453                task_terminated: false,
1454                retryable: source.is_retryable(),
1455            }),
1456            khive_storage::StorageError::WriterTaskTerminated { request_state, .. } => {
1457                Some(WriterTaskFailureContext {
1458                    stage: WRITER_TASK_TERMINATED_STAGE,
1459                    request_state: *request_state,
1460                    task_terminated: true,
1461                    retryable: false,
1462                })
1463            }
1464            _ => None,
1465        }
1466    }
1467
1468    /// Recover every typed failure for which this process can prove that
1469    /// retrying the one failed operation cannot duplicate a side effect.
1470    pub fn retryable_failure_context(&self) -> Option<RetryableFailureContext> {
1471        let mut enclosing = self;
1472        loop {
1473            match enclosing {
1474                Self::LintFix { .. } => return None,
1475                Self::RefusedWithEvents { context } => enclosing = &context.source,
1476                Self::BatchWrite { context } => enclosing = &context.source,
1477                Self::WithResolution { context } => enclosing = &context.source,
1478                Self::SearchRead { context } => enclosing = &context.source,
1479                _ => break,
1480            }
1481        }
1482
1483        let source = self.refusal_source();
1484        if let Some(context) = self.admission_failure_context() {
1485            return Some(context.into());
1486        }
1487        if let Self::Storage(error) = source {
1488            if let khive_storage::StorageError::WriterOwnerUnavailable { operation, source } =
1489                error.without_sqlite_write_stage()
1490            {
1491                if source.is_retryable() {
1492                    return Some(RetryableFailureContext {
1493                        stage: WRITER_OWNER_UNAVAILABLE_STAGE,
1494                        timeout: Duration::ZERO,
1495                        capability: source.capability(),
1496                        operation: Some(operation.to_string()),
1497                        pool_identity: None,
1498                        scope: None,
1499                        retry_after_ms: None,
1500                    });
1501                }
1502            }
1503            if let khive_storage::StorageError::WriterTaskBusy { timeout_ms } =
1504                error.without_sqlite_write_stage()
1505            {
1506                return Some(RetryableFailureContext {
1507                    stage: WRITER_TASK_BEGIN_BUSY_STAGE,
1508                    timeout: Duration::from_millis(*timeout_ms),
1509                    capability: None,
1510                    operation: Some("writer_task_begin".to_string()),
1511                    pool_identity: None,
1512                    scope: None,
1513                    retry_after_ms: None,
1514                });
1515            }
1516        }
1517        if let Self::Storage(khive_storage::StorageError::ReadTransactionAgeEvicted {
1518            operation,
1519            max_age_secs,
1520        }) = source
1521        {
1522            return Some(RetryableFailureContext {
1523                stage: READ_TX_AGE_EVICTED_STAGE,
1524                timeout: Duration::from_secs(*max_age_secs),
1525                capability: Some(khive_storage::StorageCapability::Sql),
1526                operation: Some(operation.to_string()),
1527                pool_identity: None,
1528                scope: None,
1529                retry_after_ms: None,
1530            });
1531        }
1532        if let Self::Storage(
1533            khive_storage::StorageError::ReadTransactionAgeEvictionCleanupFailed {
1534                operation,
1535                max_age_secs,
1536                ..
1537            },
1538        ) = source
1539        {
1540            return Some(RetryableFailureContext {
1541                stage: READ_TX_AGE_EVICTED_STAGE,
1542                timeout: Duration::from_secs(*max_age_secs),
1543                capability: Some(khive_storage::StorageCapability::Sql),
1544                operation: Some(operation.to_string()),
1545                pool_identity: None,
1546                scope: None,
1547                retry_after_ms: None,
1548            });
1549        }
1550        None
1551    }
1552}
1553
1554/// Resolve an FTS text-leg search result, failing loud on parser syntax
1555/// errors instead of silently degrading to vector-only fusion.
1556///
1557/// A genuine backend outage (pool exhaustion, connection failure, etc.) is
1558/// NOT a bad query and is returned as-is via the fallthrough `Err(e)` arm;
1559/// `is_fts5_syntax_error` is the narrow gate that tells the two apart.
1560pub fn fts_text_leg_or_err<T>(
1561    result: Result<Vec<T>, RuntimeError>,
1562    context: &'static str,
1563    query: &str,
1564) -> RuntimeResult<Vec<T>> {
1565    match result {
1566        Ok(hits) => Ok(hits),
1567        Err(RuntimeError::Storage(se)) if se.is_fts5_syntax_error() => {
1568            tracing::warn!(
1569                error = %se,
1570                query = %query,
1571                context,
1572                "FTS text leg failed on a parser syntax error; failing loud (#569)"
1573            );
1574            Err(RuntimeError::InvalidInput(format!(
1575                "{context}: FTS query could not be parsed: {se}"
1576            )))
1577        }
1578        Err(e) => Err(e),
1579    }
1580}
1581
1582fn format_uuid_list(uuids: &[uuid::Uuid]) -> String {
1583    uuids
1584        .iter()
1585        .map(uuid::Uuid::to_string)
1586        .collect::<Vec<_>>()
1587        .join(", ")
1588}
1589
1590/// Maps the dependency-light `khive-types` entity-type resolution error onto
1591/// `RuntimeError::InvalidInput` at the pack boundary: `khive-types` cannot
1592/// depend on `khive-runtime`, so it cannot produce `RuntimeError` directly.
1593impl From<khive_types::EntityTypeError> for RuntimeError {
1594    fn from(e: khive_types::EntityTypeError) -> Self {
1595        Self::InvalidInput(e.to_string())
1596    }
1597}
1598
1599impl From<khive_types::KhiveError> for RuntimeError {
1600    fn from(e: khive_types::KhiveError) -> Self {
1601        Self::Khive(e)
1602    }
1603}
1604
1605#[cfg(test)]
1606#[path = "error_refusal_event_context_tests.rs"]
1607mod refusal_event_context_tests;
1608
1609#[cfg(test)]
1610#[path = "error_stream_policy_refusal_tests.rs"]
1611mod stream_policy_refusal_tests;
1612
1613#[cfg(test)]
1614#[path = "error_channel_ingest_failure_class_tests.rs"]
1615mod channel_ingest_failure_class_tests;
1616
1617#[cfg(test)]
1618mod batch_write_proof_tests {
1619    use super::*;
1620    use crate::runtime_error_value;
1621
1622    fn proof() -> RuntimeError {
1623        RuntimeError::InvalidInput("fixture-prewrite-refusal".into()).before_requested_write()
1624    }
1625
1626    fn project_failed(source: RuntimeError) -> (DomainDisposition, serde_json::Value) {
1627        let error = DispatchError::after_handler(source, false);
1628        let borrowed = error.disposition();
1629        let (source, disposition) = error.into_parts();
1630        assert_eq!(borrowed, disposition);
1631        let value = runtime_error_value(source, disposition);
1632        assert_eq!(value["domain_disposition"], disposition.as_str());
1633        (disposition, value)
1634    }
1635
1636    #[test]
1637    fn rejected_before_write_preserves_enclosing_disposition_and_error_class() {
1638        let message = "decoding refused";
1639        let (disposition, value) =
1640            project_failed(RuntimeError::InvalidInput(message.into()).before_requested_write());
1641        assert_eq!(disposition, DomainDisposition::NotCommitted);
1642        assert_eq!(value["kind"], "runtime_error");
1643        assert_eq!(value["message"], format!("invalid input: {message}"));
1644        assert_eq!(
1645            RuntimeError::InvalidInput(message.into())
1646                .before_requested_write()
1647                .audit_error_class(),
1648            crate::audit_error::AuditErrorClass::InvalidParams
1649        );
1650        let (ordinary, _) = project_failed(RuntimeError::InvalidInput(message.into()));
1651        assert_eq!(ordinary, DomainDisposition::Unknown);
1652
1653        let enclosing = RuntimeError::InvalidInput(message.into())
1654            .before_requested_write()
1655            .with_resolution(ResolutionFacts {
1656                project_id: Uuid::new_v4(),
1657                duplicate_anchor_ids: vec![],
1658                slug_backfilled: false,
1659                project_created: true,
1660                orphaned_project_id: None,
1661                orphaned_note_count: 0,
1662            });
1663        let (disposition, _) = project_failed(enclosing);
1664        assert_eq!(disposition, DomainDisposition::Unknown);
1665        let committed = DispatchError::after_handler(
1666            RuntimeError::InvalidInput(message.into()).before_requested_write(),
1667            true,
1668        );
1669        assert_eq!(committed.disposition(), DomainDisposition::Committed);
1670        let (source, disposition) = committed.into_parts();
1671        assert_eq!(
1672            runtime_error_value(source, disposition)["domain_disposition"],
1673            "committed"
1674        );
1675    }
1676
1677    #[test]
1678    fn batch_proof_reaches_dispatch_owned_parts_and_projection() {
1679        let (disposition, value) = project_failed(proof());
1680        assert_eq!(disposition, DomainDisposition::NotCommitted);
1681        assert!(value["message"]
1682            .as_str()
1683            .unwrap()
1684            .contains("fixture-prewrite-refusal"));
1685        for source in [
1686            RuntimeError::InvalidInput("ordinary".into()),
1687            RuntimeError::Storage(khive_storage::StorageError::Internal(
1688                "ordinary-storage".into(),
1689            )),
1690        ] {
1691            assert_eq!(project_failed(source).0, DomainDisposition::Unknown);
1692        }
1693    }
1694
1695    #[test]
1696    fn enclosing_success_and_unknown_contexts_protect_prior_effects() {
1697        let error = DispatchError::after_handler(proof(), true);
1698        assert_eq!(error.disposition(), DomainDisposition::Committed);
1699        let (source, disposition) = error.into_parts();
1700        assert_eq!(
1701            runtime_error_value(source, disposition)["domain_disposition"],
1702            "committed"
1703        );
1704        assert_eq!(
1705            runtime_error_value(proof(), DomainDisposition::Committed)["domain_disposition"],
1706            "committed"
1707        );
1708        let source = proof().with_resolution(ResolutionFacts {
1709            project_id: Uuid::nil(),
1710            duplicate_anchor_ids: vec![],
1711            slug_backfilled: false,
1712            project_created: true,
1713            orphaned_project_id: None,
1714            orphaned_note_count: 0,
1715        });
1716        assert_eq!(
1717            source.batch_write_disposition(),
1718            None,
1719            "enclosing earlier work blocks an inner no-write proof"
1720        );
1721        let (disposition, value) = project_failed(source);
1722        assert_eq!(disposition, DomainDisposition::Unknown);
1723        assert_eq!(value["details"]["resolution"]["project_created"], true);
1724    }
1725
1726    #[test]
1727    fn batch_evidence_preserves_original_source_and_writer_finality() {
1728        let source = RuntimeError::atomic_write_failure(
1729            khive_storage::StorageError::WriterTaskRequestFailed {
1730                request_state: khive_storage::WriterTaskRequestState::TransactionRolledBack,
1731                source: Box::new(khive_storage::StorageError::Internal(
1732                    "fixture-original-cause".into(),
1733                )),
1734            },
1735        )
1736        .with_refusal_events(vec![RefusalEventRecording::Recorded {
1737            item_index: 0,
1738            subject: Uuid::nil(),
1739            event_id: Uuid::nil(),
1740        }]);
1741        assert!(matches!(source.refusal_source(), RuntimeError::Storage(_)));
1742        assert_eq!(
1743            source.writer_task_failure_context().unwrap().request_state,
1744            khive_storage::WriterTaskRequestState::TransactionRolledBack
1745        );
1746        let mut cause: &(dyn std::error::Error + 'static) = &source;
1747        let mut retained = false;
1748        while let Some(next) = cause.source() {
1749            retained |= next.to_string().contains("fixture-original-cause");
1750            cause = next;
1751        }
1752        assert!(retained, "typed cause remains below the outer error");
1753        let (disposition, value) = project_failed(source);
1754        assert_eq!(disposition, DomainDisposition::NotCommitted);
1755        assert_eq!(value["request_state"], "transaction_rolled_back");
1756        assert_eq!(value["refusal_recorded"], true);
1757        let source = RuntimeError::atomic_write_failure(
1758            khive_storage::StorageError::writer_task_terminated(
1759                khive_storage::WriterTaskRequestState::SideEffectsUnknown,
1760            ),
1761        );
1762        assert_eq!(project_failed(source).0, DomainDisposition::Unknown);
1763    }
1764}