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/// The set of KG mutations a proposal intends to apply as a proposal changeset.
768#[cfg(feature = "serde")]
769#[derive(Clone, Debug, PartialEq, serde::Serialize)]
770#[serde(tag = "kind", rename_all = "snake_case")]
771pub enum ProposalChangeset {
772    /// Add a new entity. `entity.kind` validated at apply time.
773    AddEntity {
774        entity: EntityDraft,
775    },
776    /// Modify an existing entity's properties / tags / description / entity
777    /// type (absent = unchanged, null = clear, string = set-and-validate).
778    UpdateEntity {
779        id: Id128,
780        patch: ProposalEntityPatch,
781    },
782    /// Add a typed edge. `weight` must be finite and in `[0.0, 1.0]` if present.
783    AddEdge {
784        source: Id128,
785        target: Id128,
786        relation: crate::EdgeRelation,
787        weight: Option<f32>,
788    },
789    /// Add a note (entity-annotating or stand-alone).
790    AddNote {
791        note: NoteDraft,
792    },
793    MergeEntities {
794        into: Id128,
795        from: Id128,
796    },
797    SupersedeEntity {
798        old: Id128,
799        new: Id128,
800    },
801    Canonical {
802        schema_version: u32,
803        delta: String,
804    },
805    Compound {
806        steps: Vec<ProposalChangeset>,
807    },
808}
809
810#[cfg(feature = "serde")]
811impl ProposalChangeset {
812    fn validate(&self) -> Result<(), alloc::string::String> {
813        match self {
814            Self::AddEdge { weight, .. } => {
815                if let Some(w) = weight {
816                    if !w.is_finite() {
817                        return Err(alloc::format!(
818                            "ProposalChangeset AddEdge weight must be finite, got {w}"
819                        ));
820                    }
821                    if !crate::validate_edge_weight(f64::from(*w)) {
822                        return Err(alloc::format!(
823                            "ProposalChangeset AddEdge weight must be in [0.0, 1.0], got {w}"
824                        ));
825                    }
826                }
827                Ok(())
828            }
829            Self::Compound { steps } => {
830                for step in steps {
831                    if matches!(step, Self::Canonical { .. }) {
832                        return Err("Canonical proposal changesets must be top-level".into());
833                    }
834                    step.validate()?;
835                }
836                Ok(())
837            }
838            _ => Ok(()),
839        }
840    }
841}
842
843#[cfg(feature = "serde")]
844impl<'de> serde::Deserialize<'de> for ProposalChangeset {
845    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
846    where
847        D: serde::Deserializer<'de>,
848    {
849        #[derive(serde::Deserialize)]
850        #[serde(deny_unknown_fields)]
851        struct CanonicalFields {
852            schema_version: u32,
853            delta: String,
854        }
855
856        #[derive(serde::Deserialize)]
857        #[serde(tag = "kind", rename_all = "snake_case")]
858        enum ProposalChangesetRaw {
859            AddEntity {
860                entity: EntityDraft,
861            },
862            UpdateEntity {
863                id: Id128,
864                patch: ProposalEntityPatch,
865            },
866            AddEdge {
867                source: Id128,
868                target: Id128,
869                relation: crate::EdgeRelation,
870                weight: Option<f32>,
871            },
872            AddNote {
873                note: NoteDraft,
874            },
875            MergeEntities {
876                into: Id128,
877                from: Id128,
878            },
879            SupersedeEntity {
880                old: Id128,
881                new: Id128,
882            },
883            Canonical(CanonicalFields),
884            Compound {
885                steps: Vec<ProposalChangeset>,
886            },
887        }
888
889        let raw = ProposalChangesetRaw::deserialize(deserializer)?;
890        let cs = match raw {
891            ProposalChangesetRaw::AddEntity { entity } => Self::AddEntity { entity },
892            ProposalChangesetRaw::UpdateEntity { id, patch } => Self::UpdateEntity { id, patch },
893            ProposalChangesetRaw::AddEdge {
894                source,
895                target,
896                relation,
897                weight,
898            } => Self::AddEdge {
899                source,
900                target,
901                relation,
902                weight,
903            },
904            ProposalChangesetRaw::AddNote { note } => Self::AddNote { note },
905            ProposalChangesetRaw::MergeEntities { into, from } => {
906                Self::MergeEntities { into, from }
907            }
908            ProposalChangesetRaw::SupersedeEntity { old, new } => {
909                Self::SupersedeEntity { old, new }
910            }
911            ProposalChangesetRaw::Canonical(CanonicalFields {
912                schema_version,
913                delta,
914            }) => Self::Canonical {
915                schema_version,
916                delta,
917            },
918            ProposalChangesetRaw::Compound { steps } => Self::Compound { steps },
919        };
920        cs.validate().map_err(serde::de::Error::custom)?;
921        Ok(cs)
922    }
923}
924
925#[cfg(not(feature = "serde"))]
926#[derive(Clone, Debug, PartialEq)]
927pub enum ProposalChangeset {
928    AddEdge {
929        source: Id128,
930        target: Id128,
931        relation: crate::EdgeRelation,
932        weight: Option<f32>,
933    },
934    MergeEntities {
935        into: Id128,
936        from: Id128,
937    },
938    SupersedeEntity {
939        old: Id128,
940        new: Id128,
941    },
942    Canonical {
943        schema_version: u32,
944        delta: String,
945    },
946    Compound {
947        steps: Vec<ProposalChangeset>,
948    },
949}
950
951/// Payload for the `ProposalReviewed` event — records a single reviewer's decision.
952#[derive(Clone, Debug, PartialEq)]
953#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
954pub struct ProposalReviewedPayload {
955    pub proposal_id: Id128,
956    pub reviewer: String,
957    pub decision: ProposalDecision,
958    pub comment: Option<String>,
959}
960
961/// A reviewer's decision on a proposal.
962#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
963#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
964#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
965pub enum ProposalDecision {
966    /// The reviewer approved the proposal for application.
967    Approve,
968    /// The reviewer rejected the proposal; it will not be applied.
969    Reject,
970    /// The reviewer left a comment without blocking the proposal.
971    Comment,
972    /// The reviewer requested changes before the proposal can proceed.
973    RequestChanges,
974}
975
976impl ProposalDecision {
977    /// Returns the bare variant name as a lowercase string, matching the serde
978    /// `rename_all = "snake_case"` representation.  Use this when storing the
979    /// decision as a plain TEXT column — **not** `serde_json::to_string`, which
980    /// would produce a JSON-quoted string (`"\"approve\""` instead of `"approve"`).
981    pub fn as_str(self) -> &'static str {
982        match self {
983            Self::Approve => "approve",
984            Self::Reject => "reject",
985            Self::Comment => "comment",
986            Self::RequestChanges => "request_changes",
987        }
988    }
989}
990
991/// Payload for the `ProposalApplied` event — records the outcome of the apply attempt.
992#[derive(Clone, Debug, PartialEq)]
993#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
994pub struct ProposalAppliedPayload {
995    pub proposal_id: Id128,
996    pub applied_at: crate::Timestamp,
997    pub applied_by: String,
998    pub result: ApplyResult,
999    #[cfg_attr(
1000        feature = "serde",
1001        serde(default, skip_serializing_if = "Option::is_none")
1002    )]
1003    pub preimage: Option<ProposalPreimageStatus>,
1004}
1005
1006/// Whether an apply result carries checked stage-time preimages.
1007#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1008#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1009#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
1010pub enum ProposalPreimageStatus {
1011    None,
1012    Captured,
1013}
1014
1015/// Outcome of applying a proposal: either all steps succeeded or the apply failed with an error.
1016#[derive(Clone, Debug, PartialEq)]
1017#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1018#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
1019pub enum ApplyResult {
1020    Success {
1021        created_records: Vec<Id128>,
1022    },
1023    Failed {
1024        error: String,
1025        applied_step_count: u32,
1026    },
1027}
1028
1029/// Payload for the `ProposalWithdrawn` event — records who withdrew and an optional reason.
1030#[derive(Clone, Debug, PartialEq)]
1031#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1032pub struct ProposalWithdrawnPayload {
1033    pub proposal_id: Id128,
1034    pub by: String,
1035    pub reason: Option<String>,
1036}
1037
1038/// Builder for events. Used by the verb dispatch path.
1039pub struct EventBuilder {
1040    verb: String,
1041    substrate: SubstrateKind,
1042    actor: Option<String>,
1043    kind: EventKind,
1044    payload: EventPayload,
1045    payload_schema_version: u32,
1046    profile_state_version: Option<u64>,
1047    aggregate: Option<AggregateRef>,
1048}
1049
1050impl EventBuilder {
1051    /// Create a new builder for an event produced by `verb` acting on `substrate` as `actor`.
1052    pub fn new(
1053        verb: impl Into<String>,
1054        substrate: SubstrateKind,
1055        actor: impl Into<String>,
1056    ) -> Self {
1057        Self {
1058            verb: verb.into(),
1059            substrate,
1060            actor: Some(actor.into()),
1061            kind: EventKind::Audit,
1062            payload: EventPayload::default(),
1063            payload_schema_version: 1,
1064            profile_state_version: None,
1065            aggregate: None,
1066        }
1067    }
1068
1069    /// Override the event kind discriminant.
1070    pub fn kind(mut self, kind: EventKind) -> Self {
1071        self.kind = kind;
1072        self
1073    }
1074
1075    /// Set the typed payload for this event.
1076    pub fn payload(mut self, payload: EventPayload) -> Self {
1077        self.payload = payload;
1078        self
1079    }
1080
1081    /// Set the payload schema version (defaults to 1).
1082    pub fn payload_schema_version(mut self, version: u32) -> Self {
1083        self.payload_schema_version = version;
1084        self
1085    }
1086
1087    /// Record the brain profile state version observed at emit time.
1088    pub fn profile_state_version(mut self, version: u64) -> Self {
1089        self.profile_state_version = Some(version);
1090        self
1091    }
1092
1093    /// Thread this event into an aggregate chain.
1094    pub fn aggregate(mut self, aggregate: AggregateRef) -> Self {
1095        self.aggregate = Some(aggregate);
1096        self
1097    }
1098
1099    /// Consume the builder and produce an [`Event`] with the given `header`.
1100    pub fn build(self, header: Header) -> Event {
1101        Event {
1102            header,
1103            verb: self.verb,
1104            substrate: self.substrate,
1105            actor: self.actor,
1106            kind: self.kind,
1107            payload: self.payload,
1108            payload_schema_version: self.payload_schema_version,
1109            profile_state_version: self.profile_state_version,
1110            aggregate: self.aggregate,
1111        }
1112    }
1113}
1114
1115#[cfg(test)]
1116#[path = "event_tests.rs"]
1117mod tests;
1118
1119#[cfg(all(test, feature = "serde"))]
1120#[path = "event_canonical_tests.rs"]
1121mod canonical_tests;