bones-core 0.24.6

Core data structures, CRDT event model, and projection engine for bones
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! Event data model for the bones event log.
//!
//! This module defines the core `Event` struct, the `EventType` enum covering
//! all 11 event types, typed payload data structs, and the canonical JSON
//! serialization helper needed for deterministic event hashing.
//!
//! # TSJSON Format
//!
//! Events are stored in TSJSON (tab-separated fields with JSON payload):
//!
//! ```text
//! wall_ts_us \t agent \t itc \t parents \t type \t item_id \t data \t event_hash
//! ```
//!
//! The `Event` struct maps 1:1 to a TSJSON line. Parsing and writing TSJSON
//! lines is handled by the parser/writer modules (separate beads).

pub mod canonical;
pub mod data;
pub mod hash_text;
pub mod migrate;
pub mod parser;
pub mod types;
pub mod validate;
pub mod writer;

pub use canonical::{canonicalize_json, canonicalize_json_str};
pub use data::{
    AssignAction, AssignData, CommentData, CompactData, CreateData, DataParseError, DeleteData,
    EventData, LinkData, MoveData, RedactData, SnapshotData, UnlinkData, UpdateData,
};
pub use migrate::{RawEvent, migrate_event};
pub use parser::{
    CURRENT_VERSION, FIELD_COMMENT, ParseError, ParsedLine, PartialEvent, PartialParsedLine,
    SHARD_HEADER, detect_version, parse_line, parse_line_partial, parse_lines,
};
pub use types::{EventType, UnknownEventType};

use crate::model::item_id::ItemId;
use serde::{Deserialize, Serialize};

/// A single event in the bones event log.
///
/// Each event represents an immutable, content-addressed mutation to a work
/// item. Events form a Merkle-DAG via the `parents` field, enabling
/// causally-ordered CRDT replay.
///
/// # Fields (TSJSON column order)
///
/// 1. `wall_ts_us` — wall-clock microseconds since Unix epoch
/// 2. `agent` — identifier of the agent/user that produced the event
/// 3. `itc` — Interval Tree Clock stamp (canonical text encoding)
/// 4. `parents` — parent event hashes (blake3:...), sorted lexicographically
/// 5. `event_type` — one of the 11 event types
/// 6. `item_id` — the work item this event mutates
/// 7. `data` — typed payload (JSON in TSJSON, deserialized here)
/// 8. `event_hash` — BLAKE3 hash of fields 1–7
///
/// # Serde
///
/// Custom `Deserialize` implementation uses `event_type` to drive typed
/// deserialization of the `data` field. This is necessary because the type
/// discriminant is external to the JSON payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Event {
    /// Wall-clock timestamp in microseconds since Unix epoch.
    ///
    /// Monotonically increasing per-repo via the clock file.
    pub wall_ts_us: i64,

    /// Identifier of the agent or user that produced this event.
    pub agent: String,

    /// Interval Tree Clock stamp in canonical text encoding.
    ///
    /// Used for causal ordering independent of wall-clock time.
    pub itc: String,

    /// Parent event hashes forming the Merkle-DAG.
    ///
    /// Sorted lexicographically. Empty for the first event in a repo.
    /// Format: `["blake3:abcdef...", ...]`
    pub parents: Vec<String>,

    /// The type of mutation this event represents.
    pub event_type: EventType,

    /// The work item being mutated.
    pub item_id: ItemId,

    /// Typed payload data specific to the event type.
    pub data: EventData,

    /// BLAKE3 content hash of fields 1–7.
    ///
    /// Format: `blake3:<payload>` (base64url in new writes). This is the
    /// event's identity in the
    /// Merkle-DAG and is used for parent references, shard manifests,
    /// and sync diffing.
    pub event_hash: String,
}

impl<'de> Deserialize<'de> for Event {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        /// Helper struct for two-pass deserialization: first get the `event_type`,
        /// then use it to deserialize the data payload.
        #[derive(Deserialize)]
        struct EventRaw {
            wall_ts_us: i64,
            agent: String,
            itc: String,
            parents: Vec<String>,
            event_type: EventType,
            item_id: ItemId,
            data: serde_json::Value,
            event_hash: String,
        }

        let raw = EventRaw::deserialize(deserializer)?;
        let data_json = raw.data.to_string();
        let data = EventData::deserialize_for(raw.event_type, &data_json)
            .map_err(serde::de::Error::custom)?;

