x0x 0.14.6

Agent-to-agent gossip network for AI systems — no winners, no losers, just cooperation
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
//! Task identifier and metadata types for CRDT task lists.

use crate::identity::{AgentId, UserId};
use serde::{Deserialize, Serialize};
use std::fmt;

/// Task identifier derived from BLAKE3 hash.
///
/// TaskId is content-addressed: derived from BLAKE3(title || creator || timestamp).
/// This ensures:
/// - Unique IDs for different tasks
/// - Reproducible IDs from task content
/// - Collision resistance (BLAKE3 provides 256-bit security)
///
/// # Example
///
/// ```ignore
/// use x0x::crdt::TaskId;
/// use x0x::identity::AgentId;
///
/// let agent_id = AgentId([1u8; 32]);
/// let task_id = TaskId::new("Implement feature X", &agent_id, 1234567890);
/// println!("Task ID: {}", task_id);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TaskId([u8; 32]);

impl TaskId {
    /// Create a new TaskId from task content.
    ///
    /// The ID is deterministically derived from BLAKE3(title || creator || timestamp).
    /// This makes TaskIds content-addressed and reproducible.
    ///
    /// # Arguments
    ///
    /// * `title` - The task title
    /// * `creator` - The agent who created the task
    /// * `timestamp` - Creation timestamp (Unix milliseconds)
    ///
    /// # Returns
    ///
    /// A unique TaskId for this task.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let agent = AgentId([1u8; 32]);
    /// let id1 = TaskId::new("Same title", &agent, 1000);
    /// let id2 = TaskId::new("Same title", &agent, 1000);
    /// assert_eq!(id1, id2); // Same inputs = same ID
    ///
    /// let id3 = TaskId::new("Different title", &agent, 1000);
    /// assert_ne!(id1, id3); // Different inputs = different ID
    /// ```
    #[must_use]
    pub fn new(title: &str, creator: &AgentId, timestamp: u64) -> Self {
        let mut hasher = blake3::Hasher::new();
        hasher.update(title.as_bytes());
        hasher.update(creator.as_bytes());
        hasher.update(&timestamp.to_le_bytes());
        let hash = hasher.finalize();
        Self(*hash.as_bytes())
    }

    /// Get the raw 32-byte representation of this TaskId.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Create a TaskId from raw bytes.
    ///
    /// Use this when deserializing TaskIds from storage or network.
    ///
    /// # Arguments
    ///
    /// * `bytes` - 32-byte array
    ///
    /// # Returns
    ///
    /// A TaskId wrapping the provided bytes.
    #[must_use]
    pub fn from_bytes(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    /// Create a TaskId from a hex-encoded string.
    ///
    /// # Arguments
    ///
    /// * `s` - Hex-encoded string (64 characters)
    ///
    /// # Returns
    ///
    /// A TaskId if parsing succeeds.
    ///
    /// # Errors
    ///
    /// Returns an error if the string is not valid hex or not 64 characters.
    pub fn from_string(s: &str) -> Result<Self, String> {
        if s.len() != 64 {
            return Err(format!(
                "Invalid TaskId length: expected 64 hex chars, got {}",
                s.len()
            ));
        }

        let bytes = hex::decode(s).map_err(|e| format!("Invalid hex encoding: {}", e))?;

        if bytes.len() != 32 {
            return Err(format!(
                "Invalid TaskId bytes: expected 32 bytes, got {}",
                bytes.len()
            ));
        }

        let mut array = [0u8; 32];
        array.copy_from_slice(&bytes);
        Ok(Self(array))
    }
}

impl fmt::Display for TaskId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", hex::encode(self.0))
    }
}

/// Metadata for a task item.
///
/// Contains all the descriptive information about a task that can be
/// updated after creation. The actual checkbox state is managed separately
/// in the TaskItem CRDT.
///
/// # Example
///
/// ```ignore
/// use x0x::crdt::TaskMetadata;
/// use x0x::identity::AgentId;
///
/// let agent = AgentId([1u8; 32]);
/// let metadata = TaskMetadata {
///     title: "Implement feature X".to_string(),
///     description: "Add support for Y in module Z".to_string(),
///     priority: 128,
///     created_by: agent,
///     created_at: 1234567890,
///     tags: vec!["backend".to_string(), "api".to_string()],
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskMetadata {
    /// The task title (short summary).
    pub title: String,

    /// The task description (detailed explanation).
    pub description: String,

    /// Task priority (0-255, higher = more important).
    ///
    /// Suggested values:
    /// - 255: Critical/Urgent
    /// - 192: High priority
    /// - 128: Normal priority (default)
    /// - 64: Low priority
    /// - 0: Minimal priority
    pub priority: u8,

    /// The agent who created this task.
    pub created_by: AgentId,

    /// The human owner of the agent that created this task (if known).
    ///
    /// When set, this enables trust attribution: tasks can be traced
    /// back to a human identity across different agents and machines.
    pub owner: Option<UserId>,

    /// When this task was created (Unix timestamp in milliseconds).
    pub created_at: u64,

    /// Tags for categorizing tasks.
    ///
    /// Examples: ["backend", "frontend", "bug", "feature", "docs"]
    pub tags: Vec<String>,
}

