Skip to main content

khive_types/
event.rs

1//! Event substrate — append-only log produced by every verb execution.
2
3extern crate alloc;
4use alloc::string::String;
5use alloc::vec::Vec;
6use core::fmt;
7
8use crate::{Header, Id128, SubstrateKind};
9
10/// A system event. Append-only, never mutated or deleted.
11#[derive(Clone, Debug)]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13pub struct Event {
14    #[cfg_attr(feature = "serde", serde(flatten))]
15    pub header: Header,
16    /// The verb that produced the event.
17    pub verb: String,
18    /// Which substrate type was acted upon.
19    pub substrate: SubstrateKind,
20    /// Who performed the action. Profile- or system-produced events may omit it.
21    pub actor: Option<String>,
22    /// Typed event discriminant used by replay, projections, and workers.
23    pub kind: EventKind,
24    /// Typed payload surface for known event families; raw JSON is still allowed.
25    pub payload: EventPayload,
26    /// Payload schema version interpreted per `kind`.
27    pub payload_schema_version: u32,
28    /// Brain profile state version observed when the event was emitted.
29    pub profile_state_version: Option<u64>,
30    /// Logical aggregate threaded across related event ids.
31    pub aggregate: Option<AggregateRef>,
32}
33
34/// Outcome of a verb execution recorded in an event log entry.
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
38pub enum EventOutcome {
39    /// The verb executed successfully.
40    #[default]
41    Success,
42    /// The verb was denied by a policy check.
43    Denied,
44    /// The verb encountered a runtime error.
45    Error,
46}
47
48impl EventOutcome {
49    /// Return the canonical lowercase string for this outcome.
50    pub const fn name(self) -> &'static str {
51        match self {
52            Self::Success => "success",
53            Self::Denied => "denied",
54            Self::Error => "error",
55        }
56    }
57}
58
59impl fmt::Display for EventOutcome {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str(self.name())
62    }
63}
64
65/// Declared persistence destination for an event class.
66///
67/// This metadata does not route writes or provide an operator audit store.
68/// There is deliberately no default: every new event kind must choose its sink.
69#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
70#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
71#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
72pub enum EventSink {
73    /// The event store exposed through ordinary caller event queries.
74    CallerEventStore,
75    /// A separate operator audit destination, outside caller event queries.
76    OperatorAudit,
77}
78
79impl EventSink {
80    /// Return the canonical snake_case declaration name.
81    pub const fn name(self) -> &'static str {
82        match self {
83            Self::CallerEventStore => "caller_event_store",
84            Self::OperatorAudit => "operator_audit",
85        }
86    }
87}
88
89/// Discriminant for the 44 typed event variants produced by the verb dispatch path
90/// and by lifecycle telemetry producers (channel polling/backoff, config-lock,
91/// checkpoint outcome, background phase spans).
92#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
93#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
94#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
95pub enum EventKind {
96    /// Generic audit event with no structured payload.
97    Audit,
98    /// A `recall` verb was executed and results were returned.
99    RecallExecuted,
100    /// A rerank pass was applied to search candidates.
101    RerankExecuted,
102    /// A `search` verb was executed.
103    SearchExecuted,
104    /// A tool-use policy decision was computed by tool.check or exec.run.
105    ToolCheckDecided,
106    /// A registration correction changed its canonical grant-policy inputs.
107    /// Retention: `pinned_while_referenced`; the payload/target registry row
108    /// is the referent and its deletion is the terminal condition (ADR-180 A10).
109    ToolRegistrationChanged,
110    /// A new directed edge was created between two nodes.
111    LinkCreated,
112    /// A new entity was created.
113    EntityCreated,
114    /// An existing entity was patched.
115    EntityUpdated,
116    /// An entity was soft- or hard-deleted.
117    EntityDeleted,
118    /// Two entities were merged (deduplication).
119    EntityMerged,
120    /// Two notes were merged (deduplication).
121    NoteMerged,
122    /// A new note was created.
123    NoteCreated,
124    /// An existing note was patched.
125    NoteUpdated,
126    /// A note was soft- or hard-deleted.
127    NoteDeleted,
128    /// An edge's relation or weight was updated.
129    EdgeUpdated,
130    /// An edge was removed.
131    EdgeDeleted,
132    /// A GTD task moved between lifecycle states.
133    TaskTransitioned,
134    /// An explicit user feedback signal was recorded.
135    FeedbackExplicit,
136    /// Telemetry recording a serve without a judgment (ADR-104 Amendment 3).
137    FeedbackUnjudged,
138    /// The brain recommended a profile resolution update.
139    ProfileResolutionRecommended,
140    /// Two brain profiles were merged.
141    ProfileMerged,
142    /// The active embedding model was changed.
143    EmbeddingModelChanged,
144    /// An embedding migration batch completed successfully.
145    EmbeddingMigrationCompleted,
146    /// An embedding migration batch failed.
147    EmbeddingMigrationFailed,
148    /// Drift was detected between stored and live embeddings.
149    EmbeddingDriftDetected,
150    /// A lazily loaded embedder finished initialization.
151    EmbedderInitialized,
152    /// A proposal was submitted for review.
153    ProposalCreated,
154    /// A reviewer accepted, rejected, or commented on a proposal.
155    ProposalReviewed,
156    /// A proposal was applied to the graph.
157    ProposalApplied,
158    /// A proposal was withdrawn before it was applied.
159    ProposalWithdrawn,
160    /// A channel poll cycle started for one `(kind, slug)` credential.
161    ChannelPollStarted,
162    /// A channel poll cycle returned envelopes after a prior failure.
163    ChannelPollSucceeded,
164    /// A channel poll cycle failed.
165    ChannelPollFailed,
166    /// A channel's backoff escalated to a new step after a failure.
167    ChannelBackoffArmed,
168    /// A channel's backoff reset to base after a success.
169    ChannelBackoffReset,
170    /// Persisting a channel heartbeat row failed.
171    ChannelHeartbeatPersistFailed,
172    /// A process-lifetime `OnceLock` configuration value was locked in.
173    ConfigLocked,
174    /// A WAL checkpoint tick's outcome was recorded (ADR-091 elevated/drain edge).
175    CheckpointOutcomeRecorded,
176    /// A background phase (ANN warm, index rebuild/backfill, ...) started (ADR-103 Stage 1).
177    PhaseStarted,
178    /// A background phase completed (ADR-103 Stage 1).
179    PhaseCompleted,
180    /// A background phase was cancelled before completion (ADR-103 Stage 1).
181    PhaseCancelled,
182    /// An attempted operation was refused while retaining its existing subject.
183    Refusal,
184    /// An authority record changed with its attributable transactional history.
185    GrantChange,
186}
187
188impl EventKind {
189    /// All 44 event kind variants in declaration order.
190    pub const ALL: [Self; 44] = [
191        Self::Audit,
192        Self::RecallExecuted,
193        Self::RerankExecuted,
194        Self::SearchExecuted,
195        Self::ToolCheckDecided,
196        Self::ToolRegistrationChanged,
197        Self::LinkCreated,
198        Self::EntityCreated,
199        Self::EntityUpdated,
200        Self::EntityDeleted,
201        Self::EntityMerged,
202        Self::NoteMerged,
203        Self::NoteCreated,
204        Self::NoteUpdated,
205        Self::NoteDeleted,
206        Self::EdgeUpdated,
207        Self::EdgeDeleted,
208        Self::TaskTransitioned,
209        Self::FeedbackExplicit,
210        Self::FeedbackUnjudged,
211        Self::ProfileResolutionRecommended,
212        Self::ProfileMerged,
213        Self::EmbeddingModelChanged,
214        Self::EmbeddingMigrationCompleted,
215        Self::EmbeddingMigrationFailed,
216        Self::EmbeddingDriftDetected,
217        Self::EmbedderInitialized,
218        Self::ProposalCreated,
219        Self::ProposalReviewed,
220        Self::ProposalApplied,
221        Self::ProposalWithdrawn,
222        Self::ChannelPollStarted,
223        Self::ChannelPollSucceeded,
224        Self::ChannelPollFailed,
225        Self::ChannelBackoffArmed,
226        Self::ChannelBackoffReset,
227        Self::ChannelHeartbeatPersistFailed,
228        Self::ConfigLocked,
229        Self::CheckpointOutcomeRecorded,
230        Self::PhaseStarted,
231        Self::PhaseCompleted,
232        Self::PhaseCancelled,
233        Self::Refusal,
234        Self::GrantChange,
235    ];
236
237    /// Return this class's explicitly declared persistence destination.
238    ///
239    /// Existing classes retain their caller-store declaration. The exhaustive
240    /// match makes a new kind without a sink declaration a compilation error.
241    pub const fn sink(self) -> EventSink {
242        match self {
243            Self::Audit => EventSink::CallerEventStore,
244            Self::RecallExecuted => EventSink::CallerEventStore,
245            Self::RerankExecuted => EventSink::CallerEventStore,
246            Self::SearchExecuted => EventSink::CallerEventStore,
247            Self::ToolCheckDecided => EventSink::CallerEventStore,
248            Self::ToolRegistrationChanged => EventSink::CallerEventStore,
249            Self::LinkCreated => EventSink::CallerEventStore,
250            Self::EntityCreated => EventSink::CallerEventStore,
251            Self::EntityUpdated => EventSink::CallerEventStore,
252            Self::EntityDeleted => EventSink::CallerEventStore,
253            Self::EntityMerged => EventSink::CallerEventStore,
254            Self::NoteMerged => EventSink::CallerEventStore,
255            Self::NoteCreated => EventSink::CallerEventStore,
256            Self::NoteUpdated => EventSink::CallerEventStore,
257            Self::NoteDeleted => EventSink::CallerEventStore,
258            Self::EdgeUpdated => EventSink::CallerEventStore,
259            Self::EdgeDeleted => EventSink::CallerEventStore,
260            Self::TaskTransitioned => EventSink::CallerEventStore,
261            Self::FeedbackExplicit => EventSink::CallerEventStore,
262            Self::FeedbackUnjudged => EventSink::CallerEventStore,
263            Self::ProfileResolutionRecommended => EventSink::CallerEventStore,
264            Self::ProfileMerged => EventSink::CallerEventStore,
265            Self::EmbeddingModelChanged => EventSink::CallerEventStore,
266            Self::EmbeddingMigrationCompleted => EventSink::CallerEventStore,
267            Self::EmbeddingMigrationFailed => EventSink::CallerEventStore,
268            Self::EmbeddingDriftDetected => EventSink::CallerEventStore,
269            Self::EmbedderInitialized => EventSink::CallerEventStore,
270            Self::ProposalCreated => EventSink::CallerEventStore,
271            Self::ProposalReviewed => EventSink::CallerEventStore,
272            Self::ProposalApplied => EventSink::CallerEventStore,
273            Self::ProposalWithdrawn => EventSink::CallerEventStore,
274            Self::ChannelPollStarted => EventSink::CallerEventStore,
275            Self::ChannelPollSucceeded => EventSink::CallerEventStore,
276            Self::ChannelPollFailed => EventSink::CallerEventStore,
277            Self::ChannelBackoffArmed => EventSink::CallerEventStore,
278            Self::ChannelBackoffReset => EventSink::CallerEventStore,
279            Self::ChannelHeartbeatPersistFailed => EventSink::CallerEventStore,
280            Self::ConfigLocked => EventSink::CallerEventStore,
281            Self::CheckpointOutcomeRecorded => EventSink::CallerEventStore,
282            Self::PhaseStarted => EventSink::CallerEventStore,
283            Self::PhaseCompleted => EventSink::CallerEventStore,
284            Self::PhaseCancelled => EventSink::CallerEventStore,
285            Self::Refusal => EventSink::CallerEventStore,
286            Self::GrantChange => EventSink::CallerEventStore,
287        }
288    }
289
290    /// Return the canonical snake_case string for this event kind.
291    pub const fn name(self) -> &'static str {
292        match self {
293            Self::Audit => "audit",
294            Self::RecallExecuted => "recall_executed",
295            Self::RerankExecuted => "rerank_executed",
296            Self::SearchExecuted => "search_executed",
297            Self::ToolCheckDecided => "tool_check_decided",
298            Self::ToolRegistrationChanged => "tool_registration_changed",
299            Self::LinkCreated => "link_created",
300            Self::EntityCreated => "entity_created",
301            Self::EntityUpdated => "entity_updated",
302            Self::EntityDeleted => "entity_deleted",
303            Self::EntityMerged => "entity_merged",
304            Self::NoteMerged => "note_merged",
305            Self::NoteCreated => "note_created",
306            Self::NoteUpdated => "note_updated",
307            Self::NoteDeleted => "note_deleted",
308            Self::EdgeUpdated => "edge_updated",
309            Self::EdgeDeleted => "edge_deleted",
310            Self::TaskTransitioned => "task_transitioned",
311            Self::FeedbackExplicit => "feedback_explicit",
312            Self::FeedbackUnjudged => "feedback_unjudged",
313            Self::ProfileResolutionRecommended => "profile_resolution_recommended",
314            Self::ProfileMerged => "profile_merged",
315            Self::EmbeddingModelChanged => "embedding_model_changed",
316            Self::EmbeddingMigrationCompleted => "embedding_migration_completed",
317            Self::EmbeddingMigrationFailed => "embedding_migration_failed",
318            Self::EmbeddingDriftDetected => "embedding_drift_detected",
319            Self::EmbedderInitialized => "embedder_initialized",
320            Self::ProposalCreated => "proposal_created",
321            Self::ProposalReviewed => "proposal_reviewed",
322            Self::ProposalApplied => "proposal_applied",
323            Self::ProposalWithdrawn => "proposal_withdrawn",
324            Self::ChannelPollStarted => "channel_poll_started",
325            Self::ChannelPollSucceeded => "channel_poll_succeeded",
326            Self::ChannelPollFailed => "channel_poll_failed",
327            Self::ChannelBackoffArmed => "channel_backoff_armed",
328            Self::ChannelBackoffReset => "channel_backoff_reset",
329            Self::ChannelHeartbeatPersistFailed => "channel_heartbeat_persist_failed",
330            Self::ConfigLocked => "config_locked",
331            Self::CheckpointOutcomeRecorded => "checkpoint_outcome_recorded",
332            Self::PhaseStarted => "phase_started",
333            Self::PhaseCompleted => "phase_completed",
334            Self::PhaseCancelled => "phase_cancelled",
335            Self::Refusal => "refusal",
336            Self::GrantChange => "grant_change",
337        }
338    }
339}
340
341impl fmt::Display for EventKind {
342    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343        f.write_str(self.name())
344    }
345}
346
347const EVENT_KIND_VALID: &[&str] = &[
348    "audit",
349    "recall_executed",
350    "rerank_executed",
351    "search_executed",
352    "tool_check_decided",
353    "tool_registration_changed",
354    "link_created",
355    "entity_created",
356    "entity_updated",
357    "entity_deleted",
358    "entity_merged",
359    "note_merged",
360    "note_created",
361    "note_updated",
362    "note_deleted",
363    "edge_updated",
364    "edge_deleted",
365    "task_transitioned",
366    "feedback_explicit",
367    "feedback_unjudged",
368    "profile_resolution_recommended",
369    "profile_merged",
370    "embedding_model_changed",
371    "embedding_migration_completed",
372    "embedding_migration_failed",
373    "embedding_drift_detected",
374    "embedder_initialized",
375    "proposal_created",
376    "proposal_reviewed",
377    "proposal_applied",
378    "proposal_withdrawn",
379    "channel_poll_started",
380    "channel_poll_succeeded",
381    "channel_poll_failed",
382    "channel_backoff_armed",
383    "channel_backoff_reset",
384    "channel_heartbeat_persist_failed",
385    "config_locked",
386    "checkpoint_outcome_recorded",
387    "phase_started",
388    "phase_completed",
389    "phase_cancelled",
390    "refusal",
391    "grant_change",
392];
393
394impl core::str::FromStr for EventKind {
395    type Err = crate::error::UnknownVariant;
396
397    fn from_str(s: &str) -> Result<Self, Self::Err> {
398        match s.trim().to_ascii_lowercase().as_str() {
399            "audit" => Ok(Self::Audit),
400            "recall_executed" => Ok(Self::RecallExecuted),
401            "rerank_executed" => Ok(Self::RerankExecuted),
402            "search_executed" => Ok(Self::SearchExecuted),
403            "tool_check_decided" => Ok(Self::ToolCheckDecided),
404            "tool_registration_changed" => Ok(Self::ToolRegistrationChanged),
405            "link_created" => Ok(Self::LinkCreated),
406            "entity_created" => Ok(Self::EntityCreated),
407            "entity_updated" => Ok(Self::EntityUpdated),
408            "entity_deleted" => Ok(Self::EntityDeleted),
409            "entity_merged" => Ok(Self::EntityMerged),
410            "note_merged" => Ok(Self::NoteMerged),
411            "note_created" => Ok(Self::NoteCreated),
412            "note_updated" => Ok(Self::NoteUpdated),
413            "note_deleted" => Ok(Self::NoteDeleted),
414            "edge_updated" => Ok(Self::EdgeUpdated),
415            "edge_deleted" => Ok(Self::EdgeDeleted),
416            "task_transitioned" => Ok(Self::TaskTransitioned),
417            "feedback_explicit" => Ok(Self::FeedbackExplicit),
418            "feedback_unjudged" => Ok(Self::FeedbackUnjudged),
419            "profile_resolution_recommended" => Ok(Self::ProfileResolutionRecommended),
420            "profile_merged" => Ok(Self::ProfileMerged),
421            "embedding_model_changed" => Ok(Self::EmbeddingModelChanged),
422            "embedding_migration_completed" => Ok(Self::EmbeddingMigrationCompleted),
423            "embedding_migration_failed" => Ok(Self::EmbeddingMigrationFailed),
424            "embedding_drift_detected" => Ok(Self::EmbeddingDriftDetected),
425            "embedder_initialized" => Ok(Self::EmbedderInitialized),
426            "proposal_created" => Ok(Self::ProposalCreated),
427            "proposal_reviewed" => Ok(Self::ProposalReviewed),
428            "proposal_applied" => Ok(Self::ProposalApplied),
429            "proposal_withdrawn" => Ok(Self::ProposalWithdrawn),
430            "channel_poll_started" => Ok(Self::ChannelPollStarted),
431            "channel_poll_succeeded" => Ok(Self::ChannelPollSucceeded),
432            "channel_poll_failed" => Ok(Self::ChannelPollFailed),
433            "channel_backoff_armed" => Ok(Self::ChannelBackoffArmed),
434            "channel_backoff_reset" => Ok(Self::ChannelBackoffReset),
435            "channel_heartbeat_persist_failed" => Ok(Self::ChannelHeartbeatPersistFailed),
436            "config_locked" => Ok(Self::ConfigLocked),
437            "checkpoint_outcome_recorded" => Ok(Self::CheckpointOutcomeRecorded),
438            "phase_started" => Ok(Self::PhaseStarted),
439            "phase_completed" => Ok(Self::PhaseCompleted),
440            "phase_cancelled" => Ok(Self::PhaseCancelled),
441            "refusal" => Ok(Self::Refusal),
442            "grant_change" => Ok(Self::GrantChange),
443            other => Err(crate::error::UnknownVariant::new(
444                "event_kind",
445                other,
446                EVENT_KIND_VALID,
447            )),
448        }
449    }
450}
451
452/// A reference to the logical aggregate that an event belongs to.
453///
454/// Used to thread related events (e.g. proposal lifecycle events) into a
455/// single auditable chain identified by `kind` and `id`.
456#[derive(Clone, Debug, PartialEq, Eq)]
457#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
458pub struct AggregateRef {
459    /// The aggregate type string (e.g. `"proposal"`).
460    pub kind: String,
461    /// The aggregate instance identifier.
462    pub id: Id128,
463}
464
465/// Typed payload for an [`Event`], dispatched by [`EventKind`].
466///
467/// The `Json` variant is a catch-all for events whose payload has not yet
468/// been promoted to a structured type. All other variants carry a concrete
469/// typed struct that can be pattern-matched without round-tripping through JSON.
470#[derive(Clone, Debug, PartialEq)]
471#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
472#[cfg_attr(
473    feature = "serde",
474    serde(tag = "kind", content = "payload", rename_all = "snake_case")
475)]
476pub enum EventPayload {
477    /// Raw JSON payload for untyped events.
478    Json(String),
479    /// Structured payload for a rerank pass event.
480    RerankExecuted(RerankExecutedPayload),
481    /// Structured payload for a tool-use policy decision.
482    ToolCheckDecided(ToolCheckDecidedPayload),
483    /// A registration correction without disclosing the changed field values.
484    ToolRegistrationChanged(ToolRegistrationChangedPayload),
485    /// Structured payload for a proposal-created event (requires `serde` feature).
486    #[cfg(feature = "serde")]
487    ProposalCreated(ProposalCreatedPayload),
488    /// Structured payload for a proposal-reviewed event.
489    ProposalReviewed(ProposalReviewedPayload),
490    /// Structured payload for a proposal-applied event.
491    ProposalApplied(ProposalAppliedPayload),
492    /// Structured payload for a proposal-withdrawn event.
493    ProposalWithdrawn(ProposalWithdrawnPayload),
494}
495
496impl Default for EventPayload {
497    fn default() -> Self {
498        Self::Json("{}".into())
499    }
500}
501
502/// The decision computed for one tool-use policy check.
503#[derive(Clone, Debug, PartialEq, Eq)]
504#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
505pub struct ToolCheckDecidedPayload {
506    pub actor: String,
507    pub tool: String,
508    pub registered: bool,
509    pub decision: String,
510    pub source: String,
511    pub id: Option<String>,
512    pub scope: Option<String>,
513    pub caller_verb: String,
514}
515
516/// A correction to the four policy inputs covered by a tool registration digest.
517/// Values of the corrected fields are deliberately absent.
518#[derive(Clone, Debug, PartialEq, Eq)]
519#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
520pub struct ToolRegistrationChangedPayload {
521    /// Authenticated actor stamped into the event row.
522    pub actor: String,
523    /// Canonical full UUID of the registry row.
524    pub id: String,
525    /// Canonical policy-input digest before the correction.
526    pub digest_before: String,
527    /// Canonical policy-input digest after the correction.
528    pub digest_after: String,
529}
530
531/// Implementation that produced a rerank event (ADR-042 Amendment 1).
532/// Events written before the discriminator existed are native reranks.
533#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
534#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
535#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
536pub enum RerankerKind {
537    #[default]
538    Native,
539    Weighted,
540}
541
542/// Payload for a rerank pass event, recording per-candidate scores.
543///
544/// All score values (`reranked` section scores, `final_scores`) must be finite.
545/// When the `serde` feature is enabled, deserialization rejects non-finite scores.
546#[derive(Clone, Debug, PartialEq)]
547#[cfg_attr(feature = "serde", derive(serde::Serialize))]
548pub struct RerankExecutedPayload {
549    /// Native model or weighted feature scoring; legacy events default to native.
550    pub reranker: RerankerKind,
551    /// Brain profile that served this rerank, if any.
552    pub served_by_profile_id: Option<String>,
553    /// Model used for reranking; absent for weighted feature scoring.
554    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
555    pub model_id: Option<Id128>,
556    /// Opaque caller-supplied query correlation; never generated or parsed as a UUID.
557    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
558    pub query_id: Option<String>,
559    /// Positive recognized feature weights, in scoring order.
560    pub tiers: Vec<String>,
561    /// Configured keys unknown to weighted scoring, in lexical order.
562    pub ignored_weights: Vec<String>,
563    /// Candidates without a parseable UUID, omitted from the three ID arrays.
564    pub unidentified_candidates: usize,
565    /// Candidate IDs in input order.
566    pub candidates: Vec<Id128>,
567    /// Per-candidate named sub-scores from the reranker.
568    pub reranked: Vec<(Id128, Vec<(String, f32)>)>,
569    /// Final aggregated score per candidate.
570    pub final_scores: Vec<(Id128, f32)>,
571    /// Wall-clock latency of the rerank operation in microseconds.
572    pub latency_us: u64,
573    /// Whether a brain hook was applied during this rerank.
574    pub hook_applied: bool,
575    /// Whether the hook matched the intended target.
576    pub hook_target_match: bool,
577}
578
579impl RerankExecutedPayload {
580    /// Return `true` if all score values are finite.
581    pub fn is_valid(&self) -> bool {
582        let reranked_ok = self
583            .reranked
584            .iter()
585            .all(|(_, scores)| scores.iter().all(|(_, s)| s.is_finite()));
586        let final_ok = self.final_scores.iter().all(|(_, s)| s.is_finite());
587        reranked_ok && final_ok
588    }
589}
590
591#[cfg(feature = "serde")]
592impl<'de> serde::Deserialize<'de> for RerankExecutedPayload {
593    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
594    where
595        D: serde::Deserializer<'de>,
596    {
597        #[derive(serde::Deserialize)]
598        struct Raw {
599            #[serde(default)]
600            reranker: RerankerKind,
601            served_by_profile_id: Option<String>,
602            model_id: Option<Id128>,
603            query_id: Option<String>,
604            #[serde(default)]
605            tiers: Vec<String>,
606            #[serde(default)]
607            ignored_weights: Vec<String>,
608            #[serde(default)]
609            unidentified_candidates: usize,
610            candidates: Vec<Id128>,
611            reranked: Vec<(Id128, Vec<(String, f32)>)>,
612            final_scores: Vec<(Id128, f32)>,
613            latency_us: u64,
614            hook_applied: bool,
615            hook_target_match: bool,
616        }
617
618        let raw = Raw::deserialize(deserializer)?;
619
620        for (_, score) in &raw.final_scores {
621            if !score.is_finite() {
622                return Err(serde::de::Error::custom(alloc::format!(
623                    "RerankExecutedPayload final_scores must be finite, got {score}"
624                )));
625            }
626        }
627        for (_, sections) in &raw.reranked {
628            for (section_name, score) in sections {
629                if !score.is_finite() {
630                    return Err(serde::de::Error::custom(alloc::format!(
631                        "RerankExecutedPayload reranked section '{section_name}' score must be finite, got {score}"
632                    )));
633                }
634            }
635        }
636
637        Ok(RerankExecutedPayload {
638            reranker: raw.reranker,
639            served_by_profile_id: raw.served_by_profile_id,
640            model_id: raw.model_id,
641            query_id: raw.query_id,
642            tiers: raw.tiers,
643            ignored_weights: raw.ignored_weights,
644            unidentified_candidates: raw.unidentified_candidates,
645            candidates: raw.candidates,
646            reranked: raw.reranked,
647            final_scores: raw.final_scores,
648            latency_us: raw.latency_us,
649            hook_applied: raw.hook_applied,
650            hook_target_match: raw.hook_target_match,
651        })
652    }
653}
654
655/// Payload for the `ProposalCreated` event — captures the full initial proposal state.
656#[cfg(feature = "serde")]
657#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
658pub struct ProposalCreatedPayload {
659    pub proposal_id: Id128,
660    pub proposer: String,
661    pub title: String,
662    pub description: String,
663    pub changeset: ProposalChangeset,
664    pub reviewers: Vec<String>,
665    pub expiry: Option<crate::Timestamp>,
666    pub parent_id: Option<Id128>,
667}
668
669/// Structured draft for adding a new entity via a proposal.
670///
671/// Fields mirror the `create(kind=<entity kind>)` verb surface; `kind` is
672/// validated against the closed 8-kind entity taxonomy at apply time.
673#[cfg(feature = "serde")]
674#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
675pub struct EntityDraft {
676    /// Entity kind — must be one of the 8 closed entity kind values.
677    pub kind: String,
678    /// Human-readable name (required).
679    pub name: String,
680    /// Optional long-form description.
681    #[serde(skip_serializing_if = "Option::is_none")]
682    pub description: Option<String>,
683    /// Arbitrary structured metadata.
684    #[serde(skip_serializing_if = "Option::is_none")]
685    pub properties: Option<serde_json::Value>,
686    /// Classification tags.
687    #[serde(default, skip_serializing_if = "Vec::is_empty")]
688    pub tags: Vec<String>,
689}
690
691/// Structured patch for modifying an existing entity via a proposal.
692///
693/// Absent fields mean "leave unchanged". Setting `description` or
694/// `entity_type` to `null` explicitly clears it; a string `entity_type` sets
695/// it, validated against the kind's registered vocabulary at apply time.
696#[cfg(feature = "serde")]
697#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
698pub struct ProposalEntityPatch {
699    #[serde(skip_serializing_if = "Option::is_none")]
700    pub name: Option<String>,
701    /// `null` clears the description; absent leaves it unchanged.
702    #[serde(
703        default,
704        skip_serializing_if = "Option::is_none",
705        with = "serde_opt_opt"
706    )]
707    pub description: Option<Option<String>>,
708    #[serde(skip_serializing_if = "Option::is_none")]
709    pub properties: Option<serde_json::Value>,
710    #[serde(skip_serializing_if = "Option::is_none")]
711    pub tags: Option<Vec<String>>,
712    /// ADR-014 tri-state: absent leaves the type unchanged, `null` explicitly
713    /// clears it, a string sets it (validated against the kind's vocabulary
714    /// at apply time, per ADR-046 parity with the runtime entity update).
715    #[serde(
716        default,
717        skip_serializing_if = "Option::is_none",
718        with = "serde_opt_opt"
719    )]
720    pub entity_type: Option<Option<String>>,
721}
722
723/// Structured draft for adding a new note via a proposal.
724///
725/// Fields mirror the `create(kind=<note kind>)` verb surface.
726#[cfg(feature = "serde")]
727#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
728pub struct NoteDraft {
729    /// Note kind string (validated by the loaded pack at apply time).
730    pub kind: String,
731    /// Note body / content (required).
732    pub content: String,
733    /// Optional short name.
734    #[serde(skip_serializing_if = "Option::is_none")]
735    pub name: Option<String>,
736    /// Arbitrary structured metadata.
737    #[serde(skip_serializing_if = "Option::is_none")]
738    pub properties: Option<serde_json::Value>,
739}
740
741/// Serde helper for `Option<Option<T>>` — distinguishes absent vs. explicit null.
742#[cfg(feature = "serde")]
743mod serde_opt_opt {
744    use serde::{Deserialize, Deserializer, Serialize, Serializer};
745
746    pub fn serialize<T, S>(val: &Option<Option<T>>, s: S) -> Result<S::Ok, S::Error>
747    where
748        T: Serialize,
749        S: Serializer,
750    {
751        match val {
752            None => unreachable!("skip_serializing_if guards the None case"),
753            Some(inner) => inner.serialize(s),
754        }
755    }
756
757    pub fn deserialize<'de, T, D>(d: D) -> Result<Option<Option<T>>, D::Error>
758    where
759        T: Deserialize<'de>,
760        D: Deserializer<'de>,
761    {
762        let opt: Option<T> = Option::deserialize(d)?;
763        Ok(Some(opt))
764    }
765}
766
767/// Natural key of a stored edge in a proposal: the edge from `source` to
768/// `target` with `relation`.
769#[cfg(feature = "serde")]
770#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
771pub struct ProposalEdgeKey {
772    pub source: Id128,
773    pub target: Id128,
774    pub relation: crate::EdgeRelation,
775}
776
777#[cfg(feature = "serde")]
778impl ProposalEdgeKey {
779    /// True when both keys name the same edge. A symmetric relation names one
780    /// edge whichever endpoint comes first.
781    fn names_same_edge(
782        &self,
783        source: &Id128,
784        target: &Id128,
785        relation: &crate::EdgeRelation,
786    ) -> bool {
787        if self.relation != *relation {
788            return false;
789        }
790        (self.source == *source && self.target == *target)
791            || (relation.is_symmetric() && self.source == *target && self.target == *source)
792    }
793}
794
795/// The edge a `SupersedeEdge` change adds. Fields and validation match
796/// `AddEdge`.
797#[cfg(feature = "serde")]
798#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
799pub struct ProposalEdgeDraft {
800    pub source: Id128,
801    pub target: Id128,
802    pub relation: crate::EdgeRelation,
803    #[serde(default)]
804    pub weight: Option<f32>,
805    #[serde(default, skip_serializing_if = "Option::is_none")]
806    pub metadata: Option<serde_json::Value>,
807}
808
809#[cfg(feature = "serde")]
810fn validate_proposal_edge_weight(
811    variant: &str,
812    weight: Option<f32>,
813) -> Result<(), alloc::string::String> {
814    if let Some(w) = weight {
815        if !w.is_finite() {
816            return Err(alloc::format!(
817                "ProposalChangeset {variant} weight must be finite, got {w}"
818            ));
819        }
820        if !crate::validate_edge_weight(f64::from(w)) {
821            return Err(alloc::format!(
822                "ProposalChangeset {variant} weight must be in [0.0, 1.0], got {w}"
823            ));
824        }
825    }
826    Ok(())
827}
828
829/// The set of KG mutations a proposal intends to apply as a proposal changeset.
830#[cfg(feature = "serde")]
831#[derive(Clone, Debug, PartialEq, serde::Serialize)]
832#[serde(tag = "kind", rename_all = "snake_case")]
833pub enum ProposalChangeset {
834    /// Add a new entity. `entity.kind` validated at apply time.
835    AddEntity {
836        entity: EntityDraft,
837    },
838    /// Modify an existing entity's properties / tags / description / entity
839    /// type (absent = unchanged, null = clear, string = set-and-validate).
840    UpdateEntity {
841        id: Id128,
842        patch: ProposalEntityPatch,
843    },
844    /// Add a typed edge. `weight` must be finite and in `[0.0, 1.0]` if present.
845    /// Metadata uses the same apply-time validation as `link`.
846    AddEdge {
847        source: Id128,
848        target: Id128,
849        relation: crate::EdgeRelation,
850        weight: Option<f32>,
851        #[serde(skip_serializing_if = "Option::is_none")]
852        metadata: Option<serde_json::Value>,
853    },
854    /// Retire the live edge with this natural key by soft deletion, so
855    /// `restore` on the edge's id brings it back. Applying fails, writing
856    /// nothing, when no live edge has the key.
857    RetireEdge {
858        source: Id128,
859        target: Id128,
860        relation: crate::EdgeRelation,
861    },
862    /// Retire the live edge named by `old` as `RetireEdge` does and add `new`
863    /// as `AddEdge` does, in one atomic unit: both land or neither does.
864    SupersedeEdge {
865        old: ProposalEdgeKey,
866        new: ProposalEdgeDraft,
867    },
868    /// Add a note (entity-annotating or stand-alone).
869    AddNote {
870        note: NoteDraft,
871    },
872    MergeEntities {
873        into: Id128,
874        from: Id128,
875    },
876    SupersedeEntity {
877        old: Id128,
878        new: Id128,
879    },
880    Canonical {
881        schema_version: u32,
882        delta: String,
883    },
884    Compound {
885        steps: Vec<ProposalChangeset>,
886    },
887}
888
889#[cfg(feature = "serde")]
890impl ProposalChangeset {
891    fn validate(&self) -> Result<(), alloc::string::String> {
892        match self {
893            Self::AddEdge { weight, .. } => validate_proposal_edge_weight("AddEdge", *weight),
894            Self::SupersedeEdge { old, new } => {
895                validate_proposal_edge_weight("SupersedeEdge", new.weight)?;
896                if old.names_same_edge(&new.source, &new.target, &new.relation) {
897                    return Err(
898                        "ProposalChangeset SupersedeEdge new must name a different edge than old"
899                            .into(),
900                    );
901                }
902                Ok(())
903            }
904            Self::Compound { steps } => {
905                for step in steps {
906                    if matches!(step, Self::Canonical { .. }) {
907                        return Err("Canonical proposal changesets must be top-level".into());
908                    }
909                    step.validate()?;
910                }
911                Ok(())
912            }
913            _ => Ok(()),
914        }
915    }
916}
917
918#[cfg(feature = "serde")]
919impl<'de> serde::Deserialize<'de> for ProposalChangeset {
920    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
921    where
922        D: serde::Deserializer<'de>,
923    {
924        #[derive(serde::Deserialize)]
925        #[serde(deny_unknown_fields)]
926        struct CanonicalFields {
927            schema_version: u32,
928            delta: String,
929        }
930
931        #[derive(serde::Deserialize)]
932        #[serde(tag = "kind", rename_all = "snake_case")]
933        enum ProposalChangesetRaw {
934            AddEntity {
935                entity: EntityDraft,
936            },
937            UpdateEntity {
938                id: Id128,
939                patch: ProposalEntityPatch,
940            },
941            AddEdge {
942                source: Id128,
943                target: Id128,
944                relation: crate::EdgeRelation,
945                weight: Option<f32>,
946                metadata: Option<serde_json::Value>,
947            },
948            RetireEdge {
949                source: Id128,
950                target: Id128,
951                relation: crate::EdgeRelation,
952            },
953            SupersedeEdge {
954                old: ProposalEdgeKey,
955                new: ProposalEdgeDraft,
956            },
957            AddNote {
958                note: NoteDraft,
959            },
960            MergeEntities {
961                into: Id128,
962                from: Id128,
963            },
964            SupersedeEntity {
965                old: Id128,
966                new: Id128,
967            },
968            Canonical(CanonicalFields),
969            Compound {
970                steps: Vec<ProposalChangeset>,
971            },
972        }
973
974        let raw = ProposalChangesetRaw::deserialize(deserializer)?;
975        let cs = match raw {
976            ProposalChangesetRaw::AddEntity { entity } => Self::AddEntity { entity },
977            ProposalChangesetRaw::UpdateEntity { id, patch } => Self::UpdateEntity { id, patch },
978            ProposalChangesetRaw::AddEdge {
979                source,
980                target,
981                relation,
982                weight,
983                metadata,
984            } => Self::AddEdge {
985                source,
986                target,
987                relation,
988                weight,
989                metadata,
990            },
991            ProposalChangesetRaw::RetireEdge {
992                source,
993                target,
994                relation,
995            } => Self::RetireEdge {
996                source,
997                target,
998                relation,
999            },
1000            ProposalChangesetRaw::SupersedeEdge { old, new } => Self::SupersedeEdge { old, new },
1001            ProposalChangesetRaw::AddNote { note } => Self::AddNote { note },
1002            ProposalChangesetRaw::MergeEntities { into, from } => {
1003                Self::MergeEntities { into, from }
1004            }
1005            ProposalChangesetRaw::SupersedeEntity { old, new } => {
1006                Self::SupersedeEntity { old, new }
1007            }
1008            ProposalChangesetRaw::Canonical(CanonicalFields {
1009                schema_version,
1010                delta,
1011            }) => Self::Canonical {
1012                schema_version,
1013                delta,
1014            },
1015            ProposalChangesetRaw::Compound { steps } => Self::Compound { steps },
1016        };
1017        cs.validate().map_err(serde::de::Error::custom)?;
1018        Ok(cs)
1019    }
1020}
1021
1022#[cfg(not(feature = "serde"))]
1023#[derive(Clone, Debug, PartialEq)]
1024pub enum ProposalChangeset {
1025    AddEdge {
1026        source: Id128,
1027        target: Id128,
1028        relation: crate::EdgeRelation,
1029        weight: Option<f32>,
1030    },
1031    MergeEntities {
1032        into: Id128,
1033        from: Id128,
1034    },
1035    SupersedeEntity {
1036        old: Id128,
1037        new: Id128,
1038    },
1039    Canonical {
1040        schema_version: u32,
1041        delta: String,
1042    },
1043    Compound {
1044        steps: Vec<ProposalChangeset>,
1045    },
1046}
1047
1048/// Payload for the `ProposalReviewed` event — records a single reviewer's decision.
1049#[derive(Clone, Debug, PartialEq)]
1050#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1051pub struct ProposalReviewedPayload {
1052    pub proposal_id: Id128,
1053    pub reviewer: String,
1054    pub decision: ProposalDecision,
1055    pub comment: Option<String>,
1056}
1057
1058/// A reviewer's decision on a proposal.
1059#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1060#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1061#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
1062pub enum ProposalDecision {
1063    /// The reviewer approved the proposal for application.
1064    Approve,
1065    /// The reviewer rejected the proposal; it will not be applied.
1066    Reject,
1067    /// The reviewer left a comment without blocking the proposal.
1068    Comment,
1069    /// The reviewer requested changes before the proposal can proceed.
1070    RequestChanges,
1071}
1072
1073impl ProposalDecision {
1074    /// Returns the bare variant name as a lowercase string, matching the serde
1075    /// `rename_all = "snake_case"` representation.  Use this when storing the
1076    /// decision as a plain TEXT column — **not** `serde_json::to_string`, which
1077    /// would produce a JSON-quoted string (`"\"approve\""` instead of `"approve"`).
1078    pub fn as_str(self) -> &'static str {
1079        match self {
1080            Self::Approve => "approve",
1081            Self::Reject => "reject",
1082            Self::Comment => "comment",
1083            Self::RequestChanges => "request_changes",
1084        }
1085    }
1086}
1087
1088/// Payload for the `ProposalApplied` event — records the outcome of the apply attempt.
1089#[derive(Clone, Debug, PartialEq)]
1090#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1091pub struct ProposalAppliedPayload {
1092    pub proposal_id: Id128,
1093    pub applied_at: crate::Timestamp,
1094    pub applied_by: String,
1095    pub result: ApplyResult,
1096    #[cfg_attr(
1097        feature = "serde",
1098        serde(default, skip_serializing_if = "Option::is_none")
1099    )]
1100    pub preimage: Option<ProposalPreimageStatus>,
1101}
1102
1103/// Whether an apply result carries checked stage-time preimages.
1104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1105#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1106#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
1107pub enum ProposalPreimageStatus {
1108    None,
1109    Captured,
1110}
1111
1112/// Outcome of applying a proposal: either all steps succeeded or the apply failed with an error.
1113#[derive(Clone, Debug, PartialEq)]
1114#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1115#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
1116pub enum ApplyResult {
1117    Success {
1118        created_records: Vec<Id128>,
1119    },
1120    Failed {
1121        error: String,
1122        applied_step_count: u32,
1123    },
1124}
1125
1126/// Payload for the `ProposalWithdrawn` event — records who withdrew and an optional reason.
1127#[derive(Clone, Debug, PartialEq)]
1128#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1129pub struct ProposalWithdrawnPayload {
1130    pub proposal_id: Id128,
1131    pub by: String,
1132    pub reason: Option<String>,
1133}
1134
1135/// Builder for events. Used by the verb dispatch path.
1136pub struct EventBuilder {
1137    verb: String,
1138    substrate: SubstrateKind,
1139    actor: Option<String>,
1140    kind: EventKind,
1141    payload: EventPayload,
1142    payload_schema_version: u32,
1143    profile_state_version: Option<u64>,
1144    aggregate: Option<AggregateRef>,
1145}
1146
1147impl EventBuilder {
1148    /// Create a new builder for an event produced by `verb` acting on `substrate` as `actor`.
1149    pub fn new(
1150        verb: impl Into<String>,
1151        substrate: SubstrateKind,
1152        actor: impl Into<String>,
1153    ) -> Self {
1154        Self {
1155            verb: verb.into(),
1156            substrate,
1157            actor: Some(actor.into()),
1158            kind: EventKind::Audit,
1159            payload: EventPayload::default(),
1160            payload_schema_version: 1,
1161            profile_state_version: None,
1162            aggregate: None,
1163        }
1164    }
1165
1166    /// Override the event kind discriminant.
1167    pub fn kind(mut self, kind: EventKind) -> Self {
1168        self.kind = kind;
1169        self
1170    }
1171
1172    /// Set the typed payload for this event.
1173    pub fn payload(mut self, payload: EventPayload) -> Self {
1174        self.payload = payload;
1175        self
1176    }
1177
1178    /// Set the payload schema version (defaults to 1).
1179    pub fn payload_schema_version(mut self, version: u32) -> Self {
1180        self.payload_schema_version = version;
1181        self
1182    }
1183
1184    /// Record the brain profile state version observed at emit time.
1185    pub fn profile_state_version(mut self, version: u64) -> Self {
1186        self.profile_state_version = Some(version);
1187        self
1188    }
1189
1190    /// Thread this event into an aggregate chain.
1191    pub fn aggregate(mut self, aggregate: AggregateRef) -> Self {
1192        self.aggregate = Some(aggregate);
1193        self
1194    }
1195
1196    /// Consume the builder and produce an [`Event`] with the given `header`.
1197    pub fn build(self, header: Header) -> Event {
1198        Event {
1199            header,
1200            verb: self.verb,
1201            substrate: self.substrate,
1202            actor: self.actor,
1203            kind: self.kind,
1204            payload: self.payload,
1205            payload_schema_version: self.payload_schema_version,
1206            profile_state_version: self.profile_state_version,
1207            aggregate: self.aggregate,
1208        }
1209    }
1210}
1211
1212#[cfg(test)]
1213#[path = "event_tests.rs"]
1214mod tests;
1215
1216#[cfg(all(test, feature = "serde"))]
1217#[path = "event_canonical_tests.rs"]
1218mod canonical_tests;