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 47 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    /// A registry row's source was corrected in place (ADR-180 Amendment 13).
187    /// Retention: `pinned_while_referenced`, as for `ToolRegistrationChanged`;
188    /// the payload/target registry row is the referent.
189    ToolSourceCorrected,
190    /// A retired registry row was given back its identity (ADR-180 Amendment 13).
191    /// Retention: `pinned_while_referenced`, as for `ToolRegistrationChanged`;
192    /// the payload/target registry row is the referent.
193    ToolRegistrationRestored,
194    /// A `tool.call` allowed at its decision ran, or was refused or failed after it
195    /// (ADR-180 Amendment 9 item 9). Retention: `age_archivable`, as for
196    /// `ToolCheckDecided`.
197    ToolCalled,
198}
199
200impl EventKind {
201    /// All 47 event kind variants in declaration order.
202    pub const ALL: [Self; 47] = [
203        Self::Audit,
204        Self::RecallExecuted,
205        Self::RerankExecuted,
206        Self::SearchExecuted,
207        Self::ToolCheckDecided,
208        Self::ToolRegistrationChanged,
209        Self::LinkCreated,
210        Self::EntityCreated,
211        Self::EntityUpdated,
212        Self::EntityDeleted,
213        Self::EntityMerged,
214        Self::NoteMerged,
215        Self::NoteCreated,
216        Self::NoteUpdated,
217        Self::NoteDeleted,
218        Self::EdgeUpdated,
219        Self::EdgeDeleted,
220        Self::TaskTransitioned,
221        Self::FeedbackExplicit,
222        Self::FeedbackUnjudged,
223        Self::ProfileResolutionRecommended,
224        Self::ProfileMerged,
225        Self::EmbeddingModelChanged,
226        Self::EmbeddingMigrationCompleted,
227        Self::EmbeddingMigrationFailed,
228        Self::EmbeddingDriftDetected,
229        Self::EmbedderInitialized,
230        Self::ProposalCreated,
231        Self::ProposalReviewed,
232        Self::ProposalApplied,
233        Self::ProposalWithdrawn,
234        Self::ChannelPollStarted,
235        Self::ChannelPollSucceeded,
236        Self::ChannelPollFailed,
237        Self::ChannelBackoffArmed,
238        Self::ChannelBackoffReset,
239        Self::ChannelHeartbeatPersistFailed,
240        Self::ConfigLocked,
241        Self::CheckpointOutcomeRecorded,
242        Self::PhaseStarted,
243        Self::PhaseCompleted,
244        Self::PhaseCancelled,
245        Self::Refusal,
246        Self::GrantChange,
247        Self::ToolSourceCorrected,
248        Self::ToolRegistrationRestored,
249        Self::ToolCalled,
250    ];
251
252    /// Return this class's explicitly declared persistence destination.
253    ///
254    /// Existing classes retain their caller-store declaration. The exhaustive
255    /// match makes a new kind without a sink declaration a compilation error.
256    pub const fn sink(self) -> EventSink {
257        match self {
258            Self::Audit => EventSink::CallerEventStore,
259            Self::RecallExecuted => EventSink::CallerEventStore,
260            Self::RerankExecuted => EventSink::CallerEventStore,
261            Self::SearchExecuted => EventSink::CallerEventStore,
262            Self::ToolCheckDecided => EventSink::CallerEventStore,
263            Self::ToolRegistrationChanged => EventSink::CallerEventStore,
264            Self::LinkCreated => EventSink::CallerEventStore,
265            Self::EntityCreated => EventSink::CallerEventStore,
266            Self::EntityUpdated => EventSink::CallerEventStore,
267            Self::EntityDeleted => EventSink::CallerEventStore,
268            Self::EntityMerged => EventSink::CallerEventStore,
269            Self::NoteMerged => EventSink::CallerEventStore,
270            Self::NoteCreated => EventSink::CallerEventStore,
271            Self::NoteUpdated => EventSink::CallerEventStore,
272            Self::NoteDeleted => EventSink::CallerEventStore,
273            Self::EdgeUpdated => EventSink::CallerEventStore,
274            Self::EdgeDeleted => EventSink::CallerEventStore,
275            Self::TaskTransitioned => EventSink::CallerEventStore,
276            Self::FeedbackExplicit => EventSink::CallerEventStore,
277            Self::FeedbackUnjudged => EventSink::CallerEventStore,
278            Self::ProfileResolutionRecommended => EventSink::CallerEventStore,
279            Self::ProfileMerged => EventSink::CallerEventStore,
280            Self::EmbeddingModelChanged => EventSink::CallerEventStore,
281            Self::EmbeddingMigrationCompleted => EventSink::CallerEventStore,
282            Self::EmbeddingMigrationFailed => EventSink::CallerEventStore,
283            Self::EmbeddingDriftDetected => EventSink::CallerEventStore,
284            Self::EmbedderInitialized => EventSink::CallerEventStore,
285            Self::ProposalCreated => EventSink::CallerEventStore,
286            Self::ProposalReviewed => EventSink::CallerEventStore,
287            Self::ProposalApplied => EventSink::CallerEventStore,
288            Self::ProposalWithdrawn => EventSink::CallerEventStore,
289            Self::ChannelPollStarted => EventSink::CallerEventStore,
290            Self::ChannelPollSucceeded => EventSink::CallerEventStore,
291            Self::ChannelPollFailed => EventSink::CallerEventStore,
292            Self::ChannelBackoffArmed => EventSink::CallerEventStore,
293            Self::ChannelBackoffReset => EventSink::CallerEventStore,
294            Self::ChannelHeartbeatPersistFailed => EventSink::CallerEventStore,
295            Self::ConfigLocked => EventSink::CallerEventStore,
296            Self::CheckpointOutcomeRecorded => EventSink::CallerEventStore,
297            Self::PhaseStarted => EventSink::CallerEventStore,
298            Self::PhaseCompleted => EventSink::CallerEventStore,
299            Self::PhaseCancelled => EventSink::CallerEventStore,
300            Self::Refusal => EventSink::CallerEventStore,
301            Self::GrantChange => EventSink::CallerEventStore,
302            Self::ToolSourceCorrected => EventSink::CallerEventStore,
303            Self::ToolRegistrationRestored => EventSink::CallerEventStore,
304            Self::ToolCalled => EventSink::CallerEventStore,
305        }
306    }
307
308    /// Return the canonical snake_case string for this event kind.
309    pub const fn name(self) -> &'static str {
310        match self {
311            Self::Audit => "audit",
312            Self::RecallExecuted => "recall_executed",
313            Self::RerankExecuted => "rerank_executed",
314            Self::SearchExecuted => "search_executed",
315            Self::ToolCheckDecided => "tool_check_decided",
316            Self::ToolRegistrationChanged => "tool_registration_changed",
317            Self::LinkCreated => "link_created",
318            Self::EntityCreated => "entity_created",
319            Self::EntityUpdated => "entity_updated",
320            Self::EntityDeleted => "entity_deleted",
321            Self::EntityMerged => "entity_merged",
322            Self::NoteMerged => "note_merged",
323            Self::NoteCreated => "note_created",
324            Self::NoteUpdated => "note_updated",
325            Self::NoteDeleted => "note_deleted",
326            Self::EdgeUpdated => "edge_updated",
327            Self::EdgeDeleted => "edge_deleted",
328            Self::TaskTransitioned => "task_transitioned",
329            Self::FeedbackExplicit => "feedback_explicit",
330            Self::FeedbackUnjudged => "feedback_unjudged",
331            Self::ProfileResolutionRecommended => "profile_resolution_recommended",
332            Self::ProfileMerged => "profile_merged",
333            Self::EmbeddingModelChanged => "embedding_model_changed",
334            Self::EmbeddingMigrationCompleted => "embedding_migration_completed",
335            Self::EmbeddingMigrationFailed => "embedding_migration_failed",
336            Self::EmbeddingDriftDetected => "embedding_drift_detected",
337            Self::EmbedderInitialized => "embedder_initialized",
338            Self::ProposalCreated => "proposal_created",
339            Self::ProposalReviewed => "proposal_reviewed",
340            Self::ProposalApplied => "proposal_applied",
341            Self::ProposalWithdrawn => "proposal_withdrawn",
342            Self::ChannelPollStarted => "channel_poll_started",
343            Self::ChannelPollSucceeded => "channel_poll_succeeded",
344            Self::ChannelPollFailed => "channel_poll_failed",
345            Self::ChannelBackoffArmed => "channel_backoff_armed",
346            Self::ChannelBackoffReset => "channel_backoff_reset",
347            Self::ChannelHeartbeatPersistFailed => "channel_heartbeat_persist_failed",
348            Self::ConfigLocked => "config_locked",
349            Self::CheckpointOutcomeRecorded => "checkpoint_outcome_recorded",
350            Self::PhaseStarted => "phase_started",
351            Self::PhaseCompleted => "phase_completed",
352            Self::PhaseCancelled => "phase_cancelled",
353            Self::Refusal => "refusal",
354            Self::GrantChange => "grant_change",
355            Self::ToolSourceCorrected => "tool_source_corrected",
356            Self::ToolRegistrationRestored => "tool_registration_restored",
357            Self::ToolCalled => "tool_called",
358        }
359    }
360}
361
362impl fmt::Display for EventKind {
363    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364        f.write_str(self.name())
365    }
366}
367
368const EVENT_KIND_VALID: &[&str] = &[
369    "audit",
370    "recall_executed",
371    "rerank_executed",
372    "search_executed",
373    "tool_check_decided",
374    "tool_registration_changed",
375    "link_created",
376    "entity_created",
377    "entity_updated",
378    "entity_deleted",
379    "entity_merged",
380    "note_merged",
381    "note_created",
382    "note_updated",
383    "note_deleted",
384    "edge_updated",
385    "edge_deleted",
386    "task_transitioned",
387    "feedback_explicit",
388    "feedback_unjudged",
389    "profile_resolution_recommended",
390    "profile_merged",
391    "embedding_model_changed",
392    "embedding_migration_completed",
393    "embedding_migration_failed",
394    "embedding_drift_detected",
395    "embedder_initialized",
396    "proposal_created",
397    "proposal_reviewed",
398    "proposal_applied",
399    "proposal_withdrawn",
400    "channel_poll_started",
401    "channel_poll_succeeded",
402    "channel_poll_failed",
403    "channel_backoff_armed",
404    "channel_backoff_reset",
405    "channel_heartbeat_persist_failed",
406    "config_locked",
407    "checkpoint_outcome_recorded",
408    "phase_started",
409    "phase_completed",
410    "phase_cancelled",
411    "refusal",
412    "grant_change",
413    "tool_source_corrected",
414    "tool_registration_restored",
415    "tool_called",
416];
417
418impl core::str::FromStr for EventKind {
419    type Err = crate::error::UnknownVariant;
420
421    fn from_str(s: &str) -> Result<Self, Self::Err> {
422        match s.trim().to_ascii_lowercase().as_str() {
423            "audit" => Ok(Self::Audit),
424            "recall_executed" => Ok(Self::RecallExecuted),
425            "rerank_executed" => Ok(Self::RerankExecuted),
426            "search_executed" => Ok(Self::SearchExecuted),
427            "tool_check_decided" => Ok(Self::ToolCheckDecided),
428            "tool_registration_changed" => Ok(Self::ToolRegistrationChanged),
429            "link_created" => Ok(Self::LinkCreated),
430            "entity_created" => Ok(Self::EntityCreated),
431            "entity_updated" => Ok(Self::EntityUpdated),
432            "entity_deleted" => Ok(Self::EntityDeleted),
433            "entity_merged" => Ok(Self::EntityMerged),
434            "note_merged" => Ok(Self::NoteMerged),
435            "note_created" => Ok(Self::NoteCreated),
436            "note_updated" => Ok(Self::NoteUpdated),
437            "note_deleted" => Ok(Self::NoteDeleted),
438            "edge_updated" => Ok(Self::EdgeUpdated),
439            "edge_deleted" => Ok(Self::EdgeDeleted),
440            "task_transitioned" => Ok(Self::TaskTransitioned),
441            "feedback_explicit" => Ok(Self::FeedbackExplicit),
442            "feedback_unjudged" => Ok(Self::FeedbackUnjudged),
443            "profile_resolution_recommended" => Ok(Self::ProfileResolutionRecommended),
444            "profile_merged" => Ok(Self::ProfileMerged),
445            "embedding_model_changed" => Ok(Self::EmbeddingModelChanged),
446            "embedding_migration_completed" => Ok(Self::EmbeddingMigrationCompleted),
447            "embedding_migration_failed" => Ok(Self::EmbeddingMigrationFailed),
448            "embedding_drift_detected" => Ok(Self::EmbeddingDriftDetected),
449            "embedder_initialized" => Ok(Self::EmbedderInitialized),
450            "proposal_created" => Ok(Self::ProposalCreated),
451            "proposal_reviewed" => Ok(Self::ProposalReviewed),
452            "proposal_applied" => Ok(Self::ProposalApplied),
453            "proposal_withdrawn" => Ok(Self::ProposalWithdrawn),
454            "channel_poll_started" => Ok(Self::ChannelPollStarted),
455            "channel_poll_succeeded" => Ok(Self::ChannelPollSucceeded),
456            "channel_poll_failed" => Ok(Self::ChannelPollFailed),
457            "channel_backoff_armed" => Ok(Self::ChannelBackoffArmed),
458            "channel_backoff_reset" => Ok(Self::ChannelBackoffReset),
459            "channel_heartbeat_persist_failed" => Ok(Self::ChannelHeartbeatPersistFailed),
460            "config_locked" => Ok(Self::ConfigLocked),
461            "checkpoint_outcome_recorded" => Ok(Self::CheckpointOutcomeRecorded),
462            "phase_started" => Ok(Self::PhaseStarted),
463            "phase_completed" => Ok(Self::PhaseCompleted),
464            "phase_cancelled" => Ok(Self::PhaseCancelled),
465            "refusal" => Ok(Self::Refusal),
466            "grant_change" => Ok(Self::GrantChange),
467            "tool_source_corrected" => Ok(Self::ToolSourceCorrected),
468            "tool_registration_restored" => Ok(Self::ToolRegistrationRestored),
469            "tool_called" => Ok(Self::ToolCalled),
470            other => Err(crate::error::UnknownVariant::new(
471                "event_kind",
472                other,
473                EVENT_KIND_VALID,
474            )),
475        }
476    }
477}
478
479/// A reference to the logical aggregate that an event belongs to.
480///
481/// Used to thread related events (e.g. proposal lifecycle events) into a
482/// single auditable chain identified by `kind` and `id`.
483#[derive(Clone, Debug, PartialEq, Eq)]
484#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
485pub struct AggregateRef {
486    /// The aggregate type string (e.g. `"proposal"`).
487    pub kind: String,
488    /// The aggregate instance identifier.
489    pub id: Id128,
490}
491
492/// Typed payload for an [`Event`], dispatched by [`EventKind`].
493///
494/// The `Json` variant is a catch-all for events whose payload has not yet
495/// been promoted to a structured type. All other variants carry a concrete
496/// typed struct that can be pattern-matched without round-tripping through JSON.
497#[derive(Clone, Debug, PartialEq)]
498#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
499#[cfg_attr(
500    feature = "serde",
501    serde(tag = "kind", content = "payload", rename_all = "snake_case")
502)]
503pub enum EventPayload {
504    /// Raw JSON payload for untyped events.
505    Json(String),
506    /// Structured payload for a rerank pass event.
507    RerankExecuted(RerankExecutedPayload),
508    /// Structured payload for a tool-use policy decision.
509    ToolCheckDecided(ToolCheckDecidedPayload),
510    /// A registration correction without disclosing the changed field values.
511    ToolRegistrationChanged(ToolRegistrationChangedPayload),
512    /// An in-place source correction of a registry row.
513    ToolSourceCorrected(ToolSourceCorrectedPayload),
514    /// The restore of a retired registry row.
515    ToolRegistrationRestored(ToolRegistrationRestoredPayload),
516    /// One `tool.call` after its decision allowed it.
517    ToolCalled(ToolCalledPayload),
518    /// Structured payload for a proposal-created event (requires `serde` feature).
519    #[cfg(feature = "serde")]
520    ProposalCreated(ProposalCreatedPayload),
521    /// Structured payload for a proposal-reviewed event.
522    ProposalReviewed(ProposalReviewedPayload),
523    /// Structured payload for a proposal-applied event.
524    ProposalApplied(ProposalAppliedPayload),
525    /// Structured payload for a proposal-withdrawn event.
526    ProposalWithdrawn(ProposalWithdrawnPayload),
527}
528
529impl Default for EventPayload {
530    fn default() -> Self {
531        Self::Json("{}".into())
532    }
533}
534
535/// The decision computed for one tool-use policy check.
536#[derive(Clone, Debug, PartialEq, Eq)]
537#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
538pub struct ToolCheckDecidedPayload {
539    pub actor: String,
540    pub tool: String,
541    pub registered: bool,
542    pub decision: String,
543    pub source: String,
544    pub id: Option<String>,
545    pub scope: Option<String>,
546    pub caller_verb: String,
547    /// Id of the registry row the decision was evaluated against. Set for
548    /// `tool.call` (ADR-180 Amendment 9 item 2) and absent otherwise.
549    #[cfg_attr(
550        feature = "serde",
551        serde(default, skip_serializing_if = "Option::is_none")
552    )]
553    pub registry_id: Option<String>,
554    /// Definition digest of that registry row, set and absent with `registry_id`.
555    #[cfg_attr(
556        feature = "serde",
557        serde(default, skip_serializing_if = "Option::is_none")
558    )]
559    pub definition_digest: Option<String>,
560    /// Digest of the call's arguments, set when the decision was computed for
561    /// a described call (ADR-180 Amendment 14 item 5). The arguments are
562    /// deliberately absent.
563    #[cfg_attr(
564        feature = "serde",
565        serde(default, skip_serializing_if = "Option::is_none")
566    )]
567    pub args_digest: Option<String>,
568}
569
570/// One `tool.call` that its decision allowed (ADR-180 Amendment 9 item 9). The
571/// call's arguments and result are deliberately absent.
572#[derive(Clone, Debug, PartialEq, Eq)]
573#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
574pub struct ToolCalledPayload {
575    /// Authenticated actor the call was decided for.
576    pub actor: String,
577    /// The registry row's name, or the reference the caller passed when it
578    /// resolved to no row.
579    pub tool: String,
580    /// Canonical full UUID of the registry row, absent for an unregistered name.
581    pub registry_id: Option<String>,
582    /// The row's stored source, absent for an unregistered name.
583    pub source: Option<String>,
584    /// The verb dispatched, absent when the call was refused before dispatch.
585    pub target_verb: Option<String>,
586    /// The decision's source: `grant`, `policy` or `default`.
587    pub decision_source: String,
588    /// The grant or policy id the decision cited.
589    pub decision_id: Option<String>,
590    /// Uses left on the counted grant after this call's use was spent.
591    pub uses_left: Option<i64>,
592    /// `ok`, `refused`, `failed` or `unknown`.
593    pub outcome: String,
594    /// The refusal or failure's class, from a fixed vocabulary.
595    pub error_class: Option<String>,
596    /// The refusal or failure's reason, from a fixed vocabulary.
597    pub error_reason: Option<String>,
598    /// Digest of the arguments dispatched, on every call (ADR-180 Amendment
599    /// 14 item 5).
600    #[cfg_attr(
601        feature = "serde",
602        serde(default, skip_serializing_if = "Option::is_none")
603    )]
604    pub args_digest: Option<String>,
605    /// The request whose stored call this call ran, on a call run by
606    /// `tool.call(request_id)` (ADR-180 Amendment 14 item 5).
607    #[cfg_attr(
608        feature = "serde",
609        serde(default, skip_serializing_if = "Option::is_none")
610    )]
611    pub request_id: Option<String>,
612    /// `true` on a call run by `tool.call(request_id)`.
613    #[cfg_attr(
614        feature = "serde",
615        serde(default, skip_serializing_if = "Option::is_none")
616    )]
617    pub resumed: Option<bool>,
618}
619
620/// A correction to the four policy inputs covered by a tool registration digest.
621/// Values of the corrected fields are deliberately absent.
622#[derive(Clone, Debug, PartialEq, Eq)]
623#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
624pub struct ToolRegistrationChangedPayload {
625    /// Authenticated actor stamped into the event row.
626    pub actor: String,
627    /// Canonical full UUID of the registry row.
628    pub id: String,
629    /// Canonical policy-input digest before the correction.
630    pub digest_before: String,
631    /// Canonical policy-input digest after the correction.
632    pub digest_after: String,
633}
634
635/// An in-place correction of a registry row's source (ADR-180 Amendment 13).
636#[derive(Clone, Debug, PartialEq, Eq)]
637#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
638pub struct ToolSourceCorrectedPayload {
639    /// Authenticated actor stamped into the event row.
640    pub actor: String,
641    /// Canonical full UUID of the registry row.
642    pub id: String,
643    /// The stored source before the correction.
644    pub source_before: String,
645    /// The stored source after the correction.
646    pub source_after: String,
647    /// Ids of the exact-name `allow` policies the correction retired.
648    pub policies_retired: Vec<String>,
649}
650
651/// The restore of a retired registry row (ADR-180 Amendment 13).
652#[derive(Clone, Debug, PartialEq, Eq)]
653#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
654pub struct ToolRegistrationRestoredPayload {
655    /// Authenticated actor stamped into the event row.
656    pub actor: String,
657    /// Canonical full UUID of the registry row.
658    pub id: String,
659    /// The row's retirement time, in microseconds since the Unix epoch.
660    pub retired_at: i64,
661    /// The time the restore recorded on the row, in microseconds since the Unix epoch.
662    pub restored_at: i64,
663}
664
665/// Implementation that produced a rerank event (ADR-042 Amendment 1).
666/// Events written before the discriminator existed are native reranks.
667#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
668#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
669#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
670pub enum RerankerKind {
671    #[default]
672    Native,
673    Weighted,
674}
675
676/// Payload for a rerank pass event, recording per-candidate scores.
677///
678/// All score values (`reranked` section scores, `final_scores`) must be finite.
679/// When the `serde` feature is enabled, deserialization rejects non-finite scores.
680#[derive(Clone, Debug, PartialEq)]
681#[cfg_attr(feature = "serde", derive(serde::Serialize))]
682pub struct RerankExecutedPayload {
683    /// Native model or weighted feature scoring; legacy events default to native.
684    pub reranker: RerankerKind,
685    /// Brain profile that served this rerank, if any.
686    pub served_by_profile_id: Option<String>,
687    /// Model used for reranking; absent for weighted feature scoring.
688    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
689    pub model_id: Option<Id128>,
690    /// Opaque caller-supplied query correlation; never generated or parsed as a UUID.
691    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
692    pub query_id: Option<String>,
693    /// Positive recognized feature weights, in scoring order.
694    pub tiers: Vec<String>,
695    /// Configured keys unknown to weighted scoring, in lexical order.
696    pub ignored_weights: Vec<String>,
697    /// Candidates without a parseable UUID, omitted from the three ID arrays.
698    pub unidentified_candidates: usize,
699    /// Candidate IDs in input order.
700    pub candidates: Vec<Id128>,
701    /// Per-candidate named sub-scores from the reranker.
702    pub reranked: Vec<(Id128, Vec<(String, f32)>)>,
703    /// Final aggregated score per candidate.
704    pub final_scores: Vec<(Id128, f32)>,
705    /// Wall-clock latency of the rerank operation in microseconds.
706    pub latency_us: u64,
707    /// Whether a brain hook was applied during this rerank.
708    pub hook_applied: bool,
709    /// Whether the hook matched the intended target.
710    pub hook_target_match: bool,
711}
712
713impl RerankExecutedPayload {
714    /// Return `true` if all score values are finite.
715    pub fn is_valid(&self) -> bool {
716        let reranked_ok = self
717            .reranked
718            .iter()
719            .all(|(_, scores)| scores.iter().all(|(_, s)| s.is_finite()));
720        let final_ok = self.final_scores.iter().all(|(_, s)| s.is_finite());
721        reranked_ok && final_ok
722    }
723}
724
725#[cfg(feature = "serde")]
726impl<'de> serde::Deserialize<'de> for RerankExecutedPayload {
727    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
728    where
729        D: serde::Deserializer<'de>,
730    {
731        #[derive(serde::Deserialize)]
732        struct Raw {
733            #[serde(default)]
734            reranker: RerankerKind,
735            served_by_profile_id: Option<String>,
736            model_id: Option<Id128>,
737            query_id: Option<String>,
738            #[serde(default)]
739            tiers: Vec<String>,
740            #[serde(default)]
741            ignored_weights: Vec<String>,
742            #[serde(default)]
743            unidentified_candidates: usize,
744            candidates: Vec<Id128>,
745            reranked: Vec<(Id128, Vec<(String, f32)>)>,
746            final_scores: Vec<(Id128, f32)>,
747            latency_us: u64,
748            hook_applied: bool,
749            hook_target_match: bool,
750        }
751
752        let raw = Raw::deserialize(deserializer)?;
753
754        for (_, score) in &raw.final_scores {
755            if !score.is_finite() {
756                return Err(serde::de::Error::custom(alloc::format!(
757                    "RerankExecutedPayload final_scores must be finite, got {score}"
758                )));
759            }
760        }
761        for (_, sections) in &raw.reranked {
762            for (section_name, score) in sections {
763                if !score.is_finite() {
764                    return Err(serde::de::Error::custom(alloc::format!(
765                        "RerankExecutedPayload reranked section '{section_name}' score must be finite, got {score}"
766                    )));
767                }
768            }
769        }
770
771        Ok(RerankExecutedPayload {
772            reranker: raw.reranker,
773            served_by_profile_id: raw.served_by_profile_id,
774            model_id: raw.model_id,
775            query_id: raw.query_id,
776            tiers: raw.tiers,
777            ignored_weights: raw.ignored_weights,
778            unidentified_candidates: raw.unidentified_candidates,
779            candidates: raw.candidates,
780            reranked: raw.reranked,
781            final_scores: raw.final_scores,
782            latency_us: raw.latency_us,
783            hook_applied: raw.hook_applied,
784            hook_target_match: raw.hook_target_match,
785        })
786    }
787}
788
789/// Payload for the `ProposalCreated` event — captures the full initial proposal state.
790#[cfg(feature = "serde")]
791#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
792pub struct ProposalCreatedPayload {
793    pub proposal_id: Id128,
794    pub proposer: String,
795    pub title: String,
796    pub description: String,
797    pub changeset: ProposalChangeset,
798    pub reviewers: Vec<String>,
799    pub expiry: Option<crate::Timestamp>,
800    pub parent_id: Option<Id128>,
801}
802
803/// Structured draft for adding a new entity via a proposal.
804///
805/// Fields mirror the `create(kind=<entity kind>)` verb surface; `kind` is
806/// validated against the closed 8-kind entity taxonomy at apply time.
807#[cfg(feature = "serde")]
808#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
809pub struct EntityDraft {
810    /// Entity kind — must be one of the 8 closed entity kind values.
811    pub kind: String,
812    /// Human-readable name (required).
813    pub name: String,
814    /// Optional long-form description.
815    #[serde(skip_serializing_if = "Option::is_none")]
816    pub description: Option<String>,
817    /// Arbitrary structured metadata.
818    #[serde(skip_serializing_if = "Option::is_none")]
819    pub properties: Option<serde_json::Value>,
820    /// Classification tags.
821    #[serde(default, skip_serializing_if = "Vec::is_empty")]
822    pub tags: Vec<String>,
823}
824
825/// Structured patch for modifying an existing entity via a proposal.
826///
827/// Absent fields mean "leave unchanged". Setting `description` or
828/// `entity_type` to `null` explicitly clears it; a string `entity_type` sets
829/// it, validated against the kind's registered vocabulary at apply time.
830#[cfg(feature = "serde")]
831#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
832pub struct ProposalEntityPatch {
833    #[serde(skip_serializing_if = "Option::is_none")]
834    pub name: Option<String>,
835    /// `null` clears the description; absent leaves it unchanged.
836    #[serde(
837        default,
838        skip_serializing_if = "Option::is_none",
839        with = "serde_opt_opt"
840    )]
841    pub description: Option<Option<String>>,
842    #[serde(skip_serializing_if = "Option::is_none")]
843    pub properties: Option<serde_json::Value>,
844    #[serde(skip_serializing_if = "Option::is_none")]
845    pub tags: Option<Vec<String>>,
846    /// ADR-014 tri-state: absent leaves the type unchanged, `null` explicitly
847    /// clears it, a string sets it (validated against the kind's vocabulary
848    /// at apply time, per ADR-046 parity with the runtime entity update).
849    #[serde(
850        default,
851        skip_serializing_if = "Option::is_none",
852        with = "serde_opt_opt"
853    )]
854    pub entity_type: Option<Option<String>>,
855}
856
857/// Structured draft for adding a new note via a proposal.
858///
859/// Fields mirror the `create(kind=<note kind>)` verb surface.
860#[cfg(feature = "serde")]
861#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
862pub struct NoteDraft {
863    /// Note kind string (validated by the loaded pack at apply time).
864    pub kind: String,
865    /// Note body / content (required).
866    pub content: String,
867    /// Optional short name.
868    #[serde(skip_serializing_if = "Option::is_none")]
869    pub name: Option<String>,
870    /// Arbitrary structured metadata.
871    #[serde(skip_serializing_if = "Option::is_none")]
872    pub properties: Option<serde_json::Value>,
873}
874
875/// Serde helper for `Option<Option<T>>` — distinguishes absent vs. explicit null.
876#[cfg(feature = "serde")]
877mod serde_opt_opt {
878    use serde::{Deserialize, Deserializer, Serialize, Serializer};
879
880    pub fn serialize<T, S>(val: &Option<Option<T>>, s: S) -> Result<S::Ok, S::Error>
881    where
882        T: Serialize,
883        S: Serializer,
884    {
885        match val {
886            None => unreachable!("skip_serializing_if guards the None case"),
887            Some(inner) => inner.serialize(s),
888        }
889    }
890
891    pub fn deserialize<'de, T, D>(d: D) -> Result<Option<Option<T>>, D::Error>
892    where
893        T: Deserialize<'de>,
894        D: Deserializer<'de>,
895    {
896        let opt: Option<T> = Option::deserialize(d)?;
897        Ok(Some(opt))
898    }
899}
900
901/// Natural key of a stored edge in a proposal: the edge from `source` to
902/// `target` with `relation`.
903#[cfg(feature = "serde")]
904#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
905pub struct ProposalEdgeKey {
906    pub source: Id128,
907    pub target: Id128,
908    pub relation: crate::EdgeRelation,
909}
910
911#[cfg(feature = "serde")]
912impl ProposalEdgeKey {
913    /// True when both keys name the same edge. A symmetric relation names one
914    /// edge whichever endpoint comes first.
915    fn names_same_edge(
916        &self,
917        source: &Id128,
918        target: &Id128,
919        relation: &crate::EdgeRelation,
920    ) -> bool {
921        if self.relation != *relation {
922            return false;
923        }
924        (self.source == *source && self.target == *target)
925            || (relation.is_symmetric() && self.source == *target && self.target == *source)
926    }
927}
928
929/// The edge a `SupersedeEdge` change adds. Fields and validation match
930/// `AddEdge`.
931#[cfg(feature = "serde")]
932#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
933pub struct ProposalEdgeDraft {
934    pub source: Id128,
935    pub target: Id128,
936    pub relation: crate::EdgeRelation,
937    #[serde(default)]
938    pub weight: Option<f32>,
939    #[serde(default, skip_serializing_if = "Option::is_none")]
940    pub metadata: Option<serde_json::Value>,
941}
942
943#[cfg(feature = "serde")]
944fn validate_proposal_edge_weight(
945    variant: &str,
946    weight: Option<f32>,
947) -> Result<(), alloc::string::String> {
948    if let Some(w) = weight {
949        if !w.is_finite() {
950            return Err(alloc::format!(
951                "ProposalChangeset {variant} weight must be finite, got {w}"
952            ));
953        }
954        if !crate::validate_edge_weight(f64::from(w)) {
955            return Err(alloc::format!(
956                "ProposalChangeset {variant} weight must be in [0.0, 1.0], got {w}"
957            ));
958        }
959    }
960    Ok(())
961}
962
963/// The set of KG mutations a proposal intends to apply as a proposal changeset.
964#[cfg(feature = "serde")]
965#[derive(Clone, Debug, PartialEq, serde::Serialize)]
966#[serde(tag = "kind", rename_all = "snake_case")]
967pub enum ProposalChangeset {
968    /// Add a new entity. `entity.kind` validated at apply time.
969    AddEntity {
970        entity: EntityDraft,
971    },
972    /// Modify an existing entity's properties / tags / description / entity
973    /// type (absent = unchanged, null = clear, string = set-and-validate).
974    UpdateEntity {
975        id: Id128,
976        patch: ProposalEntityPatch,
977    },
978    /// Add a typed edge. `weight` must be finite and in `[0.0, 1.0]` if present.
979    /// Metadata uses the same apply-time validation as `link`.
980    AddEdge {
981        source: Id128,
982        target: Id128,
983        relation: crate::EdgeRelation,
984        weight: Option<f32>,
985        #[serde(skip_serializing_if = "Option::is_none")]
986        metadata: Option<serde_json::Value>,
987    },
988    /// Retire the live edge with this natural key by soft deletion, so
989    /// `restore` on the edge's id brings it back. Applying fails, writing
990    /// nothing, when no live edge has the key.
991    RetireEdge {
992        source: Id128,
993        target: Id128,
994        relation: crate::EdgeRelation,
995    },
996    /// Retire the live edge named by `old` as `RetireEdge` does and add `new`
997    /// as `AddEdge` does, in one atomic unit: both land or neither does.
998    SupersedeEdge {
999        old: ProposalEdgeKey,
1000        new: ProposalEdgeDraft,
1001    },
1002    /// Add a note (entity-annotating or stand-alone).
1003    AddNote {
1004        note: NoteDraft,
1005    },
1006    MergeEntities {
1007        into: Id128,
1008        from: Id128,
1009    },
1010    SupersedeEntity {
1011        old: Id128,
1012        new: Id128,
1013    },
1014    Canonical {
1015        schema_version: u32,
1016        delta: String,
1017    },
1018    Compound {
1019        steps: Vec<ProposalChangeset>,
1020    },
1021}
1022
1023#[cfg(feature = "serde")]
1024impl ProposalChangeset {
1025    fn validate(&self) -> Result<(), alloc::string::String> {
1026        match self {
1027            Self::AddEdge { weight, .. } => validate_proposal_edge_weight("AddEdge", *weight),
1028            Self::SupersedeEdge { old, new } => {
1029                validate_proposal_edge_weight("SupersedeEdge", new.weight)?;
1030                if old.names_same_edge(&new.source, &new.target, &new.relation) {
1031                    return Err(
1032                        "ProposalChangeset SupersedeEdge new must name a different edge than old"
1033                            .into(),
1034                    );
1035                }
1036                Ok(())
1037            }
1038            Self::Compound { steps } => {
1039                for step in steps {
1040                    if matches!(step, Self::Canonical { .. }) {
1041                        return Err("Canonical proposal changesets must be top-level".into());
1042                    }
1043                    step.validate()?;
1044                }
1045                Ok(())
1046            }
1047            _ => Ok(()),
1048        }
1049    }
1050}
1051
1052#[cfg(feature = "serde")]
1053impl<'de> serde::Deserialize<'de> for ProposalChangeset {
1054    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1055    where
1056        D: serde::Deserializer<'de>,
1057    {
1058        #[derive(serde::Deserialize)]
1059        #[serde(deny_unknown_fields)]
1060        struct CanonicalFields {
1061            schema_version: u32,
1062            delta: String,
1063        }
1064
1065        #[derive(serde::Deserialize)]
1066        #[serde(tag = "kind", rename_all = "snake_case")]
1067        enum ProposalChangesetRaw {
1068            AddEntity {
1069                entity: EntityDraft,
1070            },
1071            UpdateEntity {
1072                id: Id128,
1073                patch: ProposalEntityPatch,
1074            },
1075            AddEdge {
1076                source: Id128,
1077                target: Id128,
1078                relation: crate::EdgeRelation,
1079                weight: Option<f32>,
1080                metadata: Option<serde_json::Value>,
1081            },
1082            RetireEdge {
1083                source: Id128,
1084                target: Id128,
1085                relation: crate::EdgeRelation,
1086            },
1087            SupersedeEdge {
1088                old: ProposalEdgeKey,
1089                new: ProposalEdgeDraft,
1090            },
1091            AddNote {
1092                note: NoteDraft,
1093            },
1094            MergeEntities {
1095                into: Id128,
1096                from: Id128,
1097            },
1098            SupersedeEntity {
1099                old: Id128,
1100                new: Id128,
1101            },
1102            Canonical(CanonicalFields),
1103            Compound {
1104                steps: Vec<ProposalChangeset>,
1105            },
1106        }
1107
1108        let raw = ProposalChangesetRaw::deserialize(deserializer)?;
1109        let cs = match raw {
1110            ProposalChangesetRaw::AddEntity { entity } => Self::AddEntity { entity },
1111            ProposalChangesetRaw::UpdateEntity { id, patch } => Self::UpdateEntity { id, patch },
1112            ProposalChangesetRaw::AddEdge {
1113                source,
1114                target,
1115                relation,
1116                weight,
1117                metadata,
1118            } => Self::AddEdge {
1119                source,
1120                target,
1121                relation,
1122                weight,
1123                metadata,
1124            },
1125            ProposalChangesetRaw::RetireEdge {
1126                source,
1127                target,
1128                relation,
1129            } => Self::RetireEdge {
1130                source,
1131                target,
1132                relation,
1133            },
1134            ProposalChangesetRaw::SupersedeEdge { old, new } => Self::SupersedeEdge { old, new },
1135            ProposalChangesetRaw::AddNote { note } => Self::AddNote { note },
1136            ProposalChangesetRaw::MergeEntities { into, from } => {
1137                Self::MergeEntities { into, from }
1138            }
1139            ProposalChangesetRaw::SupersedeEntity { old, new } => {
1140                Self::SupersedeEntity { old, new }
1141            }
1142            ProposalChangesetRaw::Canonical(CanonicalFields {
1143                schema_version,
1144                delta,
1145            }) => Self::Canonical {
1146                schema_version,
1147                delta,
1148            },
1149            ProposalChangesetRaw::Compound { steps } => Self::Compound { steps },
1150        };
1151        cs.validate().map_err(serde::de::Error::custom)?;
1152        Ok(cs)
1153    }
1154}
1155
1156#[cfg(not(feature = "serde"))]
1157#[derive(Clone, Debug, PartialEq)]
1158pub enum ProposalChangeset {
1159    AddEdge {
1160        source: Id128,
1161        target: Id128,
1162        relation: crate::EdgeRelation,
1163        weight: Option<f32>,
1164    },
1165    MergeEntities {
1166        into: Id128,
1167        from: Id128,
1168    },
1169    SupersedeEntity {
1170        old: Id128,
1171        new: Id128,
1172    },
1173    Canonical {
1174        schema_version: u32,
1175        delta: String,
1176    },
1177    Compound {
1178        steps: Vec<ProposalChangeset>,
1179    },
1180}
1181
1182/// Payload for the `ProposalReviewed` event — records a single reviewer's decision.
1183#[derive(Clone, Debug, PartialEq)]
1184#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1185pub struct ProposalReviewedPayload {
1186    pub proposal_id: Id128,
1187    pub reviewer: String,
1188    pub decision: ProposalDecision,
1189    pub comment: Option<String>,
1190}
1191
1192/// A reviewer's decision on a proposal.
1193#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1194#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1195#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
1196pub enum ProposalDecision {
1197    /// The reviewer approved the proposal for application.
1198    Approve,
1199    /// The reviewer rejected the proposal; it will not be applied.
1200    Reject,
1201    /// The reviewer left a comment without blocking the proposal.
1202    Comment,
1203    /// The reviewer requested changes before the proposal can proceed.
1204    RequestChanges,
1205}
1206
1207impl ProposalDecision {
1208    /// Returns the bare variant name as a lowercase string, matching the serde
1209    /// `rename_all = "snake_case"` representation.  Use this when storing the
1210    /// decision as a plain TEXT column — **not** `serde_json::to_string`, which
1211    /// would produce a JSON-quoted string (`"\"approve\""` instead of `"approve"`).
1212    pub fn as_str(self) -> &'static str {
1213        match self {
1214            Self::Approve => "approve",
1215            Self::Reject => "reject",
1216            Self::Comment => "comment",
1217            Self::RequestChanges => "request_changes",
1218        }
1219    }
1220}
1221
1222/// Payload for the `ProposalApplied` event — records the outcome of the apply attempt.
1223#[derive(Clone, Debug, PartialEq)]
1224#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1225pub struct ProposalAppliedPayload {
1226    pub proposal_id: Id128,
1227    pub applied_at: crate::Timestamp,
1228    pub applied_by: String,
1229    pub result: ApplyResult,
1230    #[cfg_attr(
1231        feature = "serde",
1232        serde(default, skip_serializing_if = "Option::is_none")
1233    )]
1234    pub preimage: Option<ProposalPreimageStatus>,
1235}
1236
1237/// Whether an apply result carries checked stage-time preimages.
1238#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1239#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1240#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
1241pub enum ProposalPreimageStatus {
1242    None,
1243    Captured,
1244}
1245
1246/// Outcome of applying a proposal: either all steps succeeded or the apply failed with an error.
1247#[derive(Clone, Debug, PartialEq)]
1248#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1249#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
1250pub enum ApplyResult {
1251    Success {
1252        created_records: Vec<Id128>,
1253    },
1254    Failed {
1255        error: String,
1256        applied_step_count: u32,
1257    },
1258}
1259
1260/// Payload for the `ProposalWithdrawn` event — records who withdrew and an optional reason.
1261#[derive(Clone, Debug, PartialEq)]
1262#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1263pub struct ProposalWithdrawnPayload {
1264    pub proposal_id: Id128,
1265    pub by: String,
1266    pub reason: Option<String>,
1267}
1268
1269/// Builder for events. Used by the verb dispatch path.
1270pub struct EventBuilder {
1271    verb: String,
1272    substrate: SubstrateKind,
1273    actor: Option<String>,
1274    kind: EventKind,
1275    payload: EventPayload,
1276    payload_schema_version: u32,
1277    profile_state_version: Option<u64>,
1278    aggregate: Option<AggregateRef>,
1279}
1280
1281impl EventBuilder {
1282    /// Create a new builder for an event produced by `verb` acting on `substrate` as `actor`.
1283    pub fn new(
1284        verb: impl Into<String>,
1285        substrate: SubstrateKind,
1286        actor: impl Into<String>,
1287    ) -> Self {
1288        Self {
1289            verb: verb.into(),
1290            substrate,
1291            actor: Some(actor.into()),
1292            kind: EventKind::Audit,
1293            payload: EventPayload::default(),
1294            payload_schema_version: 1,
1295            profile_state_version: None,
1296            aggregate: None,
1297        }
1298    }
1299
1300    /// Override the event kind discriminant.
1301    pub fn kind(mut self, kind: EventKind) -> Self {
1302        self.kind = kind;
1303        self
1304    }
1305
1306    /// Set the typed payload for this event.
1307    pub fn payload(mut self, payload: EventPayload) -> Self {
1308        self.payload = payload;
1309        self
1310    }
1311
1312    /// Set the payload schema version (defaults to 1).
1313    pub fn payload_schema_version(mut self, version: u32) -> Self {
1314        self.payload_schema_version = version;
1315        self
1316    }
1317
1318    /// Record the brain profile state version observed at emit time.
1319    pub fn profile_state_version(mut self, version: u64) -> Self {
1320        self.profile_state_version = Some(version);
1321        self
1322    }
1323
1324    /// Thread this event into an aggregate chain.
1325    pub fn aggregate(mut self, aggregate: AggregateRef) -> Self {
1326        self.aggregate = Some(aggregate);
1327        self
1328    }
1329
1330    /// Consume the builder and produce an [`Event`] with the given `header`.
1331    pub fn build(self, header: Header) -> Event {
1332        Event {
1333            header,
1334            verb: self.verb,
1335            substrate: self.substrate,
1336            actor: self.actor,
1337            kind: self.kind,
1338            payload: self.payload,
1339            payload_schema_version: self.payload_schema_version,
1340            profile_state_version: self.profile_state_version,
1341            aggregate: self.aggregate,
1342        }
1343    }
1344}
1345
1346#[cfg(test)]
1347#[path = "event_tests.rs"]
1348mod tests;
1349
1350#[cfg(all(test, feature = "serde"))]
1351#[path = "event_canonical_tests.rs"]
1352mod canonical_tests;