返回 CodeWhale
model.rs
根目录 / crates / engine / src / work_graph / model.rs
1 //! Core work-graph data model.
2 //!
3 //! One graph carries plan, todo, operations, evidence, and approvals; every
4 //! user-visible projection derives from it and never writes back. The model is
5 //! plain data — no threads, no service objects — mutated only through the
6 //! reducer in [`super::reducer`].
7 //!
8 //! Design notes where the cutover spec is silent:
9 //! - Timestamps are a plain `i64` of milliseconds since the Unix epoch
10 //! ([`Ts`]); the reducer never reads clocks, so callers supply them.
11 //! - [`WorkEdge`] is `{id, kind, from, to}` — the minimal directed labeled
12 //! edge. `Contains` points parent → child; `Verifies` points evidence →
13 //! verified node; `Supersedes` points replacement → superseded.
14 //! - Evidence payloads live on Evidence-kind nodes via [`WorkNode::evidence`];
15 //! verification checks walk `Verifies` edges to those nodes.
16 //! - [`BoundedVec`] / [`BoundedSet`] are small deterministic FIFO containers
17 //! (oldest entry evicted first); no hashing, so iteration order is stable.
18
19 use codewhale_models::reasoning_effort_tier::ReasoningEffortTier;
20 use serde::{Deserialize, Deserializer, Serialize};
21
22 use codewhale_config::ProviderKind;
23
24 use super::events::{ChangeReceipt, ObservationSummary, WorkGraphProposal};
25 use super::ids::{BindingId, WorkEdgeId, WorkNodeId};
26
27 /// Milliseconds since the Unix epoch (UTC). Supplied by callers via
28 /// [`super::ChangeCtx`]; the reducer never reads clocks itself.
29 pub type Ts = i64;
30
31 /// Current snapshot schema version.
32 pub const SCHEMA_VERSION: u32 = 1;
33
34 /// Bounded change-history window kept on the snapshot.
35 pub const HISTORY_CAP: usize = 256;
36
37 /// Bounded user-visible configuration activity kept on the snapshot.
38 pub const ACTIVITY_CAP: usize = 256;
39
40 /// Bounded idempotency-key dedup window kept on the snapshot.
41 pub const SEEN_KEYS_CAP: usize = 1024;
42
43 /// Ended, non-durable Operation nodes (one per finished shell call) kept on
44 /// the snapshot (#6842). They are a derived index — the calls and their output
45 /// live in the session transcript — so older ones are evicted, not archived.
46 pub const ENDED_OPERATION_CAP: usize = 256;
47
48 /// Bounded, receipt-only activity attached to the session graph.
49 #[derive(Debug, Clone, PartialEq, Eq)]
50 pub enum WorkActivityEvent {
51 ReasoningEffortChanged {
52 requested: ReasoningEffortTier,
53 effective: ReasoningEffortTier,
54 /// Immutable routing kind, distinct from the exact provider identity.
55 /// A custom table may legally use a built-in slug as its identity.
56 provider_kind: Option<ProviderKind>,
57 provider: String,
58 endpoint_identity: Option<String>,
59 model: Option<String>,
60 ts: Ts,
61 operation: Option<WorkNodeId>,
62 },
63 }
64
65 #[derive(Serialize, Deserialize)]
66 #[serde(tag = "kind", rename_all = "snake_case")]
67 enum WorkActivityEventWire {
68 ReasoningEffortChanged {
69 requested: ReasoningEffortTier,
70 effective: ReasoningEffortTier,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 provider_kind: Option<String>,
73 provider: String,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 endpoint_identity: Option<String>,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 model: Option<String>,
78 ts: Ts,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 operation: Option<WorkNodeId>,
81 },
82 }
83
84 impl Serialize for WorkActivityEvent {
85 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
86 where
87 S: serde::Serializer,
88 {
89 match self {
90 Self::ReasoningEffortChanged {
91 requested,
92 effective,
93 provider_kind,
94 provider,
95 endpoint_identity,
96 model,
97 ts,
98 operation,
99 } => {
100 let provider_kind = provider_kind
101 .map(|kind| {
102 codewhale_config::descriptors::tui_wire_tag_for_route(kind, provider)
103 .map(str::to_string)
104 .ok_or_else(|| {
105 serde::ser::Error::custom(
106 "contradictory activity provider identity",
107 )
108 })
109 })
110 .transpose()?;
111 WorkActivityEventWire::ReasoningEffortChanged {
112 requested: *requested,
113 effective: *effective,
114 provider_kind,
115 provider: provider.clone(),
116 endpoint_identity: endpoint_identity.clone(),
117 model: model.clone(),
118 ts: *ts,
119 operation: operation.clone(),
120 }
121 .serialize(serializer)
122 }
123 }
124 }
125 }
126
127 impl<'de> Deserialize<'de> for WorkActivityEvent {
128 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
129 where
130 D: Deserializer<'de>,
131 {
132 match WorkActivityEventWire::deserialize(deserializer)? {
133 WorkActivityEventWire::ReasoningEffortChanged {
134 requested,
135 mut effective,
136 provider_kind,
137 provider,
138 endpoint_identity,
139 model,
140 ts,
141 operation,
142 } => {
143 let provider_kind = provider_kind
144 .map(|tag| {
145 codewhale_config::descriptors::kind_from_tui_wire_tag(&tag, &provider)
146 .ok_or_else(|| {
147 serde::de::Error::custom("contradictory activity provider identity")
148 })
149 })
150 .transpose()?;
151 // Pre-provenance snapshots cannot prove what route received
152 // the control. Keep them loadable, but never preserve a
153 // claimed effective tier as if kind/endpoint/model were known.
154 // In particular, reparsing `provider` is unsafe because a
155 // custom table may legally be named after a built-in slug.
156 if provider_kind.is_none() || endpoint_identity.is_none() || model.is_none() {
157 effective = ReasoningEffortTier::Unavailable;
158 }
159 Ok(Self::ReasoningEffortChanged {
160 requested,
161 effective,
162 provider_kind,
163 provider,
164 endpoint_identity,
165 model,
166 ts,
167 operation,
168 })
169 }
170 }
171 }
172 }
173
174 /// Return the only valid effective receipt for routes whose reasoning-control
175 /// dialect is narrower than the generic provider normalization.
176 #[must_use]
177 pub fn constrained_effective_reasoning_for_route(
178 requested: ReasoningEffortTier,
179 provider: ProviderKind,
180 endpoint_identity: &str,
181 model: &str,
182 ) -> Option<ReasoningEffortTier> {
183 use ReasoningEffortTier::{
184 Auto, High, Low, Medium, Off, ThinkingEnabledGranularityUnavailable, Unavailable,
185 };
186
187 if provider == ProviderKind::Zai {
188 if !codewhale_runtime::config::is_exact_zai_chat_route(provider, endpoint_identity) {
189 return Some(Unavailable);
190 }
191 if codewhale_runtime::config::is_exact_zai_forced_thinking_route(
192 provider,
193 endpoint_identity,
194 model,
195 ) {
196 // GLM-5.3 / GLM-5.3-Flash cannot disable thinking; the wire sends
197 // `off` as the lowest documented tier and honours `low` natively.
198 return Some(match requested {
199 Off => Low,
200 Medium => High,
201 other => other,
202 });
203 }
204 if codewhale_runtime::config::is_exact_zai_tiered_effort_route(
205 provider,
206 endpoint_identity,
207 model,
208 ) {
209 return Some(match requested {
210 Low | Medium => High,
211 other => other,
212 });
213 }
214 if codewhale_runtime::config::is_exact_known_zai_reasoning_route(
215 provider,
216 endpoint_identity,
217 model,
218 ) {
219 return Some(match requested {
220 Off | Auto => requested,
221 _ => ThinkingEnabledGranularityUnavailable,
222 });
223 }
224 return Some(Unavailable);
225 }
226
227 if provider == ProviderKind::Minimax {
228 if codewhale_runtime::config::is_exact_minimax_m3_route(provider, endpoint_identity, model)
229 {
230 return Some(match requested {
231 Off | Auto => requested,
232 _ => ThinkingEnabledGranularityUnavailable,
233 });
234 }
235 return Some(Unavailable);
236 }
237
238 if provider == ProviderKind::MinimaxAnthropic {
239 if codewhale_runtime::config::is_exact_minimax_anthropic_m3_route(
240 provider,
241 endpoint_identity,
242 model,
243 ) {
244 return Some(match requested {
245 Off | Auto => requested,
246 _ => ThinkingEnabledGranularityUnavailable,
247 });
248 }
249 return Some(Unavailable);
250 }
251
252 // A named OpenAI-compatible endpoint has no verified reasoning dialect
253 // merely because it has a bounded URL and model string. Until immutable
254 // route provenance carries a validated capability contract, its effective
255 // tier must remain unavailable.
256 if provider == ProviderKind::Custom {
257 return Some(Unavailable);
258 }
259
260 if codewhale_runtime::config::is_exact_kimi_code_k3_route(provider, endpoint_identity, model) {
261 return Some(match requested {
262 Off => Low,
263 other => other,
264 });
265 }
266 if codewhale_runtime::config::is_exact_direct_moonshot_k3_route(
267 provider,
268 endpoint_identity,
269 model,
270 ) {
271 return Some(match requested {
272 Off => Low,
273 Medium => High,
274 other => other,
275 });
276 }
277
278 None
279 }
280
281 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
282 #[serde(rename_all = "snake_case")]
283 pub enum NodeKind {
284 Objective,
285 PlanStep,
286 Operation,
287 Evidence,
288 Blocker,
289 Approval,
290 RuntimeRef,
291 LaneRef,
292 }
293
294 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
295 #[serde(rename_all = "snake_case")]
296 pub enum EdgeKind {
297 Contains,
298 DependsOn,
299 Blocks,
300 Produces,
301 Verifies,
302 RunsOn,
303 RequiresApproval,
304 Supersedes,
305 }
306
307 /// Node lifecycle state. The load-bearing distinction: [`NodeState::Completed`]
308 /// means an operation *ended*; only [`NodeState::Verified`] — reachable solely
309 /// when an evidence path satisfies every acceptance requirement — means done.
310 /// An ended process is never proof its acceptance criteria hold.
311 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
312 #[serde(rename_all = "snake_case")]
313 pub enum NodeState {
314 Ready,
315 /// The owner has accepted spawn intent but has not yet reported a live
316 /// handle. Registering this state before process creation prevents work
317 /// from existing outside the graph during the spawn window.
318 Initializing,
319 Active,
320 Waiting,
321 Blocked,
322 /// Operation ended — NOT done.
323 Completed,
324 /// Evidence path satisfies acceptance — this is "done".
325 Verified,
326 /// The owner can no longer confirm the process (distinct from
327 /// silent-but-live; a confirmed-live silent job stays `Active`).
328 Stale,
329 Superseded,
330 Cancelled,
331 Failed,
332 }
333
334 impl NodeState {
335 /// Terminal states protected by invariant V9: never overwritten except
336 /// via an explicit `Supersede` change or a reconcile-rule change.
337 #[must_use]
338 pub fn is_terminal(self) -> bool {
339 matches!(
340 self,
341 NodeState::Verified | NodeState::Superseded | NodeState::Cancelled
342 )
343 }
344
345 /// Live states for invariant V2 (no orphaned live work).
346 #[must_use]
347 pub fn is_live(self) -> bool {
348 matches!(
349 self,
350 NodeState::Initializing | NodeState::Active | NodeState::Waiting
351 )
352 }
353 }
354
355 /// Fieldless discriminant of [`EvidenceKind`], used by acceptance
356 /// requirements so they can match a kind without naming payload values.
357 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
358 #[serde(rename_all = "snake_case")]
359 pub enum EvidenceKindTag {
360 ToolRun,
361 Artifact,
362 TestSummary,
363 Receipt,
364 Approval,
365 Route,
366 WebCitation,
367 }
368
369 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
370 #[serde(rename_all = "snake_case")]
371 pub enum EvidenceKind {
372 ToolRun,
373 Artifact {
374 digest: String,
375 },
376 TestSummary,
377 Receipt {
378 owner: String,
379 },
380 Approval,
381 Route,
382 WebCitation {
383 ref_id: String,
384 url: String,
385 retrieved_at: String,
386 },
387 }
388
389 impl EvidenceKind {
390 #[must_use]
391 pub fn tag(&self) -> EvidenceKindTag {
392 match self {
393 EvidenceKind::ToolRun => EvidenceKindTag::ToolRun,
394 EvidenceKind::Artifact { .. } => EvidenceKindTag::Artifact,
395 EvidenceKind::TestSummary => EvidenceKindTag::TestSummary,
396 EvidenceKind::Receipt { .. } => EvidenceKindTag::Receipt,
397 EvidenceKind::Approval => EvidenceKindTag::Approval,
398 EvidenceKind::Route => EvidenceKindTag::Route,
399 EvidenceKind::WebCitation { .. } => EvidenceKindTag::WebCitation,
400 }
401 }
402 }
403
404 /// Reason an [`EvidenceRef`] could not be constructed.
405 #[derive(Debug, Clone, PartialEq, Eq)]
406 pub enum EvidenceRefError {
407 EmptyReference,
408 ReferenceTooLong { len: usize },
409 AbsolutePath,
410 HomeRelativePath,
411 ContainsWhitespaceOrControl,
412 LooksLikeKeyMaterial,
413 WebCitationReferenceMismatch,
414 InvalidWebCitationUrl,
415 InvalidWebCitationTimestamp,
416 }
417
418 impl std::fmt::Display for EvidenceRefError {
419 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
420 match self {
421 EvidenceRefError::EmptyReference => write!(f, "evidence reference is empty"),
422 EvidenceRefError::ReferenceTooLong { len } => {
423 write!(f, "evidence reference too long ({len} chars)")
424 }
425 EvidenceRefError::AbsolutePath => {
426 write!(f, "evidence reference must not be an absolute path")
427 }
428 EvidenceRefError::HomeRelativePath => {
429 write!(f, "evidence reference must not be a home-relative path")
430 }
431 EvidenceRefError::ContainsWhitespaceOrControl => {
432 write!(
433 f,
434 "evidence reference must not contain whitespace or control chars"
435 )
436 }
437 EvidenceRefError::LooksLikeKeyMaterial => {
438 write!(f, "evidence reference must not embed key material")
439 }
440 EvidenceRefError::WebCitationReferenceMismatch => {
441 write!(f, "web citation reference must match its ref_id")
442 }
443 EvidenceRefError::InvalidWebCitationUrl => {
444 write!(f, "web citation URL must be HTTP(S) without credentials")
445 }
446 EvidenceRefError::InvalidWebCitationTimestamp => {
447 write!(f, "web citation retrieved_at must be RFC 3339")
448 }
449 }
450 }
451 }
452
453 impl std::error::Error for EvidenceRefError {}
454
455 const EVIDENCE_REFERENCE_MAX_LEN: usize = 512;
456
457 fn web_citation_url_has_sensitive_query(url: &reqwest::Url) -> bool {
458 url.query_pairs().any(|(name, _)| {
459 let name = name.to_ascii_lowercase();
460 matches!(
461 name.as_ref(),
462 "access_token"
463 | "api_key"
464 | "authorization"
465 | "auth"
466 | "credential"
467 | "key"
468 | "session"
469 | "session_id"
470 | "sig"
471 | "signature"
472 | "token"
473 | "x-amz-credential"
474 | "x-amz-signature"
475 | "x-goog-credential"
476 | "x-goog-signature"
477 ) || name.ends_with("_token")
478 || name.ends_with("_key")
479 })
480 }
481
482 /// Summary/reference-only pointer to evidence: a logical artifact ID, run ID,
483 /// or receipt handle — never absolute paths, never secrets, never raw logs or
484 /// reasoning text.
485 ///
486 /// Enforced by construction where feasible: fields are private, [`Self::new`]
487 /// is the only way to build one (serde routes through it via `try_from`), and
488 /// it rejects absolute/home paths, whitespace/control characters (which also
489 /// blocks pasted log or prose content), and PEM-style key-material markers.
490 /// `raw_bytes` records the pre-truncation size of the underlying output so
491 /// "still growing" and "stuck" stay distinguishable after truncation.
492 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
493 #[serde(try_from = "EvidenceRefRaw", into = "EvidenceRefRaw")]
494 pub struct EvidenceRef {
495 kind: EvidenceKind,
496 reference: String,
497 raw_bytes: Option<u64>,
498 truncated: bool,
499 }
500
501 impl EvidenceRef {
502 pub fn new(
503 kind: EvidenceKind,
504 reference: impl Into<String>,
505 raw_bytes: Option<u64>,
506 truncated: bool,
507 ) -> Result<Self, EvidenceRefError> {
508 let reference = reference.into();
509 if reference.is_empty() {
510 return Err(EvidenceRefError::EmptyReference);
511 }
512 if reference.chars().count() > EVIDENCE_REFERENCE_MAX_LEN {
513 return Err(EvidenceRefError::ReferenceTooLong {
514 len: reference.chars().count(),
515 });
516 }
517 let mut chars = reference.chars();
518 let first = chars.next().unwrap_or('\0');
519 // Unix absolute, UNC/backslash, or `X:/`-style drive paths.
520 let drive_absolute = {
521 let bytes = reference.as_bytes();
522 bytes.len() >= 3
523 && bytes[0].is_ascii_alphabetic()
524 && bytes[1] == b':'
525 && (bytes[2] == b'/' || bytes[2] == b'\\')
526 };
527 if first == '/' || first == '\\' || drive_absolute {
528 return Err(EvidenceRefError::AbsolutePath);
529 }
530 if first == '~' {
531 return Err(EvidenceRefError::HomeRelativePath);
532 }
533 if reference
534 .chars()
535 .any(|c| c.is_whitespace() || c.is_control())
536 {
537 return Err(EvidenceRefError::ContainsWhitespaceOrControl);
538 }
539 if reference.contains("-----BEGIN") {
540 return Err(EvidenceRefError::LooksLikeKeyMaterial);
541 }
542 if let EvidenceKind::WebCitation {
543 ref_id,
544 url,
545 retrieved_at,
546 } = &kind
547 {
548 if ref_id != &reference {
549 return Err(EvidenceRefError::WebCitationReferenceMismatch);
550 }
551 let parsed = reqwest::Url::parse(url)
552 .ok()
553 .filter(|url| matches!(url.scheme(), "http" | "https"))
554 .filter(|url| url.host_str().is_some())
555 .filter(|url| url.username().is_empty() && url.password().is_none())
556 .filter(|url| !web_citation_url_has_sensitive_query(url));
557 if parsed.is_none() {
558 return Err(EvidenceRefError::InvalidWebCitationUrl);
559 }
560 if chrono::DateTime::parse_from_rfc3339(retrieved_at).is_err() {
561 return Err(EvidenceRefError::InvalidWebCitationTimestamp);
562 }
563 }
564 Ok(Self {
565 kind,
566 reference,
567 raw_bytes,
568 truncated,
569 })
570 }
571
572 #[must_use]
573 pub fn kind(&self) -> &EvidenceKind {
574 &self.kind
575 }
576
577 #[must_use]
578 pub fn reference(&self) -> &str {
579 &self.reference
580 }
581
582 /// Pre-truncation size of the underlying output, persisted on the node.
583 #[must_use]
584 pub fn raw_bytes(&self) -> Option<u64> {
585 self.raw_bytes
586 }
587
588 #[must_use]
589 pub fn truncated(&self) -> bool {
590 self.truncated
591 }
592 }
593
594 /// Serde shadow for [`EvidenceRef`] so deserialization re-runs constructor
595 /// validation instead of bypassing it.
596 #[derive(Debug, Clone, Serialize, Deserialize)]
597 pub struct EvidenceRefRaw {
598 kind: EvidenceKind,
599 reference: String,
600 raw_bytes: Option<u64>,
601 truncated: bool,
602 }
603
604 impl TryFrom<EvidenceRefRaw> for EvidenceRef {
605 type Error = EvidenceRefError;
606
607 fn try_from(raw: EvidenceRefRaw) -> Result<Self, Self::Error> {
608 EvidenceRef::new(raw.kind, raw.reference, raw.raw_bytes, raw.truncated)
609 }
610 }
611
612 impl From<EvidenceRef> for EvidenceRefRaw {
613 fn from(value: EvidenceRef) -> Self {
614 EvidenceRefRaw {
615 kind: value.kind,
616 reference: value.reference,
617 raw_bytes: value.raw_bytes,
618 truncated: value.truncated,
619 }
620 }
621 }
622
623 /// A requirement that must be satisfied by evidence before a node may be
624 /// [`NodeState::Verified`] (invariant V4).
625 ///
626 /// Deliberately minimal for this slice: one variant matching an evidence kind.
627 /// Richer predicates (thresholds, specific commands) can be added as variants
628 /// without touching the verification walk.
629 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
630 #[serde(rename_all = "snake_case")]
631 pub enum AcceptanceRequirement {
632 /// Satisfied when at least one attached evidence item has this kind.
633 EvidenceOfKind { kind: EvidenceKindTag },
634 }
635
636 impl AcceptanceRequirement {
637 #[must_use]
638 pub fn is_satisfied_by(&self, evidence: &EvidenceRef) -> bool {
639 match self {
640 AcceptanceRequirement::EvidenceOfKind { kind } => evidence.kind().tag() == *kind,
641 }
642 }
643 }
644
645 /// Where a fact in the graph came from.
646 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
647 #[serde(rename_all = "snake_case")]
648 pub enum Provenance {
649 Import {
650 source_digest: String,
651 ordinal: Option<u32>,
652 },
653 ToolUpdate {
654 tool: String,
655 call_id: String,
656 },
657 RuntimeReconcile {
658 source: String,
659 observed_at: Ts,
660 },
661 UserEdit {
662 proposal_id: super::ids::ProposalId,
663 },
664 }
665
666 /// Binding from an Operation node to the external process that owns its
667 /// lifecycle. `external` uses the existing identity scheme verbatim:
668 /// `"task:{id}" | "shell:{id}" | "worker:{id}" | "workflow:{id}" |
669 /// "fleet:{run}/{task}" | "lane:{id}"` — the same strings the live work
670 /// surface already parses for actions, so bindings stay joinable with
671 /// today's owners without translation.
672 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
673 pub struct OperationBinding {
674 pub external: String,
675 /// Whether the owner persists lifecycle records across restart. Shell
676 /// sessions are in-memory only (`durable == false`): after a restart they
677 /// become [`NodeState::Stale`], never silently "still running".
678 pub durable: bool,
679 #[serde(default)]
680 pub last_observation: Option<ObservationSummary>,
681 }
682
683 /// Returns true when `external` is well-formed under exactly one prefix of
684 /// the existing identity scheme.
685 #[must_use]
686 pub fn external_identity_is_well_formed(external: &str) -> bool {
687 fn plain(id: &str) -> bool {
688 !id.is_empty() && !id.chars().any(|c| c.is_whitespace() || c.is_control())
689 }
690 if let Some(rest) = external.strip_prefix("fleet:") {
691 return match rest.split_once('/') {
692 Some((run, task)) => plain(run) && plain(task),
693 None => false,
694 };
695 }
696 ["task:", "shell:", "worker:", "workflow:", "lane:"]
697 .iter()
698 .any(|prefix| external.strip_prefix(prefix).is_some_and(plain))
699 }
700
701 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
702 pub struct WorkNode {
703 pub id: WorkNodeId,
704 pub kind: NodeKind,
705 pub title: String,
706 pub state: NodeState,
707 /// Empty acceptance means [`NodeState::Completed`] may render as done;
708 /// non-empty acceptance makes `Verified` (evidence-gated) the only done.
709 pub acceptance: Vec<AcceptanceRequirement>,
710 /// Operation nodes only (invariant V3).
711 pub binding: Option<OperationBinding>,
712 /// Evidence-kind nodes only; the payload the `Verifies` walk reads.
713 pub evidence: Option<EvidenceRef>,
714 pub provenance: Provenance,
715 pub created_at: Ts,
716 pub updated_at: Ts,
717 }
718
719 /// Directed labeled edge. Minimal by design; edge-level metadata can be
720 /// modeled as nodes (e.g. Approval) rather than edge payloads.
721 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
722 pub struct WorkEdge {
723 pub id: WorkEdgeId,
724 pub kind: EdgeKind,
725 pub from: WorkNodeId,
726 pub to: WorkNodeId,
727 }
728
729 /// Graph-owned presentation metadata for the legacy Strategy/Plan surface.
730 ///
731 /// Plan steps themselves live as `PlanStep` nodes. These fields have no
732 /// first-class node equivalent yet, so they remain attached to the graph as
733 /// presentation metadata rather than living in a separately writable store.
734 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
735 pub struct CompatPlanMetadata {
736 #[serde(default, skip_serializing_if = "Option::is_none")]
737 pub title: Option<String>,
738 #[serde(default, skip_serializing_if = "Option::is_none")]
739 pub objective: Option<String>,
740 #[serde(default, skip_serializing_if = "Option::is_none")]
741 pub context_summary: Option<String>,
742 #[serde(default, skip_serializing_if = "Option::is_none")]
743 pub explanation: Option<String>,
744 #[serde(default, skip_serializing_if = "Vec::is_empty")]
745 pub sources_used: Vec<String>,
746 #[serde(default, skip_serializing_if = "Vec::is_empty")]
747 pub critical_files: Vec<String>,
748 #[serde(default, skip_serializing_if = "Vec::is_empty")]
749 pub constraints: Vec<String>,
750 #[serde(default, skip_serializing_if = "Option::is_none")]
751 pub recommended_approach: Option<String>,
752 #[serde(default, skip_serializing_if = "Option::is_none")]
753 pub verification_plan: Option<String>,
754 #[serde(default, skip_serializing_if = "Option::is_none")]
755 pub risks_and_unknowns: Option<String>,
756 #[serde(default, skip_serializing_if = "Option::is_none")]
757 pub handoff_packet: Option<String>,
758 #[serde(default, skip_serializing_if = "Vec::is_empty")]
759 pub replan_if: Vec<String>,
760 }
761
762 impl CompatPlanMetadata {
763 #[must_use]
764 pub fn is_empty(&self) -> bool {
765 self.title.is_none()
766 && self.objective.is_none()
767 && self.context_summary.is_none()
768 && self.explanation.is_none()
769 && self.sources_used.is_empty()
770 && self.critical_files.is_empty()
771 && self.constraints.is_empty()
772 && self.recommended_approach.is_none()
773 && self.verification_plan.is_none()
774 && self.risks_and_unknowns.is_none()
775 && self.handoff_packet.is_none()
776 && self.replan_if.is_empty()
777 }
778 }
779
780 /// One row in the legacy To-do projection.
781 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
782 pub struct CompatTodoBinding {
783 pub legacy_id: u32,
784 pub node: WorkNodeId,
785 /// When present, the legacy row aliases this ordinal in `plan_order`.
786 /// The retired invisible marker is never reconstructed; the graph keeps
787 /// the provenance explicitly while old readers receive clean content.
788 #[serde(default, skip_serializing_if = "Option::is_none")]
789 pub plan_index: Option<u32>,
790 }
791
792 /// Ordering and presentation state needed to derive old Plan/To-do snapshots.
793 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
794 pub struct CompatProjectionState {
795 #[serde(default, skip_serializing_if = "CompatPlanMetadata::is_empty")]
796 pub plan: CompatPlanMetadata,
797 #[serde(default, skip_serializing_if = "Vec::is_empty")]
798 pub plan_order: Vec<WorkNodeId>,
799 #[serde(default, skip_serializing_if = "Vec::is_empty")]
800 pub todos: Vec<CompatTodoBinding>,
801 }
802
803 impl CompatProjectionState {
804 #[must_use]
805 pub fn is_empty(&self) -> bool {
806 self.plan.is_empty() && self.plan_order.is_empty() && self.todos.is_empty()
807 }
808
809 /// Whether `node` is still part of the live Plan or To-do projection.
810 /// Replacing either list drops bindings but keeps the old plan-step nodes
811 /// in the graph (there is no node removal), so presentation must treat an
812 /// unreferenced plan step as retired, not as live work (#6546).
813 #[must_use]
814 pub fn projects(&self, node: &WorkNodeId) -> bool {
815 self.plan_order.contains(node) || self.todos.iter().any(|binding| &binding.node == node)
816 }
817 }
818
819 /// Idempotency key for owner-reported observations: `(binding, seq)`. Applied
820 /// changes carrying a key already inside the snapshot's dedup window become
821 /// receipts without effect, so replayed runtime events cannot double-apply.
822 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
823 pub struct IdempotencyKey {
824 pub binding: BindingId,
825 pub seq: u64,
826 }
827
828 /// Deterministic FIFO vector bounded at `N`: pushing beyond capacity evicts
829 /// the oldest entry. Kept as a plain `Vec` so ordering (and serialization) is
830 /// stable. The bound is re-checked by validation (V8), so an oversized
831 /// deserialized snapshot fails closed rather than growing unbounded.
832 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
833 #[serde(transparent)]
834 pub struct BoundedVec<T, const N: usize> {
835 items: Vec<T>,
836 }
837
838 impl<T, const N: usize> BoundedVec<T, N> {
839 #[must_use]
840 pub fn new() -> Self {
841 Self { items: Vec::new() }
842 }
843
844 pub fn push_bounded(&mut self, item: T) {
845 if self.items.len() >= N {
846 self.items.remove(0);
847 }
848 self.items.push(item);
849 }
850
851 #[must_use]
852 pub fn len(&self) -> usize {
853 self.items.len()
854 }
855
856 #[must_use]
857 pub fn is_empty(&self) -> bool {
858 self.items.is_empty()
859 }
860
861 #[must_use]
862 pub fn last(&self) -> Option<&T> {
863 self.items.last()
864 }
865
866 pub fn iter(&self) -> std::slice::Iter<'_, T> {
867 self.items.iter()
868 }
869
870 #[must_use]
871 pub const fn capacity() -> usize {
872 N
873 }
874 }
875
876 impl<T, const N: usize> Default for BoundedVec<T, N> {
877 fn default() -> Self {
878 Self::new()
879 }
880 }
881
882 /// Deterministic FIFO set bounded at `N`: inserting a duplicate is a no-op;
883 /// inserting beyond capacity evicts the oldest member. Linear scans keep it
884 /// hash-free and iteration-order stable for reproducible serialization.
885 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
886 #[serde(transparent)]
887 pub struct BoundedSet<T, const N: usize> {
888 items: Vec<T>,
889 }
890
891 impl<T: PartialEq, const N: usize> BoundedSet<T, N> {
892 #[must_use]
893 pub fn new() -> Self {
894 Self { items: Vec::new() }
895 }
896
897 #[must_use]
898 pub fn contains(&self, item: &T) -> bool {
899 self.items.contains(item)
900 }
901
902 /// Returns true if the item was newly inserted.
903 pub fn insert(&mut self, item: T) -> bool {
904 if self.contains(&item) {
905 return false;
906 }
907 if self.items.len() >= N {
908 self.items.remove(0);
909 }
910 self.items.push(item);
911 true
912 }
913
914 #[must_use]
915 pub fn len(&self) -> usize {
916 self.items.len()
917 }
918
919 #[must_use]
920 pub fn is_empty(&self) -> bool {
921 self.items.is_empty()
922 }
923 }
924
925 impl<T: PartialEq, const N: usize> Default for BoundedSet<T, N> {
926 fn default() -> Self {
927 Self::new()
928 }
929 }
930
931 /// The whole graph as a value. Serialized opaquely inside session state by a
932 /// later slice; this slice keeps it standalone.
933 ///
934 /// `proposals` is a spec-silent addition: pending plan-diff proposals must
935 /// live somewhere the reducer can find them when `AcceptPlanDiff` arrives by
936 /// ID, and the snapshot is the only state the reducer sees.
937 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
938 pub struct WorkGraphSnapshot {
939 pub schema: u32,
940 pub revision: u64,
941 pub nodes: Vec<WorkNode>,
942 pub edges: Vec<WorkEdge>,
943 pub history: BoundedVec<ChangeReceipt, HISTORY_CAP>,
944 /// Configuration facts only; never prompts, output, or reasoning text.
945 #[serde(default, skip_serializing_if = "BoundedVec::is_empty")]
946 pub activities: BoundedVec<WorkActivityEvent, ACTIVITY_CAP>,
947 pub import_digest: Option<String>,
948 /// `(binding, seq)` dedup window for replayed runtime observations.
949 pub seen_keys: BoundedSet<IdempotencyKey, SEEN_KEYS_CAP>,
950 pub proposals: Vec<WorkGraphProposal>,
951 /// Graph-owned inputs for the fully populated legacy Plan/To-do views.
952 #[serde(default, skip_serializing_if = "CompatProjectionState::is_empty")]
953 pub compat: CompatProjectionState,
954 }
955
956 impl WorkGraphSnapshot {
957 #[must_use]
958 pub fn new() -> Self {
959 Self {
960 schema: SCHEMA_VERSION,
961 revision: 0,
962 nodes: Vec::new(),
963 edges: Vec::new(),
964 history: BoundedVec::new(),
965 activities: BoundedVec::new(),
966 import_digest: None,
967 seen_keys: BoundedSet::new(),
968 proposals: Vec::new(),
969 compat: CompatProjectionState::default(),
970 }
971 }
972
973 #[must_use]
974 pub fn node(&self, id: &WorkNodeId) -> Option<&WorkNode> {
975 self.nodes.iter().find(|n| &n.id == id)
976 }
977
978 pub(super) fn node_mut(&mut self, id: &WorkNodeId) -> Option<&mut WorkNode> {
979 self.nodes.iter_mut().find(|n| &n.id == id)
980 }
981
982 #[must_use]
983 pub fn edge(&self, id: &WorkEdgeId) -> Option<&WorkEdge> {
984 self.edges.iter().find(|e| &e.id == id)
985 }
986
987 /// "Done" for dependency/approval purposes: verified, or completed with
988 /// no acceptance requirements (nothing left to verify).
989 #[must_use]
990 pub fn node_is_done(node: &WorkNode) -> bool {
991 matches!(node.state, NodeState::Verified)
992 || (matches!(node.state, NodeState::Completed) && node.acceptance.is_empty())
993 }
994
995 #[must_use]
996 pub fn is_empty(&self) -> bool {
997 self.nodes.is_empty()
998 && self.edges.is_empty()
999 && self.history.is_empty()
1000 && self.activities.is_empty()
1001 && self.import_digest.is_none()
1002 && self.proposals.is_empty()
1003 && self.compat.is_empty()
1004 }
1005 }
1006
1007 impl Default for WorkGraphSnapshot {
1008 fn default() -> Self {
1009 Self::new()
1010 }
1011 }
1012
1012 lines RUST