        Ok(Self {
            wall_ts_us: raw.wall_ts_us,
            agent: raw.agent,
            itc: raw.itc,
            parents: raw.parents,
            event_type: raw.event_type,
            item_id: raw.item_id,
            data,
            event_hash: raw.event_hash,
        })
    }
}

impl Event {
    /// Return the TSJSON parents field string (comma-separated, sorted).
    ///
    /// Returns an empty string for root events (no parents).
    #[must_use]
    pub fn parents_str(&self) -> String {
        self.parents.join(",")
    }
}

fn truncate_for_display(value: &str, max_chars: usize) -> String {
    if value.chars().count() <= max_chars {
        return value.to_string();
    }

    let mut preview: String = value.chars().take(max_chars).collect();
    preview.push_str("...");
    preview
}

impl std::fmt::Display for Event {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}\t{}\t{}\t{}\t{}\t{}",
            self.wall_ts_us,
            self.agent,
            self.event_type,
            self.item_id,
            self.event_hash,
            // Abbreviated data display
            match &self.data {
                EventData::Create(d) => format!("create: {}", d.title),
                EventData::Update(d) => format!("update: {}={}", d.field, d.value),
                EventData::Move(d) => format!("move: {}", d.state),
                EventData::Assign(d) => format!("{}: {}", d.action, d.agent),
                EventData::Comment(d) => {
                    let preview = truncate_for_display(&d.body, 40);
                    format!("comment: {preview}")
                }
                EventData::Link(d) => format!("link: {} {}", d.link_type, d.target),
                EventData::Unlink(d) => format!("unlink: {}", d.target),
                EventData::Delete(_) => "delete".to_string(),
                EventData::Compact(d) => {
                    let preview = truncate_for_display(&d.summary, 40);
                    format!("compact: {preview}")
                }
                EventData::Snapshot(_) => "snapshot".to_string(),
                EventData::Redact(d) => format!("redact: {}", d.target_hash),
            }
        )
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::collections::BTreeMap;

    fn sample_create_event() -> Event {
        Event {
            wall_ts_us: 1_708_012_200_123_456,
            agent: "claude-abc".into(),
            itc: "itc:AQ".into(),
            parents: vec![],
            event_type: EventType::Create,
            item_id: ItemId::new_unchecked("bn-a3f8"),
            data: EventData::Create(CreateData {
                title: "Fix auth retry".into(),
                kind: crate::model::item::Kind::Task,
                size: Some(crate::model::item::Size::M),
                urgency: crate::model::item::Urgency::Default,
                labels: vec!["backend".into()],
                parent: None,
                causation: None,
                description: None,
                extra: BTreeMap::new(),
            }),
            event_hash: "blake3:a1b2c3d4e5f6".into(),
        }
    }

    fn sample_move_event() -> Event {
        Event {
            wall_ts_us: 1_708_012_201_000_000,
            agent: "claude-abc".into(),
            itc: "itc:AQ.1".into(),
            parents: vec!["blake3:a1b2c3d4e5f6".into()],
            event_type: EventType::Move,
            item_id: ItemId::new_unchecked("bn-a3f8"),
            data: EventData::Move(MoveData {
                state: crate::model::item::State::Doing,
                reason: None,
                extra: BTreeMap::new(),
            }),
            event_hash: "blake3:d4e5f6789abc".into(),
        }
    }

    #[test]
    fn event_struct_fields() {
        let event = sample_create_event();
        assert_eq!(event.wall_ts_us, 1_708_012_200_123_456);
        assert_eq!(event.agent, "claude-abc");
        assert_eq!(event.itc, "itc:AQ");
        assert!(event.parents.is_empty());
        assert_eq!(event.event_type, EventType::Create);
        assert_eq!(event.item_id.as_str(), "bn-a3f8");
        assert!(matches!(event.data, EventData::Create(_)));
        assert_eq!(event.event_hash, "blake3:a1b2c3d4e5f6");
    }

    #[test]
    fn event_parents_str_empty() {
        let event = sample_create_event();
        assert_eq!(event.parents_str(), "");
    }

    #[test]
    fn event_parents_str_single() {
        let event = sample_move_event();
        assert_eq!(event.parents_str(), "blake3:a1b2c3d4e5f6");
    }

    #[test]
    fn event_parents_str_multiple() {
        let mut event = sample_move_event();
        event.parents = vec!["blake3:aaa".into(), "blake3:bbb".into()];
        assert_eq!(event.parents_str(), "blake3:aaa,blake3:bbb");
    }

    #[test]
    fn event_display() {
        let event = sample_create_event();
        let display = event.to_string();
        assert!(display.contains("1708012200123456"));
        assert!(display.contains("claude-abc"));
        assert!(display.contains("item.create"));
        assert!(display.contains("bn-a3f8"));
        assert!(display.contains("Fix auth retry"));
    }

    #[test]
    fn event_display_truncates_unicode_comment_without_panicking() {
        let mut event = sample_create_event();
        event.event_type = EventType::Comment;
        event.data = EventData::Comment(CommentData {
            body: "é".repeat(60),
            extra: BTreeMap::new(),
        });

        let display = event.to_string();
        assert!(display.contains("comment:"));
        assert!(display.contains("..."));
    }

    #[test]
    fn event_serde_json_roundtrip() {
        let event = sample_create_event();
        let json = serde_json::to_string(&event).expect("serialize");
        let deser: Event = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(event, deser);
    }

    #[test]
    fn event_serde_json_roundtrip_with_parents() {
        let event = sample_move_event();
        let json = serde_json::to_string(&event).expect("serialize");
        let deser: Event = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(event, deser);
    }

    #[test]
    fn event_serde_all_types_roundtrip() {
        let base = || -> (i64, String, String, Vec<String>, ItemId, String) {
            (
                1_000_000,
                "agent".into(),
                "itc:X".into(),
                vec![],
                ItemId::new_unchecked("bn-a7x"),
                "blake3:000".into(),
            )
        };

        let events: Vec<Event> = vec![
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Create,
                    item_id,
                    data: EventData::Create(CreateData {
                        title: "T".into(),
                        kind: crate::model::item::Kind::Task,
                        size: None,
                        urgency: crate::model::item::Urgency::Default,
                        labels: vec![],
                        parent: None,
                        causation: None,
                        description: None,
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Update,
                    item_id,
                    data: EventData::Update(UpdateData {
                        field: "title".into(),
                        value: json!("New"),
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Move,
                    item_id,
                    data: EventData::Move(MoveData {
                        state: crate::model::item::State::Done,
                        reason: Some("done".into()),
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Assign,
                    item_id,
                    data: EventData::Assign(AssignData {
                        agent: "alice".into(),
                        action: AssignAction::Assign,
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Comment,
                    item_id,
                    data: EventData::Comment(CommentData {
                        body: "Note".into(),
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Link,
                    item_id,
                    data: EventData::Link(LinkData {
                        target: "bn-b8y".into(),
                        link_type: "blocks".into(),
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Unlink,
                    item_id,
                    data: EventData::Unlink(UnlinkData {
                        target: "bn-b8y".into(),
                        link_type: None,
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Delete,
                    item_id,
                    data: EventData::Delete(DeleteData {
                        reason: None,
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Compact,
                    item_id,
                    data: EventData::Compact(CompactData {
                        summary: "TL;DR".into(),
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Snapshot,
                    item_id,
                    data: EventData::Snapshot(SnapshotData {
                        state: json!({"id": "bn-a7x"}),
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
            {
                let (ts, agent, itc, parents, item_id, hash) = base();
                Event {
                    wall_ts_us: ts,
                    agent,
                    itc,
                    parents,
                    event_type: EventType::Redact,
                    item_id,
                    data: EventData::Redact(RedactData {
                        target_hash: "blake3:xyz".into(),
                        reason: "oops".into(),
                        extra: BTreeMap::new(),
                    }),
                    event_hash: hash,
                }
            },
        ];

        assert_eq!(events.len(), 11, "should cover all 11 event types");

        for event in &events {
            let json = serde_json::to_string(event)
                .unwrap_or_else(|e| panic!("serialize {} failed: {e}", event.event_type));
            let deser: Event = serde_json::from_str(&json)
                .unwrap_or_else(|e| panic!("deserialize {} failed: {e}", event.event_type));
            assert_eq!(*event, deser, "roundtrip failed for {}", event.event_type);
        }
    }

    #[test]
    fn event_display_all_data_types() {
        // Smoke test: Display doesn't panic for any variant
        let events = vec![sample_create_event(), sample_move_event()];
        for event in events {
            let _ = event.to_string(); // Should not panic
        }
    }
}