interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-bench / tests / crumb_synapse_qualification.rs

1477 lines · 54662 bytes Raw Blame History
1//! ADR 0004 deliverable D5: combined qualification of the Crumb-Synapse agent workflow
2//! (issue #12). Every scenario drives the merged D1 to D4 surfaces together: the shared
3//! coordination plane (`synapse-coord`, and the pinned `crumb.c` when `CRUMB_C_BIN` is set),
4//! the pre-submit advisory, Crumb contexts, signed evidence receipts, the Git bridge, and
5//! Synapse's two publication gates (`Capability::Publish`, Radicle canonical promotion).
6//!
7//! Each scenario prints one line `D5-RESULT <id> <PASS|KNOWN-GAP|UNVERIFIED> <detail>` when it
8//! finishes; `scripts/qualify-crumb-synapse.sh` collects those lines into
9//! `evidence/crumb-synapse/`. A panicking scenario prints nothing and fails the run.
10//!
11//! Scope limit: AEGIS (aienos `crates/aienos-aegis`) is not integrated here. The exit rule is
12//! proven against Synapse's own gates only.
13
14use ed25519_dalek::{Signer, SigningKey};
15use serde::Serialize;
16use std::collections::BTreeMap;
17use std::fs;
18use std::path::{Path, PathBuf};
19use std::process::Command;
20use synapse_api::{
21 ChangesetAdvisory, ChangesetAdvisoryPayload, CoordinationStatus, CrumbContextQueryPayload,
22 EvidenceBase, EvidenceBaseQueryPayload, ReceiptVerification, StaleReason, Staleness,
23 SynapseService, TreeTarget, VerifyEvidenceReceiptPayload,
24};
25use synapse_auth::{AgentCapabilityGrant, AuthenticatedRequest, Capability};
26use synapse_coord::{
27 ClaimOutcome, CoordError, CoordStore, Holder, NoOracle, RecordRefusal, StoreId, Workspace,
28};
29use synapse_core::{
30 encode_did_key_ed25519, BlobDigest, ChangesetEnvelope, ChangesetId, FileMode, GitOid,
31 IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, SYNAPSE_ENVELOPE_VERSION,
32};
33use synapse_crumb::{CrumbContext, Dialect, ROOT_DIR};
34use synapse_evidence::{
35 EvidenceReceipt, ExitStatus, InputRoot, Observation, Outcome, ReceiptBody, ReceiptError,
36 ReceiptResult, TestIdentity, MAX_LOG_BYTES, MAX_RECEIPT_BYTES,
37};
38use synapse_git::{
39 advance_human_branch_fast_forward, materialize_changeset_to_git, project_github_pull_request,
40 GitHubPrProjectionRequest, GitProjectionIndex, HumanBranchAdvanceRequest,
41};
42use synapse_radicle::{
43 CanonicalPromotionEngine, DelegateSigrefs, PromotionCandidate, RadicleIdentityDoc,
44 RadiclePayloadMap, RadicleProjectPayload,
45};
46use synapse_store::{
47 FaultInjection, FsyncPolicy, IngestOutcome, RecoveryPolicy, StoreLimits, FAULT_CRASH_EXIT_CODE,
48};
49
50const ROOT_CRUMB: &[u8] =
51 br#"{"schema_version":"1.0.0","name":"root","purpose":"Root.","invariants":["root rule"]}"#;
52const SRC_CRUMB: &[u8] =
53 br#"{"schema_version":"1.0.0","name":"src","purpose":"Sources.","invariants":["src rule"]}"#;
54const SRC_CRUMB_V2: &[u8] = br#"{"schema_version":"1.0.0","name":"src","purpose":"Sources, rewritten.","invariants":["new src rule"]}"#;
55const FIX_ROOT: &[u8] = include_bytes!("../../synapse-crumb/tests/fixtures/tree/dot.crumb");
56const FIX_D1: &[u8] = include_bytes!("../../synapse-crumb/tests/fixtures/tree/d1/dot.crumb");
57const FIX_D2: &[u8] = include_bytes!("../../synapse-crumb/tests/fixtures/tree/d2/dot.crumb");
58const FIX_D3: &[u8] = include_bytes!("../../synapse-crumb/tests/fixtures/tree/d3/dot.crumb");
59/// Fixed coordination clock (2027-01-15), so expiry is deterministic.
60const T0: i64 = 1_800_000_000;
61/// Environment variable naming the coordination store for a re-executed child scenario.
62const CHILD_ENV: &str = "D5_CHILD_DIR";
63
64fn result(id: &str, status: &str, detail: &str) {
65 println!("D5-RESULT {id} {status} {detail}");
66}
67
68fn scratch(label: &str) -> PathBuf {
69 let dir = std::env::temp_dir().join(format!(
70 "synapse-d5-{label}-{}-{}",
71 std::process::id(),
72 std::time::SystemTime::now()
73 .duration_since(std::time::UNIX_EPOCH)
74 .unwrap()
75 .as_nanos()
76 ));
77 fs::create_dir_all(&dir).unwrap();
78 dir
79}
80
81fn did(key: &SigningKey) -> String {
82 encode_did_key_ed25519(&key.verifying_key().to_bytes())
83}
84
85fn alice() -> SigningKey {
86 SigningKey::from_bytes(&[21u8; 32])
87}
88fn bob() -> SigningKey {
89 SigningKey::from_bytes(&[22u8; 32])
90}
91fn carol() -> SigningKey {
92 SigningKey::from_bytes(&[23u8; 32])
93}
94fn runner() -> SigningKey {
95 SigningKey::from_bytes(&[30u8; 32])
96}
97fn delegate() -> SigningKey {
98 SigningKey::from_bytes(&[40u8; 32])
99}
100
101/// A Synapse service with one registered base tree, plus helpers that sign every request.
102struct Fx {
103 svc: SynapseService,
104 auth: SigningKey,
105 repo: RepoId,
106 nonce: u64,
107 dir: PathBuf,
108 base_oid: GitOid,
109 base_files: Vec<(String, FileMode, Vec<u8>)>,
110}
111
112impl Drop for Fx {
113 fn drop(&mut self) {
114 let _ = fs::remove_dir_all(&self.dir);
115 }
116}
117
118fn default_files() -> Vec<(String, FileMode, Vec<u8>)> {
119 [
120 (".crumb", ROOT_CRUMB),
121 ("src/.crumb", SRC_CRUMB),
122 ("src/a.rs", b"fn a() {}\n".as_slice()),
123 ("src/b.rs", b"fn b() {}\n".as_slice()),
124 ("docs/x.md", b"# x\n".as_slice()),
125 ]
126 .iter()
127 .map(|(p, b)| (p.to_string(), FileMode::Regular644, b.to_vec()))
128 .collect()
129}
130
131impl Fx {
132 fn new(label: &str) -> Self {
133 Self::with(label, FsyncPolicy::EveryCommit, default_files())
134 }
135
136 fn with(label: &str, policy: FsyncPolicy, files: Vec<(String, FileMode, Vec<u8>)>) -> Self {
137 let dir = scratch(label);
138 let repo = RepoId::new("aien-spark/synapse").unwrap();
139 let svc = SynapseService::open(
140 dir.join("svc"),
141 repo.clone(),
142 policy,
143 RecoveryPolicy::StrictFailClosed,
144 StoreLimits::default(),
145 )
146 .unwrap();
147 let mut fx = Self {
148 svc,
149 auth: SigningKey::from_bytes(&[10u8; 32]),
150 repo,
151 nonce: 0,
152 dir,
153 base_oid: GitOid([1; 20]),
154 base_files: files,
155 };
156 fx.prime();
157 fx
158 }
159
160 /// Register the authority and base tree (in memory only; repeated after a reopen).
161 fn prime(&mut self) {
162 self.svc.register_authority(did(&self.auth));
163 self.svc
164 .register_base_tree(self.base_oid, self.base_files.clone())
165 .unwrap();
166 }
167
168 fn base(&self) -> TreeTarget {
169 TreeTarget::BaseGitCommit(self.base_oid)
170 }
171
172 fn coord(&self, now: i64) -> CoordStore {
173 CoordStore::open(self.dir.join("coord")).with_clock(move || now)
174 }
175
176 fn now(&self) -> u64 {
177 1_000 + self.nonce
178 }
179
180 fn sign_as<T: Serialize>(
181 &mut self,
182 key: &SigningKey,
183 caps: Vec<Capability>,
184 cap: Capability,
185 payload: T,
186 ) -> AuthenticatedRequest<T> {
187 self.nonce += 1;
188 let mut n = [0u8; 32];
189 n[..8].copy_from_slice(&self.nonce.to_le_bytes());
190 let grant = AgentCapabilityGrant::issue(
191 &self.auth,
192 n,
193 self.repo.clone(),
194 did(key),
195 caps,
196 8 * 1024 * 1024,
197 10_000,
198 60_000,
199 1,
200 10_000_000,
201 );
202 AuthenticatedRequest::sign_new(
203 key,
204 grant,
205 self.repo.clone(),
206 cap,
207 n,
208 self.now(),
209 0,
210 payload,
211 )
212 .unwrap()
213 }
214
215 fn envelope(
216 &self,
217 key: &SigningKey,
218 label: &str,
219 files: &[(&str, &[u8])],
220 ) -> ChangesetEnvelope {
221 let mut env = ChangesetEnvelope {
222 version: SYNAPSE_ENVELOPE_VERSION,
223 repo_id: self.repo.clone(),
224 base_git_oid: self.base_oid,
225 parent_changesets: vec![],
226 author_did: String::new(),
227 idempotency_key: IdempotencyKey::from_label(label),
228 created_at_ms: 100,
229 intent_summary: label.to_string(),
230 mutations: files
231 .iter()
232 .map(|(p, b)| PathMutation {
233 path: p.to_string(),
234 op: MutationOp::Upsert {
235 mode: FileMode::Regular644,
236 blob_digest: BlobDigest::compute(b),
237 size_bytes: b.len() as u64,
238 },
239 })
240 .collect(),
241 evidence_receipts: vec![],
242 signature: vec![],
243 };
244 env.sign(key);
245 env
246 }
247
248 fn submit(
249 &mut self,
250 key: &SigningKey,
251 label: &str,
252 files: &[(&str, &[u8])],
253 ) -> synapse_core::SynapseResult<IngestOutcome> {
254 let env = self.envelope(key, label, files);
255 let blobs = files
256 .iter()
257 .map(|(_, b)| (BlobDigest::compute(b), b.to_vec()))
258 .collect();
259 let req = self.sign_as(
260 key,
261 vec![Capability::Propose],
262 Capability::Propose,
263 synapse_api::SubmitChangesetPayload {
264 envelope: env,
265 blobs,
266 },
267 );
268 let now = self.now();
269 self.svc.submit(&req, now)
270 }
271
272 /// Submit and require a fresh commit; files must be sorted by path.
273 fn propose(&mut self, key: &SigningKey, label: &str, files: &[(&str, &[u8])]) -> ChangesetId {
274 match self.submit(key, label, files).unwrap() {
275 IngestOutcome::Committed { changeset_id, .. } => changeset_id,
276 other => panic!("unexpected {other:?}"),
277 }
278 }
279
280 fn advise(
281 &mut self,
282 agent: &str,
283 paths: &[&str],
284 coord: Option<&CoordStore>,
285 ) -> ChangesetAdvisory {
286 let payload = ChangesetAdvisoryPayload {
287 base: self.base(),
288 latest: None,
289 paths: paths.iter().map(|p| p.to_string()).collect(),
290 agent: agent.to_string(),
291 snapshot_seq: None,
292 };
293 let req = self.sign_as(&bob(), vec![Capability::Read], Capability::Read, payload);
294 let now = self.now();
295 self.svc.changeset_advisory(&req, coord, now).unwrap()
296 }
297
298 fn context(&mut self, target: TreeTarget, path: &str) -> CrumbContext {
299 let payload = CrumbContextQueryPayload {
300 target,
301 path: path.to_string(),
302 snapshot_seq: None,
303 };
304 let req = self.sign_as(&bob(), vec![Capability::Read], Capability::Read, payload);
305 let now = self.now();
306 self.svc.crumb_context(&req, now).unwrap()
307 }
308
309 fn evidence_base(&mut self, cs: ChangesetId) -> EvidenceBase {
310 let payload = EvidenceBaseQueryPayload {
311 changeset_id: cs,
312 snapshot_seq: None,
313 };
314 let req = self.sign_as(&runner(), vec![Capability::Read], Capability::Read, payload);
315 let now = self.now();
316 self.svc.evidence_base(&req, now).unwrap()
317 }
318
319 fn body(&self, cs: ChangesetId, base: EvidenceBase) -> ReceiptBody {
320 ReceiptBody {
321 repo_id: self.repo.clone(),
322 changeset_id: cs,
323 source: base.source,
324 crumb_contexts: base.crumb_contexts,
325 input_root: InputRoot::single_repo(self.repo.clone(), cs),
326 test: TestIdentity {
327 name: "cargo-test-workspace".into(),
328 command: vec!["cargo".into(), "test".into(), "--workspace".into()],
329 toolchain: "rustc".into(),
330 platform: "aarch64-unknown-linux-gnu".into(),
331 environment: vec![],
332 },
333 result: ReceiptResult {
334 exit_status: ExitStatus::Code(0),
335 outcome: Outcome::Pass,
336 outputs: vec![],
337 },
338 observation: Observation {
339 started_at_ms: 1,
340 duration_ms: 2,
341 log: b"test result: ok\n".to_vec(),
342 },
343 }
344 }
345
346 fn verify(&mut self, receipt: Vec<u8>) -> ReceiptVerification {
347 let payload = VerifyEvidenceReceiptPayload {
348 receipt,
349 snapshot_seq: None,
350 };
351 let req = self.sign_as(&bob(), vec![Capability::Read], Capability::Read, payload);
352 let now = self.now();
353 self.svc.verify_evidence_receipt(&req, now).unwrap()
354 }
355}
356
357fn ws(agent: &str) -> Workspace {
358 Workspace::with_oracle(
359 format!("/synapse/ws/{agent}"),
360 Holder::synapse(
361 &format!("lane/{agent}"),
362 "00112233445566778899",
363 "aabbccddeeff00112233",
364 ),
365 Box::new(NoOracle),
366 )
367}
368
369fn claim(store: &CoordStore, agent: &str, target: &str, ttl: i64) -> ClaimOutcome {
370 store
371 .claim(&ws(agent), agent, ROOT_DIR, target, "edit", Some(ttl))
372 .unwrap()
373}
374
375fn no_warnings(adv: &ChangesetAdvisory) -> bool {
376 adv.coordination == CoordinationStatus::Read
377 && adv.paths.iter().all(|p| {
378 p.claims.is_empty()
379 && p.overlapping_proposals.is_empty()
380 && p.pending_crumb_changes.is_empty()
381 && !matches!(p.staleness, Staleness::Stale { .. })
382 })
383}
384
385// ------------------------------------------------------------------------------------------
386// S01 to S04: the normal multi-agent flow.
387
388#[test]
389fn s01_two_agents_same_file() {
390 let mut fx = Fx::new("s01");
391 let store = fx.coord(T0);
392 assert!(matches!(
393 claim(&store, "alice", "src/a.rs", 600),
394 ClaimOutcome::Claimed { .. }
395 ));
396 match claim(&store, "bob", "src/a.rs", 600) {
397 ClaimOutcome::Blocked { key, holder } => {
398 assert_eq!(key, "src/a.rs");
399 assert_eq!(holder.holder, "alice");
400 }
401 other => panic!("bob's claim was not refused: {other:?}"),
402 }
403 let cs = fx.propose(&alice(), "alice-a", &[("src/a.rs", b"fn a2() {}\n")]);
404 let adv = fx.advise("bob", &["src/a.rs"], Some(&store));
405 assert_eq!(adv.coordination, CoordinationStatus::Read);
406 let p = &adv.paths[0];
407 assert_eq!(p.claims.len(), 1);
408 assert_eq!(p.claims[0].holder, "alice");
409 assert_eq!(p.claims[0].key, "src/a.rs");
410 assert_eq!(p.overlapping_proposals.len(), 1);
411 assert_eq!(p.overlapping_proposals[0].changeset_id, cs);
412 assert_eq!(p.overlapping_proposals[0].author_did, did(&alice()));
413 // The caller's own claim is not reported back to the caller.
414 let own = fx.advise("alice", &["src/a.rs"], Some(&store));
415 assert!(own.paths[0].claims.is_empty());
416 result(
417 "S01",
418 "PASS",
419 "bob's claim on src/a.rs refused (held by alice); bob's advisory shows alice's claim and alice's open proposal",
420 );
421}
422
423#[test]
424fn s02_two_agents_separate_files() {
425 let mut fx = Fx::new("s02");
426 let store = fx.coord(T0);
427 assert!(matches!(
428 claim(&store, "alice", "src/a.rs", 600),
429 ClaimOutcome::Claimed { .. }
430 ));
431 assert!(matches!(
432 claim(&store, "bob", "src/b.rs", 600),
433 ClaimOutcome::Claimed { .. }
434 ));
435 fx.propose(&alice(), "alice-a", &[("src/a.rs", b"fn a2() {}\n")]);
436 let adv = fx.advise("bob", &["src/b.rs", "docs/x.md"], Some(&store));
437 assert!(no_warnings(&adv), "{adv:?}");
438 // Guidance (invariants) is still surfaced: it is context, not a warning.
439 assert!(adv.paths[0].guidance.iter().any(|g| g.text == "src rule"));
440 result(
441 "S02",
442 "PASS",
443 "separate files: both claims granted; advisory has no claims, overlaps, pending .crumb changes or staleness",
444 );
445}
446
447#[test]
448fn s03_stale_crumb_snapshot() {
449 let mut files = default_files();
450 let mut fx = Fx::new("s03");
451 // A second base where src/.crumb was rewritten: a stale-snapshot runner reads this one.
452 files[1].2 = SRC_CRUMB_V2.to_vec();
453 fx.svc.register_base_tree(GitOid([2; 20]), files).unwrap();
454
455 // Advisory: carol's open proposal rewrites src/.crumb after bob's base.
456 let rewrite = fx.propose(&carol(), "carol-crumb", &[("src/.crumb", SRC_CRUMB_V2)]);
457 let adv = fx.advise("bob", &["src/a.rs"], None);
458 let p = &adv.paths[0];
459 assert!(
460 matches!(p.staleness, Staleness::Stale { .. }),
461 "{:?}",
462 p.staleness
463 );
464 assert_eq!(p.pending_crumb_changes.len(), 1);
465 assert_eq!(p.pending_crumb_changes[0].changeset_id, rewrite);
466
467 // Receipts: bob's changeset edits src/.crumb and src/b.rs.
468 let cs = fx.propose(
469 &bob(),
470 "bob-edit",
471 &[("src/.crumb", SRC_CRUMB_V2), ("src/b.rs", b"fn b2() {}\n")],
472 );
473 let base = fx.evidence_base(cs);
474 let src = base
475 .crumb_contexts
476 .iter()
477 .find(|c| c.dir == "src")
478 .unwrap()
479 .clone();
480 assert_ne!(src.at_base, src.in_changeset);
481 let good = EvidenceReceipt::sign(fx.body(cs, base.clone()), &runner()).unwrap();
482 assert!(matches!(
483 fx.verify(good.encode().unwrap()),
484 ReceiptVerification::Current { .. }
485 ));
486
487 // Changeset side stale: the runner claims it tested under the base context.
488 let mut b = base.clone();
489 b.crumb_contexts
490 .iter_mut()
491 .find(|c| c.dir == "src")
492 .unwrap()
493 .in_changeset = src.at_base;
494 let r = EvidenceReceipt::sign(fx.body(cs, b), &runner()).unwrap();
495 match fx.verify(r.encode().unwrap()) {
496 ReceiptVerification::Stale { stale, .. } => {
497 assert_eq!(stale.len(), 1);
498 assert_eq!(stale[0].dir, "src");
499 assert_eq!(stale[0].reason, StaleReason::InChangeset);
500 assert_eq!(stale[0].expected, src.in_changeset);
501 }
502 other => panic!("expected Stale InChangeset, got {other:?}"),
503 }
504
505 // Base side stale: the runner read a stale snapshot (base 2) for "what the author saw".
506 let stale_base = fx
507 .context(TreeTarget::BaseGitCommit(GitOid([2; 20])), "src")
508 .digest();
509 let fresh_base = fx.context(fx.base(), "src").digest();
510 assert_eq!(fresh_base, src.at_base);
511 assert_ne!(stale_base, fresh_base);
512 let mut b = base;
513 b.crumb_contexts
514 .iter_mut()
515 .find(|c| c.dir == "src")
516 .unwrap()
517 .at_base = stale_base;
518 let r = EvidenceReceipt::sign(fx.body(cs, b), &runner()).unwrap();
519 match fx.verify(r.encode().unwrap()) {
520 ReceiptVerification::Stale { stale, .. } => {
521 assert_eq!(stale.len(), 1);
522 assert_eq!(stale[0].reason, StaleReason::AtBase);
523 assert_eq!(stale[0].in_receipt, stale_base);
524 assert_eq!(stale[0].expected, fresh_base);
525 }
526 other => panic!("expected Stale AtBase, got {other:?}"),
527 }
528 result(
529 "S03",
530 "PASS",
531 "advisory Stale + pending .crumb rewrite named; receipt Stale InChangeset and Stale AtBase each name dir src and the expected digest",
532 );
533}
534
535#[test]
536fn s04_expired_claims_ignored() {
537 let mut fx = Fx::new("s04");
538 assert!(matches!(
539 claim(&fx.coord(T0), "alice", "src/a.rs", 60),
540 ClaimOutcome::Claimed { .. }
541 ));
542 let live = fx.advise("bob", &["src/a.rs"], Some(&fx.coord(T0 + 60)));
543 assert_eq!(live.paths[0].claims.len(), 1);
544 let later = fx.advise("bob", &["src/a.rs"], Some(&fx.coord(T0 + 61)));
545 assert_eq!(later.coordination, CoordinationStatus::Read);
546 assert!(later.paths[0].claims.is_empty());
547 // And the plane lets bob take the file over once alice's lock expired.
548 assert!(matches!(
549 claim(&fx.coord(T0 + 61), "bob", "src/a.rs", 600),
550 ClaimOutcome::Claimed { .. }
551 ));
552 // An unparseable timestamp counts as expired too (crumb.c rule).
553 let st = fx.coord(T0 + 61);
554 let rec = fx.dir.join("coord/dirs/docs.json");
555 fs::write(
556 &rec,
557 br#"{"schema_version":"1.0.0","directory":"docs","locks":{"docs/x.md":{"holder":"mallory","acquired_at":"not-a-time","ttl_seconds":999999}}}"#,
558 )
559 .unwrap();
560 assert!(fx.advise("bob", &["docs/x.md"], Some(&st)).paths[0]
561 .claims
562 .is_empty());
563 result(
564 "S04",
565 "PASS",
566 "claim live at ttl, ignored at ttl+1s by advisory and taken over in the plane; unparseable stamp treated as expired",
567 );
568}
569
570// ------------------------------------------------------------------------------------------
571// S05: forged and tampered coordination records.
572
573#[test]
574fn s05_forged_coordination_records() {
575 let mut fx = Fx::new("s05");
576 let st = fx.coord(T0);
577 assert!(matches!(
578 claim(&st, "alice", "src/a.rs", 600),
579 ClaimOutcome::Claimed { .. }
580 ));
581 let dirs = fx.dir.join("coord/dirs");
582 let agents = fx.dir.join("coord/agents");
583
584 // (a) Corrupt JSON: the advisory still answers, reports Unavailable, and no claims.
585 let docs = dirs.join("docs.json");
586 fs::write(&docs, b"{\"locks\": {not json").unwrap();
587 let adv = fx.advise("bob", &["src/a.rs"], Some(&st));
588 assert!(
589 matches!(adv.coordination, CoordinationStatus::Unavailable { .. }),
590 "{adv:?}"
591 );
592 assert!(adv.paths[0].claims.is_empty());
593 // A mutation refuses the corrupt record and never overwrites it.
594 let err = st
595 .claim(&ws("bob"), "bob", ROOT_DIR, "docs/x.md", "edit", Some(60))
596 .unwrap_err();
597 assert!(matches!(err, CoordError::CorruptRecord { .. }), "{err}");
598 assert_eq!(fs::read(&docs).unwrap(), b"{\"locks\": {not json");
599 // Nesting past the parser's depth bound is also corrupt, not a stack overflow.
600 let deep = format!("{}{}", "[".repeat(100_000), "]".repeat(100_000));
601 fs::write(agents.join("deep.json"), deep).unwrap();
602 fs::remove_file(&docs).unwrap();
603 let adv = fx.advise("bob", &["src/a.rs"], Some(&st));
604 assert!(matches!(
605 adv.coordination,
606 CoordinationStatus::Unavailable { .. }
607 ));
608 fs::remove_file(agents.join("deep.json")).unwrap();
609
610 // (b) Wrong holders: empty or non-string holders are skipped; a forged holder is shown
611 // as information only.
612 fs::write(
613 &docs,
614 format!(
615 r#"{{"schema_version":"1.0.0","directory":"docs","locks":{{
616 "docs/x.md":{{"holder":"","acquired_at":"{t}","ttl_seconds":600}},
617 "docs/y.md":{{"holder":42,"acquired_at":"{t}","ttl_seconds":600}},
618 "docs":{{"holder":"mallory","acquired_at":"{t}","ttl_seconds":600}}}}}}"#,
619 t = synapse_coord::time::iso(T0)
620 ),
621 )
622 .unwrap();
623 let adv = fx.advise("bob", &["docs/x.md", "docs/y.md"], Some(&st));
624 assert_eq!(adv.coordination, CoordinationStatus::Read);
625 for p in &adv.paths {
626 let holders: Vec<&str> = p.claims.iter().map(|c| c.holder.as_str()).collect();
627 assert_eq!(holders, ["mallory"], "{}: {holders:?}", p.path);
628 }
629 // A forged lock in the caller's own name hides it from the caller only (self-declared
630 // agent names, ADR 0004 section 2.6): mallory sees nothing about mallory's own lock.
631 assert!(fx.advise("mallory", &["docs/x.md"], Some(&st)).paths[0]
632 .claims
633 .is_empty());
634
635 // (c) Hostile keys: traversal, absolute, empty, NUL, oversized, non-UTF-8.
636 let long = "k".repeat(70_000);
637 let mut hostile = format!(
638 r#"{{"schema_version":"1.0.0","directory":"src","locks":{{
639 "../../etc/passwd":{{"holder":"h1","acquired_at":"{t}","ttl_seconds":600}},
640 "/src/b.rs":{{"holder":"h2","acquired_at":"{t}","ttl_seconds":600}},
641 "":{{"holder":"h3","acquired_at":"{t}","ttl_seconds":600}},
642 "src/b.rs\u0000x":{{"holder":"h4","acquired_at":"{t}","ttl_seconds":600}},
643 "src/b.rs/../a.rs":{{"holder":"h5","acquired_at":"{t}","ttl_seconds":600}},
644 "{long}":{{"holder":"h6","acquired_at":"{t}","ttl_seconds":600}},
645 "src/b":{{"holder":"h7","acquired_at":"{t}","ttl_seconds":600}}"#,
646 t = synapse_coord::time::iso(T0)
647 )
648 .into_bytes();
649 hostile.extend_from_slice(b",\n \"src/\xff\xfe\":{\"holder\":\"h8\",\"acquired_at\":\"");
650 hostile.extend_from_slice(synapse_coord::time::iso(T0).as_bytes());
651 hostile.extend_from_slice(b"\",\"ttl_seconds\":600}}}");
652 fs::write(dirs.join("src.json"), &hostile).unwrap();
653 fs::write(
654 agents.join("..%2f..json"),
655 b"{\"agent\":\"../../x\",\"updated_at\":\"bad\"}",
656 )
657 .unwrap();
658 let adv = fx.advise("bob", &["src/b.rs", "src/a.rs"], Some(&st));
659 assert_eq!(adv.coordination, CoordinationStatus::Read, "{adv:?}");
660 // No hostile key matches by traversal, absolute, empty, prefix or byte tricks: keys are
661 // compared as exact strings. One exception, by crumb.c parity (ADR 0004 section 2.3
662 // item 8): an escaped `\u0000` ends the string, so `"src/b.rs\u0000x"` reads as the key
663 // `src/b.rs`. That is no escalation (the same writer could write `src/b.rs` directly)
664 // and the claim is information only.
665 let holders = |i: usize| -> Vec<&str> {
666 adv.paths[i]
667 .claims
668 .iter()
669 .map(|c| c.holder.as_str())
670 .collect()
671 };
672 assert_eq!(holders(0), ["h4"], "src/b.rs: {:?}", adv.paths[0].claims);
673 assert!(holders(1).is_empty(), "src/a.rs: {:?}", adv.paths[1].claims);
674
675 // Never authority: with all of the above in the store, Synapse still commits a changeset
676 // on src/a.rs (claimed by alice, forged locks around it) and its receipt is Current.
677 let cs = fx.propose(&bob(), "bob-a", &[("src/a.rs", b"fn a3() {}\n")]);
678 let base = fx.evidence_base(cs);
679 let r = EvidenceReceipt::sign(fx.body(cs, base), &runner()).unwrap();
680 assert!(matches!(
681 fx.verify(r.encode().unwrap()),
682 ReceiptVerification::Current { .. }
683 ));
684 result(
685 "S05",
686 "PASS",
687 "corrupt/deep JSON => Unavailable (no panic, not overwritten); empty/non-string holders skipped; forged holder shown as info only; hostile keys (traversal, absolute, empty, prefix, oversized, non-UTF-8) match nothing, escaped-NUL key truncates as in crumb.c; submit and receipt unaffected",
688 );
689}
690
691/// Found by D5, fixed by #58: a non-regular `*.json` record (a FIFO) in the coordination
692/// store used to block `sniff` forever, so the advisory never answered. Now the record is
693/// refused without being opened (typed `RefusedRecord`), `sniff` answers at once, the
694/// advisory reports `Unavailable`, and the FIFO is left as found. A 5 s watchdog turns a
695/// regression into a failure instead of a hang.
696#[test]
697fn s05_fifo_record_refused_advisory_answers() {
698 use std::os::unix::fs::{FileTypeExt, OpenOptionsExt};
699 let mut fx = Fx::new("s05-fifo");
700 let st = fx.coord(T0);
701 assert!(matches!(
702 claim(&st, "alice", "src/a.rs", 600),
703 ClaimOutcome::Claimed { .. }
704 ));
705 let fifo = fx.dir.join("coord/dirs/evil.json");
706 let c = std::ffi::CString::new(fifo.to_str().unwrap()).unwrap();
707 // SAFETY: valid NUL-terminated path.
708 assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o644) }, 0);
709 let root = fx.dir.join("coord");
710 let (tx, rx) = std::sync::mpsc::channel();
711 std::thread::spawn(move || {
712 let st = CoordStore::open(root).with_clock(|| T0);
713 let _ = tx.send(st.sniff(&ws("bob"), "bob", ROOT_DIR).err());
714 });
715 let answered = rx.recv_timeout(std::time::Duration::from_secs(5));
716 if answered.is_err() {
717 // Regression: unblock the reader (non-blocking writer open) so the thread can end.
718 let _ = fs::OpenOptions::new()
719 .write(true)
720 .custom_flags(libc::O_NONBLOCK)
721 .open(&fifo);
722 }
723 let err = answered.expect("sniff did not answer within 5 s on a FIFO record");
724 assert!(
725 matches!(
726 err,
727 Some(CoordError::RefusedRecord {
728 ref path,
729 reason: RecordRefusal::NotRegular("fifo"),
730 }) if *path == fifo
731 ),
732 "{err:?}"
733 );
734 // The sniff answered, so the advisory (same read path) answers too: Unavailable.
735 let adv = fx.advise("bob", &["src/a.rs"], Some(&st));
736 assert!(
737 matches!(adv.coordination, CoordinationStatus::Unavailable { .. }),
738 "{adv:?}"
739 );
740 assert!(fs::symlink_metadata(&fifo).unwrap().file_type().is_fifo());
741}
742
743// ------------------------------------------------------------------------------------------
744// S06, S07: forged, tampered, and self-signed receipts.
745
746#[test]
747fn s06_forged_and_tampered_receipts_refused() {
748 let mut fx = Fx::new("s06");
749 let cs = fx.propose(&alice(), "alice-a", &[("src/a.rs", b"fn a2() {}\n")]);
750 let base = fx.evidence_base(cs);
751 let good = EvidenceReceipt::sign(fx.body(cs, base.clone()), &runner()).unwrap();
752 let bytes = good.encode().unwrap();
753 assert!(matches!(
754 fx.verify(bytes.clone()),
755 ReceiptVerification::Current { .. }
756 ));
757 let refused = |v: ReceiptVerification| match v {
758 ReceiptVerification::Refused(e) => e,
759 other => panic!("not refused: {other:?}"),
760 };
761 let mut cases = 0;
762
763 // Bad signature: last byte flipped.
764 let mut b = bytes.clone();
765 *b.last_mut().unwrap() ^= 1;
766 assert_eq!(refused(fx.verify(b)), ReceiptError::SignatureInvalid);
767 cases += 1;
768 // Forged: signed by mallory, labelled with the runner's DID.
769 let mallory = SigningKey::from_bytes(&[66u8; 32]);
770 let mut forged = EvidenceReceipt::sign(fx.body(cs, base.clone()), &mallory).unwrap();
771 forged.executor_did = did(&runner());
772 assert_eq!(
773 refused(fx.verify(forged.encode().unwrap())),
774 ReceiptError::SignatureInvalid
775 );
776 cases += 1;
777 // Non-canonical DID (bare multibase), correctly re-signed by the same key.
778 let mut bare = good.clone();
779 bare.executor_did = did(&runner()).strip_prefix("did:key:").unwrap().to_string();
780 bare.signature = runner().sign(&bare.signable_bytes()).to_bytes();
781 assert_eq!(
782 refused(fx.verify(bare.encode().unwrap())),
783 ReceiptError::ExecutorDidInvalid
784 );
785 cases += 1;
786 // Field tampers without re-signing: changeset, context digest, outcome+exit, log.
787 type Tamper = Box<dyn Fn(&mut EvidenceReceipt)>;
788 let tampers: Vec<Tamper> = vec![
789 Box::new(|r| {
790 r.body.changeset_id.0[0] ^= 1;
791 r.body.input_root = InputRoot::single_repo(r.body.repo_id.clone(), r.body.changeset_id);
792 }),
793 Box::new(|r| r.body.crumb_contexts[0].at_base.0[0] ^= 1),
794 Box::new(|r| r.body.crumb_contexts[0].in_changeset.0[0] ^= 1),
795 Box::new(|r| {
796 r.body.result.exit_status = ExitStatus::Code(1);
797 r.body.result.outcome = Outcome::Fail;
798 }),
799 Box::new(|r| r.body.observation.log = b"forged log\n".to_vec()),
800 Box::new(|r| r.body.test.name = "other-test".into()),
801 ];
802 for t in &tampers {
803 let mut r = good.clone();
804 t(&mut r);
805 assert_eq!(
806 refused(fx.verify(r.encode().unwrap())),
807 ReceiptError::SignatureInvalid
808 );
809 cases += 1;
810 }
811 // Wrong domain, truncation, trailing bytes.
812 let mut b = bytes.clone();
813 b[0] ^= 1;
814 assert_eq!(refused(fx.verify(b)), ReceiptError::WrongDomain);
815 let b = bytes[..bytes.len() - 10].to_vec();
816 refused(fx.verify(b));
817 let mut b = bytes.clone();
818 b.push(0);
819 assert_eq!(refused(fx.verify(b)), ReceiptError::TrailingBytes);
820 cases += 3;
821 // Oversize: a record over the total cap is refused before parsing; a log over its cap
822 // cannot even be signed.
823 let mut b = bytes.clone();
824 b.resize(MAX_RECEIPT_BYTES + 1, 0);
825 assert!(matches!(refused(fx.verify(b)), ReceiptError::OverCap(_)));
826 let mut big = fx.body(cs, base);
827 big.observation.log = vec![b'x'; MAX_LOG_BYTES + 1];
828 assert!(matches!(
829 EvidenceReceipt::sign(big, &runner()),
830 Err(ReceiptError::OverCap(_))
831 ));
832 cases += 2;
833 // Every single-byte flip of the record is refused (none reaches Current/Stale).
834 let mut flips = 0;
835 for i in (0..bytes.len()).step_by(7) {
836 let mut b = bytes.clone();
837 b[i] ^= 0x40;
838 assert!(
839 matches!(fx.verify(b), ReceiptVerification::Refused(_)),
840 "flip at {i} accepted"
841 );
842 flips += 1;
843 }
844 result(
845 "S06",
846 "PASS",
847 &format!("{cases} forged/tampered/oversize cases refused with the expected typed error; {flips} byte flips refused"),
848 );
849}
850
851#[test]
852fn s07_self_signed_receipt_known_gap() {
853 let mut fx = Fx::new("s07");
854 let cs = fx.propose(&alice(), "alice-a", &[("src/a.rs", b"fn a2() {}\n")]);
855 let base = fx.evidence_base(cs);
856 // Executor = changeset author. Version 1 has no executor registry.
857 let r = EvidenceReceipt::sign(fx.body(cs, base), &alice()).unwrap();
858 assert_eq!(r.executor_did, did(&alice()));
859 match fx.verify(r.encode().unwrap()) {
860 ReceiptVerification::Current { outcome, .. } => assert_eq!(outcome, Outcome::Pass),
861 other => {
862 panic!("self-signed receipt no longer Current ({other:?}): update D5 and ADR 0004")
863 }
864 }
865 result(
866 "S07",
867 "KNOWN-GAP",
868 "receipt signed by the changeset author's own key verifies Current; executor independence deferred to ADR 0003 E0/E1; Current grants nothing (S12)",
869 );
870}
871
872// ------------------------------------------------------------------------------------------
873// S08, S09: crashes.
874
875/// Child half of S08: claim through the library with `SYNAPSE_COORD_FAULT=before-rename`, so
876/// the process aborts after the tmp record is written and before the rename. A no-op unless
877/// re-executed by `s08_crash_mid_claim`.
878#[test]
879fn s08_child_claim_then_abort() {
880 let Ok(dir) = std::env::var(CHILD_ENV) else {
881 return;
882 };
883 let st = CoordStore::open(PathBuf::from(dir)).with_clock(|| T0);
884 let _ = st.claim(
885 &ws("crasher"),
886 "crasher",
887 ROOT_DIR,
888 "src/b.rs",
889 "edit",
890 Some(600),
891 );
892 // Only reached if the fault point did not fire.
893 std::process::exit(0);
894}
895
896fn rerun_child(
897 test: &str,
898 env: &[(&str, &Path)],
899 extra: &[(&str, &str)],
900) -> std::process::ExitStatus {
901 let mut cmd = Command::new(std::env::current_exe().unwrap());
902 cmd.args(["--exact", test, "--nocapture", "--test-threads=1"]);
903 for (k, v) in env {
904 cmd.env(k, v);
905 }
906 for (k, v) in extra {
907 cmd.env(k, v);
908 }
909 cmd.output().unwrap().status
910}
911
912#[test]
913fn s08_crash_mid_claim() {
914 use std::os::unix::process::ExitStatusExt;
915 let mut fx = Fx::new("s08");
916 let root = fx.dir.join("coord");
917 let st = fx.coord(T0);
918 assert!(matches!(
919 claim(&st, "alice", "src/a.rs", 600),
920 ClaimOutcome::Claimed { .. }
921 ));
922 let rec = root.join("dirs/src.json");
923 let before = fs::read(&rec).unwrap();
924
925 // Torn tmp files from an earlier crash are never read as records.
926 fs::write(
927 root.join("dirs/src.json.tmp4242"),
928 b"{\"locks\":{\"src/a.rs\":{\"hol",
929 )
930 .unwrap();
931 fs::write(root.join("agents/alice.json.tmp4242"), b"garbage").unwrap();
932 let adv = fx.advise("bob", &["src/a.rs"], Some(&st));
933 assert_eq!(adv.coordination, CoordinationStatus::Read);
934 assert_eq!(adv.paths[0].claims.len(), 1);
935
936 // Kill between tmp write and rename (real process abort).
937 let status = rerun_child(
938 "s08_child_claim_then_abort",
939 &[(CHILD_ENV, &root)],
940 &[("SYNAPSE_COORD_FAULT", "before-rename")],
941 );
942 assert_eq!(
943 status.signal(),
944 Some(libc::SIGABRT),
945 "child status {status:?}"
946 );
947 assert_eq!(
948 fs::read(&rec).unwrap(),
949 before,
950 "record changed by an aborted claim"
951 );
952 let tmps = fs::read_dir(root.join("dirs"))
953 .unwrap()
954 .filter_map(|e| e.ok())
955 .filter(|e| e.file_name().to_string_lossy().contains(".tmp"))
956 .count();
957 assert!(tmps >= 2, "aborted claim left no tmp record");
958 // The store stays readable and consistent: alice still holds src/a.rs, the crasher holds
959 // nothing, and src/b.rs can be claimed.
960 let adv = fx.advise("bob", &["src/a.rs", "src/b.rs"], Some(&st));
961 assert_eq!(adv.coordination, CoordinationStatus::Read);
962 assert_eq!(adv.paths[0].claims[0].holder, "alice");
963 assert!(adv.paths[1].claims.is_empty());
964 assert!(matches!(
965 claim(&st, "bob", "src/b.rs", 600),
966 ClaimOutcome::Claimed { .. }
967 ));
968 result(
969 "S08",
970 "PASS",
971 "torn tmp records ignored; child aborted (SIGABRT) between tmp write and rename left the record byte-identical; plane usable afterwards",
972 );
973}
974
975/// Child half of S09: open the service with group commit, arm `CrashMidBatchWrite` (PR #18),
976/// and submit. The store terminates the process mid-write with `FAULT_CRASH_EXIT_CODE`.
977#[test]
978fn s09_child_submit_then_crash() {
979 let Ok(dir) = std::env::var(CHILD_ENV) else {
980 return;
981 };
982 let repo = RepoId::new("aien-spark/synapse").unwrap();
983 let svc = SynapseService::open(
984 PathBuf::from(&dir),
985 repo.clone(),
986 FsyncPolicy::GROUP_COMMIT_DEFAULT,
987 RecoveryPolicy::TruncateTornTail,
988 StoreLimits::default(),
989 )
990 .unwrap();
991 let mut fx = Fx {
992 svc,
993 auth: SigningKey::from_bytes(&[10u8; 32]),
994 repo,
995 nonce: 100,
996 dir: scratch("s09-child"),
997 base_oid: GitOid([1; 20]),
998 base_files: default_files(),
999 };
1000 fx.prime();
1001 fx.svc
1002 .store_mut()
1003 .set_fault_injection(FaultInjection::CrashMidBatchWrite { bytes_written: 64 });
1004 let _ = fx.submit(&bob(), "bob-crash", &[("src/a.rs", b"fn crashed() {}\n")]);
1005 std::process::exit(0);
1006}
1007
1008#[test]
1009fn s09_crash_mid_submit() {
1010 let mut fx = Fx::with("s09", FsyncPolicy::GROUP_COMMIT_DEFAULT, default_files());
1011 let st = fx.coord(T0);
1012 assert!(matches!(
1013 claim(&st, "bob", "src/a.rs", 600),
1014 ClaimOutcome::Claimed { .. }
1015 ));
1016 let first = fx.propose(&alice(), "alice-b", &[("src/b.rs", b"fn b2() {}\n")]);
1017 let svc_dir = fx.dir.join("svc");
1018 // Release the store before the child process opens it.
1019 let placeholder = SynapseService::open(
1020 fx.dir.join("placeholder"),
1021 fx.repo.clone(),
1022 FsyncPolicy::EveryCommit,
1023 RecoveryPolicy::StrictFailClosed,
1024 StoreLimits::default(),
1025 )
1026 .unwrap();
1027 drop(std::mem::replace(&mut fx.svc, placeholder));
1028
1029 let status = rerun_child("s09_child_submit_then_crash", &[(CHILD_ENV, &svc_dir)], &[]);
1030 assert_eq!(
1031 status.code(),
1032 Some(FAULT_CRASH_EXIT_CODE),
1033 "child status {status:?}"
1034 );
1035
1036 // Strict recovery refuses the torn batch; truncating recovery drops it.
1037 let strict = SynapseService::open(
1038 &svc_dir,
1039 fx.repo.clone(),
1040 FsyncPolicy::GROUP_COMMIT_DEFAULT,
1041 RecoveryPolicy::StrictFailClosed,
1042 StoreLimits::default(),
1043 );
1044 let strict_refused = match strict {
1045 Err(e) => {
1046 assert_eq!(e.code, RefusalCode::WalTornFrame);
1047 true
1048 }
1049 Ok(_) => false,
1050 };
1051 assert!(
1052 strict_refused,
1053 "strict reopen must refuse the torn WAL tail (WalTornFrame)"
1054 );
1055 fx.svc = SynapseService::open(
1056 &svc_dir,
1057 fx.repo.clone(),
1058 FsyncPolicy::GROUP_COMMIT_DEFAULT,
1059 RecoveryPolicy::TruncateTornTail,
1060 StoreLimits::default(),
1061 )
1062 .unwrap();
1063 fx.nonce = 1_000;
1064 fx.prime();
1065 let visible: Vec<ChangesetId> = fx
1066 .svc
1067 .store()
1068 .list_changesets(None, None, None)
1069 .unwrap()
1070 .iter()
1071 .map(|c| c.changeset_id)
1072 .collect();
1073 assert_eq!(
1074 visible,
1075 vec![first],
1076 "phantom or lost changeset after crash"
1077 );
1078 // No phantom proposal in the advisory, and bob's claim survives the crash untouched.
1079 let adv = fx.advise("alice", &["src/a.rs"], Some(&st));
1080 assert!(adv.paths[0].overlapping_proposals.is_empty());
1081 assert_eq!(adv.paths[0].claims.len(), 1);
1082 assert_eq!(adv.paths[0].claims[0].holder, "bob");
1083 // Bob resubmits after recovery and everything lines up again.
1084 let cs = fx.propose(&bob(), "bob-retry", &[("src/a.rs", b"fn retried() {}\n")]);
1085 let adv = fx.advise("alice", &["src/a.rs"], Some(&st));
1086 assert_eq!(adv.paths[0].overlapping_proposals[0].changeset_id, cs);
1087 let base = fx.evidence_base(cs);
1088 let r = EvidenceReceipt::sign(fx.body(cs, base), &runner()).unwrap();
1089 assert!(matches!(
1090 fx.verify(r.encode().unwrap()),
1091 ReceiptVerification::Current { .. }
1092 ));
1093 result(
1094 "S09",
1095 "PASS",
1096 &format!(
1097 "child exited {FAULT_CRASH_EXIT_CODE} mid WAL v2 batch write; strict reopen refused torn tail: {strict_refused}; truncating reopen shows only the acknowledged changeset, claim kept, resubmit + receipt Current"
1098 ),
1099 );
1100}
1101
1102// ------------------------------------------------------------------------------------------
1103// S10: mixed agents (crumb.c in a Git worktree, synapse-coord, one store).
1104
1105fn git(dir: &Path, args: &[&str]) -> Vec<u8> {
1106 let out = Command::new("git")
1107 .arg("-C")
1108 .arg(dir)
1109 .args(["-c", "user.name=d5", "-c", "user.email=d5@example.invalid"])
1110 .args(args)
1111 .output()
1112 .unwrap();
1113 assert!(
1114 out.status.success(),
1115 "git {args:?}: {}",
1116 String::from_utf8_lossy(&out.stderr)
1117 );
1118 out.stdout
1119}
1120
1121#[test]
1122fn s10_mixed_agents_crumb_c_and_synapse() {
1123 let Ok(crumb) = std::env::var("CRUMB_C_BIN") else {
1124 result(
1125 "S10",
1126 "UNVERIFIED",
1127 "CRUMB_C_BIN not set (run scripts/qualify-crumb-synapse.sh, which builds the pinned crumb.c)",
1128 );
1129 return;
1130 };
1131 let mut fx = Fx::new("s10");
1132 let rc = fx.dir.join("rc");
1133 fs::create_dir_all(rc.join("src")).unwrap();
1134 fs::write(rc.join(".crumb"), ROOT_CRUMB).unwrap();
1135 fs::write(rc.join("src/a.rs"), b"fn a() {}\n").unwrap();
1136 fs::write(rc.join("src/b.rs"), b"fn b() {}\n").unwrap();
1137 git(&rc, &["init", "-q", "-b", "main"]);
1138 git(&rc, &["add", "-A"]);
1139 git(&rc, &["commit", "-qm", "init"]);
1140 let wa = fx.dir.join("wa");
1141 git(
1142 &rc,
1143 &["worktree", "add", "-q", "-b", "laneC", wa.to_str().unwrap()],
1144 );
1145 fx.base_oid = fx.svc.import_base_tree_from_git_repo(&rc, "HEAD").unwrap();
1146 let store_root = fx.dir.join("store/crumb/v1");
1147 let c = |root: &Path, args: &[&str]| {
1148 Command::new(&crumb)
1149 .current_dir(&wa)
1150 .env("CRUMB_COORD_ROOT", root)
1151 .args(args)
1152 .output()
1153 .unwrap()
1154 };
1155
1156 // crumb.c claims in the Git worktree; Synapse's side is refused and sees the holder.
1157 let out = c(&store_root, &["claim", "c-agent", "src", "a.rs", "C edit"]);
1158 assert!(
1159 out.status.success(),
1160 "{}",
1161 String::from_utf8_lossy(&out.stderr)
1162 );
1163 let st = CoordStore::open(&store_root);
1164 match st
1165 .claim(
1166 &ws("rust-agent"),
1167 "rust-agent",
1168 ROOT_DIR,
1169 "src/a.rs",
1170 "edit",
1171 None,
1172 )
1173 .unwrap()
1174 {
1175 ClaimOutcome::Blocked { holder, .. } => {
1176 assert_eq!(holder.holder, "c-agent");
1177 assert_eq!(holder.branch, "laneC");
1178 }
1179 other => panic!("{other:?}"),
1180 }
1181 let adv = fx.advise("rust-agent", &["src/a.rs"], Some(&st));
1182 assert_eq!(adv.paths[0].claims.len(), 1);
1183 assert_eq!(adv.paths[0].claims[0].holder, "c-agent");
1184 assert_eq!(adv.paths[0].claims[0].branch, "laneC");
1185 // Synapse claims; crumb.c is refused with exit 2.
1186 assert!(matches!(
1187 st.claim(
1188 &ws("rust-agent"),
1189 "rust-agent",
1190 ROOT_DIR,
1191 "src/b.rs",
1192 "edit",
1193 None
1194 )
1195 .unwrap(),
1196 ClaimOutcome::Claimed { .. }
1197 ));
1198 let out = c(
1199 &store_root,
1200 &["claim", "c-agent", "src", "b.rs", "C wants it"],
1201 );
1202 assert_eq!(out.status.code(), Some(2));
1203
1204 // STORE_ID: the Rust mutation created the marker; crumb.c keeps working beside it.
1205 let id = st
1206 .store_id()
1207 .unwrap()
1208 .expect("marker after a Rust mutation");
1209 let expecting = CoordStore::open_expecting(&store_root, id).unwrap();
1210 let adv = fx.advise("crumbless", &["src/a.rs", "src/b.rs"], Some(&expecting));
1211 assert_eq!(adv.coordination, CoordinationStatus::Read);
1212 assert_eq!(adv.paths[1].claims[0].holder, "rust-agent");
1213 let out = c(
1214 &store_root,
1215 &["claim", "c-agent", "src", ".crumb", "C again"],
1216 );
1217 assert!(out.status.success());
1218 // Misconfigured roots are refused by open_expecting: missing marker and another store.
1219 let empty = fx.dir.join("wrong/empty");
1220 assert!(matches!(
1221 CoordStore::open_expecting(&empty, id),
1222 Err(CoordError::StoreIdMissing { .. })
1223 ));
1224 let other = fx.dir.join("wrong/other");
1225 let other_id = CoordStore::open(&other).ensure_store_id().unwrap();
1226 assert_ne!(other_id, id);
1227 match CoordStore::open_expecting(&other, id) {
1228 Err(CoordError::StoreIdMismatch {
1229 expected, found, ..
1230 }) => {
1231 assert_eq!((expected, found), (id, other_id));
1232 }
1233 other => panic!("{other:?}"),
1234 }
1235 // Limit: crumb.c itself does not check STORE_ID, so crumb.c pointed at the wrong root
1236 // still grants a second claim on src/a.rs there (ADR 0004 D2 "not yet done").
1237 let out = c(&other, &["claim", "c-agent2", "src", "a.rs", "split brain"]);
1238 let crumb_c_split = out.status.success();
1239 let _ = StoreId::parse_hex(&id.to_hex()).unwrap();
1240 result(
1241 "S10",
1242 "PASS",
1243 &format!(
1244 "crumb.c (Git worktree) and synapse-coord share one store both ways; advisory shows the crumb.c holder; open_expecting refuses missing and mismatched STORE_ID; limit: crumb.c on a wrong root granted a split claim: {crumb_c_split}"
1245 ),
1246 );
1247}
1248
1249// ------------------------------------------------------------------------------------------
1250// S11: Git round trip of .crumb files (D1, D2, D3) through synapse-git, byte for byte.
1251
1252#[test]
1253fn s11_git_round_trip_crumb_bytes() {
1254 let mut fx = Fx::new("s11");
1255 let repo = fx.dir.join("repo");
1256 for (p, b) in [
1257 (".crumb", FIX_ROOT),
1258 ("d1/.crumb", FIX_D1),
1259 ("d1/x.txt", b"x\n".as_slice()),
1260 ("d2/.crumb", FIX_D2),
1261 ("d3/.crumb", FIX_D3),
1262 ] {
1263 let f = repo.join(p);
1264 fs::create_dir_all(f.parent().unwrap()).unwrap();
1265 fs::write(f, b).unwrap();
1266 }
1267 git(&repo, &["init", "-q", "-b", "main"]);
1268 git(&repo, &["add", "-A"]);
1269 git(&repo, &["commit", "-qm", "crumbs"]);
1270 fx.base_oid = fx
1271 .svc
1272 .import_base_tree_from_git_repo(&repo, "HEAD")
1273 .unwrap();
1274 for (dir, dialect) in [
1275 ("d1", Dialect::Rfc0001Json),
1276 ("d2", Dialect::AtlasJson),
1277 ("d3", Dialect::YamlV1),
1278 ] {
1279 let ctx = fx.context(fx.base(), dir);
1280 assert_eq!(ctx.leaf().dialect(), Some(dialect), "{dir}");
1281 }
1282 // A changeset rewrites the D1 crumb and adds a file next to D2.
1283 let new_d1 = br#"{"schema_version":"1.0.0","name":"d1","purpose":"Rewritten through Synapse.","invariants":["d1 rule v2"]}
1284"#;
1285 let cs = fx.propose(
1286 &alice(),
1287 "alice-crumbs",
1288 &[("d1/.crumb", new_d1), ("d2/note.txt", b"n\n")],
1289 );
1290 let mut index = GitProjectionIndex::new();
1291 let mat =
1292 materialize_changeset_to_git(&mut fx.svc, &mut index, &repo.join(".git"), cs, None, None)
1293 .unwrap();
1294 let commit = mat.commit_oid.to_hex();
1295 let show = |p: &str| git(&repo, &["cat-file", "blob", &format!("{commit}:{p}")]);
1296 assert_eq!(show(".crumb"), FIX_ROOT);
1297 assert_eq!(show("d1/.crumb"), new_d1);
1298 assert_eq!(show("d2/.crumb"), FIX_D2);
1299 assert_eq!(show("d3/.crumb"), FIX_D3);
1300 // The untouched directory (d3) keeps its Git tree OID exactly.
1301 assert_eq!(
1302 git(&repo, &["rev-parse", &format!("{commit}:d3")]),
1303 git(&repo, &["rev-parse", "HEAD:d3"])
1304 );
1305 // Back again: import the materialized commit into a fresh service; every .crumb context
1306 // digest equals the one Synapse computes in the changeset's own tree.
1307 let mut back = Fx::new("s11-back");
1308 back.base_oid = back
1309 .svc
1310 .import_base_tree_from_git_repo(&repo, &commit)
1311 .unwrap();
1312 for dir in [".", "d1", "d2", "d3"] {
1313 let there = fx.context(TreeTarget::Changeset(cs), dir).digest();
1314 let here = back.context(back.base(), dir).digest();
1315 assert_eq!(there, here, "{dir}");
1316 }
1317 result(
1318 "S11",
1319 "PASS",
1320 "Git -> Synapse (D1/D2/D3 dialects recognised) -> changeset -> Git: all four .crumb blobs byte-identical, untouched tree OID kept, re-import gives identical context digests",
1321 );
1322}
1323
1324// ------------------------------------------------------------------------------------------
1325// S12: exit rule. A fully passing run never grants publication.
1326
1327#[test]
1328fn s12_exit_rule_passing_run_is_not_publication() {
1329 let mut fx = Fx::new("s12");
1330 let store = fx.coord(T0);
1331 assert!(matches!(
1332 claim(&store, "alice", "src/a.rs", 600),
1333 ClaimOutcome::Claimed { .. }
1334 ));
1335 let cs = fx.propose(&alice(), "alice-a", &[("src/a.rs", b"fn a2() {}\n")]);
1336 // Alice's own view: coordination read, no foreign claims (her own proposal is listed as
1337 // open, which is expected: the advisory is not author-aware).
1338 let adv = fx.advise("alice", &["src/a.rs"], Some(&store));
1339 assert_eq!(adv.coordination, CoordinationStatus::Read);
1340 assert!(adv.paths[0].claims.is_empty());
1341 let base = fx.evidence_base(cs);
1342 let receipt = EvidenceReceipt::sign(fx.body(cs, base), &runner()).unwrap();
1343 assert!(matches!(
1344 fx.verify(receipt.encode().unwrap()),
1345 ReceiptVerification::Current {
1346 outcome: Outcome::Pass,
1347 ..
1348 }
1349 ));
1350 let bare = fx.dir.join("bare.git");
1351 git(&fx.dir, &["init", "-q", "--bare", bare.to_str().unwrap()]);
1352 let mut index = GitProjectionIndex::new();
1353 let mat = materialize_changeset_to_git(&mut fx.svc, &mut index, &bare, cs, None, None).unwrap();
1354
1355 // Gate 1: Capability::Publish (both GitHub PR projection and human branch fast-forward).
1356 // Every other capability, plus a Current Pass receipt in hand, is refused, and refs/heads/main
1357 // is never created or moved. (Neither gate takes a receipt as input: there is no field for one.)
1358 let pr = |n| GitHubPrProjectionRequest {
1359 pr_number: n,
1360 changeset_id: cs,
1361 pr_branch_ref: "refs/synapse/agent-head/alice".into(),
1362 title: "d5".into(),
1363 github_merged: false,
1364 };
1365 let adv_branch = || HumanBranchAdvanceRequest {
1366 branch: "main".into(),
1367 new_commit_oid: mat.commit_oid,
1368 };
1369 for signer in [alice(), runner()] {
1370 let req = fx.sign_as(
1371 &signer,
1372 vec![
1373 Capability::Read,
1374 Capability::Propose,
1375 Capability::Evaluate,
1376 Capability::Review,
1377 ],
1378 Capability::Publish,
1379 pr(1),
1380 );
1381 let now = fx.now();
1382 let err = project_github_pull_request(&mut fx.svc, &index, &req, now).unwrap_err();
1383 assert_eq!(err.code, RefusalCode::AuthCapabilityDenied);
1384
1385 let branch_req = fx.sign_as(
1386 &signer,
1387 vec![
1388 Capability::Read,
1389 Capability::Propose,
1390 Capability::Evaluate,
1391 Capability::Review,
1392 ],
1393 Capability::Publish,
1394 adv_branch(),
1395 );
1396 let now = fx.now();
1397 let err =
1398 advance_human_branch_fast_forward(&mut fx.svc, &bare, &branch_req, now).unwrap_err();
1399 assert_eq!(err.code, RefusalCode::AuthCapabilityDenied);
1400 assert!(
1401 !bare.join("refs/heads/main").exists(),
1402 "refs/heads/main must not be created or moved without Publish"
1403 );
1404 }
1405
1406 // Gate 2: Radicle canonical promotion needs the delegate quorum. Neither the author nor
1407 // the receipt's executor is a delegate; a merged GitHub PR does not help.
1408 let doc = RadicleIdentityDoc {
1409 delegates: vec![did(&delegate())],
1410 payload: RadiclePayloadMap {
1411 project: RadicleProjectPayload {
1412 default_branch: "main".into(),
1413 description: String::new(),
1414 name: "synapse".into(),
1415 },
1416 },
1417 threshold: 1,
1418 };
1419 let candidate = PromotionCandidate {
1420 repo_id: fx.repo.clone(),
1421 changeset_id: Some(cs),
1422 proposal_base_git_oid: fx.base_oid,
1423 candidate_git_oid: mat.commit_oid,
1424 github_pr_merged: true,
1425 verified_at_ms: 5,
1426 };
1427 let refs: BTreeMap<String, GitOid> = [("refs/heads/main".to_string(), mat.commit_oid)].into();
1428 let mut engine = CanonicalPromotionEngine::new(doc.clone(), None, None).unwrap();
1429 let e = engine.verify_and_promote(&candidate, &[]).unwrap_err();
1430 assert_eq!(e.code, RefusalCode::RadicleQuorumInsufficient);
1431 for k in [runner(), alice()] {
1432 let e = engine
1433 .verify_and_promote(&candidate, &[DelegateSigrefs::sign_refs(&k, &refs)])
1434 .unwrap_err();
1435 assert_eq!(e.code, RefusalCode::RadicleIdentityInvalid);
1436 }
1437 assert!(engine.current_canonical().is_none());
1438 // The Radicle engine above is standalone: it never writes the Synapse store, so the
1439 // store's canonical head is not evidence here and is deliberately not asserted.
1440
1441 // Positive controls: the gates open only for their own credentials.
1442 let req = fx.sign_as(
1443 &alice(),
1444 vec![Capability::Publish],
1445 Capability::Publish,
1446 pr(2),
1447 );
1448 let now = fx.now();
1449 let proj = project_github_pull_request(&mut fx.svc, &index, &req, now).unwrap();
1450 assert_eq!(proj.head_git_oid, mat.commit_oid);
1451 let branch_req = fx.sign_as(
1452 &alice(),
1453 vec![Capability::Publish],
1454 Capability::Publish,
1455 adv_branch(),
1456 );
1457 let now = fx.now();
1458 advance_human_branch_fast_forward(&mut fx.svc, &bare, &branch_req, now).unwrap();
1459 assert_eq!(
1460 fs::read_to_string(bare.join("refs/heads/main"))
1461 .unwrap()
1462 .trim(),
1463 mat.commit_oid.to_hex()
1464 );
1465 let head = engine
1466 .verify_and_promote(
1467 &candidate,
1468 &[DelegateSigrefs::sign_refs(&delegate(), &refs)],
1469 )
1470 .unwrap();
1471 assert_eq!(head.canonical_git_oid, mat.commit_oid);
1472 result(
1473 "S12",
1474 "PASS",
1475 "advisory read (no foreign claims) + Current Pass receipt: GitHub PR projection and advance_human_branch_fast_forward refused without Publish (AuthCapabilityDenied, author and runner; refs/heads/main untouched); Radicle promotion refused without delegate quorum (none / runner / author sigrefs); all open only for a Publish grant / delegate sigrefs. AEGIS not integrated (separate repo)",
1476 );
1477}