1use super::{Error, Result, identity_of_document};
9use crate::context::Context;
10use crate::in_use::{self, InUse};
11use crate::permit::Permit;
12use crate::provider::{self, LoginKind, Provider, ProviderId};
13use crate::state::{Account, Key, Park, ParkKind, State};
14use crate::{atomic, home, park, state, store};
15use serde_json::Value;
16use std::path::PathBuf;
17
18#[derive(serde::Serialize, serde::Deserialize)]
19pub(super) struct Journal {
20 #[serde(default = "claude")]
26 pub(super) provider: ProviderId,
27 pub(super) started_at: i64,
28 pub(super) from_label: String,
29 #[serde(rename = "from_uuid")]
31 pub(super) from_id: String,
32 pub(super) to_label: String,
33 #[serde(rename = "to_uuid")]
34 pub(super) to_id: String,
35 pub(super) park_service: String,
36 pub(super) incoming_service: String,
38 #[serde(default)]
44 pub(super) from_fingerprint: String,
45 #[serde(default)]
46 pub(super) to_fingerprint: String,
47 #[serde(default)]
54 pub(super) slot: Option<String>,
55}
56
57#[derive(Debug)]
59pub struct Recovered {
60 pub from: String,
61 pub to: String,
62 pub finished: bool,
63}
64
65impl Recovered {
66 pub fn code(&self) -> &'static str {
67 if self.finished {
68 "interrupted_switch_finished"
69 } else {
70 "interrupted_switch_undone"
71 }
72 }
73}
74
75impl std::fmt::Display for Recovered {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 let from = if self.from.is_empty() {
78 String::new()
79 } else {
80 format!(" from `{}`", self.from)
81 };
82 write!(
83 f,
84 "an earlier switch{from} to `{}` was interrupted; {}",
85 self.to,
86 if self.finished {
87 "it had in fact finished, and Pitboard has recorded that"
88 } else {
89 "it had not finished, and nothing was lost"
90 }
91 )
92 }
93}
94
95fn claude() -> ProviderId {
96 ProviderId::Claude
97}
98
99impl Journal {
100 fn from(&self) -> Key {
101 Key::new(self.provider, self.from_label.clone())
102 }
103
104 fn to(&self) -> Key {
105 Key::new(self.provider, self.to_label.clone())
106 }
107
108 fn replaces(&self) -> bool {
110 self.from_id.is_empty()
111 }
112}
113
114fn journal_path(ctx: &Context) -> PathBuf {
115 home::dir(ctx).join("journal.json")
116}
117
118pub(super) fn write_journal(ctx: &Context, permit: Permit, entry: &Journal) -> Result<()> {
121 let path = journal_path(ctx);
122 let fail = |source| Error::RecoveryFailed {
123 path: path.clone(),
124 source,
125 };
126 home::ensure(ctx, permit).map_err(fail)?;
127 let body = serde_json::to_string(entry).expect("a journal entry is always serialisable");
128 atomic::write(permit, &path, body.as_bytes(), atomic::Perms::Secret).map_err(fail)
129}
130
131pub(crate) fn pending(ctx: &Context) -> bool {
133 journal_path(ctx).exists()
134}
135
136pub(crate) fn interrupted_tool(ctx: &Context) -> Option<ProviderId> {
138 let raw = std::fs::read_to_string(journal_path(ctx)).ok()?;
139 serde_json::from_str::<Journal>(&raw)
140 .ok()
141 .map(|journal| journal.provider)
142}
143
144pub(super) fn clear_journal(ctx: &Context, permit: Permit) {
146 let _ = crate::host::fs::remove_file(permit, &journal_path(ctx));
147}
148
149struct Found {
150 parked: Option<Option<Value>>,
152 live_owner: Option<String>,
154}
155
156#[derive(Default, Debug, PartialEq)]
157struct Repair {
158 hold: Option<(String, Park)>,
161 drop: bool,
164 landed: bool,
166}
167
168struct Seen {
171 named: Option<String>,
173 login: String,
176}
177
178fn repair_for(
180 state: &State,
181 tool: &'static dyn Provider,
182 journal: &Journal,
183 found: &Found,
184) -> Option<Repair> {
185 let parked = found.parked.as_ref()?;
186 let owner = found.live_owner.as_deref()?;
187 let mut repair = Repair {
188 landed: owner == journal.to_id,
189 ..Repair::default()
190 };
191 if owner == journal.from_id {
192 repair.drop = parked.is_some();
193 } else if let Some(oauth) = parked
194 && !state.references(&journal.park_service)
195 {
196 repair.hold = Some((
197 journal.from_id.clone(),
198 park::describe(tool, &journal.park_service, journal.started_at, oauth),
199 ));
200 }
201 Some(repair)
202}
203
204fn apply(state: &mut State, journal: &Journal, repair: Repair, seen: Seen, at: i64) {
207 if repair.drop {
208 state.discard(&journal.park_service, ParkKind::Vault);
209 }
210 if let Some((id, park)) = repair.hold {
211 match state.by_id(journal.provider, &id).map(Account::key) {
212 Some(key) => state.park(&key, park),
213 None => state.release(&park.service),
216 }
217 }
218 if !repair.landed {
219 return;
220 }
221 match state
222 .by_id(journal.provider, &journal.to_id)
223 .map(Account::owner)
224 {
225 Some(owner) => {
226 let installed = InUse {
227 owner: Some(owner),
228 login: seen.login,
229 known_at: at,
230 named: seen.named,
231 };
232 state.identified(journal.provider, installed, at);
233 state.discard(&journal.incoming_service, ParkKind::Vault);
234 }
235 None => {
239 state.in_use.remove(journal.provider.code());
240 }
241 }
242}
243
244fn read_park(ctx: &Context, service: &str) -> Option<Option<Value>> {
245 match store::vault_read(ctx, service) {
246 Ok(raw) => Some(raw.and_then(|r| serde_json::from_str(&r).ok())),
247 Err(_) => None,
248 }
249}
250
251enum Owner {
253 Is(String),
255 Unknown(String),
257 Unasked(Value),
259 Unfinished(String),
262}
263
264fn live_owner(ctx: &Context, tool: &'static dyn Provider, journal: &Journal) -> (Owner, String) {
270 match tool.read_live(ctx) {
271 Err(e) => match left_unfinished(ctx, tool) {
272 Some(why) => (Owner::Unfinished(why), String::new()),
273 None => (Owner::Unknown(e.to_string()), String::new()),
274 },
275 Ok(None) if journal.replaces() => (Owner::Is(String::new()), String::new()),
277 Ok(None) => (Owner::Unknown("nothing is signed in".into()), String::new()),
278 Ok(Some(live)) => {
279 let login = tool.fingerprint(&live.raw);
280 let owner = match live_owner_by_fingerprint(journal, &login) {
281 Some(id) => Owner::Is(id),
282 None => Owner::Unasked(live.raw),
283 };
284 (owner, login)
285 }
286 }
287}
288
289fn left_unfinished(ctx: &Context, tool: &'static dyn Provider) -> Option<String> {
292 let live = tool.live(ctx).ok()?;
293 match store::read_raw(&live.chain, &live.service) {
294 Err(store::Error::Unfinished(why)) => Some(why),
295 _ => None,
296 }
297}
298
299fn not_finished(state: &State, journal: &Journal, why: &str, detail: impl ToString) -> Error {
300 Error::RecoveryUnfinished {
301 tool: journal.provider,
302 from: state.typed(&journal.from()),
303 to: state.typed(&journal.to()),
304 detail: format!("{why}; {}", detail.to_string()),
305 }
306}
307
308fn finishing(
312 ctx: &Context,
313 state: &State,
314 tool: &'static dyn Provider,
315 journal: &Journal,
316 why: &str,
317) -> Result<String> {
318 let Some(Some(incoming)) = read_park(ctx, &journal.incoming_service) else {
319 return Err(not_finished(
320 state,
321 journal,
322 why,
323 "its parked login could not be read",
324 ));
325 };
326 tool.splice(&Value::Object(serde_json::Map::new()), &incoming)
327 .map(|next| super::to_body(&next))
328 .map_err(|e| not_finished(state, journal, why, e))
329}
330
331fn finish(ctx: &Context, permit: Permit, tool: &'static dyn Provider, body: &str) -> Result<()> {
333 let live = tool.live(ctx).map_err(|e| super::shape(tool.id(), e))?;
334 let _guard = super::write_lock(ctx, permit, tool)?;
335 Ok(store::write_raw(&live.chain, permit, &live.service, body)?)
336}
337
338fn ask(
341 ctx: &Context,
342 state: &State,
343 tool: &'static dyn Provider,
344 owner: Owner,
345) -> std::result::Result<String, String> {
346 match owner {
347 Owner::Is(id) => Ok(id),
348 Owner::Unknown(why) | Owner::Unfinished(why) => Err(why),
349 Owner::Unasked(live) => identity_of_document(ctx, tool, &live)
350 .map(|identity| state.id_for(tool.id(), &identity))
351 .map_err(|e| e.to_string()),
352 }
353}
354
355fn live_owner_by_fingerprint(journal: &Journal, found: &str) -> Option<String> {
368 if journal.replaces() && found.is_empty() {
371 return Some(journal.from_id.clone());
372 }
373 if journal.from_fingerprint.is_empty() || journal.to_fingerprint.is_empty() {
374 return None;
375 }
376 if journal.from_fingerprint == journal.to_fingerprint {
377 return None;
378 }
379 if found.is_empty() {
380 return None;
381 }
382 if found == journal.to_fingerprint {
383 Some(journal.to_id.clone())
384 } else if found == journal.from_fingerprint {
385 Some(journal.from_id.clone())
386 } else {
387 None
388 }
389}
390
391#[derive(Debug)]
393pub struct Abandoned {
394 pub from: String,
395 pub to: String,
396 pub kept: usize,
398}
399
400pub(super) fn abandon(
412 ctx: &Context,
413 permit: Permit,
414 state: &mut State,
415) -> Result<Option<Abandoned>> {
416 let path = journal_path(ctx);
417 let raw = match std::fs::read_to_string(&path) {
418 Ok(r) => r,
419 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
420 Err(source) => return Err(Error::RecoveryFailed { path, source }),
421 };
422 let journal =
423 serde_json::from_str::<Journal>(&raw).map_err(|source| Error::RecoveryRecordCorrupt {
424 path: path.clone(),
425 source,
426 })?;
427 let tool = match provider::of(journal.provider) {
428 LoginKind::Document(tool) => tool,
429 LoginKind::Folder(_) => {
430 return Err(Error::RecoveryRecordCorrupt {
431 path,
432 source: serde::de::Error::custom(
433 "it names a tool whose login no switch records here",
434 ),
435 });
436 }
437 };
438
439 let mut kept = 0;
442 if let Some(Some(document)) = read_park(ctx, &journal.park_service)
443 && park::is_live_twin(ctx, tool, &document)
444 {
445 state.discard(&journal.park_service, ParkKind::Vault);
446 } else if let Some(Some(document)) = read_park(ctx, &journal.park_service)
447 && let Some(key) = state
448 .by_id(journal.provider, &journal.from_id)
449 .map(Account::key)
450 {
451 state.park(
452 &key,
453 park::describe(tool, &journal.park_service, ctx.now(), &document),
454 );
455 kept += 1;
456 }
457 let incoming = read_park(ctx, &journal.incoming_service).flatten();
458 if incoming.is_some_and(|document| park::is_live_twin(ctx, tool, &document)) {
459 state.discard(&journal.incoming_service, ParkKind::Vault);
460 } else if state
461 .by_id(journal.provider, &journal.to_id)
462 .and_then(|a| a.parked.as_ref())
463 .is_some()
464 {
465 kept += 1;
466 }
467 state::save(ctx, permit, state)?;
468 clear_journal(ctx, permit);
469 Ok(Some(Abandoned {
470 from: state.typed(&journal.from()),
471 to: state.typed(&journal.to()),
472 kept,
473 }))
474}
475
476struct Waiting {
479 tool: &'static dyn Provider,
480 journal: Journal,
481 parked: Option<Option<Value>>,
483 owner: Owner,
484 seen: Seen,
485}
486
487fn read(ctx: &Context, state: &State) -> Result<Option<Waiting>> {
490 let path = journal_path(ctx);
491 let raw = match std::fs::read_to_string(&path) {
492 Ok(r) => r,
493 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
494 Err(source) => return Err(Error::RecoveryFailed { path, source }),
495 };
496 let journal =
499 serde_json::from_str::<Journal>(&raw).map_err(|source| Error::RecoveryRecordCorrupt {
500 path: path.clone(),
501 source,
502 })?;
503 let tool = match provider::of(journal.provider) {
504 LoginKind::Document(tool) => tool,
505 LoginKind::Folder(_) => {
506 return Err(Error::RecoveryRecordCorrupt {
507 path,
508 source: serde::de::Error::custom(
509 "it names a tool whose login no switch records here",
510 ),
511 });
512 }
513 };
514
515 if let Some(slot) = &journal.slot {
516 let here = tool.slot(ctx);
517 if *slot != here {
518 return Err(Error::RecoveryElsewhere {
519 tool: journal.provider,
520 from: state.typed(&journal.from()),
521 to: state.typed(&journal.to()),
522 slot: slot.clone(),
523 });
524 }
525 }
526
527 let named = in_use::named(ctx, journal.provider);
528 let (owner, login) = live_owner(ctx, tool, &journal);
529 let parked = if journal.park_service.is_empty() {
531 Some(None)
532 } else {
533 read_park(ctx, &journal.park_service)
534 };
535 Ok(Some(Waiting {
536 tool,
537 parked,
538 journal,
539 owner,
540 seen: Seen { named, login },
541 }))
542}
543
544fn decide(
547 ctx: &Context,
548 state: &State,
549 tool: &'static dyn Provider,
550 journal: &Journal,
551 parked: Option<Option<Value>>,
552 owner: std::result::Result<String, String>,
553) -> Result<Repair> {
554 let found = Found {
555 parked,
556 live_owner: owner.as_ref().ok().cloned(),
557 };
558 repair_for(state, tool, journal, &found).ok_or_else(|| Error::RecoveryUndetermined {
559 tool: journal.provider,
560 from: state.typed(&journal.from()),
561 to: state.typed(&journal.to()),
562 detail: owner
563 .err()
564 .unwrap_or_else(|| "its parked login could not be read".into()),
565 spelling: crate::words::spelled(ctx, journal.provider),
566 })
567}
568
569pub(super) fn reconcile(
570 ctx: &Context,
571 permit: Permit,
572 state: &mut State,
573) -> Result<Option<Recovered>> {
574 let Some(mut waiting) = read(ctx, state)? else {
575 return Ok(None);
576 };
577 if let Owner::Unfinished(why) = &waiting.owner {
578 let (tool, journal) = (waiting.tool, &waiting.journal);
579 let body = finishing(ctx, state, tool, journal, why)?;
580 finish(ctx, permit, tool, &body).map_err(|e| not_finished(state, journal, why, e))?;
581 (waiting.owner, waiting.seen.login) = live_owner(ctx, tool, journal);
582 }
583 let Waiting {
584 tool,
585 journal,
586 parked,
587 owner,
588 seen,
589 } = waiting;
590 let owner = ask(ctx, state, tool, owner);
591 let repair = decide(ctx, state, tool, &journal, parked, owner)?;
592 let finished = repair.landed;
593 apply(state, &journal, repair, seen, ctx.now());
594 state::save(ctx, permit, state)?;
595 clear_journal(ctx, permit);
596
597 Ok(Some(Recovered {
598 from: state.typed(&journal.from()),
599 to: state.typed(&journal.to()),
600 finished,
601 }))
602}
603
604#[derive(Clone, Copy, Debug, PartialEq, Eq)]
610pub(crate) enum Asking {
611 Service,
612 Nobody,
613}
614
615pub(super) fn refusal(ctx: &Context, state: &State, asking: Asking) -> Option<Error> {
623 let Waiting {
624 tool,
625 journal,
626 parked,
627 owner,
628 ..
629 } = read(ctx, state).ok()??;
630 if let Owner::Unfinished(why) = &owner {
631 return finishing(ctx, state, tool, &journal, why).err();
632 }
633 if asking == Asking::Nobody
634 && matches!(owner, Owner::Unasked(_))
635 && !tool.identifies_by_itself()
636 {
637 return None;
638 }
639 let owner = ask(ctx, state, tool, owner);
640 decide(ctx, state, tool, &journal, parked, owner).err()
641}
642
643#[cfg(test)]
644mod tests {
645 use super::*;
646
647 const NOW: i64 = 1_700_000_100;
648 const PARK: &str = "pitboard-park-from-uuid-1700000000000";
649 const INCOMING: &str = "pitboard-park-to-uuid-1690000000000";
650
651 #[test]
654 fn a_record_0_8_0_wrote_names_each_side_by_its_id() {
655 let written: Journal = serde_json::from_value(serde_json::json!({
656 "provider": "claude",
657 "started_at": 1_700_000_000,
658 "from_label": "from",
659 "from_uuid": "from-uuid",
660 "to_label": "to",
661 "to_uuid": "to-uuid",
662 "park_service": PARK,
663 "incoming_service": INCOMING,
664 "from_fingerprint": "f",
665 "to_fingerprint": "t",
666 "slot": "Claude Code-credentials"
667 }))
668 .expect("still read");
669 assert_eq!(
670 (written.from_id.as_str(), written.to_id.as_str()),
671 ("from-uuid", "to-uuid")
672 );
673 }
674
675 fn journal() -> Journal {
676 Journal {
677 provider: ProviderId::Claude,
678 started_at: 1_700_000_000,
679 from_label: "from".into(),
680 from_id: "from-uuid".into(),
681 to_label: "to".into(),
682 to_id: "to-uuid".into(),
683 park_service: PARK.into(),
684 incoming_service: INCOMING.into(),
685 from_fingerprint: "ffffffffffffffff".into(),
686 to_fingerprint: "0000000000000000".into(),
687 slot: None,
688 }
689 }
690
691 #[test]
694 fn a_record_from_before_the_fingerprints_falls_back_to_asking() {
695 let mut j = journal();
696 j.from_fingerprint = String::new();
697 j.to_fingerprint = String::new();
698 assert_eq!(live_owner_by_fingerprint(&j, &fingerprint("refresh")), None);
699 }
700
701 #[test]
704 fn identical_fingerprints_settle_nothing() {
705 let mut j = journal();
706 j.from_fingerprint = fingerprint("refresh");
707 j.to_fingerprint = j.from_fingerprint.clone();
708 assert_eq!(live_owner_by_fingerprint(&j, &fingerprint("refresh")), None);
709 }
710
711 fn fingerprint(refresh: &str) -> String {
713 let live =
714 serde_json::json!({"claudeAiOauth": {"refreshToken": refresh, "accessToken": "a"}});
715 provider::document(ProviderId::Claude).fingerprint(&live)
716 }
717
718 fn seen(login: &str) -> Seen {
721 Seen {
722 named: None,
723 login: login.into(),
724 }
725 }
726
727 fn identified_from(s: &mut State) {
730 let from = InUse {
731 owner: Some(account("from", None).owner()),
732 login: journal().from_fingerprint,
733 known_at: NOW - 60,
734 named: None,
735 };
736 s.identified(ProviderId::Claude, from, NOW - 60);
737 }
738
739 fn account(label: &str, parked: Option<&str>) -> Account {
740 Account {
741 last_used_at: None,
742 replaced_at: None,
743 plan: None,
744 label: label.into(),
745 id: format!("{label}-uuid"),
746 account_uuid: format!("{label}-uuid"),
747 email: format!("{label}@example.com"),
748 detail: state::Detail::Claude {
749 organization_uuid: format!("{label}-org"),
750 oauth_account: serde_json::json!({}),
751 },
752 parked: parked.map(|s| Park {
753 service: s.into(),
754 parked_at: 1_699_000_000,
755 kind: ParkKind::Vault,
756 login: "f".into(),
757 access_expires_at: None,
758 refresh_expires_at: None,
759 session_expires_at: None,
760 }),
761 }
762 }
763
764 fn before() -> State {
766 State {
767 accounts: vec![account("from", None), account("to", Some(INCOMING))],
768 ..State::default()
769 }
770 }
771
772 fn written() -> Option<Option<Value>> {
773 Some(Some(
774 serde_json::json!({"refreshToken": "outgoing", "accessToken": "a"}),
775 ))
776 }
777
778 fn found(parked: Option<Option<Value>>, owner: Option<&str>) -> Found {
779 Found {
780 parked,
781 live_owner: owner.map(str::to_owned),
782 }
783 }
784
785 #[test]
787 fn nothing_parked_and_nothing_installed_changes_nothing() {
788 let repair = repair_for(
789 &before(),
790 provider::document(ProviderId::Claude),
791 &journal(),
792 &found(Some(None), Some("from-uuid")),
793 );
794 assert_eq!(repair, Some(Repair::default()));
795 }
796
797 #[test]
800 fn a_park_of_a_login_still_signed_in_is_dropped_not_kept() {
801 for s in [before(), {
802 let mut recorded = before();
803 recorded.park(
804 &Key::new(ProviderId::Claude, "from"),
805 account("x", Some(PARK)).parked.unwrap(),
806 );
807 recorded
808 }] {
809 let repair = repair_for(
810 &s,
811 provider::document(ProviderId::Claude),
812 &journal(),
813 &found(written(), Some("from-uuid")),
814 )
815 .unwrap();
816 assert!(repair.drop && repair.hold.is_none() && !repair.landed);
817
818 let mut applied = s;
819 apply(
820 &mut applied,
821 &journal(),
822 repair,
823 seen(&journal().from_fingerprint),
824 NOW,
825 );
826 assert!(!applied.references(PARK));
827 assert!(applied.discarded.iter().any(|d| d.service == PARK));
828 }
829 }
830
831 #[test]
834 fn a_landed_switch_holds_the_outgoing_login_and_consumes_the_incoming_one() {
835 let mut s = before();
836 identified_from(&mut s);
837 let repair = repair_for(
838 &s,
839 provider::document(ProviderId::Claude),
840 &journal(),
841 &found(written(), Some("to-uuid")),
842 )
843 .unwrap();
844 let (uuid, park) = repair.hold.clone().expect("the orphan must be recovered");
845 assert_eq!(uuid, "from-uuid", "held by account id, never by a label");
846 assert_eq!(park.service, PARK);
847 assert!(repair.landed);
848
849 let rotated = fingerprint("rotated-since");
850 apply(&mut s, &journal(), repair, seen(&rotated), NOW);
851 assert_eq!(
852 s.account_in_use(ProviderId::Claude)
853 .map(|a| a.label.as_str()),
854 Some("to")
855 );
856 assert_eq!(
857 s.in_use(ProviderId::Claude)
858 .map(|r| (r.login.as_str(), r.known_at)),
859 Some((rotated.as_str(), NOW)),
860 "the login the store holds, which Claude Code may have rotated since the install"
861 );
862 let from = s.get(&Key::new(ProviderId::Claude, "from")).unwrap();
863 assert_eq!(from.parked.as_ref().unwrap().service, PARK);
864 assert_eq!(
865 from.replaced_at, None,
866 "its login is parked, so nothing of it was lost"
867 );
868 assert!(
869 s.get(&Key::new(ProviderId::Claude, "to"))
870 .unwrap()
871 .parked
872 .is_none(),
873 "the copy now live must never be offered again"
874 );
875 assert!(s.discarded.iter().any(|d| d.service == INCOMING));
876 }
877
878 #[test]
881 fn a_third_account_signed_in_since_keeps_both_parks() {
882 let mut s = before();
883 let repair = repair_for(
884 &s,
885 provider::document(ProviderId::Claude),
886 &journal(),
887 &found(written(), Some("other-uuid")),
888 )
889 .unwrap();
890 apply(&mut s, &journal(), repair, seen(&fingerprint("other")), NOW);
891 assert!(s.references(PARK) && s.references(INCOMING));
892 assert!(s.discarded.is_empty());
893 }
894
895 #[test]
896 fn an_already_recorded_park_is_not_held_twice() {
897 let mut s = before();
898 s.park(
899 &Key::new(ProviderId::Claude, "from"),
900 account("x", Some(PARK)).parked.unwrap(),
901 );
902 let repair = repair_for(
903 &s,
904 provider::document(ProviderId::Claude),
905 &journal(),
906 &found(written(), Some("to-uuid")),
907 )
908 .unwrap();
909 assert_eq!(repair.hold, None);
910 }
911
912 #[test]
913 fn an_unknown_outcome_changes_nothing_and_keeps_the_record() {
914 for unknown in [found(written(), None), found(None, Some("to-uuid"))] {
915 assert_eq!(
916 repair_for(
917 &before(),
918 provider::document(ProviderId::Claude),
919 &journal(),
920 &unknown
921 ),
922 None,
923 "could-not-tell must never be read as nothing-there"
924 );
925 }
926 }
927
928 #[test]
929 fn a_park_whose_account_was_forgotten_is_not_filed_under_another() {
930 let mut s = State {
931 accounts: vec![account("other", None)],
932 ..State::default()
933 };
934 identified_from(&mut s);
935 let repair = repair_for(
936 &s,
937 provider::document(ProviderId::Claude),
938 &journal(),
939 &found(written(), Some("to-uuid")),
940 )
941 .unwrap();
942 apply(
943 &mut s,
944 &journal(),
945 repair,
946 seen(&journal().to_fingerprint),
947 NOW,
948 );
949 assert!(
950 !s.references(PARK),
951 "a park must never be filed under whatever account happens to hold a label"
952 );
953 assert_eq!(
954 s.in_use(ProviderId::Claude),
955 None,
956 "the store no longer holds `from`'s login, and nobody here says whose it holds"
957 );
958 }
959
960 #[test]
964 fn a_label_given_to_another_account_since_is_not_the_destination() {
965 const THEIRS: &str = "pitboard-park-someone-uuid-1695000000000";
966 let someone = Account {
967 id: "someone-uuid".into(),
968 account_uuid: "someone-uuid".into(),
969 ..account("to", Some(THEIRS))
970 };
971 let mut s = State {
972 accounts: vec![account("from", None), someone],
973 ..State::default()
974 };
975 identified_from(&mut s);
976 let repair = repair_for(
977 &s,
978 provider::document(ProviderId::Claude),
979 &journal(),
980 &found(written(), Some("to-uuid")),
981 )
982 .unwrap();
983 apply(
984 &mut s,
985 &journal(),
986 repair,
987 seen(&journal().to_fingerprint),
988 NOW,
989 );
990
991 assert_eq!(
992 s.in_use(ProviderId::Claude),
993 None,
994 "the login installed is not the account that holds the label now"
995 );
996 let to = s.get(&Key::new(ProviderId::Claude, "to")).unwrap();
997 assert_eq!(to.last_used_at, None, "never in use");
998 assert_eq!(to.parked.as_ref().map(|p| p.service.as_str()), Some(THEIRS));
999 assert!(
1000 !s.discarded.iter().any(|d| d.service == INCOMING),
1001 "the destination's park is no account's here to consume"
1002 );
1003 }
1004}