返回 CodeWhale
ledger.rs
根目录 / crates / engine / src / tools / subagent / coord / ledger.rs
1 //! Durable coordination records for delegated Work (#4647).
2 //!
3 //! Split out of `coord.rs` unchanged (#5462): the decision/claim/contention
4 //! ledger and its receipt types are the half of that file with consumers
5 //! outside the tool layer — `tui::coordination_detail`, `tui::work_surface`,
6 //! `tui::ui::tests`, and `core::engine::tests` all name these types — while
7 //! the tool wrappers around them are model-surface code. Keeping both in one
8 //! 3.8k-line file meant every read of either started by scrolling past the
9 //! other.
10 //!
11 //! This is a pure move with re-exports: `coord` re-publishes every public item
12 //! under its original path, so no consumer needed an edited import and no
13 //! behavior changed. New coordination *state* belongs here; new coordination
14 //! *tools* belong in `coord.rs`.
15
16 use std::collections::{BTreeSet, HashMap};
17 use std::path::{Path, PathBuf};
18
19 use serde::{Deserialize, Serialize};
20 use serde_json::Value;
21
22 use super::{
23 COORDINATION_PROJECTION_BYTE_LIMIT, COORDINATION_PROJECTION_DECISION_LIMIT,
24 COORDINATION_RECORD_LIMIT,
25 };
26 use crate::tools::subagent::normalize_claim_path;
27
28 /// Coordination records for delegated Work (#4647).
29 ///
30 /// Decision records, write-scope claims, and contention detection for parallel
31 /// agent work. Parallel work may proceed only when scopes and contracts do not
32 /// collide silently.
33 /// Status of a coordination decision.
34 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35 #[serde(rename_all = "snake_case")]
36 pub enum DecisionStatus {
37 Proposed,
38 Accepted,
39 Superseded,
40 }
41
42 /// Serialized coordination state schema. Increment only with an explicit
43 /// migration; restart/replay must never infer a newer contract from old data.
44 pub const COORDINATION_SCHEMA_VERSION: u32 = 1;
45
46 pub(super) const MAX_RECONCILIATION_RETRIES: u32 = 3;
47
48 const fn coordination_schema_version() -> u32 {
49 COORDINATION_SCHEMA_VERSION
50 }
51
52 /// A bounded coordination decision record (#4647).
53 ///
54 /// Persisted with stable subject, concise constraints, one active owner,
55 /// applicability scope, evidence handles, and sequence/version.
56 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
57 pub struct DecisionRecord {
58 pub decision_id: String,
59 pub subject: String,
60 pub status: DecisionStatus,
61 pub owner: String,
62 pub scope: Vec<String>,
63 pub constraints: Vec<String>,
64 pub evidence_handles: Vec<String>,
65 pub version: u32,
66 pub sequence: u64,
67 }
68
69 /// A write-scope claim for a write-capable child (#4647).
70 ///
71 /// Declares expected repo-relative paths/trees and named contracts.
72 /// This is coordination metadata, not another approval system.
73 ///
74 /// An `exact_files` entry beneath a declared root binds that root to the
75 /// files listed under it (#6278): peers may then share the root with
76 /// disjoint file claims, and the claim's authorized surface is what
77 /// [`WriteScopeClaim::contains_path`] and [`WriteScopeClaim::overlaps`]
78 /// both see.
79 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
80 pub struct WriteScopeClaim {
81 pub owner: String,
82 pub roots: Vec<String>,
83 pub exact_files: Vec<String>,
84 pub contracts: Vec<String>,
85 }
86
87 impl WriteScopeClaim {
88 /// Roots that authorize their whole tree. A root with declared
89 /// `exact_files` beneath it is bound to those files instead: the files
90 /// are the real exclusion boundary, so peers may share one root while
91 /// claiming disjoint outputs (#6278). A root carrying no declared file
92 /// keeps tree-wide authority, and an exact file outside every root
93 /// stands alone.
94 fn open_roots(&self) -> impl Iterator<Item = &String> {
95 self.roots.iter().filter(|root| {
96 !self
97 .exact_files
98 .iter()
99 .any(|file| paths_overlap_by_containment(root, file))
100 })
101 }
102
103 /// Check whether this claim overlaps with another. A claim overlaps when
104 /// either normalized open tree contains the other or exact files collide.
105 #[must_use]
106 pub fn overlaps(&self, other: &WriteScopeClaim) -> bool {
107 for root_a in self.open_roots() {
108 for root_b in other.open_roots() {
109 if paths_overlap_by_containment(root_a, root_b)
110 || paths_overlap_by_containment(root_b, root_a)
111 {
112 return true;
113 }
114 }
115 }
116 for file_a in &self.exact_files {
117 if other
118 .exact_files
119 .iter()
120 .any(|file| paths_overlap_equal(file, file_a))
121 || other
122 .open_roots()
123 .any(|root| paths_overlap_by_containment(root, file_a))
124 {
125 return true;
126 }
127 }
128 for file_b in &other.exact_files {
129 if self
130 .open_roots()
131 .any(|root| paths_overlap_by_containment(root, file_b))
132 {
133 return true;
134 }
135 }
136 self.contracts
137 .iter()
138 .any(|contract| other.contracts.iter().any(|other| other == contract))
139 }
140
141 #[must_use]
142 pub fn contains_path(&self, path: &str) -> bool {
143 self.exact_files.iter().any(|file| file == path)
144 || self.open_roots().any(|root| path_contains(root, path))
145 }
146 }
147
148 fn path_contains(root: &str, candidate: &str) -> bool {
149 let root = root.trim_end_matches('/');
150 let candidate = candidate.trim_end_matches('/');
151 root == "."
152 || root == candidate
153 || candidate
154 .strip_prefix(root)
155 .is_some_and(|suffix| suffix.starts_with('/'))
156 }
157
158 fn paths_overlap_equal(left: &str, right: &str) -> bool {
159 left == right || left.to_lowercase() == right.to_lowercase()
160 }
161
162 fn paths_overlap_by_containment(root: &str, candidate: &str) -> bool {
163 path_contains(root, candidate) || path_contains(&root.to_lowercase(), &candidate.to_lowercase())
164 }
165
166 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
167 pub struct PersistedWriteClaim {
168 pub claim: WriteScopeClaim,
169 pub sequence: u64,
170 #[serde(default)]
171 pub isolated_worktree: bool,
172 /// Which of this claim's roots/exact files existed on disk when it was
173 /// registered (#5906).
174 ///
175 /// Recorded because "the claimed path is gone" and "the claimed path does
176 /// not exist yet" look identical from a later `exists()` call and mean
177 /// opposite things. A claim on a worktree that has since been removed
178 /// describes work nobody can be doing and must stop refusing claimants; a
179 /// claim on a directory its owner is about to create is exactly the
180 /// forward-looking reservation the ledger exists to honor, and disarming
181 /// that would let two writers into the same new tree.
182 ///
183 /// Empty for claims persisted before this field existed and for claims
184 /// that named nothing on disk at the time — both mean "no evidence of
185 /// disappearance", so neither is ever treated as stale.
186 #[serde(default, skip_serializing_if = "Vec::is_empty")]
187 pub present_at_claim: Vec<String>,
188 }
189
190 impl PersistedWriteClaim {
191 /// Whether every path this claim was recorded as actually covering has
192 /// since disappeared from disk (#5906).
193 ///
194 /// Isolated-worktree claims are excluded because they never contend at
195 /// all — the answer would be unused, and their paths are not resolved
196 /// against the coordination root.
197 pub fn names_only_vanished_paths<F>(&self, mut path_exists: F) -> bool
198 where
199 F: FnMut(&str) -> bool,
200 {
201 !self.isolated_worktree
202 && !self.present_at_claim.is_empty()
203 && !self
204 .present_at_claim
205 .iter()
206 .any(|path| path_exists(path.as_str()))
207 }
208 }
209
210 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
211 pub struct ReconciliationReceipt {
212 pub reconciliation_id: String,
213 pub subject: String,
214 pub owner: String,
215 pub input_decisions: Vec<String>,
216 pub outcome: String,
217 pub evidence_handles: Vec<String>,
218 /// Preserved candidate branches, patches, or artifact handles. A fan-in
219 /// receipt is not valid if either conflicting candidate was discarded.
220 #[serde(default)]
221 pub candidate_handles: Vec<String>,
222 #[serde(default)]
223 pub retry_count: u32,
224 #[serde(default)]
225 pub retry_limit: u32,
226 #[serde(default)]
227 pub reviewer_evidence_handles: Vec<String>,
228 #[serde(default)]
229 pub verifier_evidence_handles: Vec<String>,
230 #[serde(default)]
231 pub verification_outcome: String,
232 pub sequence: u64,
233 }
234
235 /// Durable receipt for the minimal accepted-decision context projected into a
236 /// child. It records counts and stable ids, never the child's transcript.
237 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
238 pub struct ContextProjectionReceipt {
239 pub child_id: String,
240 pub decision_ids: Vec<String>,
241 pub projected_bytes: usize,
242 /// Repeated constraint facts elided across otherwise distinct decisions.
243 /// Decision records themselves are never collapsed by this count.
244 pub deduplicated: usize,
245 /// Relevant unique decisions omitted solely because the hard count or
246 /// byte bound was reached. This must not be conflated with deduplication.
247 #[serde(default)]
248 pub omitted: usize,
249 pub sequence: u64,
250 }
251
252 /// Admission outcome persisted with a write-contention receipt.
253 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
254 #[serde(rename_all = "snake_case")]
255 pub enum WriteContentionDisposition {
256 BlockedPendingIsolationOrSerialization,
257 ResolvedBySuccessfulClaim,
258 }
259
260 impl WriteContentionDisposition {
261 #[must_use]
262 pub const fn as_str(self) -> &'static str {
263 match self {
264 Self::BlockedPendingIsolationOrSerialization => {
265 "blocked_pending_isolation_or_serialization"
266 }
267 Self::ResolvedBySuccessfulClaim => "resolved_by_successful_claim",
268 }
269 }
270
271 #[must_use]
272 pub const fn blocks_admission(self) -> bool {
273 matches!(self, Self::BlockedPendingIsolationOrSerialization)
274 }
275 }
276
277 /// Durable non-secret receipt emitted when two active shared-workspace claims
278 /// collide. Rejected scope expansion remains visible after restart.
279 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
280 pub struct WriteContentionReceipt {
281 pub claimant: String,
282 pub conflicting_owner: String,
283 pub roots: Vec<String>,
284 pub exact_files: Vec<String>,
285 pub contracts: Vec<String>,
286 pub disposition: WriteContentionDisposition,
287 /// Sequence of the later successful claim that resolved this receipt.
288 /// It intentionally references that claim's sequence instead of consuming
289 /// another ledger sequence.
290 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub resolution_sequence: Option<u64>,
292 pub sequence: u64,
293 }
294
295 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
296 pub struct CoordinationHotPath {
297 pub path: String,
298 pub active_claims: usize,
299 }
300
301 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
302 pub struct CoordinationDetailMetrics {
303 pub hottest_paths: Vec<CoordinationHotPath>,
304 pub package_or_module_growth: Option<Value>,
305 pub route_or_cost: Option<Value>,
306 pub note: String,
307 }
308
309 /// One bounded typed projection shared by headless inspection and the TUI.
310 /// It contains durable coordination facts only, never raw reasoning or a
311 /// delegated transcript.
312 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
313 pub struct CoordinationDetailProjection {
314 pub schema_version: u32,
315 pub sequence: u64,
316 pub decisions: Vec<DecisionRecord>,
317 pub write_claims: Vec<PersistedWriteClaim>,
318 pub reconciliations: Vec<ReconciliationReceipt>,
319 pub context_projections: Vec<ContextProjectionReceipt>,
320 pub contentions: Vec<WriteContentionReceipt>,
321 pub metrics: CoordinationDetailMetrics,
322 pub bounded: bool,
323 pub limit: usize,
324 /// Whether this manager's durable store is admitted. When false, durable
325 /// ledger writes are refused until admission is retried and the UI must
326 /// say so — a counter must never tick on a turn the engine has already
327 /// settled.
328 #[serde(default = "default_process_lock_held")]
329 pub process_lock_held: bool,
330 /// Human-readable reason when [`Self::process_lock_held`] is false.
331 #[serde(default, skip_serializing_if = "Option::is_none")]
332 pub process_lock_note: Option<String>,
333 }
334
335 fn default_process_lock_held() -> bool {
336 // Legacy projections (tests, older sessions) assume the lock is held so
337 // they do not spuriously light the unavailable banner.
338 true
339 }
340
341 /// Attribution minted from an owner-admitted directory. Serialized data never
342 /// admits that directory: the manager requires its current held identity.
343 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
344 pub struct CoordinationClaimScope {
345 pub canonical_root: PathBuf,
346 pub platform: String,
347 pub volume: u64,
348 pub index: u64,
349 }
350
351 impl CoordinationClaimScope {
352 pub fn validate_shape(&self) -> Result<(), String> {
353 if !self.canonical_root.is_absolute()
354 || self.canonical_root.as_os_str().len() > 32768
355 || self.canonical_root.components().any(|component| {
356 matches!(
357 component,
358 std::path::Component::ParentDir | std::path::Component::CurDir
359 )
360 })
361 || !matches!(self.platform.as_str(), "unix" | "windows")
362 {
363 return Err("coordination root attribution is not bounded and canonical".into());
364 }
365 Ok(())
366 }
367 }
368
369 fn projected_claim(claim: &WriteScopeClaim, root: &Path) -> WriteScopeClaim {
370 let project = |path: &String| {
371 let joined = if path == "." {
372 root.to_path_buf()
373 } else {
374 root.join(path)
375 };
376 joined.to_string_lossy().replace('\\', "/")
377 };
378 WriteScopeClaim {
379 owner: claim.owner.clone(),
380 roots: claim.roots.iter().map(project).collect(),
381 exact_files: claim.exact_files.iter().map(project).collect(),
382 contracts: claim.contracts.clone(),
383 }
384 }
385
386 /// Durable, bounded coordination state owned by `SubAgentManager`.
387 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
388 pub struct CoordinationLedger {
389 #[serde(default = "coordination_schema_version")]
390 pub schema_version: u32,
391 #[serde(default)]
392 pub sequence: u64,
393 #[serde(default)]
394 pub decisions: Vec<DecisionRecord>,
395 #[serde(default)]
396 pub write_claims: Vec<PersistedWriteClaim>,
397 #[serde(default)]
398 pub reconciliations: Vec<ReconciliationReceipt>,
399 #[serde(default)]
400 pub projections: Vec<ContextProjectionReceipt>,
401 #[serde(default)]
402 pub contentions: Vec<WriteContentionReceipt>,
403 /// Root-session provenance for records whose logical owner (`root`) is
404 /// otherwise shared by every conversation in a workspace. Agent-owned
405 /// records can also be stamped here, but may be resolved through their
406 /// immutable `SubAgent.owner_session_id`. Missing legacy provenance is
407 /// never guessed by active-session views.
408 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
409 pub record_sessions: HashMap<u64, String>,
410 /// One bounded sequence-root map for shared claims and path-qualified
411 /// decisions. The historical wire name stays stable; original schema1
412 /// omits it, and scope-bearing schema2 never guesses an absent map.
413 #[serde(default, skip_serializing_if = "Option::is_none")]
414 pub claim_scopes: Option<HashMap<u64, CoordinationClaimScope>>,
415 }
416
417 impl Default for CoordinationLedger {
418 fn default() -> Self {
419 Self {
420 schema_version: COORDINATION_SCHEMA_VERSION,
421 sequence: 0,
422 decisions: Vec::new(),
423 write_claims: Vec::new(),
424 reconciliations: Vec::new(),
425 projections: Vec::new(),
426 contentions: Vec::new(),
427 record_sessions: HashMap::new(),
428 claim_scopes: None,
429 }
430 }
431 }
432
433 impl CoordinationLedger {
434 fn next_sequence(&mut self) -> u64 {
435 self.sequence = self.sequence.saturating_add(1);
436 self.sequence
437 }
438
439 #[cfg(any(test, feature = "test-support"))]
440 pub fn record_decision(&mut self, decision: DecisionRecord) -> Result<DecisionRecord, String> {
441 self.record_decision_in_scope(decision, None)
442 }
443
444 pub fn record_decision_in_scope(
445 &mut self,
446 mut decision: DecisionRecord,
447 scope: Option<CoordinationClaimScope>,
448 ) -> Result<DecisionRecord, String> {
449 self.validate_schema()?;
450 if let Some(scope) = &scope {
451 scope.validate_shape()?;
452 if self
453 .claim_scopes
454 .as_ref()
455 .is_some_and(|scopes| scopes.len() >= COORDINATION_RECORD_LIMIT)
456 {
457 return Err("coordination root attribution capacity reached".into());
458 }
459 }
460 decision.decision_id = decision.decision_id.trim().to_string();
461 if !decision.decision_id.is_empty() {
462 decision.decision_id = bounded_coordination_atom("decision id", &decision.decision_id)?;
463 }
464 decision.subject = bounded_coordination_atom("decision subject", &decision.subject)?;
465 decision.owner = bounded_coordination_atom("decision owner", &decision.owner)?;
466 decision.scope = normalize_coordination_values("decision scope", &decision.scope, 24)?;
467 decision.constraints =
468 normalize_coordination_values("decision constraints", &decision.constraints, 24)?;
469 decision.evidence_handles = normalize_coordination_values(
470 "decision evidence handles",
471 &decision.evidence_handles,
472 24,
473 )?;
474 reject_sensitive_coordination_values(&decision.constraints)?;
475 reject_sensitive_coordination_values(&decision.evidence_handles)?;
476 if decision.subject.trim().is_empty() || decision.owner.trim().is_empty() {
477 return Err("decision subject and owner are required".to_string());
478 }
479 if !decision.decision_id.trim().is_empty()
480 && self
481 .decisions
482 .iter()
483 .any(|existing| existing.decision_id == decision.decision_id)
484 {
485 return Err(format!(
486 "decision id '{}' already exists",
487 decision.decision_id
488 ));
489 }
490 if decision.status == DecisionStatus::Accepted
491 && let Some(existing) = self.decisions.iter().find(|existing| {
492 existing.subject == decision.subject
493 && existing.status == DecisionStatus::Accepted
494 && existing.decision_id != decision.decision_id
495 })
496 {
497 return Err(format!(
498 "subject '{}' already has accepted decision '{}' owned by '{}'; preserve both candidates and use neutral reconciliation",
499 decision.subject, existing.decision_id, existing.owner
500 ));
501 }
502 let next_version = self
503 .decisions
504 .iter()
505 .filter(|existing| existing.subject == decision.subject)
506 .map(|existing| existing.version)
507 .max()
508 .unwrap_or(0)
509 .saturating_add(1);
510 decision.version = decision.version.max(next_version);
511 decision.sequence = self.next_sequence();
512 if decision.decision_id.trim().is_empty() {
513 decision.decision_id = format!("decision_{}", decision.sequence);
514 }
515 self.decisions.push(decision.clone());
516 if self.decisions.len() > COORDINATION_RECORD_LIMIT {
517 let referenced = self
518 .reconciliations
519 .iter()
520 .flat_map(|receipt| receipt.input_decisions.iter())
521 .cloned()
522 .collect::<BTreeSet<_>>();
523 if let Some(index) = self.decisions.iter().position(|existing| {
524 existing.status != DecisionStatus::Accepted
525 && !referenced.contains(&existing.decision_id)
526 }) {
527 self.decisions.remove(index);
528 } else {
529 self.decisions.pop();
530 return Err(
531 "coordination decision capacity is occupied by accepted or reconciled records"
532 .to_string(),
533 );
534 }
535 }
536 self.prune_claim_scopes();
537 if let Some(scope) = scope {
538 self.schema_version = 2;
539 self.claim_scopes
540 .get_or_insert_with(HashMap::new)
541 .insert(decision.sequence, scope);
542 }
543 Ok(decision)
544 }
545
546 pub fn update_decision_status(
547 &mut self,
548 decision_id: &str,
549 status: DecisionStatus,
550 owner: &str,
551 expected_version: u32,
552 ) -> Result<DecisionRecord, String> {
553 self.validate_schema()?;
554 let Some(index) = self
555 .decisions
556 .iter()
557 .position(|decision| decision.decision_id == decision_id)
558 else {
559 return Err(format!("decision '{decision_id}' not found"));
560 };
561 if self.decisions[index].owner != owner {
562 return Err(format!(
563 "decision '{decision_id}' is owned by '{}'; caller '{owner}' cannot change it",
564 self.decisions[index].owner
565 ));
566 }
567 if self.decisions[index].version != expected_version {
568 return Err(format!(
569 "decision '{decision_id}' version changed: expected {expected_version}, current {}",
570 self.decisions[index].version
571 ));
572 }
573 let subject = self.decisions[index].subject.clone();
574 if status == DecisionStatus::Accepted
575 && let Some(existing) =
576 self.decisions
577 .iter()
578 .enumerate()
579 .find_map(|(other_index, existing)| {
580 (other_index != index
581 && existing.subject == subject
582 && existing.status == DecisionStatus::Accepted)
583 .then_some(existing)
584 })
585 {
586 return Err(format!(
587 "subject '{subject}' already has accepted decision '{}' owned by '{}'; preserve both candidates and use neutral reconciliation",
588 existing.decision_id, existing.owner
589 ));
590 }
591 let previous_sequence = self.decisions[index].sequence;
592 let previous_scope = self.claim_scope(previous_sequence).cloned();
593 let sequence = self.next_sequence();
594 let decision = &mut self.decisions[index];
595 decision.status = status;
596 decision.version = decision.version.saturating_add(1);
597 decision.sequence = sequence;
598 let result = decision.clone();
599 if let Some(scopes) = &mut self.claim_scopes {
600 scopes.remove(&previous_sequence);
601 if let Some(scope) = previous_scope {
602 scopes.insert(sequence, scope);
603 }
604 }
605 Ok(result)
606 }
607
608 /// Register a bounded write claim.
609 ///
610 /// `owner_is_active` is the caller's whole answer to "may this existing
611 /// claim refuse a new claimant" — liveness and, since #5906, whether the
612 /// claim's recorded paths still exist. The ledger has no filesystem of its
613 /// own; [`super::SubAgentManager::admissible_coordination_owners`] resolves
614 /// both before calling, and stamps
615 /// [`PersistedWriteClaim::present_at_claim`] on the record afterwards.
616 #[cfg(any(test, feature = "test-support"))]
617 pub fn register_claim<F>(
618 &mut self,
619 claim: WriteScopeClaim,
620 isolated_worktree: bool,
621 owner_is_active: F,
622 ) -> Result<PersistedWriteClaim, String>
623 where
624 F: FnMut(&str) -> bool,
625 {
626 self.register_claim_in_scope(claim, isolated_worktree, None, None, owner_is_active)
627 }
628
629 pub fn claim_scope(&self, sequence: u64) -> Option<&CoordinationClaimScope> {
630 self.claim_scopes
631 .as_ref()
632 .and_then(|scopes| scopes.get(&sequence))
633 }
634
635 pub(in crate::tools::subagent) fn prune_claim_scopes(&mut self) {
636 if let Some(scopes) = &mut self.claim_scopes {
637 scopes.retain(|sequence, _| {
638 self.write_claims
639 .iter()
640 .any(|claim| claim.sequence == *sequence)
641 || self
642 .decisions
643 .iter()
644 .any(|decision| decision.sequence == *sequence)
645 });
646 }
647 }
648
649 pub fn register_claim_in_scope<F>(
650 &mut self,
651 mut claim: WriteScopeClaim,
652 isolated_worktree: bool,
653 scope: Option<CoordinationClaimScope>,
654 original_root: Option<&Path>,
655 mut owner_is_active: F,
656 ) -> Result<PersistedWriteClaim, String>
657 where
658 F: FnMut(&str) -> bool,
659 {
660 self.validate_schema()?;
661 if let Some(scope) = &scope {
662 scope.validate_shape()?;
663 if isolated_worktree || original_root.is_none() {
664 return Err(
665 "attributed claims require the held original root and shared execution".into(),
666 );
667 }
668 }
669 if self
670 .claim_scopes
671 .as_ref()
672 .is_some_and(|scopes| !scopes.is_empty())
673 && original_root.is_none()
674 {
675 return Err("attributed coordination state requires its held original root".into());
676 }
677 claim.owner = bounded_coordination_atom("write claim owner", &claim.owner)?;
678 claim.roots = normalize_claim_paths(&claim.roots)?;
679 claim.exact_files = normalize_claim_paths(&claim.exact_files)?;
680 claim.contracts = normalize_claim_strings(&claim.contracts, 16, 128, "contracts")?;
681 if claim.roots.is_empty() && claim.exact_files.is_empty() && claim.contracts.is_empty() {
682 return Err(
683 "write claim requires an owner and at least one root, file, or contract"
684 .to_string(),
685 );
686 }
687 let replacing_existing_owner = self
688 .write_claims
689 .iter()
690 .any(|existing| existing.claim.owner == claim.owner);
691 if scope.is_some()
692 && self
693 .claim_scopes
694 .as_ref()
695 .is_some_and(|scopes| scopes.len() >= COORDINATION_RECORD_LIMIT)
696 && !self.write_claims.iter().any(|existing| {
697 existing.claim.owner == claim.owner && self.claim_scope(existing.sequence).is_some()
698 })
699 {
700 return Err("coordination root attribution capacity reached".into());
701 }
702 if !replacing_existing_owner && self.write_claims.len() >= COORDINATION_RECORD_LIMIT {
703 let mut inactive = Vec::new();
704 for existing in &self.write_claims {
705 if !owner_is_active(&existing.claim.owner) {
706 inactive.push((existing.sequence, existing.claim.owner.clone()));
707 }
708 }
709 inactive.sort_by_key(|(sequence, _)| *sequence);
710 for (_, owner) in inactive {
711 if self.write_claims.len() < COORDINATION_RECORD_LIMIT {
712 break;
713 }
714 self.write_claims
715 .retain(|existing| existing.claim.owner != owner);
716 }
717 self.prune_claim_scopes();
718 if self.write_claims.len() >= COORDINATION_RECORD_LIMIT {
719 return Err(format!(
720 "write-claim capacity is {COORDINATION_RECORD_LIMIT} active owners; complete, serialize, or isolate existing work before admitting another writer"
721 ));
722 }
723 }
724 if !isolated_worktree
725 && let Some(existing) = self
726 .write_claims
727 .iter()
728 .find(|existing| {
729 !existing.isolated_worktree
730 && existing.claim.owner != claim.owner
731 && owner_is_active(&existing.claim.owner)
732 && match original_root {
733 Some(original) => {
734 let existing_root = self
735 .claim_scope(existing.sequence)
736 .map_or(original, |scope| scope.canonical_root.as_path());
737 let candidate_root = scope
738 .as_ref()
739 .map_or(original, |scope| scope.canonical_root.as_path());
740 projected_claim(&existing.claim, existing_root)
741 .overlaps(&projected_claim(&claim, candidate_root))
742 }
743 None => existing.claim.overlaps(&claim),
744 }
745 })
746 .cloned()
747 {
748 let receipt = WriteContentionReceipt {
749 claimant: claim.owner.clone(),
750 conflicting_owner: existing.claim.owner.clone(),
751 roots: claim.roots.clone(),
752 exact_files: claim.exact_files.clone(),
753 contracts: claim.contracts.clone(),
754 disposition: WriteContentionDisposition::BlockedPendingIsolationOrSerialization,
755 resolution_sequence: None,
756 sequence: self.next_sequence(),
757 };
758 self.contentions.push(receipt);
759 trim_front(&mut self.contentions, COORDINATION_RECORD_LIMIT);
760 return Err(format!(
761 "write-scope contention with {}: requested roots {:?}, files {:?}, contracts {:?} overlap its writable roots {:?}, files {:?}, contracts {:?}. Claim disjoint sibling write_roots (for example tmp/scan/worker-a and tmp/scan/worker-b) or exact_files for each output. A read-only worker uses write_authority=read_only without a write claim. Otherwise serialize the writers (wait for that owner to settle, or cancel it) or use worktree isolation; a nested path inside an existing writable root still overlaps.",
762 existing.claim.owner,
763 claim.roots,
764 claim.exact_files,
765 claim.contracts,
766 existing.claim.roots,
767 existing.claim.exact_files,
768 existing.claim.contracts
769 ));
770 }
771 self.write_claims
772 .retain(|existing| existing.claim.owner != claim.owner);
773 let record = PersistedWriteClaim {
774 claim,
775 sequence: self.next_sequence(),
776 isolated_worktree,
777 // Stamped by the caller, which owns the filesystem.
778 present_at_claim: Vec::new(),
779 };
780 for contention in &mut self.contentions {
781 if contention.claimant == record.claim.owner
782 && contention.disposition.blocks_admission()
783 {
784 contention.disposition = WriteContentionDisposition::ResolvedBySuccessfulClaim;
785 contention.resolution_sequence = Some(record.sequence);
786 }
787 }
788 self.write_claims.push(record.clone());
789 self.prune_claim_scopes();
790 if let Some(scope) = scope {
791 self.schema_version = 2;
792 self.claim_scopes
793 .get_or_insert_with(HashMap::new)
794 .insert(record.sequence, scope);
795 }
796 Ok(record)
797 }
798
799 /// Release write claims whose owner is not a live claimant (#5562).
800 ///
801 /// Claims are durable records and legitimately outlive the agents that
802 /// registered them; that is fine for history, but a stale claim must never
803 /// keep blocking a later writer. An optional owner restricts the sweep to
804 /// one claim owner; live claimants are never removed. Returns the released
805 /// owners (one entry per claim, in ledger order).
806 pub fn release_stale_claims<F>(
807 &mut self,
808 owner: Option<&str>,
809 mut owner_is_active: F,
810 ) -> Result<Vec<String>, String>
811 where
812 F: FnMut(&str) -> bool,
813 {
814 self.validate_schema()?;
815 let owner_filter = match owner {
816 Some(value) => Some(bounded_coordination_atom("write claim owner", value)?),
817 None => None,
818 };
819 let mut released = Vec::new();
820 self.write_claims.retain(|record| {
821 if owner_filter
822 .as_deref()
823 .is_some_and(|wanted| wanted != record.claim.owner)
824 {
825 return true;
826 }
827 if owner_is_active(&record.claim.owner) {
828 return true;
829 }
830 released.push(record.claim.owner.clone());
831 false
832 });
833 // A release is a mutation: advance the ledger sequence so receipts
834 // stamped by the caller stay coherent (coordinator contract).
835 if !released.is_empty() {
836 self.next_sequence();
837 self.prune_claim_scopes();
838 }
839 Ok(released)
840 }
841
842 #[allow(clippy::too_many_arguments)]
843 pub fn reconcile(
844 &mut self,
845 subject: String,
846 owner: String,
847 input_decisions: Vec<String>,
848 outcome: String,
849 evidence_handles: Vec<String>,
850 candidate_handles: Vec<String>,
851 retry_count: u32,
852 retry_limit: u32,
853 reviewer_evidence_handles: Vec<String>,
854 verifier_evidence_handles: Vec<String>,
855 verification_outcome: String,
856 ) -> Result<ReconciliationReceipt, String> {
857 self.validate_schema()?;
858 let subject = bounded_coordination_atom("reconciliation subject", &subject)?;
859 let owner = bounded_coordination_atom("reconciliation owner", &owner)?;
860 let outcome = bounded_coordination_atom("reconciliation outcome", &outcome)?;
861 let verification_outcome = bounded_coordination_atom(
862 "reconciliation verification outcome",
863 &verification_outcome,
864 )?;
865 if input_decisions.len() < 2 {
866 return Err("neutral fan-in requires at least two input decisions".to_string());
867 }
868 if input_decisions.iter().collect::<BTreeSet<_>>().len() != input_decisions.len() {
869 return Err("neutral fan-in decision ids must be distinct".to_string());
870 }
871 if candidate_handles.len() < 2
872 || candidate_handles
873 .iter()
874 .any(|handle| handle.trim().is_empty())
875 {
876 return Err(
877 "neutral fan-in must preserve at least two candidate branch, patch, or artifact handles"
878 .to_string(),
879 );
880 }
881 if candidate_handles.iter().collect::<BTreeSet<_>>().len() != candidate_handles.len() {
882 return Err("neutral fan-in candidate handles must be distinct".to_string());
883 }
884 let input_decisions =
885 normalize_coordination_values("input decision ids", &input_decisions, 24)?;
886 let evidence_handles = normalize_coordination_values(
887 "reconciliation evidence handles",
888 &evidence_handles,
889 24,
890 )?;
891 let candidate_handles =
892 normalize_coordination_values("candidate handles", &candidate_handles, 24)?;
893 if input_decisions.len() < 2 {
894 return Err(
895 "neutral fan-in requires at least two distinct normalized input decisions"
896 .to_string(),
897 );
898 }
899 if candidate_handles.len() < 2 {
900 return Err(
901 "neutral fan-in must preserve at least two distinct normalized candidate handles"
902 .to_string(),
903 );
904 }
905 let reviewer_evidence_handles = normalize_coordination_values(
906 "Reviewer evidence handles",
907 &reviewer_evidence_handles,
908 24,
909 )?;
910 let verifier_evidence_handles = normalize_coordination_values(
911 "Verifier evidence handles",
912 &verifier_evidence_handles,
913 24,
914 )?;
915 reject_sensitive_coordination_values(&evidence_handles)?;
916 reject_sensitive_coordination_values(&candidate_handles)?;
917 reject_sensitive_coordination_values(&reviewer_evidence_handles)?;
918 reject_sensitive_coordination_values(&verifier_evidence_handles)?;
919 if retry_limit == 0 || retry_limit > MAX_RECONCILIATION_RETRIES {
920 return Err(format!(
921 "reconciliation retry_limit must be between 1 and {MAX_RECONCILIATION_RETRIES}"
922 ));
923 }
924 if retry_count > retry_limit {
925 return Err("reconciliation retry_count exceeds retry_limit".to_string());
926 }
927 if reviewer_evidence_handles.is_empty() || verifier_evidence_handles.is_empty() {
928 return Err(
929 "neutral fan-in requires independent Reviewer and Verifier evidence handles"
930 .to_string(),
931 );
932 }
933 if reviewer_evidence_handles.iter().any(|review| {
934 verifier_evidence_handles
935 .iter()
936 .any(|verify| verify == review)
937 }) {
938 return Err("Reviewer and Verifier evidence handles must be independent".to_string());
939 }
940 if !matches!(
941 verification_outcome.as_str(),
942 "verified" | "failed" | "blocked"
943 ) {
944 return Err(
945 "neutral fan-in verification_outcome must be verified, failed, or blocked"
946 .to_string(),
947 );
948 }
949 if input_decisions.iter().any(|id| {
950 !self
951 .decisions
952 .iter()
953 .any(|decision| &decision.decision_id == id)
954 }) {
955 return Err("reconciliation references an unknown decision".to_string());
956 }
957 let inputs = input_decisions
958 .iter()
959 .filter_map(|id| {
960 self.decisions
961 .iter()
962 .find(|decision| &decision.decision_id == id)
963 })
964 .collect::<Vec<_>>();
965 if inputs.iter().any(|decision| decision.subject != subject) {
966 return Err("reconciliation inputs must share the requested subject".to_string());
967 }
968 if inputs.iter().any(|decision| decision.owner == owner) {
969 return Err(
970 "neutral fan-in owner must differ from every input decision owner".to_string(),
971 );
972 }
973 let sequence = self.next_sequence();
974 let receipt = ReconciliationReceipt {
975 reconciliation_id: format!("reconcile_{sequence}"),
976 subject,
977 owner,
978 input_decisions,
979 outcome,
980 evidence_handles,
981 candidate_handles,
982 retry_count,
983 retry_limit,
984 reviewer_evidence_handles,
985 verifier_evidence_handles,
986 verification_outcome,
987 sequence,
988 };
989 self.reconciliations.push(receipt.clone());
990 trim_front(&mut self.reconciliations, COORDINATION_RECORD_LIMIT);
991 Ok(receipt)
992 }
993
994 #[cfg(any(test, feature = "test-support"))]
995 pub fn project_relevant_decisions(
996 &mut self,
997 child_id: &str,
998 claim: Option<&WriteScopeClaim>,
999 capabilities: &[String],
1000 ) -> (String, ContextProjectionReceipt) {
1001 self.project_relevant_decisions_in_scope(child_id, claim, capabilities, None, None)
1002 }
1003
1004 pub fn project_relevant_decisions_in_scope(
1005 &mut self,
1006 child_id: &str,
1007 claim: Option<&WriteScopeClaim>,
1008 capabilities: &[String],
1009 claim_root: Option<&Path>,
1010 original_root: Option<&Path>,
1011 ) -> (String, ContextProjectionReceipt) {
1012 const HEADER: &str = "Accepted coordination decisions relevant to this child (bounded):\n";
1013 let mut seen_constraint_facts = BTreeSet::new();
1014 let mut decision_ids = Vec::new();
1015 let mut lines = Vec::new();
1016 let mut projected_bytes = 0usize;
1017 let mut deduplicated = 0usize;
1018 let mut omitted = 0usize;
1019 for decision in self
1020 .decisions
1021 .iter()
1022 .rev()
1023 .filter(|decision| decision.status == DecisionStatus::Accepted)
1024 .filter(|decision| {
1025 decision_is_relevant(
1026 decision,
1027 claim,
1028 capabilities,
1029 claim_root,
1030 self.claim_scope(decision.sequence)
1031 .map(|scope| scope.canonical_root.as_path())
1032 .or(original_root),
1033 )
1034 })
1035 {
1036 if decision_ids.len() >= COORDINATION_PROJECTION_DECISION_LIMIT {
1037 omitted = omitted.saturating_add(1);
1038 continue;
1039 }
1040 let constraints = decision
1041 .constraints
1042 .iter()
1043 .filter_map(|value| {
1044 let value = bounded_utf8(value, 192);
1045 if seen_constraint_facts.insert(value.clone()) {
1046 Some(value)
1047 } else {
1048 deduplicated = deduplicated.saturating_add(1);
1049 None
1050 }
1051 })
1052 .take(8)
1053 .collect::<Vec<_>>()
1054 .join("; ");
1055 let mut line = format!(
1056 "- {} v{} [{}] owner={}",
1057 decision.subject, decision.version, decision.decision_id, decision.owner,
1058 );
1059 if !constraints.is_empty() {
1060 line.push_str(": ");
1061 line.push_str(&constraints);
1062 }
1063 let line = bounded_utf8(&line, 512);
1064 let added_bytes = line.len().saturating_add(1);
1065 if HEADER
1066 .len()
1067 .saturating_add(projected_bytes)
1068 .saturating_add(added_bytes)
1069 > COORDINATION_PROJECTION_BYTE_LIMIT
1070 {
1071 omitted = omitted.saturating_add(1);
1072 continue;
1073 }
1074 projected_bytes = projected_bytes.saturating_add(added_bytes);
1075 decision_ids.push(decision.decision_id.clone());
1076 lines.push(line);
1077 }
1078 let projection = if lines.is_empty() {
1079 String::new()
1080 } else {
1081 format!("{HEADER}{}", lines.join("\n"))
1082 };
1083 let receipt = ContextProjectionReceipt {
1084 child_id: child_id.to_string(),
1085 decision_ids,
1086 projected_bytes: projection.len(),
1087 deduplicated,
1088 omitted,
1089 sequence: self.next_sequence(),
1090 };
1091 self.projections.push(receipt.clone());
1092 trim_front(&mut self.projections, COORDINATION_RECORD_LIMIT);
1093 (projection, receipt)
1094 }
1095
1096 pub(in crate::tools::subagent) fn validate_replay(&mut self) -> Result<(), String> {
1097 self.validate_schema()?;
1098 if self.decisions.len() > COORDINATION_RECORD_LIMIT
1099 || self.write_claims.len() > COORDINATION_RECORD_LIMIT
1100 || self.reconciliations.len() > COORDINATION_RECORD_LIMIT
1101 || self.projections.len() > COORDINATION_RECORD_LIMIT
1102 || self.contentions.len() > COORDINATION_RECORD_LIMIT
1103 {
1104 return Err("coordination record count exceeds the durable bound".to_string());
1105 }
1106
1107 let mut sequences = BTreeSet::new();
1108 let mut max_sequence = 0_u64;
1109 let mut decision_ids = BTreeSet::new();
1110 let mut accepted_subjects = BTreeSet::new();
1111 for decision in &self.decisions {
1112 bounded_coordination_atom("decision id", &decision.decision_id)?;
1113 bounded_coordination_atom("decision subject", &decision.subject)?;
1114 bounded_coordination_atom("decision owner", &decision.owner)?;
1115 if decision.version == 0 {
1116 return Err(format!(
1117 "decision '{}' has zero version",
1118 decision.decision_id
1119 ));
1120 }
1121 validate_sequence(
1122 decision.sequence,
1123 "decision",
1124 &mut sequences,
1125 &mut max_sequence,
1126 )?;
1127 if !decision_ids.insert(decision.decision_id.clone()) {
1128 return Err(format!("duplicate decision id '{}'", decision.decision_id));
1129 }
1130 if decision.status == DecisionStatus::Accepted
1131 && !accepted_subjects.insert(decision.subject.clone())
1132 {
1133 return Err(format!(
1134 "multiple accepted decisions own subject '{}'",
1135 decision.subject
1136 ));
1137 }
1138 validate_normalized_coordination_values("decision scope", &decision.scope, 24)?;
1139 validate_normalized_coordination_values(
1140 "decision constraints",
1141 &decision.constraints,
1142 24,
1143 )?;
1144 validate_normalized_coordination_values(
1145 "decision evidence handles",
1146 &decision.evidence_handles,
1147 24,
1148 )?;
1149 reject_sensitive_coordination_values(&decision.constraints)?;
1150 reject_sensitive_coordination_values(&decision.evidence_handles)?;
1151 }
1152
1153 let mut claim_owners = BTreeSet::new();
1154 for claim in &self.write_claims {
1155 validate_sequence(
1156 claim.sequence,
1157 "write claim",
1158 &mut sequences,
1159 &mut max_sequence,
1160 )?;
1161 bounded_coordination_atom("write claim owner", &claim.claim.owner)?;
1162 if !claim_owners.insert(claim.claim.owner.clone()) {
1163 return Err(format!(
1164 "duplicate write claim owner '{}'",
1165 claim.claim.owner
1166 ));
1167 }
1168 let roots = normalize_claim_paths(&claim.claim.roots)?;
1169 let exact_files = normalize_claim_paths(&claim.claim.exact_files)?;
1170 let contracts = normalize_claim_strings(&claim.claim.contracts, 16, 128, "contracts")?;
1171 if roots != claim.claim.roots
1172 || exact_files != claim.claim.exact_files
1173 || contracts != claim.claim.contracts
1174 || (roots.is_empty() && exact_files.is_empty() && contracts.is_empty())
1175 {
1176 return Err(format!(
1177 "write claim for '{}' is not normalized and bounded",
1178 claim.claim.owner
1179 ));
1180 }
1181 }
1182
1183 if let Some(scopes) = &self.claim_scopes {
1184 if scopes.len() > COORDINATION_RECORD_LIMIT {
1185 return Err("coordination root attribution exceeds claim capacity".into());
1186 }
1187 for (sequence, scope) in scopes {
1188 scope.validate_shape()?;
1189 if !self
1190 .write_claims
1191 .iter()
1192 .any(|claim| claim.sequence == *sequence && !claim.isolated_worktree)
1193 && !self
1194 .decisions
1195 .iter()
1196 .any(|decision| decision.sequence == *sequence)
1197 {
1198 return Err(
1199 "coordination root attribution has no matching shared claim or decision"
1200 .into(),
1201 );
1202 }
1203 }
1204 }
1205
1206 for receipt in &self.reconciliations {
1207 validate_sequence(
1208 receipt.sequence,
1209 "reconciliation",
1210 &mut sequences,
1211 &mut max_sequence,
1212 )?;
1213 validate_reconciliation_receipt(receipt, &self.decisions)?;
1214 }
1215 for projection in &self.projections {
1216 validate_sequence(
1217 projection.sequence,
1218 "context projection",
1219 &mut sequences,
1220 &mut max_sequence,
1221 )?;
1222 bounded_coordination_atom("projection child", &projection.child_id)?;
1223 if projection.decision_ids.len() > COORDINATION_PROJECTION_DECISION_LIMIT
1224 || projection.projected_bytes > COORDINATION_PROJECTION_BYTE_LIMIT
1225 || projection
1226 .decision_ids
1227 .iter()
1228 .collect::<BTreeSet<_>>()
1229 .len()
1230 != projection.decision_ids.len()
1231 {
1232 return Err(format!(
1233 "context projection for '{}' exceeds its bounds or duplicates decisions",
1234 projection.child_id
1235 ));
1236 }
1237 }
1238 for contention in &self.contentions {
1239 validate_sequence(
1240 contention.sequence,
1241 "contention",
1242 &mut sequences,
1243 &mut max_sequence,
1244 )?;
1245 bounded_coordination_atom("contention claimant", &contention.claimant)?;
1246 bounded_coordination_atom(
1247 "contention conflicting owner",
1248 &contention.conflicting_owner,
1249 )?;
1250 match (contention.disposition, contention.resolution_sequence) {
1251 (WriteContentionDisposition::BlockedPendingIsolationOrSerialization, None) => {}
1252 (WriteContentionDisposition::ResolvedBySuccessfulClaim, Some(sequence))
1253 if sequence > contention.sequence && sequence <= self.sequence => {}
1254 (WriteContentionDisposition::BlockedPendingIsolationOrSerialization, Some(_)) => {
1255 return Err(
1256 "blocked contention receipt cannot carry a resolution sequence".to_string(),
1257 );
1258 }
1259 (WriteContentionDisposition::ResolvedBySuccessfulClaim, _) => {
1260 return Err(
1261 "resolved contention receipt requires a later valid resolution sequence"
1262 .to_string(),
1263 );
1264 }
1265 }
1266 if normalize_claim_paths(&contention.roots)? != contention.roots
1267 || normalize_claim_paths(&contention.exact_files)? != contention.exact_files
1268 || normalize_claim_strings(&contention.contracts, 16, 128, "contracts")?
1269 != contention.contracts
1270 {
1271 return Err("contention receipt paths/contracts are not normalized".to_string());
1272 }
1273 }
1274 if self.sequence < max_sequence {
1275 return Err(format!(
1276 "coordination sequence {} is behind record sequence {max_sequence}",
1277 self.sequence
1278 ));
1279 }
1280 Ok(())
1281 }
1282
1283 fn validate_schema(&self) -> Result<(), String> {
1284 match (self.schema_version, self.claim_scopes.as_ref()) {
1285 (COORDINATION_SCHEMA_VERSION, None) | (2, Some(_)) => Ok(()),
1286 (2, None) => {
1287 Err("coordination schema 2 requires explicit root attribution state".into())
1288 }
1289 (COORDINATION_SCHEMA_VERSION, Some(_)) => {
1290 Err("legacy coordination schema cannot contain attributed roots".into())
1291 }
1292 (version, _) => Err(format!(
1293 "unsupported coordination schema {version}; expected 1 or 2"
1294 )),
1295 }
1296 }
1297 }
1298
1299 fn normalize_claim_paths(paths: &[String]) -> Result<Vec<String>, String> {
1300 if paths.len() > 32 {
1301 return Err("write claim paths accept at most 32 entries".to_string());
1302 }
1303 let mut normalized = Vec::new();
1304 for path in paths {
1305 let path = normalize_claim_path(path)?;
1306 if !normalized.contains(&path) {
1307 normalized.push(path);
1308 }
1309 }
1310 Ok(normalized)
1311 }
1312
1313 fn normalize_claim_strings(
1314 values: &[String],
1315 count_limit: usize,
1316 char_limit: usize,
1317 field: &str,
1318 ) -> Result<Vec<String>, String> {
1319 if values.len() > count_limit {
1320 return Err(format!(
1321 "write claim {field} accepts at most {count_limit} entries"
1322 ));
1323 }
1324 let mut normalized = Vec::new();
1325 for value in values {
1326 let value = value.trim();
1327 if value.is_empty()
1328 || value.chars().count() > char_limit
1329 || value.chars().any(char::is_control)
1330 {
1331 return Err(format!(
1332 "write claim {field} entries must be 1..={char_limit} characters"
1333 ));
1334 }
1335 if !normalized.iter().any(|existing| existing == value) {
1336 normalized.push(value.to_string());
1337 }
1338 }
1339 Ok(normalized)
1340 }
1341
1342 fn bounded_coordination_atom(field: &str, value: &str) -> Result<String, String> {
1343 let value = value.trim();
1344 if value.is_empty()
1345 || value.chars().count() > 512
1346 || value.chars().any(|ch| matches!(ch, '\r' | '\n'))
1347 {
1348 return Err(format!(
1349 "{field} must be one non-empty line of at most 512 characters"
1350 ));
1351 }
1352 Ok(value.to_string())
1353 }
1354
1355 fn normalize_coordination_values(
1356 field: &str,
1357 values: &[String],
1358 limit: usize,
1359 ) -> Result<Vec<String>, String> {
1360 if values.len() > limit {
1361 return Err(format!("{field} accepts at most {limit} entries"));
1362 }
1363 let mut normalized = Vec::new();
1364 for value in values {
1365 let value = bounded_coordination_atom(field, value)?;
1366 if !normalized.contains(&value) {
1367 normalized.push(value);
1368 }
1369 }
1370 Ok(normalized)
1371 }
1372
1373 fn validate_normalized_coordination_values(
1374 field: &str,
1375 values: &[String],
1376 limit: usize,
1377 ) -> Result<(), String> {
1378 if normalize_coordination_values(field, values, limit)? != values {
1379 return Err(format!("{field} is not trimmed and deduplicated"));
1380 }
1381 Ok(())
1382 }
1383
1384 fn reject_sensitive_coordination_values(values: &[String]) -> Result<(), String> {
1385 const SENSITIVE_MARKERS: &[&str] = &[
1386 "secret",
1387 "password",
1388 "api_key",
1389 "api-key",
1390 "authorization:",
1391 "bearer ",
1392 "token=",
1393 "sk-",
1394 "ghp_",
1395 "xoxb-",
1396 "<thinking",
1397 "chain of thought",
1398 "raw reasoning",
1399 ];
1400 for value in values {
1401 let lower = value.to_ascii_lowercase();
1402 if let Some(marker) = SENSITIVE_MARKERS
1403 .iter()
1404 .find(|marker| lower.contains(**marker))
1405 {
1406 return Err(format!(
1407 "coordination metadata rejected sensitive or raw-reasoning marker '{marker}'"
1408 ));
1409 }
1410 }
1411 Ok(())
1412 }
1413
1414 fn validate_sequence(
1415 sequence: u64,
1416 kind: &str,
1417 sequences: &mut BTreeSet<u64>,
1418 max_sequence: &mut u64,
1419 ) -> Result<(), String> {
1420 if sequence == 0 || !sequences.insert(sequence) {
1421 return Err(format!(
1422 "{kind} has a zero or duplicate sequence {sequence}"
1423 ));
1424 }
1425 *max_sequence = (*max_sequence).max(sequence);
1426 Ok(())
1427 }
1428
1429 fn validate_reconciliation_receipt(
1430 receipt: &ReconciliationReceipt,
1431 decisions: &[DecisionRecord],
1432 ) -> Result<(), String> {
1433 bounded_coordination_atom("reconciliation id", &receipt.reconciliation_id)?;
1434 bounded_coordination_atom("reconciliation subject", &receipt.subject)?;
1435 bounded_coordination_atom("reconciliation owner", &receipt.owner)?;
1436 bounded_coordination_atom("reconciliation outcome", &receipt.outcome)?;
1437 if receipt.input_decisions.len() < 2
1438 || receipt
1439 .input_decisions
1440 .iter()
1441 .collect::<BTreeSet<_>>()
1442 .len()
1443 != receipt.input_decisions.len()
1444 {
1445 return Err("reconciliation requires at least two distinct decision ids".to_string());
1446 }
1447 let inputs = receipt
1448 .input_decisions
1449 .iter()
1450 .map(|id| {
1451 decisions
1452 .iter()
1453 .find(|decision| &decision.decision_id == id)
1454 .ok_or_else(|| format!("reconciliation references unknown decision '{id}'"))
1455 })
1456 .collect::<Result<Vec<_>, _>>()?;
1457 if inputs
1458 .iter()
1459 .any(|decision| decision.subject != receipt.subject)
1460 {
1461 return Err("reconciliation inputs must share the requested subject".to_string());
1462 }
1463 if inputs
1464 .iter()
1465 .any(|decision| decision.owner == receipt.owner)
1466 {
1467 return Err("neutral fan-in owner must differ from every candidate owner".to_string());
1468 }
1469 if receipt.candidate_handles.len() < 2
1470 || receipt
1471 .candidate_handles
1472 .iter()
1473 .collect::<BTreeSet<_>>()
1474 .len()
1475 != receipt.candidate_handles.len()
1476 {
1477 return Err("reconciliation requires at least two distinct candidate handles".to_string());
1478 }
1479 validate_normalized_coordination_values("candidate handles", &receipt.candidate_handles, 24)?;
1480 validate_normalized_coordination_values(
1481 "reconciliation evidence handles",
1482 &receipt.evidence_handles,
1483 24,
1484 )?;
1485 validate_normalized_coordination_values(
1486 "Reviewer evidence handles",
1487 &receipt.reviewer_evidence_handles,
1488 24,
1489 )?;
1490 validate_normalized_coordination_values(
1491 "Verifier evidence handles",
1492 &receipt.verifier_evidence_handles,
1493 24,
1494 )?;
1495 reject_sensitive_coordination_values(&receipt.candidate_handles)?;
1496 reject_sensitive_coordination_values(&receipt.evidence_handles)?;
1497 reject_sensitive_coordination_values(&receipt.reviewer_evidence_handles)?;
1498 reject_sensitive_coordination_values(&receipt.verifier_evidence_handles)?;
1499 if receipt.retry_limit == 0
1500 || receipt.retry_limit > MAX_RECONCILIATION_RETRIES
1501 || receipt.retry_count > receipt.retry_limit
1502 {
1503 return Err("reconciliation retry count/limit is invalid".to_string());
1504 }
1505 if receipt.reviewer_evidence_handles.is_empty()
1506 || receipt.verifier_evidence_handles.is_empty()
1507 || receipt.reviewer_evidence_handles.iter().any(|review| {
1508 receipt
1509 .verifier_evidence_handles
1510 .iter()
1511 .any(|verify| verify == review)
1512 })
1513 {
1514 return Err("Reviewer and Verifier evidence must be present and independent".to_string());
1515 }
1516 if !matches!(
1517 receipt.verification_outcome.as_str(),
1518 "verified" | "failed" | "blocked"
1519 ) {
1520 return Err("reconciliation verification outcome is invalid".to_string());
1521 }
1522 Ok(())
1523 }
1524
1525 fn decision_is_relevant(
1526 decision: &DecisionRecord,
1527 claim: Option<&WriteScopeClaim>,
1528 capabilities: &[String],
1529 claim_root: Option<&Path>,
1530 decision_root: Option<&Path>,
1531 ) -> bool {
1532 let relevant_path = |claim: &WriteScopeClaim, value: &str| match (claim_root, decision_root) {
1533 (Some(claim_root), Some(decision_root)) => {
1534 let Ok(relative) = normalize_claim_path(value) else {
1535 return false;
1536 };
1537 let path = if relative == "." {
1538 decision_root.to_path_buf()
1539 } else {
1540 decision_root.join(relative)
1541 };
1542 let contained = path
1543 .strip_prefix(claim_root)
1544 .ok()
1545 .is_some_and(|relative| claim.contains_path(&relative.to_string_lossy()));
1546 contained
1547 || claim
1548 .roots
1549 .iter()
1550 .chain(&claim.exact_files)
1551 .any(|relative| claim_root.join(relative).starts_with(&path))
1552 }
1553 _ => claim_reaches_path(claim, value),
1554 };
1555 if decision.scope.is_empty() {
1556 return true;
1557 }
1558 decision.scope.iter().any(|raw| {
1559 let value = raw.trim();
1560 let (kind, value) = value
1561 .split_once(':')
1562 .map_or(("", value), |(kind, value)| (kind.trim(), value.trim()));
1563 match kind {
1564 "capability" => capabilities.iter().any(|capability| capability == value),
1565 "contract" => {
1566 claim.is_some_and(|claim| claim.contracts.iter().any(|contract| contract == value))
1567 }
1568 "path" => claim.is_some_and(|claim| relevant_path(claim, value)),
1569 _ => {
1570 capabilities.iter().any(|capability| capability == value)
1571 || claim.is_some_and(|claim| {
1572 claim.contracts.iter().any(|contract| contract == value)
1573 || relevant_path(claim, value)
1574 })
1575 }
1576 }
1577 })
1578 }
1579
1580 fn claim_reaches_path(claim: &WriteScopeClaim, path: &str) -> bool {
1581 let Ok(path) = normalize_claim_path(path) else {
1582 return false;
1583 };
1584 claim.contains_path(&path)
1585 || claim.roots.iter().any(|root| path_contains(&path, root))
1586 || claim
1587 .exact_files
1588 .iter()
1589 .any(|file| path_contains(&path, file))
1590 }
1591
1592 fn bounded_utf8(value: &str, byte_limit: usize) -> String {
1593 if value.len() <= byte_limit {
1594 return value.to_string();
1595 }
1596 let mut end = byte_limit;
1597 while !value.is_char_boundary(end) {
1598 end = end.saturating_sub(1);
1599 }
1600 value[..end].to_string()
1601 }
1602
1603 fn trim_front<T>(records: &mut Vec<T>, limit: usize) {
1604 if records.len() > limit {
1605 records.drain(..records.len() - limit);
1606 }
1607 }
1608
1609 #[cfg(test)]
1610 mod records_tests {
1611 use super::*;
1612 use serde_json::json;
1613
1614 fn scoped_root(path: impl AsRef<Path>) -> CoordinationClaimScope {
1615 CoordinationClaimScope {
1616 canonical_root: path.as_ref().to_path_buf(),
1617 platform: if cfg!(windows) { "windows" } else { "unix" }.into(),
1618 volume: 1,
1619 index: 1,
1620 }
1621 }
1622
1623 fn root_claim(owner: &str, path: &str, contract: Option<&str>) -> WriteScopeClaim {
1624 WriteScopeClaim {
1625 owner: owner.into(),
1626 roots: vec![path.into()],
1627 exact_files: Vec::new(),
1628 contracts: contract.map(String::from).into_iter().collect(),
1629 }
1630 }
1631
1632 #[test]
1633 fn attributed_claims_project_nested_and_alias_roots_and_keep_contracts_global() {
1634 let temp = tempfile::tempdir().unwrap();
1635 let root = temp.path().canonicalize().unwrap();
1636 let original = root.join("original");
1637 let mut ledger = CoordinationLedger::default();
1638 ledger
1639 .register_claim_in_scope(
1640 root_claim("a", "src", None),
1641 false,
1642 Some(scoped_root(root.join("shared"))),
1643 Some(&original),
1644 |_| true,
1645 )
1646 .unwrap();
1647 assert!(
1648 ledger
1649 .register_claim_in_scope(
1650 root_claim("nested", ".", None),
1651 false,
1652 Some(scoped_root(root.join("shared/src"))),
1653 Some(&original),
1654 |_| true
1655 )
1656 .is_err()
1657 );
1658 assert!(
1659 ledger
1660 .register_claim_in_scope(
1661 root_claim("alias", "src", None),
1662 false,
1663 Some(scoped_root(root.join("shared"))),
1664 Some(&original),
1665 |_| true
1666 )
1667 .is_err()
1668 );
1669 ledger
1670 .register_claim_in_scope(
1671 root_claim("disjoint", "src", Some("release")),
1672 false,
1673 Some(scoped_root(root.join("other"))),
1674 Some(&original),
1675 |_| true,
1676 )
1677 .unwrap();
1678 assert!(
1679 ledger
1680 .register_claim_in_scope(
1681 root_claim("global-contract", "unrelated", Some("release")),
1682 false,
1683 None,
1684 Some(&original),
1685 |_| true
1686 )
1687 .is_err()
1688 );
1689 }
1690
1691 #[test]
1692 fn attributed_schema_is_sticky_and_absent_map_or_orphan_receipt_refuses() {
1693 let temp = tempfile::tempdir().unwrap();
1694 let root = temp.path().canonicalize().unwrap();
1695 let original = root.join("original");
1696 let mut legacy = CoordinationLedger::default();
1697 legacy
1698 .register_claim(root_claim("legacy", "src", None), false, |_| false)
1699 .unwrap();
1700 let legacy_bytes = serde_json::to_vec(&legacy).unwrap();
1701 assert!(
1702 !String::from_utf8(legacy_bytes.clone())
1703 .unwrap()
1704 .contains("claim_scopes")
1705 );
1706 let mut decoded: CoordinationLedger = serde_json::from_slice(&legacy_bytes).unwrap();
1707 decoded.validate_replay().unwrap();
1708 assert_eq!(serde_json::to_vec(&decoded).unwrap(), legacy_bytes);
1709 decoded
1710 .register_claim_in_scope(
1711 root_claim("extra", "src", None),
1712 false,
1713 Some(scoped_root(root.join("other"))),
1714 Some(&original),
1715 |_| false,
1716 )
1717 .unwrap();
1718 assert_eq!(decoded.schema_version, 2);
1719 decoded.release_stale_claims(None, |_| false).unwrap();
1720 assert!(decoded.claim_scopes.as_ref().unwrap().is_empty());
1721 assert_eq!(decoded.schema_version, 2);
1722 decoded.validate_replay().unwrap();
1723 decoded.claim_scopes = None;
1724 assert!(
1725 decoded
1726 .validate_replay()
1727 .unwrap_err()
1728 .contains("requires explicit")
1729 );
1730 decoded.claim_scopes = Some(HashMap::from([(100, scoped_root(root.join("other")))]));
1731 assert!(
1732 decoded
1733 .validate_replay()
1734 .unwrap_err()
1735 .contains("matching shared claim")
1736 );
1737 decoded.schema_version = 1;
1738 assert!(
1739 decoded
1740 .validate_replay()
1741 .unwrap_err()
1742 .contains("legacy coordination schema")
1743 );
1744 }
1745
1746 #[test]
1747 fn overlapping_roots_detected() {
1748 let a = WriteScopeClaim {
1749 owner: "agent-a".into(),
1750 roots: vec!["src/tui/".into()],
1751 exact_files: vec![],
1752 contracts: vec![],
1753 };
1754 let b = WriteScopeClaim {
1755 owner: "agent-b".into(),
1756 roots: vec!["src/tui/widgets/".into()],
1757 exact_files: vec![],
1758 contracts: vec![],
1759 };
1760 assert!(a.overlaps(&b));
1761 }
1762
1763 #[test]
1764 fn disjoint_roots_no_overlap() {
1765 let a = WriteScopeClaim {
1766 owner: "agent-a".into(),
1767 roots: vec!["src/tui/".into()],
1768 exact_files: vec![],
1769 contracts: vec![],
1770 };
1771 let b = WriteScopeClaim {
1772 owner: "agent-b".into(),
1773 roots: vec!["src/core/".into()],
1774 exact_files: vec![],
1775 contracts: vec![],
1776 };
1777 assert!(!a.overlaps(&b));
1778 }
1779
1780 #[test]
1781 fn exact_file_collision_detected() {
1782 let a = WriteScopeClaim {
1783 owner: "agent-a".into(),
1784 roots: vec![],
1785 exact_files: vec!["src/main.rs".into()],
1786 contracts: vec![],
1787 };
1788 let b = WriteScopeClaim {
1789 owner: "agent-b".into(),
1790 roots: vec![],
1791 exact_files: vec!["src/main.rs".into()],
1792 contracts: vec![],
1793 };
1794 assert!(a.overlaps(&b));
1795 }
1796
1797 #[test]
1798 fn release_stale_claims_releases_only_inactive_owners_and_honours_an_owner_filter() {
1799 let mut ledger = CoordinationLedger::default();
1800 for (owner, root) in [
1801 ("live-builder", "src/live"),
1802 ("zombie-builder", "src/zombie"),
1803 ("prior-session-builder", "src/prior"),
1804 ] {
1805 ledger
1806 .register_claim(
1807 WriteScopeClaim {
1808 owner: owner.into(),
1809 roots: vec![root.into()],
1810 exact_files: Vec::new(),
1811 contracts: Vec::new(),
1812 },
1813 false,
1814 |candidate| candidate == "live-builder",
1815 )
1816 .expect("non-overlapping claim registers");
1817 }
1818 assert_eq!(ledger.write_claims.len(), 3);
1819
1820 let released = ledger
1821 .release_stale_claims(None, |candidate| candidate == "live-builder")
1822 .expect("release sweeps stale claims");
1823 assert_eq!(released, vec!["zombie-builder", "prior-session-builder"]);
1824 assert_eq!(ledger.write_claims.len(), 1);
1825 assert_eq!(ledger.write_claims[0].claim.owner, "live-builder");
1826
1827 // A second sweep is idempotent and never touches a live claimant.
1828 let released = ledger
1829 .release_stale_claims(None, |candidate| candidate == "live-builder")
1830 .expect("idempotent sweep");
1831 assert!(released.is_empty());
1832 }
1833
1834 #[test]
1835 fn release_stale_claims_refuses_to_remove_an_owner_filter_for_a_live_claimant() {
1836 let mut ledger = CoordinationLedger::default();
1837 ledger
1838 .register_claim(
1839 WriteScopeClaim {
1840 owner: "live-builder".into(),
1841 roots: vec!["src/live".into()],
1842 exact_files: Vec::new(),
1843 contracts: Vec::new(),
1844 },
1845 false,
1846 |candidate| candidate == "live-builder",
1847 )
1848 .expect("claim registers");
1849 let released = ledger
1850 .release_stale_claims(Some("live-builder"), |candidate| {
1851 candidate == "live-builder"
1852 })
1853 .expect("a live claimant is never released");
1854 assert!(released.is_empty());
1855
1856 // A stale owner named in the filter IS released; other stale owners are not touched.
1857 ledger
1858 .register_claim(
1859 WriteScopeClaim {
1860 owner: "zombie-builder".into(),
1861 roots: vec!["src/zombie".into()],
1862 exact_files: Vec::new(),
1863 contracts: Vec::new(),
1864 },
1865 false,
1866 |candidate| candidate == "live-builder",
1867 )
1868 .expect("claim registers");
1869 let released = ledger
1870 .release_stale_claims(Some("zombie-builder"), |candidate| {
1871 candidate == "live-builder"
1872 })
1873 .expect("filtered release");
1874 assert_eq!(released, vec!["zombie-builder"]);
1875 assert_eq!(ledger.write_claims.len(), 1);
1876 }
1877
1878 #[test]
1879 fn path_overlap_respects_component_boundaries_and_root_coverage() {
1880 let root = WriteScopeClaim {
1881 owner: "agent-a".into(),
1882 roots: vec!["src".into()],
1883 exact_files: vec![],
1884 contracts: vec![],
1885 };
1886 let sibling = WriteScopeClaim {
1887 owner: "agent-b".into(),
1888 roots: vec!["src2".into()],
1889 exact_files: vec![],
1890 contracts: vec![],
1891 };
1892 let child_file = WriteScopeClaim {
1893 owner: "agent-c".into(),
1894 roots: vec![],
1895 exact_files: vec!["src/lib.rs".into()],
1896 contracts: vec![],
1897 };
1898 assert!(!root.overlaps(&sibling));
1899 assert!(root.overlaps(&child_file));
1900 }
1901
1902 #[test]
1903 fn disjoint_exact_files_share_a_root() {
1904 // #6278: N workers, one results directory, one disjoint file each.
1905 let a = WriteScopeClaim {
1906 owner: "agent-a".into(),
1907 roots: vec!["tmp/scan".into()],
1908 exact_files: vec!["tmp/scan/a.txt".into()],
1909 contracts: vec![],
1910 };
1911 let b = WriteScopeClaim {
1912 owner: "agent-b".into(),
1913 roots: vec!["tmp/scan".into()],
1914 exact_files: vec!["tmp/scan/b.txt".into()],
1915 contracts: vec![],
1916 };
1917 assert!(!a.overlaps(&b));
1918 assert!(!b.overlaps(&a));
1919 // The bound root is the file boundary: the shared tree and the
1920 // peer's file are outside this claim's authorized surface.
1921 assert!(a.contains_path("tmp/scan/a.txt"));
1922 assert!(!a.contains_path("tmp/scan/b.txt"));
1923 assert!(!a.contains_path("tmp/scan/scratch.txt"));
1924 }
1925
1926 #[test]
1927 fn file_bound_roots_still_refuse_real_overlap() {
1928 let a = WriteScopeClaim {
1929 owner: "agent-a".into(),
1930 roots: vec!["tmp/scan".into()],
1931 exact_files: vec!["tmp/scan/a.txt".into()],
1932 contracts: vec![],
1933 };
1934 // The same file under the shared root still contends.
1935 let same_file = WriteScopeClaim {
1936 owner: "agent-b".into(),
1937 roots: vec!["tmp/scan".into()],
1938 exact_files: vec!["tmp/scan/a.txt".into()],
1939 contracts: vec![],
1940 };
1941 assert!(a.overlaps(&same_file));
1942 // An open root — no files declared beneath it — keeps tree-wide
1943 // authority and still contends with a file beneath it.
1944 let open_root = WriteScopeClaim {
1945 owner: "agent-c".into(),
1946 roots: vec!["tmp/scan".into()],
1947 exact_files: vec![],
1948 contracts: vec![],
1949 };
1950 assert!(a.overlaps(&open_root));
1951 // A root whose files sit elsewhere stays open: union claims are
1952 // unchanged for files outside the claimed trees.
1953 let mixed = WriteScopeClaim {
1954 owner: "agent-d".into(),
1955 roots: vec!["src".into()],
1956 exact_files: vec!["README.md".into()],
1957 contracts: vec![],
1958 };
1959 assert!(mixed.contains_path("src/lib.rs"));
1960 assert!(mixed.contains_path("README.md"));
1961 }
1962
1963 #[test]
1964 fn disjoint_file_claims_under_one_root_both_register() {
1965 let mut ledger = CoordinationLedger::default();
1966 for (owner, file) in [("agent-a", "tmp/scan/a.txt"), ("agent-b", "tmp/scan/b.txt")] {
1967 ledger
1968 .register_claim(
1969 WriteScopeClaim {
1970 owner: owner.into(),
1971 roots: vec!["tmp/scan".into()],
1972 exact_files: vec![file.into()],
1973 contracts: vec![],
1974 },
1975 false,
1976 |_| true,
1977 )
1978 .expect("disjoint files under a shared root register");
1979 }
1980 assert_eq!(ledger.write_claims.len(), 2);
1981 assert!(ledger.contentions.is_empty());
1982 }
1983
1984 #[test]
1985 fn legacy_blocked_contention_wire_defaults_to_unresolved() {
1986 let receipt: WriteContentionReceipt = serde_json::from_value(json!({
1987 "claimant": "agent-b",
1988 "conflicting_owner": "agent-a",
1989 "roots": ["src"],
1990 "exact_files": [],
1991 "contracts": ["public-api"],
1992 "disposition": "blocked_pending_isolation_or_serialization",
1993 "sequence": 3
1994 }))
1995 .expect("existing blocked wire receipt remains readable");
1996
1997 assert_eq!(
1998 receipt.disposition,
1999 WriteContentionDisposition::BlockedPendingIsolationOrSerialization
2000 );
2001 assert_eq!(receipt.resolution_sequence, None);
2002 assert!(receipt.disposition.blocks_admission());
2003 }
2004
2005 #[test]
2006 fn active_shared_claims_contend_but_isolated_claims_do_not() {
2007 let mut ledger = CoordinationLedger::default();
2008 let first = WriteScopeClaim {
2009 owner: "agent-a".into(),
2010 roots: vec!["src".into()],
2011 exact_files: vec![],
2012 contracts: vec!["public-api".into()],
2013 };
2014 ledger.register_claim(first, false, |_| false).unwrap();
2015 let second = WriteScopeClaim {
2016 owner: "agent-b".into(),
2017 roots: vec!["docs".into()],
2018 exact_files: vec![],
2019 contracts: vec!["public-api".into()],
2020 };
2021 let err = ledger
2022 .register_claim(second.clone(), false, |owner| owner == "agent-a")
2023 .unwrap_err();
2024 assert!(
2025 err.contains("contention") && err.contains("agent-a"),
2026 "{err}"
2027 );
2028 assert_eq!(ledger.contentions.len(), 1);
2029 assert_eq!(ledger.contentions[0].claimant, "agent-b");
2030 assert_eq!(ledger.contentions[0].conflicting_owner, "agent-a");
2031 assert_eq!(
2032 ledger.contentions[0].disposition,
2033 WriteContentionDisposition::BlockedPendingIsolationOrSerialization
2034 );
2035 assert_eq!(
2036 serde_json::to_value(&ledger.contentions[0]).unwrap()["disposition"],
2037 json!("blocked_pending_isolation_or_serialization")
2038 );
2039 let resolving_claim = ledger
2040 .register_claim(second, true, |owner| owner == "agent-a")
2041 .expect("isolated claim resolves the blocked admission");
2042 assert_eq!(
2043 ledger.contentions[0].disposition,
2044 WriteContentionDisposition::ResolvedBySuccessfulClaim
2045 );
2046 assert_eq!(
2047 ledger.contentions[0].resolution_sequence,
2048 Some(resolving_claim.sequence)
2049 );
2050 }
2051
2052 #[test]
2053 fn active_write_claims_are_never_evicted_by_receipt_retention() {
2054 let mut ledger = CoordinationLedger::default();
2055 for index in 0..COORDINATION_RECORD_LIMIT {
2056 ledger
2057 .register_claim(
2058 WriteScopeClaim {
2059 owner: format!("agent-{index:03}"),
2060 roots: vec![format!("pkg-{index:03}")],
2061 exact_files: vec![],
2062 contracts: vec![],
2063 },
2064 false,
2065 |_| true,
2066 )
2067 .unwrap();
2068 }
2069 let error = ledger
2070 .register_claim(
2071 WriteScopeClaim {
2072 owner: "agent-over-cap".into(),
2073 roots: vec!["new-package".into()],
2074 exact_files: vec![],
2075 contracts: vec![],
2076 },
2077 false,
2078 |_| true,
2079 )
2080 .expect_err("all-active capacity must fail before evicting ownership");
2081 assert!(error.contains("active owners"), "{error}");
2082 assert_eq!(ledger.write_claims.len(), COORDINATION_RECORD_LIMIT);
2083 assert!(
2084 ledger
2085 .write_claims
2086 .iter()
2087 .any(|record| record.claim.owner == "agent-000")
2088 );
2089 }
2090
2091 #[test]
2092 fn accepted_decisions_require_owner_and_explicit_neutral_reconciliation() {
2093 let mut ledger = CoordinationLedger::default();
2094 let make = |id: &str, owner: &str, status| DecisionRecord {
2095 decision_id: id.into(),
2096 subject: "storage".into(),
2097 status,
2098 owner: owner.into(),
2099 scope: vec!["router".into()],
2100 constraints: vec![],
2101 evidence_handles: vec![format!("receipt:{id}")],
2102 version: 1,
2103 sequence: 0,
2104 };
2105 ledger
2106 .record_decision(make("a", "agent-a", DecisionStatus::Accepted))
2107 .unwrap();
2108 ledger
2109 .record_decision(make("b", "agent-b", DecisionStatus::Proposed))
2110 .unwrap();
2111 let owner_error = ledger
2112 .update_decision_status("b", DecisionStatus::Accepted, "root", 2)
2113 .unwrap_err();
2114 assert!(owner_error.contains("owned by 'agent-b'"), "{owner_error}");
2115 let stale = ledger
2116 .update_decision_status("b", DecisionStatus::Accepted, "agent-b", 1)
2117 .unwrap_err();
2118 assert!(stale.contains("expected 1, current 2"), "{stale}");
2119 let conflict = ledger
2120 .update_decision_status("b", DecisionStatus::Accepted, "agent-b", 2)
2121 .unwrap_err();
2122 assert!(conflict.contains("neutral reconciliation"), "{conflict}");
2123 ledger
2124 .update_decision_status("a", DecisionStatus::Superseded, "agent-a", 1)
2125 .unwrap();
2126 ledger
2127 .update_decision_status("b", DecisionStatus::Accepted, "agent-b", 2)
2128 .unwrap();
2129 let receipt = ledger
2130 .reconcile(
2131 "storage".into(),
2132 "root".into(),
2133 vec!["a".into(), "b".into()],
2134 "use bounded origin-session artifacts".into(),
2135 vec!["test:coord".into()],
2136 vec!["branch:agent-a".into(), "branch:agent-b".into()],
2137 1,
2138 3,
2139 vec!["review:independent".into()],
2140 vec!["verify:locked".into()],
2141 "verified".into(),
2142 )
2143 .unwrap();
2144 assert_eq!(receipt.input_decisions.len(), 2);
2145 assert!(receipt.sequence > ledger.decisions[1].sequence);
2146 }
2147
2148 #[test]
2149 fn relevant_decision_projection_is_deduplicated_bounded_and_receipted() {
2150 let mut ledger = CoordinationLedger::default();
2151 for (id, subject, scope) in [
2152 ("file", "file-contract", "path:src"),
2153 ("docs", "docs-contract", "path:docs"),
2154 ("api", "api-contract", "contract:public-api"),
2155 ] {
2156 ledger
2157 .record_decision(DecisionRecord {
2158 decision_id: id.into(),
2159 subject: subject.into(),
2160 status: DecisionStatus::Accepted,
2161 owner: "planner".into(),
2162 scope: vec![scope.into()],
2163 constraints: vec!["bounded".into(), "bounded".into()],
2164 evidence_handles: vec![format!("receipt:{id}")],
2165 version: 1,
2166 sequence: 0,
2167 })
2168 .unwrap();
2169 }
2170 let claim = WriteScopeClaim {
2171 owner: "worker".into(),
2172 roots: vec!["src/tui".into()],
2173 exact_files: vec![],
2174 contracts: vec!["public-api".into()],
2175 };
2176 let (projection, receipt) =
2177 ledger.project_relevant_decisions("worker", Some(&claim), &["File".into()]);
2178 assert!(projection.contains("file-contract"), "{projection}");
2179 assert!(projection.contains("api-contract"), "{projection}");
2180 assert!(!projection.contains("docs-contract"), "{projection}");
2181 assert!(projection.len() <= COORDINATION_PROJECTION_BYTE_LIMIT);
2182 assert_eq!(receipt.decision_ids, vec!["api", "file"]);
2183 assert_eq!(receipt.deduplicated, 1);
2184 assert_eq!(ledger.projections.last(), Some(&receipt));
2185 }
2186
2187 #[test]
2188 fn projection_receipt_distinguishes_unique_omissions_from_deduplication() {
2189 let mut ledger = CoordinationLedger::default();
2190 for index in 0..(COORDINATION_PROJECTION_DECISION_LIMIT + 2) {
2191 ledger
2192 .record_decision(DecisionRecord {
2193 decision_id: format!("decision-{index}"),
2194 subject: format!("subject-{index}"),
2195 status: DecisionStatus::Accepted,
2196 owner: "planner".into(),
2197 scope: vec!["path:src".into()],
2198 constraints: vec![format!("constraint-{index}")],
2199 evidence_handles: vec![format!("receipt:{index}")],
2200 version: 1,
2201 sequence: 0,
2202 })
2203 .unwrap();
2204 }
2205 let claim = WriteScopeClaim {
2206 owner: "worker".into(),
2207 roots: vec!["src".into()],
2208 exact_files: vec![],
2209 contracts: vec![],
2210 };
2211
2212 let (projection, receipt) = ledger.project_relevant_decisions("worker", Some(&claim), &[]);
2213
2214 assert!(projection.len() <= COORDINATION_PROJECTION_BYTE_LIMIT);
2215 assert_eq!(
2216 receipt.decision_ids.len(),
2217 COORDINATION_PROJECTION_DECISION_LIMIT
2218 );
2219 assert_eq!(receipt.deduplicated, 0);
2220 assert_eq!(receipt.omitted, 2);
2221 }
2222
2223 #[test]
2224 fn coordination_schema_drift_fails_closed_before_mutation() {
2225 let mut ledger = CoordinationLedger {
2226 schema_version: COORDINATION_SCHEMA_VERSION + 2,
2227 ..CoordinationLedger::default()
2228 };
2229 let error = ledger
2230 .register_claim(
2231 WriteScopeClaim {
2232 owner: "worker".into(),
2233 roots: vec!["src".into()],
2234 exact_files: vec![],
2235 contracts: vec![],
2236 },
2237 false,
2238 |_| false,
2239 )
2240 .unwrap_err();
2241 assert!(error.contains("unsupported coordination schema"), "{error}");
2242 assert!(ledger.write_claims.is_empty());
2243 }
2244 }
2245
2245 lines RUST