1use std::collections::BTreeMap;
2
3use gitiverse_core::ids::{ActorId, RepoId};
4use serde::{Deserialize, Serialize};
5
6use crate::dag::{CobError, Dag, Lww, OpId, require_root};
7
8pub const PATCH_KIND: &str = "patch";
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12pub enum VerdictKind {
13 Approve,
14 RequestChanges,
15 Comment,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub enum PatchStatus {
21 Open,
22 Merged {
23 merge_commit: String,
24 merged_by: ActorId,
25 },
26 Closed,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub enum PatchAction {
32 Propose {
33 title: String,
34 description: String,
35 base_ref: String,
36 base_commit: String,
37 head_commit: String,
38 },
39 UpdateRevision {
40 revision_commit: String,
41 base_commit: Option<String>,
42 summary: Option<String>,
43 },
44 ReviewComment {
45 path: String,
46 line: u32,
47 commit: String,
48 body: String,
49 },
50 ReviewVerdict {
51 verdict: VerdictKind,
52 commit: String,
53 body: Option<String>,
54 },
55 Merge {
56 merge_commit: String,
57 merged_by: ActorId,
58 },
59 Close,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct PatchRevision {
65 pub id: OpId,
66 pub author: ActorId,
67 pub commit: String,
68 pub summary: Option<String>,
69 pub lamport: u64,
70 pub timestamp: u64,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct PatchReviewComment {
76 pub id: OpId,
77 pub author: ActorId,
78 pub path: String,
79 pub line: u32,
80 pub commit: String,
81 pub body: String,
82 pub lamport: u64,
83 pub timestamp: u64,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct PatchReviewVerdict {
89 pub id: OpId,
90 pub author: ActorId,
91 pub verdict: VerdictKind,
92 pub commit: String,
93 pub body: Option<String>,
94 pub lamport: u64,
95 pub timestamp: u64,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100pub struct PatchState {
101 pub id: OpId,
102 pub repo_id: RepoId,
103 pub author: ActorId,
104 pub title: String,
105 pub description: String,
106 pub base_ref: String,
107 pub base_commit: String,
108 pub head_commit: String,
109 pub revisions: Vec<PatchRevision>,
110 pub status: PatchStatus,
111 pub review_comments: Vec<PatchReviewComment>,
112 pub verdicts_by_reviewer: BTreeMap<ActorId, PatchReviewVerdict>,
113 pub all_verdicts: Vec<PatchReviewVerdict>,
114 pub created_at: u64,
115 pub updated_at: u64,
116}
117
118struct PatchAccum {
119 id: OpId,
120 repo_id: RepoId,
121 author: ActorId,
122 title: String,
123 description: String,
124 base_ref: String,
125 base_commit: Lww<String>,
126 head_commit: Lww<String>,
127 revisions: BTreeMap<(u64, OpId), PatchRevision>,
128 status: Lww<PatchStatus>,
129 review_comments: BTreeMap<(u64, OpId), PatchReviewComment>,
130 verdicts_by_reviewer: BTreeMap<ActorId, Lww<PatchReviewVerdict>>,
131 all_verdicts: BTreeMap<(u64, OpId), PatchReviewVerdict>,
132 created_at: u64,
133 updated_at: u64,
134}
135
136impl PatchState {
137 pub fn from_dag(dag: &Dag<PatchAction>) -> Result<Self, CobError> {
139 let accum: Option<PatchAccum> =
140 dag.fold(None, |state, op_id, op, _ancestors| match &op.payload {
141 PatchAction::Propose {
142 title,
143 description,
144 base_ref,
145 base_commit,
146 head_commit,
147 } => {
148 if state.is_some() {
149 return Err(CobError::InvalidOp(
150 "duplicate patch Propose operation".to_owned(),
151 ));
152 }
153 if !op.parents.is_empty() {
154 return Err(CobError::InvalidOp(
155 "patch Propose operation must have no parents".to_owned(),
156 ));
157 }
158 let mut revisions = BTreeMap::new();
159 revisions.insert(
160 (op.lamport, op_id),
161 PatchRevision {
162 id: op_id,
163 author: op.author,
164 commit: head_commit.clone(),
165 summary: Some("initial revision".to_owned()),
166 lamport: op.lamport,
167 timestamp: op.timestamp,
168 },
169 );
170 *state = Some(PatchAccum {
171 id: op_id,
172 repo_id: op.repo_id,
173 author: op.author,
174 title: title.clone(),
175 description: description.clone(),
176 base_ref: base_ref.clone(),
177 base_commit: Lww::new(op.lamport, op_id, base_commit.clone()),
178 head_commit: Lww::new(op.lamport, op_id, head_commit.clone()),
179 revisions,
180 status: Lww::new(op.lamport, op_id, PatchStatus::Open),
181 review_comments: BTreeMap::new(),
182 verdicts_by_reviewer: BTreeMap::new(),
183 all_verdicts: BTreeMap::new(),
184 created_at: op.timestamp,
185 updated_at: op.timestamp,
186 });
187 Ok(())
188 }
189 PatchAction::UpdateRevision {
190 revision_commit,
191 base_commit,
192 summary,
193 } => {
194 let acc = require_root(state, PATCH_KIND, op_id)?;
195 acc.head_commit
196 .update(op.lamport, op_id, revision_commit.clone());
197 if let Some(base) = base_commit {
198 acc.base_commit.update(op.lamport, op_id, base.clone());
199 }
200 acc.revisions.insert(
201 (op.lamport, op_id),
202 PatchRevision {
203 id: op_id,
204 author: op.author,
205 commit: revision_commit.clone(),
206 summary: summary.clone(),
207 lamport: op.lamport,
208 timestamp: op.timestamp,
209 },
210 );
211 acc.updated_at = acc.updated_at.max(op.timestamp);
212 Ok(())
213 }
214 PatchAction::ReviewComment {
215 path,
216 line,
217 commit,
218 body,
219 } => {
220 let acc = require_root(state, PATCH_KIND, op_id)?;
221 acc.review_comments.insert(
222 (op.lamport, op_id),
223 PatchReviewComment {
224 id: op_id,
225 author: op.author,
226 path: path.clone(),
227 line: *line,
228 commit: commit.clone(),
229 body: body.clone(),
230 lamport: op.lamport,
231 timestamp: op.timestamp,
232 },
233 );
234 acc.updated_at = acc.updated_at.max(op.timestamp);
235 Ok(())
236 }
237 PatchAction::ReviewVerdict {
238 verdict,
239 commit,
240 body,
241 } => {
242 let acc = require_root(state, PATCH_KIND, op_id)?;
243 let entry = PatchReviewVerdict {
244 id: op_id,
245 author: op.author,
246 verdict: *verdict,
247 commit: commit.clone(),
248 body: body.clone(),
249 lamport: op.lamport,
250 timestamp: op.timestamp,
251 };
252 acc.all_verdicts.insert((op.lamport, op_id), entry.clone());
253 match acc.verdicts_by_reviewer.get_mut(&op.author) {
254 Some(lww) => lww.update(op.lamport, op_id, entry),
255 None => {
256 acc.verdicts_by_reviewer
257 .insert(op.author, Lww::new(op.lamport, op_id, entry));
258 }
259 }
260 acc.updated_at = acc.updated_at.max(op.timestamp);
261 Ok(())
262 }
263 PatchAction::Merge {
264 merge_commit,
265 merged_by,
266 } => {
267 let acc = require_root(state, PATCH_KIND, op_id)?;
268 acc.status.update(
269 op.lamport,
270 op_id,
271 PatchStatus::Merged {
272 merge_commit: merge_commit.clone(),
273 merged_by: *merged_by,
274 },
275 );
276 acc.updated_at = acc.updated_at.max(op.timestamp);
277 Ok(())
278 }
279 PatchAction::Close => {
280 let acc = require_root(state, PATCH_KIND, op_id)?;
281 acc.status.update(op.lamport, op_id, PatchStatus::Closed);
282 acc.updated_at = acc.updated_at.max(op.timestamp);
283 Ok(())
284 }
285 })?;
286
287 let acc = accum.ok_or_else(|| CobError::InvalidOp("empty patch DAG".to_owned()))?;
288 Ok(PatchState {
289 id: acc.id,
290 repo_id: acc.repo_id,
291 author: acc.author,
292 title: acc.title,
293 description: acc.description,
294 base_ref: acc.base_ref,
295 base_commit: acc.base_commit.value,
296 head_commit: acc.head_commit.value,
297 revisions: acc.revisions.into_values().collect(),
298 status: acc.status.value,
299 review_comments: acc.review_comments.into_values().collect(),
300 verdicts_by_reviewer: acc
301 .verdicts_by_reviewer
302 .into_iter()
303 .map(|(k, v)| (k, v.value))
304 .collect(),
305 all_verdicts: acc.all_verdicts.into_values().collect(),
306 created_at: acc.created_at,
307 updated_at: acc.updated_at,
308 })
309 }
310
311 #[must_use]
313 pub fn maintainer_approvals(&self, maintainers: &[ActorId]) -> Vec<ActorId> {
314 self.verdicts_by_reviewer
315 .iter()
316 .filter_map(|(actor, verdict)| {
317 if maintainers.contains(actor)
318 && verdict.verdict == VerdictKind::Approve
319 && verdict.commit == self.head_commit
320 {
321 Some(*actor)
322 } else {
323 None
324 }
325 })
326 .collect()
327 }
328
329 #[must_use]
331 pub fn has_blocking_changes(&self, maintainers: &[ActorId]) -> bool {
332 self.verdicts_by_reviewer.iter().any(|(actor, verdict)| {
333 maintainers.contains(actor)
334 && verdict.verdict == VerdictKind::RequestChanges
335 && verdict.commit == self.head_commit
336 })
337 }
338
339 #[must_use]
341 pub fn meets_quorum(&self, quorum: u32, maintainers: &[ActorId]) -> bool {
342 !self.has_blocking_changes(maintainers)
343 && self.maintainer_approvals(maintainers).len() >= quorum as usize
344 }
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350 use crate::dag::DagOp;
351 use gitiverse_core::ids::RepoId;
352 use proptest::prelude::*;
353 use wire_mesh_core::adapters::NodeIdentity;
354 use wire_mesh_core::ports::Identity;
355
356 #[tokio::test]
357 async fn patch_tracks_revisions_verdicts_quorum_and_merge() {
358 let author = NodeIdentity::generate_ed25519();
359 let reviewer = NodeIdentity::generate_es256();
360 let repo_id = RepoId::from_bytes([0x66; 32]);
361 let reviewer_id = ActorId(*reviewer.device_id());
362
363 let c1 = "1".repeat(40);
364 let c2 = "2".repeat(40);
365 let c_merge = "3".repeat(40);
366
367 let propose = DagOp::sign_new(
368 repo_id,
369 PATCH_KIND,
370 vec![],
371 1,
372 100,
373 PatchAction::Propose {
374 title: "Add COB patch CRDT".to_owned(),
375 description: "Implements SEC patch flow".to_owned(),
376 base_ref: "refs/heads/main".to_owned(),
377 base_commit: "0".repeat(40),
378 head_commit: c1.clone(),
379 },
380 &author,
381 )
382 .await
383 .unwrap();
384 let propose_id = propose.op_id().unwrap();
385
386 let req_changes = DagOp::sign_new(
387 repo_id,
388 PATCH_KIND,
389 vec![propose_id],
390 2,
391 101,
392 PatchAction::ReviewVerdict {
393 verdict: VerdictKind::RequestChanges,
394 commit: c1.clone(),
395 body: Some("needs test".to_owned()),
396 },
397 &reviewer,
398 )
399 .await
400 .unwrap();
401
402 let rev2 = DagOp::sign_new(
403 repo_id,
404 PATCH_KIND,
405 vec![propose_id],
406 2,
407 102,
408 PatchAction::UpdateRevision {
409 revision_commit: c2.clone(),
410 base_commit: None,
411 summary: Some("added test".to_owned()),
412 },
413 &author,
414 )
415 .await
416 .unwrap();
417 let rev2_id = rev2.op_id().unwrap();
418
419 let approve = DagOp::sign_new(
420 repo_id,
421 PATCH_KIND,
422 vec![rev2_id],
423 3,
424 103,
425 PatchAction::ReviewVerdict {
426 verdict: VerdictKind::Approve,
427 commit: c2.clone(),
428 body: Some("LGTM".to_owned()),
429 },
430 &reviewer,
431 )
432 .await
433 .unwrap();
434 let approve_id = approve.op_id().unwrap();
435
436 let merge = DagOp::sign_new(
437 repo_id,
438 PATCH_KIND,
439 vec![approve_id],
440 4,
441 104,
442 PatchAction::Merge {
443 merge_commit: c_merge.clone(),
444 merged_by: reviewer_id,
445 },
446 &reviewer,
447 )
448 .await
449 .unwrap();
450
451 let mut dag = Dag::new();
452 for op in [merge, approve, rev2, req_changes, propose] {
453 dag.insert_verified(op, &author, Some(&repo_id), Some(PATCH_KIND))
454 .await
455 .unwrap();
456 }
457 let state = PatchState::from_dag(&dag).unwrap();
458 assert_eq!(state.head_commit, c2);
459 assert!(state.meets_quorum(1, &[reviewer_id]));
460 assert_eq!(
461 state.status,
462 PatchStatus::Merged {
463 merge_commit: c_merge,
464 merged_by: reviewer_id,
465 }
466 );
467 }
468
469 proptest! {
470 #[test]
471 fn prop_patch_crdt_commutes_is_idempotent_and_converges(
472 perm in prop::collection::vec(0usize..100, 1..20),
473 dups in prop::collection::vec(0usize..10, 0..10),
474 ) {
475 let rt = tokio::runtime::Runtime::new().unwrap();
476 rt.block_on(async {
477 let alice = NodeIdentity::from_ed25519_secret(&[3u8; 32]).unwrap();
478 let bob = NodeIdentity::from_ed25519_secret(&[4u8; 32]).unwrap();
479 let repo_id = RepoId::from_bytes([0x88; 32]);
480
481 let c1 = "a".repeat(40);
482 let c2 = "b".repeat(40);
483
484 let propose = DagOp::sign_new(
485 repo_id,
486 PATCH_KIND,
487 vec![],
488 1,
489 10,
490 PatchAction::Propose {
491 title: "Fix".to_owned(),
492 description: "desc".to_owned(),
493 base_ref: "refs/heads/main".to_owned(),
494 base_commit: "0".repeat(40),
495 head_commit: c1.clone(),
496 },
497 &alice,
498 ).await.unwrap();
499 let id_propose = propose.op_id().unwrap();
500
501 let comment = DagOp::sign_new(
502 repo_id, PATCH_KIND, vec![id_propose], 2, 11,
503 PatchAction::ReviewComment {
504 path: "src/lib.rs".to_owned(),
505 line: 12,
506 commit: c1.clone(),
507 body: "nit".to_owned(),
508 },
509 &bob,
510 ).await.unwrap();
511 let rev2 = DagOp::sign_new(
512 repo_id, PATCH_KIND, vec![id_propose], 2, 12,
513 PatchAction::UpdateRevision {
514 revision_commit: c2.clone(),
515 base_commit: None,
516 summary: Some("addressed nit".to_owned()),
517 },
518 &alice,
519 ).await.unwrap();
520 let id_rev2 = rev2.op_id().unwrap();
521
522 let verdict_req = DagOp::sign_new(
523 repo_id, PATCH_KIND, vec![id_propose], 2, 13,
524 PatchAction::ReviewVerdict {
525 verdict: VerdictKind::RequestChanges,
526 commit: c1,
527 body: None,
528 },
529 &bob,
530 ).await.unwrap();
531 let verdict_ok = DagOp::sign_new(
532 repo_id, PATCH_KIND, vec![id_rev2], 3, 14,
533 PatchAction::ReviewVerdict {
534 verdict: VerdictKind::Approve,
535 commit: c2.clone(),
536 body: Some("nice".to_owned()),
537 },
538 &bob,
539 ).await.unwrap();
540 let merge_op = DagOp::sign_new(
541 repo_id, PATCH_KIND, vec![verdict_ok.op_id().unwrap()], 4, 15,
542 PatchAction::Merge {
543 merge_commit: "c".repeat(40),
544 merged_by: ActorId(*bob.device_id()),
545 },
546 &bob,
547 ).await.unwrap();
548 let close_op = DagOp::sign_new(
549 repo_id, PATCH_KIND, vec![id_rev2], 3, 16,
550 PatchAction::Close,
551 &alice,
552 ).await.unwrap();
553
554 let all_ops = vec![
555 propose, comment, rev2, verdict_req, verdict_ok, merge_op, close_op,
556 ];
557
558 let mut dag_a = Dag::new();
559 for op in &all_ops {
560 dag_a.insert_unchecked(op.clone()).unwrap();
561 }
562 let expected = PatchState::from_dag(&dag_a).unwrap();
563
564 let mut indices: Vec<usize> = (0..all_ops.len()).collect();
565 for (i, &swap_seed) in perm.iter().enumerate() {
566 let a = i % all_ops.len();
567 let b = swap_seed % all_ops.len();
568 indices.swap(a, b);
569 }
570 let mut dag_b = Dag::new();
571 for idx in indices {
572 dag_b.insert_unchecked(all_ops[idx].clone()).unwrap();
573 }
574 for dup in dups {
575 dag_b.insert_unchecked(all_ops[dup % all_ops.len()].clone()).unwrap();
576 }
577 let actual = PatchState::from_dag(&dag_b).unwrap();
578 assert_eq!(actual, expected);
579 assert_eq!(dag_b.len(), all_ops.len());
580 });
581 }
582 }
583}