返回 CodeWhale
events.rs
根目录 / crates / engine / src / work_graph / events.rs
1 //! Changes, observations, and receipts — the reducer's entire input/output
2 //! vocabulary.
3 //!
4 //! The reducer never reads clocks or RNG: [`ChangeCtx`] carries the timestamp,
5 //! the session identity used for deterministic ID derivation, and an optional
6 //! idempotency key. Same snapshot + same change + same ctx ⇒ same result,
7 //! always.
8 //!
9 //! Spec-silent shapes chosen minimally here (documented on each type):
10 //! [`WorkNodePatch`], [`WorkGraphProposal`], [`ApprovalRef`], and the
11 //! placeholder observation types that later slices' liveness adapters will
12 //! feed ([`OperationObservation`], [`OwnerState`], [`CancelOutcome`]).
13
14 use serde::{Deserialize, Serialize};
15
16 use super::ids::{ChangeId, ProposalId, WorkEdgeId, WorkNodeId};
17 use super::model::{
18 AcceptanceRequirement, CompatProjectionState, EvidenceRef, IdempotencyKey, NodeState,
19 OperationBinding, Provenance, Ts, WorkActivityEvent, WorkEdge, WorkNode,
20 };
21
22 /// A single mutation of the work graph. The reducer is the only write path;
23 /// UI, tools, and runtime adapters all speak this vocabulary.
24 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25 #[serde(rename_all = "snake_case")]
26 // Variants intentionally carry full payloads (a node, a proposal) rather than
27 // boxed indirection: changes are transient values, not stored long-term.
28 #[allow(clippy::large_enum_variant)]
29 pub enum WorkGraphChange {
30 AddNode {
31 node: WorkNode,
32 },
33 UpdateNode {
34 id: WorkNodeId,
35 patch: WorkNodePatch,
36 },
37 AddEdge {
38 edge: WorkEdge,
39 },
40 RemoveEdge {
41 id: WorkEdgeId,
42 },
43 BindOperation {
44 node: WorkNodeId,
45 binding: OperationBinding,
46 },
47 ReconcileOperation {
48 node: WorkNodeId,
49 obs: OperationObservation,
50 },
51 AttachEvidence {
52 node: WorkNodeId,
53 evidence: EvidenceRef,
54 },
55 ProposePlanDiff {
56 proposal: WorkGraphProposal,
57 },
58 /// Explicitly retire a pending proposal before a replacement is
59 /// proposed. This keeps repeated "Revise plan" turns reviewable without
60 /// silently rewriting or accumulating stale proposals.
61 WithdrawPlanDiff {
62 proposal_id: ProposalId,
63 },
64 AcceptPlanDiff {
65 proposal_id: ProposalId,
66 approval: ApprovalRef,
67 },
68 Supersede {
69 old: WorkNodeId,
70 replacement: WorkNodeId,
71 },
72 /// Atomically replace the inputs for the legacy Plan/To-do projections.
73 ReplaceCompatProjection {
74 compat: CompatProjectionState,
75 },
76 /// Record the canonical digest of a completed legacy import.
77 SetImportDigest {
78 digest: String,
79 },
80 /// Append one bounded, configuration-only activity receipt.
81 RecordActivity {
82 event: WorkActivityEvent,
83 },
84 /// Evict the oldest ended, non-durable Operation nodes beyond `keep`
85 /// (#6842). See `reducer::prune_ended_operations` for eligibility.
86 PruneEndedOperations {
87 keep: usize,
88 },
89 }
90
91 impl WorkGraphChange {
92 /// Stable discriminant name recorded on receipts. Names only — receipts
93 /// never carry payload text.
94 #[must_use]
95 pub fn kind_name(&self) -> &'static str {
96 match self {
97 WorkGraphChange::AddNode { .. } => "add_node",
98 WorkGraphChange::UpdateNode { .. } => "update_node",
99 WorkGraphChange::AddEdge { .. } => "add_edge",
100 WorkGraphChange::RemoveEdge { .. } => "remove_edge",
101 WorkGraphChange::BindOperation { .. } => "bind_operation",
102 WorkGraphChange::ReconcileOperation {
103 obs: OperationObservation::OwnerUnreadable { .. },
104 ..
105 } => "reconcile_operation_owner_unreadable",
106 WorkGraphChange::ReconcileOperation { .. } => "reconcile_operation",
107 WorkGraphChange::AttachEvidence { .. } => "attach_evidence",
108 WorkGraphChange::ProposePlanDiff { .. } => "propose_plan_diff",
109 WorkGraphChange::WithdrawPlanDiff { .. } => "withdraw_plan_diff",
110 WorkGraphChange::AcceptPlanDiff { .. } => "accept_plan_diff",
111 WorkGraphChange::Supersede { .. } => "supersede",
112 WorkGraphChange::ReplaceCompatProjection { .. } => "replace_compat_projection",
113 WorkGraphChange::SetImportDigest { .. } => "set_import_digest",
114 WorkGraphChange::RecordActivity { .. } => "record_activity",
115 WorkGraphChange::PruneEndedOperations { .. } => "prune_ended_operations",
116 }
117 }
118 }
119
120 /// Partial update of a node. Spec-silent shape: `Option` per patchable field,
121 /// `None` meaning "leave unchanged". Identity, kind, binding, and evidence
122 /// are deliberately NOT patchable here — they move only through their
123 /// dedicated changes (`BindOperation`, `AttachEvidence`, `Supersede`).
124 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
125 pub struct WorkNodePatch {
126 pub title: Option<String>,
127 pub state: Option<NodeState>,
128 pub acceptance: Option<Vec<AcceptanceRequirement>>,
129 pub provenance: Option<Provenance>,
130 }
131
132 /// A reviewable plan diff. Spec-silent shape: explicit added/updated/removed
133 /// sets rather than nested changes, so the whole delta is inspectable before
134 /// acceptance and applies atomically (validated as one unit — no silent
135 /// mutation of objectives, dependencies, acceptance, or scope).
136 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137 pub struct WorkGraphProposal {
138 pub id: ProposalId,
139 #[serde(default)]
140 pub added_nodes: Vec<WorkNode>,
141 #[serde(default)]
142 pub added_edges: Vec<WorkEdge>,
143 #[serde(default)]
144 pub updated_nodes: Vec<ProposedNodeUpdate>,
145 #[serde(default)]
146 pub removed_nodes: Vec<WorkNodeId>,
147 #[serde(default)]
148 pub removed_edges: Vec<WorkEdgeId>,
149 /// Graph-owned inputs for the legacy Plan/To-do projections. This is part
150 /// of the reviewed scope delta and is applied atomically with the graph
151 /// changes. Older saved proposals deserialize with no replacement.
152 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub replacement_compat: Option<CompatProjectionState>,
154 }
155
156 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
157 pub struct ProposedNodeUpdate {
158 pub id: WorkNodeId,
159 pub patch: WorkNodePatch,
160 }
161
162 /// Reference to the approval that accepted a plan diff. Spec-silent shape:
163 /// a reference-only string (approval receipt / user action handle), recorded
164 /// on the Approval node the acceptance creates.
165 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166 pub struct ApprovalRef {
167 pub reference: String,
168 }
169
170 /// Lifecycle state as reported by an operation's owner. Placeholder for the
171 /// liveness slice; present now so reducer signatures are final.
172 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
173 #[serde(rename_all = "snake_case")]
174 pub enum OwnerState {
175 Initializing,
176 Running,
177 Waiting,
178 Completed,
179 /// Terminal: finished and produced output, but with dropped or failed
180 /// slots the operator must be able to distinguish from an ordinary
181 /// success (#5582). Collapsing this into `Completed` let dashboards and
182 /// automation treat a partial workflow as fully accepted.
183 Degraded,
184 Failed,
185 Cancelled,
186 }
187
188 /// Typed cancellation outcomes, mirroring real owner semantics (immediate
189 /// abort vs teardown-wait vs already-finished vs unknown-after-restart).
190 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
191 #[serde(rename_all = "snake_case")]
192 pub enum CancelOutcome {
193 Requested,
194 Acknowledged,
195 Forced,
196 AlreadyFinished,
197 NotFound,
198 StaleUnknown,
199 }
200
201 /// An observation about a bound operation, produced by owner adapters (later
202 /// slice) and consumed by the reducer. The reducer applies these purely; it
203 /// never queries owners itself.
204 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205 #[serde(rename_all = "snake_case")]
206 pub enum OperationObservation {
207 /// Owner is authoritative. Idempotency key = `(binding, seq)`.
208 OwnerReported {
209 state: OwnerState,
210 seq: u64,
211 at: Ts,
212 /// Bounded logical output receipt. The reference never contains raw
213 /// logs or reasoning; `raw_bytes` preserves the pre-truncation size.
214 #[serde(default, skip_serializing_if = "Option::is_none")]
215 output: Option<EvidenceRef>,
216 },
217 /// No live handle for the binding (e.g. after restart). Never maps to
218 /// Active or Completed — only to Stale (fail toward honesty).
219 OwnerMissing {
220 checked_at: Ts,
221 },
222 /// Owner record could not be loaded (e.g. corrupt JSON or I/O error).
223 /// Maps to Stale like OwnerMissing while preserving the load failure.
224 OwnerUnreadable {
225 checked_at: Ts,
226 reason: String,
227 },
228 CancelUpdate {
229 outcome: CancelOutcome,
230 at: Ts,
231 },
232 }
233
234 /// Compact record of the most recent observation, stored on the binding.
235 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236 pub struct ObservationSummary {
237 pub owner_state: OwnerState,
238 pub seq: u64,
239 pub observed_at: Ts,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub output: Option<EvidenceRef>,
242 }
243
244 /// Everything ambient the reducer needs, supplied by the caller so the
245 /// reducer itself stays pure: no clock reads, no RNG, no globals.
246 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247 pub struct ChangeCtx {
248 /// Session identity used for deterministic ID derivation.
249 pub session_id: String,
250 /// Timestamp to record for this change (milliseconds since Unix epoch).
251 pub now: Ts,
252 /// Present for owner-observation changes; duplicates inside the
253 /// snapshot's dedup window become no-op receipts.
254 pub idempotency_key: Option<IdempotencyKey>,
255 }
256
257 /// Receipt for an applied (or deduplicated) change. Bounded history of these
258 /// lives on the snapshot. Receipts carry discriminant names and identifiers
259 /// only — no payload text, no secrets.
260 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
261 pub struct ChangeReceipt {
262 pub change_id: ChangeId,
263 pub revision: u64,
264 pub summary: String,
265 pub applied_at: Ts,
266 pub idempotency_key: Option<IdempotencyKey>,
267 pub no_op: bool,
268 }
269
270 impl ChangeReceipt {
271 #[must_use]
272 pub fn of(change: &WorkGraphChange, revision: u64, ctx: &ChangeCtx) -> Self {
273 let kind = change.kind_name();
274 ChangeReceipt {
275 change_id: ChangeId::derive(&ctx.session_id, &format!("change:{revision}:{kind}")),
276 revision,
277 summary: kind.to_string(),
278 applied_at: ctx.now,
279 idempotency_key: ctx.idempotency_key.clone(),
280 no_op: false,
281 }
282 }
283 }
284
284 lines RUST