impl TaskMetadata {
    /// Create new task metadata.
    ///
    /// # Arguments
    ///
    /// * `title` - Task title
    /// * `description` - Task description
    /// * `priority` - Priority level (0-255)
    /// * `created_by` - Creator's agent ID
    /// * `created_at` - Creation timestamp
    ///
    /// # Returns
    ///
    /// A new TaskMetadata instance.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let agent = AgentId([1u8; 32]);
    /// let metadata = TaskMetadata::new(
    ///     "Add tests",
    ///     "Write unit tests for parser module",
    ///     128,
    ///     agent,
    ///     1234567890,
    /// );
    /// ```
    #[must_use]
    pub fn new(
        title: impl Into<String>,
        description: impl Into<String>,
        priority: u8,
        created_by: AgentId,
        created_at: u64,
    ) -> Self {
        Self {
            title: title.into(),
            description: description.into(),
            priority,
            created_by,
            owner: None,
            created_at,
            tags: Vec::new(),
        }
    }

    /// Create metadata with default priority (128).
    ///
    /// # Arguments
    ///
    /// * `title` - Task title
    /// * `description` - Task description
    /// * `created_by` - Creator's agent ID
    /// * `created_at` - Creation timestamp
    ///
    /// # Returns
    ///
    /// A new TaskMetadata instance with priority=128.
    #[must_use]
    pub fn with_default_priority(
        title: impl Into<String>,
        description: impl Into<String>,
        created_by: AgentId,
        created_at: u64,
    ) -> Self {
        Self::new(title, description, 128, created_by, created_at)
    }

    /// Set the human owner of this task's creator.
    ///
    /// # Arguments
    ///
    /// * `user_id` - The owner's user ID
    ///
    /// # Returns
    ///
    /// Self for chaining.
    #[must_use]
    pub fn with_owner(mut self, user_id: UserId) -> Self {
        self.owner = Some(user_id);
        self
    }

