Skip to main content

heddle_thread_api/
collaboration.rs

1//! Portable collaboration commands. Original parent records reconstruct both
2//! causal frontiers; callers never translate UI version tokens into proofs.
3mod references;
4mod tags;
5use std::collections::BTreeSet;
6
7use crypto::{Signer, thread_operation::SignedOperation};
8use heddle_object_model::object::{
9    Attribution, CollabOpId, CollaborationIdempotencyKey, CollaborationMetadata,
10    CollaborationOperationBodyV1, CollaborationOperationEnvelope, ContentHash, ContextRevision,
11    DiscussionRecordId,
12    thread_replication::{OPERATION_FORMAT, ThreadOperation, ThreadOperationBody},
13};
14pub use references::{
15    anchor, anchor_ref, audience, mention, mention_ref, source_target_ref, visibility,
16};
17pub use tags::{
18    annotation_query, annotation_source, annotation_source_ref, annotation_tag, annotation_tag_ref,
19    annotation_tags, annotation_value, annotation_value_ref,
20};
21
22use crate::{
23    contract::{RecordSignature, SignedRecord},
24    transport::Error,
25};
26
27/// Verified original operation, before host authorization or causal admission.
28/// A valid signature never establishes a principal's spool permissions.
29pub fn verify(record: &SignedRecord) -> Result<ThreadOperation, Error> {
30    if record.format != OPERATION_FORMAT || record.signatures.len() != 1 {
31        return Err(Error::Protocol("unsupported collaboration signed record"));
32    }
33    let operation = SignedOperation {
34        canonical: record.canonical_record.clone(),
35        signature: record.signatures[0].signature.clone(),
36    }
37    .verify()
38    .map_err(|_| Error::Protocol("invalid collaboration author signature"))?;
39    if record.signatures[0].public_key != operation.publisher {
40        return Err(Error::Protocol(
41            "collaboration signature key differs from publisher",
42        ));
43    }
44    if !matches!(
45        operation.body,
46        ThreadOperationBody::Discussion(_) | ThreadOperationBody::Context(_)
47    ) {
48        return Err(Error::Protocol(
49            "collaboration requires a discussion or context operation",
50        ));
51    }
52    Ok(operation)
53}
54
55/// Typed content plus the account identity which the receiving host will bind
56/// to its independently verified delivery credential. Display names are not IDs.
57pub struct Command {
58    pub discussion: DiscussionRecordId,
59    pub operation_id: CollaborationIdempotencyKey,
60    pub metadata: CollaborationMetadata,
61    pub author: Attribution,
62    pub occurred_at_ms: i64,
63    pub body: CollaborationOperationBodyV1,
64}
65
66impl Command {
67    /// Sign after observing original frontier records. Concurrent operations can
68    /// share parents; observing both lets a subsequent command join both heads.
69    /// Root commands use an empty parent slice. Never pass mutable view versions.
70    pub fn sign(
71        self,
72        parents: &[SignedRecord],
73        signer: &impl Signer,
74    ) -> Result<SignedRecord, Error> {
75        if parents.len() > 128 {
76            return Err(Error::Protocol(
77                "collaboration has more than 128 causal parents",
78            ));
79        }
80        let thread = self.metadata.scope.thread.ok_or(Error::Protocol(
81            "Thread command requires native Thread scope",
82        ))?;
83        let mut outer = BTreeSet::new();
84        let mut inner = BTreeSet::new();
85        for record in parents {
86            let operation = verify(record)?;
87            if operation.thread != thread {
88                return Err(Error::Protocol("parent belongs to another Thread"));
89            }
90            let ThreadOperationBody::Discussion(bytes) = &operation.body else {
91                return Err(Error::Protocol("parent is not a collaboration operation"));
92            };
93            let decoded = CollaborationOperationEnvelope::decode(bytes)
94                .map_err(|_| Error::Protocol("invalid collaboration parent"))?;
95            if decoded.operation.discussion_id != self.discussion
96                || decoded
97                    .operation
98                    .metadata
99                    .as_ref()
100                    .is_none_or(|m| m.scope != self.metadata.scope)
101            {
102                return Err(Error::Protocol(
103                    "parent belongs to another discussion or spool",
104                ));
105            }
106            let id = operation
107                .id()
108                .map_err(|error| Error::Io(error.to_string()))?;
109            if !outer.insert(id) {
110                return Err(Error::Protocol("duplicate collaboration causal parent"));
111            }
112            inner.insert(decoded.operation_id);
113        }
114        self.sign_frontier(thread, outer, inner, signer)
115    }
116
117    /// Sign after observing discussion heads by original operation id.
118    ///
119    /// Hosted ObserveCollaboration returns turn/open op ids, not the original
120    /// signed records. Root commands still use an empty parent slice.
121    pub fn sign_parent_ids(
122        self,
123        parent_ids: &[ContentHash],
124        signer: &impl Signer,
125    ) -> Result<SignedRecord, Error> {
126        if parent_ids.len() > 128 {
127            return Err(Error::Protocol(
128                "collaboration has more than 128 causal parents",
129            ));
130        }
131        let thread = self.metadata.scope.thread.ok_or(Error::Protocol(
132            "Thread command requires native Thread scope",
133        ))?;
134        let mut outer = BTreeSet::new();
135        let mut inner = BTreeSet::new();
136        for id in parent_ids {
137            if !outer.insert(*id) {
138                return Err(Error::Protocol("duplicate collaboration causal parent"));
139            }
140            inner.insert(CollabOpId::from_bytes(*id.as_bytes()));
141        }
142        self.sign_frontier(thread, outer, inner, signer)
143    }
144
145    fn sign_frontier(
146        self,
147        thread: ContentHash,
148        outer: BTreeSet<ContentHash>,
149        inner: BTreeSet<CollabOpId>,
150        signer: &impl Signer,
151    ) -> Result<SignedRecord, Error> {
152        let mut body = self.body;
153        if let CollaborationOperationBodyV1::Resolve {
154            resolution:
155                heddle_object_model::object::CollaborationResolution::IntoContext { context },
156        } = &mut body
157        {
158            context.parents = outer.iter().copied().collect();
159        }
160        let envelope = CollaborationOperationEnvelope::new(
161            self.discussion,
162            inner.into_iter().collect(),
163            self.operation_id,
164            self.author,
165            self.occurred_at_ms,
166            body,
167        )
168        .and_then(|envelope| envelope.with_metadata(self.metadata))
169        .map_err(|error| Error::Io(error.to_string()))?;
170        let operation = ThreadOperation {
171            version: 1,
172            thread,
173            parents: outer,
174            publisher: signer
175                .public_key()
176                .try_into()
177                .map_err(|_| Error::Protocol("collaboration requires an Ed25519 signer"))?,
178            body: ThreadOperationBody::Discussion(
179                envelope
180                    .encode()
181                    .map_err(|error| Error::Io(error.to_string()))?,
182            ),
183        };
184        let signed = SignedOperation::sign(&operation, signer)
185            .map_err(|error| Error::Io(error.to_string()))?;
186        Ok(SignedRecord {
187            format: OPERATION_FORMAT.into(),
188            canonical_record: signed.canonical,
189            signatures: vec![RecordSignature {
190                public_key: operation.publisher.to_vec(),
191                signature: signed.signature,
192            }],
193        })
194    }
195}
196
197/// Append an immutable context revision. Original signed parent records bind
198/// the same stable record and scope; concurrent revisions remain separate heads.
199pub fn sign_context(
200    context: ContextRevision,
201    parents: &[SignedRecord],
202    signer: &impl Signer,
203) -> Result<SignedRecord, Error> {
204    if parents.len() > 128 {
205        return Err(Error::Protocol("context has more than 128 causal parents"));
206    }
207    let thread = context.metadata.scope.thread.ok_or(Error::Protocol(
208        "Thread context requires native Thread scope",
209    ))?;
210    if parents.is_empty() && context.extracted_from.is_some() {
211        return Err(Error::Protocol(
212            "context extraction requires a signed discussion resolution",
213        ));
214    }
215    let mut ids = BTreeSet::new();
216    for record in parents {
217        let parent = verify(record)?;
218        let previous = parent
219            .context_revision()
220            .map_err(|error| Error::Io(error.to_string()))?
221            .ok_or(Error::Protocol(
222                "context parent is not a context revision or extraction",
223            ))?;
224        if parent.thread != thread
225            || previous.id != context.id
226            || previous.metadata.scope != context.metadata.scope
227            || previous.extracted_from != context.extracted_from
228        {
229            return Err(Error::Protocol(
230                "context parent belongs to another record or scope",
231            ));
232        }
233        if !ids.insert(parent.id().map_err(|error| Error::Io(error.to_string()))?) {
234            return Err(Error::Protocol("duplicate context causal parent"));
235        }
236    }
237    sign_context_ids(context, thread, ids, signer)
238}
239
240/// Sign a context revision after observing current heads by original
241/// operation id. First PutContext stays parentless; supersede/edit parents
242/// the observed causal heads.
243pub fn sign_context_parent_ids(
244    context: ContextRevision,
245    parent_ids: &[ContentHash],
246    signer: &impl Signer,
247) -> Result<SignedRecord, Error> {
248    if parent_ids.len() > 128 {
249        return Err(Error::Protocol("context has more than 128 causal parents"));
250    }
251    let thread = context.metadata.scope.thread.ok_or(Error::Protocol(
252        "Thread context requires native Thread scope",
253    ))?;
254    if parent_ids.is_empty() && context.extracted_from.is_some() {
255        return Err(Error::Protocol(
256            "context extraction requires a signed discussion resolution",
257        ));
258    }
259    let mut ids = BTreeSet::new();
260    for id in parent_ids {
261        if !ids.insert(*id) {
262            return Err(Error::Protocol("duplicate context causal parent"));
263        }
264    }
265    sign_context_ids(context, thread, ids, signer)
266}
267
268fn sign_context_ids(
269    mut context: ContextRevision,
270    thread: ContentHash,
271    ids: BTreeSet<ContentHash>,
272    signer: &impl Signer,
273) -> Result<SignedRecord, Error> {
274    context.parents = ids.iter().copied().collect();
275    let operation = ThreadOperation {
276        version: 1,
277        thread,
278        parents: ids,
279        publisher: signer
280            .public_key()
281            .try_into()
282            .map_err(|_| Error::Protocol("context requires an Ed25519 signer"))?,
283        body: ThreadOperationBody::Context(
284            context
285                .encode()
286                .map_err(|error| Error::Io(error.to_string()))?,
287        ),
288    };
289    let signed =
290        SignedOperation::sign(&operation, signer).map_err(|error| Error::Io(error.to_string()))?;
291    Ok(SignedRecord {
292        format: OPERATION_FORMAT.into(),
293        canonical_record: signed.canonical,
294        signatures: vec![RecordSignature {
295            public_key: operation.publisher.to_vec(),
296            signature: signed.signature,
297        }],
298    })
299}
300
301/// The public causal vocabulary is the outer replication operation identity.
302pub fn operation_id(record: &SignedRecord) -> Result<ContentHash, Error> {
303    verify(record)?
304        .id()
305        .map_err(|error| Error::Io(error.to_string()))
306}
307
308#[cfg(test)]
309mod tests {
310    use crypto::Ed25519Signer;
311    use heddle_object_model::object::{
312        CollaborationActor, CollaborationAnchor, CollaborationScope, DiscussionTurnV1, Principal,
313        VisibilityTier,
314    };
315    use uuid::Uuid;
316
317    use super::*;
318
319    fn command(discussion: DiscussionRecordId, body: CollaborationOperationBodyV1) -> Command {
320        Command {
321            discussion,
322            operation_id: CollaborationIdempotencyKey::new("operation-1").expect("operation ID"),
323            metadata: CollaborationMetadata {
324                scope: CollaborationScope {
325                    spool: Uuid::from_u128(1),
326                    thread: Some(ContentHash::from_bytes([2; 32])),
327                },
328                actor: CollaborationActor {
329                    principal_id: Uuid::from_u128(3),
330                    agent_id: Some("agent-4".into()),
331                },
332                mentions: vec![],
333            },
334            author: Attribution::human(Principal::new("Account", "")),
335            occurred_at_ms: 100,
336            body,
337        }
338    }
339    fn append(body: &str) -> CollaborationOperationBodyV1 {
340        CollaborationOperationBodyV1::AppendTurn {
341            turn: DiscussionTurnV1::new(body).expect("turn"),
342        }
343    }
344    #[test]
345    fn signed_parents_preserve_concurrent_heads_and_reject_changed_proofs() {
346        let signer = Ed25519Signer::from_seed(&[7; 32]).expect("signer");
347        let discussion = DiscussionRecordId::generate();
348        let root = command(
349            discussion,
350            CollaborationOperationBodyV1::Open {
351                blocking: false,
352                title: "Review".into(),
353                anchor: CollaborationAnchor::Repository,
354                visibility: VisibilityTier::Private {
355                    scope_label: "owner".into(),
356                },
357                turn: DiscussionTurnV1::new("Review this Thread").expect("turn"),
358                thread_ref: None,
359            },
360        )
361        .sign(&[], &signer)
362        .expect("root");
363        let left = command(discussion, append("left"))
364            .sign(std::slice::from_ref(&root), &signer)
365            .expect("left");
366        let right = command(discussion, append("right"))
367            .sign(std::slice::from_ref(&root), &signer)
368            .expect("right");
369        assert_ne!(
370            operation_id(&left).expect("left ID"),
371            operation_id(&right).expect("right ID")
372        );
373        let joined = command(discussion, append("both observed"))
374            .sign(&[left.clone(), right.clone()], &signer)
375            .expect("join");
376        assert_eq!(
377            verify(&joined).expect("verified").parents,
378            BTreeSet::from([
379                operation_id(&left).expect("left ID"),
380                operation_id(&right).expect("right ID")
381            ])
382        );
383        let mut changed = root.clone();
384        changed.signatures[0].signature[0] ^= 1;
385        assert!(
386            command(discussion, append("bad proof"))
387                .sign(&[changed], &signer)
388                .is_err()
389        );
390        assert!(
391            command(DiscussionRecordId::generate(), append("wrong discussion"))
392                .sign(std::slice::from_ref(&root), &signer)
393                .is_err()
394        );
395        assert!(
396            command(discussion, append("duplicate parent"))
397                .sign(&[root.clone(), root], &signer)
398                .is_err()
399        );
400    }
401    #[test]
402    fn observed_parent_ids_are_sorted_unique_and_required_for_append() {
403        let signer = Ed25519Signer::from_seed(&[7; 32]).expect("signer");
404        let discussion = DiscussionRecordId::generate();
405        let root = command(
406            discussion,
407            CollaborationOperationBodyV1::Open {
408                blocking: false,
409                title: "Review".into(),
410                anchor: CollaborationAnchor::Repository,
411                visibility: VisibilityTier::Private {
412                    scope_label: "owner".into(),
413                },
414                turn: DiscussionTurnV1::new("Review this Thread").expect("turn"),
415                thread_ref: None,
416            },
417        )
418        .sign(&[], &signer)
419        .expect("root");
420        let root_id = operation_id(&root).expect("root ID");
421        let appended = command(discussion, append("follow-up"))
422            .sign_parent_ids(&[root_id], &signer)
423            .expect("append");
424        assert_eq!(
425            verify(&appended).expect("verified").parents,
426            BTreeSet::from([root_id])
427        );
428        assert!(
429            command(discussion, append("no parent"))
430                .sign_parent_ids(&[], &signer)
431                .is_err()
432        );
433    }
434    #[test]
435    fn context_revisions_retain_history_and_bind_parent_record_identity() {
436        let signer = Ed25519Signer::from_seed(&[7; 32]).expect("signer");
437        let context = ContextRevision {
438            version: 2,
439            id: Uuid::from_u128(9),
440            parents: vec![],
441            metadata: command(DiscussionRecordId::generate(), append("metadata")).metadata,
442            anchor: CollaborationAnchor::Repository,
443            content: "Original rationale".into(),
444            tags: vec!["decision".into()],
445            supersedes: None,
446            extracted_from: None,
447            occurred_at_ms: 100,
448            provenance: None,
449        };
450        let first = sign_context(context.clone(), &[], &signer).expect("first context");
451        let mut revised = context.clone();
452        revised.content = "Revised rationale".into();
453        let second =
454            sign_context(revised.clone(), std::slice::from_ref(&first), &signer).expect("revision");
455        assert_eq!(
456            verify(&second).expect("second").parents,
457            BTreeSet::from([operation_id(&first).expect("first ID")])
458        );
459        let ThreadOperationBody::Context(bytes) = verify(&first).expect("first").body else {
460            panic!("context");
461        };
462        assert_eq!(
463            ContextRevision::decode(&bytes)
464                .expect("original context")
465                .content,
466            "Original rationale"
467        );
468        revised.id = Uuid::from_u128(10);
469        assert!(
470            sign_context(revised, std::slice::from_ref(&first), &signer).is_err(),
471            "parent cannot silently change record identity"
472        );
473    }
474    #[test]
475    fn extracted_context_keeps_original_resolution_proof_and_actor_binding() {
476        use heddle_object_model::object::{
477            CollaborationResolution, StateId, thread_replication::ThreadGenesis,
478        };
479        let signer = Ed25519Signer::from_seed(&[7; 32]).expect("signer");
480        let genesis = ThreadGenesis {
481            version: 1,
482            spool: Uuid::from_u128(1).to_string(),
483            parent: None,
484            base: StateId::from_bytes([3; 32]),
485            name: "extraction".into(),
486            intent: "retain proof".into(),
487            creator: signer.public_key().try_into().expect("key"),
488            owner: heddle_object_model::object::thread_replication::GenesisOwner::LocalKey(
489                signer.public_key().try_into().expect("key"),
490            ),
491            nonce: vec![1; 16],
492        };
493        let discussion = DiscussionRecordId::generate();
494        let make = |body| {
495            let mut command = command(discussion, body);
496            command.metadata.scope.thread = Some(genesis.id().expect("Thread"));
497            command
498        };
499        let open = make(CollaborationOperationBodyV1::Open {
500            blocking: true,
501            title: "Review".into(),
502            anchor: CollaborationAnchor::Repository,
503            visibility: VisibilityTier::Public,
504            turn: DiscussionTurnV1::new("Evidence").expect("turn"),
505            thread_ref: None,
506        })
507        .sign(&[], &signer)
508        .expect("root");
509        let mut context = ContextRevision {
510            version: 2,
511            id: Uuid::from_u128(9),
512            parents: vec![],
513            metadata: make(append("metadata")).metadata,
514            anchor: CollaborationAnchor::Repository,
515            content: "Durable rationale".into(),
516            tags: vec!["decision".into()],
517            supersedes: None,
518            extracted_from: Some(discussion),
519            occurred_at_ms: 100,
520            provenance: None,
521        };
522        let extracted = make(CollaborationOperationBodyV1::Resolve {
523            resolution: CollaborationResolution::IntoContext {
524                context: context.clone(),
525            },
526        })
527        .sign(std::slice::from_ref(&open), &signer)
528        .expect("atomic extraction");
529        let extracted_operation = verify(&extracted).expect("original resolution");
530        extracted_operation
531            .validate_parents(&genesis, &[verify(&open).expect("root")])
532            .expect("discussion causal proof");
533        assert_eq!(
534            extracted_operation
535                .context_revision()
536                .expect("extracted context")
537                .expect("context")
538                .parents,
539            vec![operation_id(&open).expect("root ID")]
540        );
541        context.content = "Refined rationale".into();
542        let revision = sign_context(context.clone(), std::slice::from_ref(&extracted), &signer)
543            .expect("revise directly from original extraction");
544        verify(&revision)
545            .expect("revision")
546            .validate_parents(&genesis, &[extracted_operation])
547            .expect("context retains discussion extraction as causal root");
548        let mut detached = verify(&revision).expect("context operation");
549        let mut detached_context = detached
550            .context_revision()
551            .expect("decode")
552            .expect("context");
553        detached_context.extracted_from = None;
554        detached.body = ThreadOperationBody::Context(detached_context.encode().expect("context"));
555        assert!(
556            detached
557                .validate_parents(
558                    &genesis,
559                    &[verify(&extracted).expect("original extraction")]
560                )
561                .is_err(),
562            "context revision cannot strip its extraction provenance"
563        );
564        let mut invented_root = verify(&revision).expect("context operation");
565        let mut invented_context = invented_root
566            .context_revision()
567            .expect("decode")
568            .expect("context");
569        invented_context.parents.clear();
570        invented_root.parents.clear();
571        invented_root.body =
572            ThreadOperationBody::Context(invented_context.encode().expect("context"));
573        assert!(
574            invented_root.validate_parents(&genesis, &[]).is_err(),
575            "extraction requires an original signed discussion resolution"
576        );
577        context.metadata.actor.principal_id = Uuid::from_u128(10);
578        assert!(
579            make(CollaborationOperationBodyV1::Resolve {
580                resolution: CollaborationResolution::IntoContext { context }
581            })
582            .sign(&[open], &signer)
583            .is_err(),
584            "extraction cannot assert a different author than the signed resolution"
585        );
586    }
587    #[test]
588    fn canonical_browser_interop_vectors() {
589        use heddle_object_model::object::{CollaborationMention, CollaborationResolution, StateId};
590        let signer = Ed25519Signer::from_seed(&[7; 32]).expect("signer");
591        let discussion: DiscussionRecordId = "disc-01980000-0000-7000-8000-000000000123"
592            .parse()
593            .expect("stable discussion ID");
594        let open = command(
595            discussion,
596            CollaborationOperationBodyV1::Open {
597                blocking: true,
598                title: "Review".into(),
599                anchor: CollaborationAnchor::Repository,
600                visibility: VisibilityTier::Public,
601                turn: DiscussionTurnV1::new("First turn").expect("turn"),
602                thread_ref: None,
603            },
604        )
605        .sign(&[], &signer)
606        .expect("open");
607        let mut append_command = command(discussion, append("See the reviewed state"));
608        append_command.metadata.mentions = vec![CollaborationMention::State {
609            spool: Uuid::from_u128(1),
610            state: StateId::from_bytes([5; 32]),
611        }];
612        let append = append_command
613            .sign(std::slice::from_ref(&open), &signer)
614            .expect("append");
615        let resolve = command(
616            discussion,
617            CollaborationOperationBodyV1::Resolve {
618                resolution: CollaborationResolution::Dismissed {
619                    reason: "Verified".into(),
620                },
621            },
622        )
623        .sign(std::slice::from_ref(&append), &signer)
624        .expect("resolve");
625        let reopen = command(
626            discussion,
627            CollaborationOperationBodyV1::Reopen {
628                reason: "New evidence".into(),
629            },
630        )
631        .sign(std::slice::from_ref(&resolve), &signer)
632        .expect("reopen");
633        let context = ContextRevision {
634            version: 2,
635            id: Uuid::from_u128(9),
636            parents: vec![],
637            metadata: command(
638                discussion,
639                CollaborationOperationBodyV1::Reopen {
640                    reason: "metadata".into(),
641                },
642            )
643            .metadata,
644            anchor: CollaborationAnchor::Repository,
645            content: "Design rationale".into(),
646            tags: vec!["decision".into()],
647            supersedes: None,
648            extracted_from: Some(discussion),
649            occurred_at_ms: 100,
650            provenance: None,
651        };
652        let extraction = command(
653            discussion,
654            CollaborationOperationBodyV1::Resolve {
655                resolution: CollaborationResolution::IntoContext {
656                    context: context.clone(),
657                },
658            },
659        )
660        .sign(std::slice::from_ref(&reopen), &signer)
661        .expect("extraction");
662        let mut revision = context.clone();
663        revision.content = "Refined extracted rationale".into();
664        let extracted_revision = sign_context(revision, std::slice::from_ref(&extraction), &signer)
665            .expect("extracted context revision");
666        let mut standalone_context = context;
667        standalone_context.extracted_from = None;
668        let context = sign_context(standalone_context, &[], &signer).expect("context");
669        let source_record = |revision, target| {
670            command(
671                discussion,
672                CollaborationOperationBodyV1::Open {
673                    blocking: true,
674                    title: "Review source".into(),
675                    visibility: VisibilityTier::Public,
676                    anchor: CollaborationAnchor::Source {
677                        source: heddle_object_model::object::CollaborationSourceAnchor {
678                            revision,
679                            path: "src/main.rs".into(),
680                            symbol_id: "run".into(),
681                            start_line: Some(12),
682                            end_line: Some(18),
683                            target,
684                        },
685                    },
686                    turn: DiscussionTurnV1::new("Check these lines").expect("turn"),
687                    thread_ref: None,
688                },
689            )
690            .sign(&[], &signer)
691            .expect("source root")
692        };
693        let source_state = source_record(
694            heddle_object_model::object::CollaborationRevision::State {
695                state_id: StateId::from_bytes([5; 32]),
696            },
697            None,
698        );
699        let source_git = source_record(
700            heddle_object_model::object::CollaborationRevision::GitCommit {
701                oid: "a".repeat(40),
702            },
703            None,
704        );
705        let mut structured = verify(&context)
706            .expect("context proof")
707            .context_revision()
708            .expect("decode")
709            .expect("context");
710        structured.tags = vec![
711            "decision".into(),
712            heddle_object_model::object::AnnotationTag::Symbol {
713                name: "authorize".into(),
714                target: Some(heddle_object_model::object::AnnotationSourceReference {
715                    scope: structured.metadata.scope.clone(),
716                    source: heddle_object_model::object::CollaborationSourceAnchor {
717                        revision: heddle_object_model::object::CollaborationRevision::GitCommit {
718                            oid: "a".repeat(40),
719                        },
720                        path: "src/auth.rs".into(),
721                        symbol_id: "auth::authorize".into(),
722                        start_line: Some(12),
723                        end_line: Some(18),
724                        target: None,
725                    },
726                }),
727            },
728            heddle_object_model::object::AnnotationTag::Property {
729                key: "confidence".into(),
730                value: heddle_object_model::object::AnnotationValue::Decimal(
731                    heddle_object_model::object::AnnotationDecimal {
732                        coefficient: 9,
733                        scale: 1,
734                    },
735                ),
736            },
737            heddle_object_model::object::AnnotationTag::Property {
738                key: "requires_review".into(),
739                value: heddle_object_model::object::AnnotationValue::Boolean(false),
740            },
741            heddle_object_model::object::AnnotationTag::Property {
742                key: "large".into(),
743                value: heddle_object_model::object::AnnotationValue::Integer(i64::MAX),
744            },
745            heddle_object_model::object::AnnotationTag::Property {
746                key: "severity".into(),
747                value: heddle_object_model::object::AnnotationValue::Text("high".into()),
748            },
749        ];
750        let structured_context =
751            sign_context(structured, &[], &signer).expect("structured context");
752        use heddle_object_model::object::{
753            AnnotationSourceReference, AnnotationTag, CollaborationRevision, CollaborationScope,
754            CollaborationSourceAnchor,
755            source_target::{SourceTargetBinding, SourceTargetReference},
756        };
757        let mut tracked = Vec::new();
758        for (name, tag_name, binding) in [
759            (
760                "target_viewed",
761                "tag_viewed",
762                SourceTargetBinding::ViewedThread,
763            ),
764            (
765                "target_named",
766                "tag_named",
767                SourceTargetBinding::NamedThread {
768                    scope: CollaborationScope {
769                        spool: Uuid::from_u128(1),
770                        thread: Some(ContentHash::from_bytes([8; 32])),
771                    },
772                },
773            ),
774            (
775                "target_pinned",
776                "tag_pinned",
777                SourceTargetBinding::PinnedRevision {
778                    scope: CollaborationScope {
779                        spool: Uuid::from_u128(1),
780                        thread: None,
781                    },
782                    revision: CollaborationRevision::State {
783                        state_id: StateId::from_bytes([5; 32]),
784                    },
785                },
786            ),
787        ] {
788            let target = SourceTargetReference {
789                target: ContentHash::from_bytes([6; 32]),
790                binding,
791            };
792            let record = source_record(
793                CollaborationRevision::State {
794                    state_id: StateId::from_bytes([5; 32]),
795                },
796                Some(target.clone()),
797            );
798            let mut revision = verify(&context)
799                .expect("context proof")
800                .context_revision()
801                .expect("decode")
802                .expect("context");
803            revision.tags = vec![AnnotationTag::Source {
804                target: AnnotationSourceReference {
805                    scope: revision.metadata.scope.clone(),
806                    source: CollaborationSourceAnchor {
807                        revision: CollaborationRevision::State {
808                            state_id: StateId::from_bytes([5; 32]),
809                        },
810                        path: "src/main.rs".into(),
811                        symbol_id: String::new(),
812                        start_line: None,
813                        end_line: None,
814                        target: Some(target),
815                    },
816                },
817            }];
818            tracked.push((name, record));
819            tracked.push((
820                tag_name,
821                sign_context(revision, &[], &signer).expect("tracked context"),
822            ));
823        }
824        let mut vectors = String::new();
825        for (name, record) in [
826            ("open", open),
827            ("append", append),
828            ("resolve", resolve),
829            ("reopen", reopen),
830            ("context", context),
831            ("structured_context", structured_context),
832            ("source_state", source_state),
833            ("source_git", source_git),
834            ("extract_context", extraction),
835            ("extracted_revision", extracted_revision),
836        ]
837        .into_iter()
838        .chain(tracked)
839        {
840            vectors.push_str(&format!(
841                "{} {} {} {} {}\n",
842                name,
843                hex::encode(&record.signatures[0].public_key),
844                hex::encode(&record.canonical_record),
845                hex::encode(&record.signatures[0].signature),
846                operation_id(&record).expect("operation ID").to_hex()
847            ));
848        }
849        assert_eq!(
850            vectors,
851            include_str!("../tests/fixtures/collaboration_v2.txt")
852        );
853    }
854}