    /// Add a tag to this task.
    ///
    /// # Arguments
    ///
    /// * `tag` - Tag to add
    ///
    /// # Returns
    ///
    /// Self for chaining.
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tags.push(tag.into());
        self
    }

    /// Add multiple tags to this task.
    ///
    /// # Arguments
    ///
    /// * `tags` - Iterator of tags to add
    ///
    /// # Returns
    ///
    /// Self for chaining.
    pub fn with_tags<I, S>(mut self, tags: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.tags.extend(tags.into_iter().map(|t| t.into()));
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn agent(n: u8) -> AgentId {
        AgentId([n; 32])
    }

    #[test]
    fn test_task_id_deterministic() {
        let agent = agent(1);
        let title = "Test task";
        let timestamp = 1000;

        let id1 = TaskId::new(title, &agent, timestamp);
        let id2 = TaskId::new(title, &agent, timestamp);

        assert_eq!(id1, id2, "Same inputs should produce same TaskId");
    }

    #[test]
    fn test_task_id_different_titles() {
        let agent = agent(1);
        let timestamp = 1000;

        let id1 = TaskId::new("Title A", &agent, timestamp);
        let id2 = TaskId::new("Title B", &agent, timestamp);

        assert_ne!(id1, id2, "Different titles should produce different IDs");
    }

    #[test]
    fn test_task_id_different_creators() {
        let agent1 = agent(1);
        let agent2 = agent(2);
        let title = "Same title";
        let timestamp = 1000;

        let id1 = TaskId::new(title, &agent1, timestamp);
        let id2 = TaskId::new(title, &agent2, timestamp);

        assert_ne!(id1, id2, "Different creators should produce different IDs");
    }

    #[test]
    fn test_task_id_different_timestamps() {
        let agent = agent(1);
        let title = "Same title";

        let id1 = TaskId::new(title, &agent, 1000);
        let id2 = TaskId::new(title, &agent, 2000);

        assert_ne!(
            id1, id2,
            "Different timestamps should produce different IDs"
        );
    }

    #[test]
    fn test_task_id_as_bytes() {
        let agent = agent(1);
        let id = TaskId::new("Test", &agent, 1000);
        let bytes = id.as_bytes();

        assert_eq!(bytes.len(), 32, "TaskId should be 32 bytes");
    }

    #[test]
    fn test_task_id_from_bytes() {
        let original_bytes = [42u8; 32];
        let id = TaskId::from_bytes(original_bytes);

        assert_eq!(id.as_bytes(), &original_bytes);
    }

    #[test]
    fn test_task_id_display() {
        let agent = agent(1);
        let id = TaskId::new("Test", &agent, 1000);
        let display = format!("{}", id);

        // Should be 64 hex characters (32 bytes * 2)
        assert_eq!(display.len(), 64);
        // Should only contain hex characters
        assert!(display.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_task_id_serialization() {
        let agent = agent(1);
        let id = TaskId::new("Test", &agent, 1000);

        let serialized = bincode::serialize(&id).ok().unwrap();
        let deserialized: TaskId = bincode::deserialize(&serialized).ok().unwrap();

        assert_eq!(id, deserialized);
    }

    #[test]
    fn test_task_metadata_new() {
        let agent = agent(1);
        let metadata = TaskMetadata::new("Title", "Description", 200, agent, 1234567890);

        assert_eq!(metadata.title, "Title");
        assert_eq!(metadata.description, "Description");
        assert_eq!(metadata.priority, 200);
        assert_eq!(metadata.created_by, agent);
        assert_eq!(metadata.created_at, 1234567890);
        assert!(metadata.tags.is_empty());
    }

    #[test]
    fn test_task_metadata_default_priority() {
        let agent = agent(1);
        let metadata =
            TaskMetadata::with_default_priority("Title", "Description", agent, 1234567890);

        assert_eq!(metadata.priority, 128);
    }

    #[test]
    fn test_task_metadata_with_tag() {
        let agent = agent(1);
        let metadata = TaskMetadata::new("Title", "Desc", 128, agent, 1000).with_tag("backend");

        assert_eq!(metadata.tags.len(), 1);
        assert_eq!(metadata.tags[0], "backend");
    }

    #[test]
    fn test_task_metadata_with_tags() {
        let agent = agent(1);
        let metadata = TaskMetadata::new("Title", "Desc", 128, agent, 1000)
            .with_tags(vec!["backend", "api", "feature"]);

        assert_eq!(metadata.tags.len(), 3);
        assert_eq!(metadata.tags[0], "backend");
        assert_eq!(metadata.tags[1], "api");
        assert_eq!(metadata.tags[2], "feature");
    }

    #[test]
    fn test_task_metadata_chaining() {
        let agent = agent(1);
        let metadata = TaskMetadata::new("Title", "Desc", 128, agent, 1000)
            .with_tag("backend")
            .with_tag("urgent")
            .with_tags(vec!["api", "feature"]);

        assert_eq!(metadata.tags.len(), 4);
        assert_eq!(metadata.tags, vec!["backend", "urgent", "api", "feature"]);
    }

    #[test]
    fn test_task_metadata_serialization() {
        let agent = agent(1);
        let metadata = TaskMetadata::new("Title", "Description", 200, agent, 1234567890)
            .with_tags(vec!["tag1", "tag2"]);

        let serialized = bincode::serialize(&metadata).ok().unwrap();
        let deserialized: TaskMetadata = bincode::deserialize(&serialized).ok().unwrap();

        assert_eq!(metadata, deserialized);
    }

    #[test]
    fn test_task_metadata_equality() {
        let agent = agent(1);

        let meta1 = TaskMetadata::new("Title", "Desc", 128, agent, 1000).with_tag("test");

        let meta2 = TaskMetadata::new("Title", "Desc", 128, agent, 1000).with_tag("test");

        assert_eq!(meta1, meta2);
    }

    #[test]
    fn test_task_metadata_inequality_different_title() {
        let agent = agent(1);

        let meta1 = TaskMetadata::new("Title A", "Desc", 128, agent, 1000);
        let meta2 = TaskMetadata::new("Title B", "Desc", 128, agent, 1000);

        assert_ne!(meta1, meta2);
    }

    #[test]
    fn test_task_metadata_inequality_different_tags() {
        let agent = agent(1);

        let meta1 = TaskMetadata::new("Title", "Desc", 128, agent, 1000).with_tag("tag1");

        let meta2 = TaskMetadata::new("Title", "Desc", 128, agent, 1000).with_tag("tag2");

        assert_ne!(meta1, meta2);
    }
}