1use std::fmt;
23use std::path::Path;
24
25use chrono::Utc;
26use serde::{Deserialize, Serialize};
27use serde_json::Value;
28
29use super::auth::Session;
30use super::config::HiveConfig;
31use super::consent::{self, Broker, ConsentError, Kind, Trust};
32use super::identity_v2;
33use super::state::MATCH_FILE;
34use super::vault::{VaultRecord, identity_digest, resolve_request};
35use super::{HiveError, HiveStore};
36use lean_ctx_protocol::hive::vault::{VaultRefV1, VaultV1};
37
38pub const MATCH_REQUEST_SCHEMA: &str = "leanctx.hive.vault-match-request/v1";
39pub const MATCH_SCHEMA: &str = "leanctx.hive.vault-match/v1";
40const REPROBE_SECONDS: i64 = 24 * 60 * 60;
42pub const NEW_VAULT_WS: &str = "new";
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum MapError {
48 Hive(HiveError),
49 Consent(ConsentError),
51}
52
53impl fmt::Display for MapError {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 match self {
56 Self::Hive(error) => error.fmt(f),
57 Self::Consent(error) => write!(f, "{}: {error}", error.code()),
58 }
59 }
60}
61
62impl From<HiveError> for MapError {
63 fn from(error: HiveError) -> Self {
64 Self::Hive(error)
65 }
66}
67
68impl From<ConsentError> for MapError {
69 fn from(error: ConsentError) -> Self {
70 Self::Consent(error)
71 }
72}
73
74impl From<MapError> for HiveError {
75 fn from(error: MapError) -> Self {
76 match error {
77 MapError::Hive(error) => error,
78 MapError::Consent(error) => error.into(),
79 }
80 }
81}
82
83#[derive(Serialize)]
84struct MatchCandidate {
85 kind: &'static str,
86 digest: String,
87}
88
89#[derive(Serialize)]
92struct MatchRequest<'a> {
93 schema: &'static str,
94 org_salt_id: &'a str,
95 candidates: &'a [MatchCandidate],
96}
97
98fn match_candidates(root: &Path, salt: &[u8]) -> Vec<MatchCandidate> {
101 salted(&identity_v2::match_candidates(root), salt)
102}
103
104fn salted(candidates: &[identity_v2::Candidate], salt: &[u8]) -> Vec<MatchCandidate> {
105 candidates
106 .iter()
107 .map(|c| MatchCandidate {
108 kind: c.kind.as_str(),
109 digest: identity_digest(salt, &c.stable),
110 })
111 .collect()
112}
113
114#[derive(Debug, Clone, Deserialize)]
117pub struct MatchAnswer {
118 pub schema: String,
119 #[serde(rename = "match")]
120 pub outcome: String,
121 #[serde(default)]
122 pub vault: Option<VaultV1>,
123 #[serde(default)]
124 pub suggestion: Option<VaultRefV1>,
125 #[serde(default)]
126 pub can_create: bool,
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum Step {
132 Mapped(VaultV1),
134 Suggested(VaultRefV1),
136 Create,
138 NoVault,
140}
141
142pub fn step_from_answer(answer: MatchAnswer) -> Result<Step, HiveError> {
144 let bad = |why: &str| HiveError::Protocol(format!("vault match: {why}"));
145 if answer.schema != MATCH_SCHEMA {
146 return Err(bad("unknown schema"));
147 }
148 match answer.outcome.as_str() {
149 "bound" => {
150 let vault = answer.vault.ok_or_else(|| bad("bound without a vault"))?;
151 vault.validate().map_err(|e| bad(&e.to_string()))?;
152 Ok(Step::Mapped(vault))
153 }
154 "suggested" => {
155 let vault = answer
156 .suggestion
157 .ok_or_else(|| bad("suggested without a suggestion"))?;
158 vault.validate().map_err(|e| bad(&e.to_string()))?;
159 Ok(Step::Suggested(vault))
160 }
161 "none" if answer.can_create => Ok(Step::Create),
162 "none" => Ok(Step::NoVault),
163 _ => Err(bad("unknown match")),
164 }
165}
166
167pub fn route_missing(error: &HiveError) -> bool {
170 matches!(
171 error,
172 HiveError::NotFound
173 | HiveError::Server {
174 status: 404 | 405 | 426,
175 ..
176 }
177 )
178}
179
180#[derive(Serialize, Deserialize)]
181struct MatchProbe {
182 unsupported_at: i64,
184}
185
186pub fn match_available(store: &HiveStore, now: i64) -> bool {
189 if !super::bus::relay_v2::speaks_v2(store) {
190 return false;
191 }
192 store
193 .read_config::<MatchProbe>(MATCH_FILE)
194 .ok()
195 .flatten()
196 .is_none_or(|probe| {
197 now < probe.unsupported_at || now - probe.unsupported_at >= REPROBE_SECONDS
198 })
199}
200
201fn remember_missing(store: &HiveStore, now: i64) {
202 let _ = store.write_config(
204 MATCH_FILE,
205 &MatchProbe {
206 unsupported_at: now,
207 },
208 );
209}
210
211pub fn first_share_gated(session: &Session) -> bool {
214 super::connect::decision(&session.store, &session.instance.org_id).is_some()
215}
216
217#[derive(Debug, Clone, PartialEq, Eq)]
219pub enum Target {
220 Bind(VaultRefV1),
222 Own,
225}
226
227pub fn new_vault_name(root: &Path) -> String {
229 let raw = root
230 .file_name()
231 .map(|n| n.to_string_lossy().to_lowercase())
232 .unwrap_or_default();
233 let slug: String = raw
234 .chars()
235 .map(|c| {
236 if c.is_ascii_lowercase() || c.is_ascii_digit() {
237 c
238 } else {
239 '-'
240 }
241 })
242 .collect();
243 let slug: String = slug.trim_matches('-').chars().take(40).collect();
244 let slug = slug.trim_end_matches('-');
245 if slug.len() >= 2 {
246 slug.to_string()
247 } else {
248 "project".into()
249 }
250}
251
252pub fn consent_subject(target: &Target, stable: &str, root: &Path) -> Value {
255 let vault = match target {
256 Target::Bind(vault) => format!("{}/{}", vault.ns, vault.name),
257 Target::Own => format!("{NEW_VAULT_WS}/{}", new_vault_name(root)),
258 };
259 let text = |value: Option<String>| {
260 value
261 .filter(|v| (1..=500).contains(&v.chars().count()))
262 .map_or(Value::Null, Value::String)
263 };
264 consent::subject(&[
265 (
266 "bound_repo",
267 text(root.file_name().map(|n| n.to_string_lossy().into_owned())),
268 ),
269 ("link_digest", Value::String(stable.to_string())),
270 ("remote_seen", text(identity_v2::origin_remote(root))),
271 ("target_vault", Value::Null),
272 ("vault", Value::String(vault)),
273 ])
274}
275
276fn require(
277 session: &Session,
278 config: &HiveConfig,
279 target: &Target,
280 stable: &str,
281 root: &Path,
282) -> Result<(), MapError> {
283 let broker = Broker::open(&session.store, Trust::load(&session.store, config));
284 let now = u64::try_from(Utc::now().timestamp_millis()).unwrap_or_default();
285 broker.require(Kind::LinkVault, &consent_subject(target, stable, root), now)?;
286 Ok(())
287}
288
289pub fn satisfied(record: &consent::Record, map: &super::vault::VaultMap) -> bool {
293 record
294 .subject
295 .get("link_digest")
296 .and_then(Value::as_str)
297 .and_then(|stable| map.vaults.get(stable))
298 .is_some_and(|mapped| satisfied_by(record, mapped))
299}
300
301fn satisfied_by(record: &consent::Record, mapped: &VaultRecord) -> bool {
305 if record.kind != Kind::LinkVault || !record.subject["target_vault"].is_null() {
306 return false;
307 }
308 let vault = record.subject["vault"].as_str().unwrap_or_default();
309 vault == format!("{}/{}", mapped.ns, mapped.name)
310 || vault.starts_with(&format!("{NEW_VAULT_WS}/"))
311}
312
313pub fn close_satisfied(
319 session: &Session,
320 config: &HiveConfig,
321 stable: &str,
322 mapped: &VaultRecord,
323) -> Vec<String> {
324 let broker = Broker::open(&session.store, Trust::load(&session.store, config));
325 let closed = broker
326 .close_satisfied(&|r| r.subject["link_digest"] == stable && satisfied_by(r, mapped))
327 .unwrap_or_else(|error| {
328 tracing::info!("hive consent close: {error}");
329 Vec::new()
330 });
331 for id in &closed {
332 let _ = session.with_client(|client| {
333 consent::web::withdraw_relayed(client, id);
334 Ok(())
335 });
336 }
337 closed
338}
339
340pub fn map_root(
344 session: &Session,
345 config: &HiveConfig,
346 salt: &(String, Vec<u8>),
347 stable: &str,
348 root: &Path,
349 known: Option<&VaultRecord>,
350) -> Result<VaultV1, MapError> {
351 super::company_bound::on_map(&session.store, &session.instance, stable)?;
354 let (resolved, mut request) = resolve_request(root, &salt.0, &salt.1, config.vault_labels)?;
355 if resolved != stable {
356 return Err(HiveError::Config(format!(
357 "{} changed its identity since the draft was made",
358 root.display()
359 ))
360 .into());
361 }
362 let gated = first_share_gated(session) && known.is_none();
363 let now = Utc::now().timestamp();
364 let candidates = match_candidates(root, &salt.1);
365 let mut matched = false;
368 let target = match request.vault.clone() {
371 Some(vault) => Target::Bind(vault),
372 None if match_available(&session.store, now) => {
373 let step = ask_match(session, &salt.0, &candidates, now)?;
374 matched = step.is_some();
375 match step {
376 Some(Step::Mapped(vault)) => {
377 return confirm_move(session, config, stable, root, known, vault);
378 }
379 Some(Step::Suggested(vault)) if gated => Target::Bind(vault),
380 Some(Step::NoVault) => {
381 return Err(HiveError::Refused(
382 "this project has no vault in the workspace and this engine may not create one; ask a maintainer, or name one with `lean-ctx hive link <workspace>/<vault>`".into(),
383 )
384 .into());
385 }
386 Some(Step::Suggested(_) | Step::Create) | None => Target::Own,
389 }
390 }
391 None => Target::Own,
392 };
393 if gated {
394 require(session, config, &target, stable, root)?;
395 }
396 if let Target::Bind(vault) = &target {
397 request.vault = Some(vault.clone());
398 }
399 if matched && let Some(exact) = candidates.iter().find(|c| c.kind == "exact") {
400 request.identity_digest.clone_from(&exact.digest);
401 }
402 let body = serde_json::to_value(&request).map_err(|e| HiveError::Local(e.to_string()))?;
403 let answer = session.with_client(|c| c.post("/vaults/resolve", &body))?;
404 let vault: VaultV1 =
405 serde_json::from_value(answer).map_err(|e| HiveError::Protocol(format!("vault: {e}")))?;
406 vault
407 .validate()
408 .map_err(|e| HiveError::Protocol(e.to_string()))?;
409 if matched {
410 let _ = ask_match(session, &salt.0, &candidates, now);
413 }
414 confirm_move(session, config, stable, root, known, vault)
415}
416
417fn confirm_move(
420 session: &Session,
421 config: &HiveConfig,
422 stable: &str,
423 root: &Path,
424 known: Option<&VaultRecord>,
425 vault: VaultV1,
426) -> Result<VaultV1, MapError> {
427 if first_share_gated(session)
428 && let Some(known) = known
429 && known.ns != vault.vault.ns
430 {
431 require(
432 session,
433 config,
434 &Target::Bind(vault.vault.clone()),
435 stable,
436 root,
437 )?;
438 }
439 Ok(vault)
440}
441
442fn ask_match(
444 session: &Session,
445 org_salt_id: &str,
446 candidates: &[MatchCandidate],
447 now: i64,
448) -> Result<Option<Step>, HiveError> {
449 if candidates.is_empty() {
450 return Ok(None);
451 }
452 let body = match_body(org_salt_id, candidates)?;
453 match session.with_client(|c| c.post("/vaults/match", &body)) {
454 Ok(answer) => {
455 let answer: MatchAnswer = serde_json::from_value(answer)
456 .map_err(|e| HiveError::Protocol(format!("vault match: {e}")))?;
457 step_from_answer(answer).map(Some)
458 }
459 Err(error) if route_missing(&error) => {
460 remember_missing(&session.store, now);
461 Ok(None)
462 }
463 Err(error) => Err(error),
464 }
465}
466
467fn match_body(org_salt_id: &str, candidates: &[MatchCandidate]) -> Result<Value, HiveError> {
468 serde_json::to_value(MatchRequest {
469 schema: MATCH_REQUEST_SCHEMA,
470 org_salt_id,
471 candidates,
472 })
473 .map_err(|e| HiveError::Local(e.to_string()))
474}
475
476#[cfg(test)]
477mod tests {
478 use super::*;
479 use serde_json::json;
480
481 fn vault_json() -> Value {
482 json!({
483 "schema": "leanctx.hive.vault/v1",
484 "vault_id": "3f6c1e9a0b7d4c2e8f5a1b6c9d0e7f42",
485 "vault": {"ns": "acme", "name": "payments"},
486 "sealed": false,
487 })
488 }
489
490 fn answer(value: Value) -> MatchAnswer {
491 serde_json::from_value(value).unwrap()
492 }
493
494 fn route_fixture(name: &str) -> Value {
495 let path = Path::new(env!("CARGO_MANIFEST_DIR"))
496 .join("crates/lean-ctx-protocol/tests/fixtures/hive-v2/routes")
497 .join(name);
498 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
499 }
500
501 #[test]
504 fn the_match_request_is_the_contract_fixture() {
505 use base64::Engine as _;
506 let vectors = identity_v2::contract_vectors();
507 let salt = base64::engine::general_purpose::STANDARD
508 .decode(vectors["salt"].as_str().unwrap())
509 .unwrap();
510 let input = &vectors["cases"][0]["input"];
511 let candidates = identity_v2::candidates_from(
512 &identity_v2::vector_parts(input),
513 input["legacy_identity"].as_str(),
514 );
515 let body = match_body(
516 vectors["org_salt_id"].as_str().unwrap(),
517 &salted(&candidates, &salt),
518 )
519 .unwrap();
520 assert_eq!(body, route_fixture("vault_match.request.json"));
521 }
522
523 #[test]
526 fn the_contract_responses_become_steps() {
527 let step = |name: &str| step_from_answer(answer(route_fixture(name)));
528 assert!(
529 matches!(step("vault_match.bound.response.json"), Ok(Step::Mapped(v)) if v.vault.name == "payments")
530 );
531 assert!(
532 matches!(step("vault_match.bound_legacy.response.json"), Ok(Step::Mapped(v)) if v.sealed)
533 );
534 assert!(
535 matches!(step("vault_match.suggested.response.json"), Ok(Step::Suggested(v)) if v.ns == "acme")
536 );
537 assert_eq!(step("vault_match.none.response.json"), Ok(Step::Create));
538 let mut bound = route_fixture("vault_match.bound.response.json");
539 bound.as_object_mut().unwrap().remove("vault");
540 assert!(
541 step_from_answer(answer(bound)).is_err(),
542 "bound_without_vault"
543 );
544 }
545
546 #[test]
547 fn match_answers_become_steps_and_broken_ones_are_refused() {
548 let bound = answer(json!({
549 "schema": MATCH_SCHEMA, "match": "bound", "matched": "legacy",
550 "vault": vault_json(), "something_new": 1,
551 }));
552 match step_from_answer(bound).unwrap() {
553 Step::Mapped(vault) => assert_eq!(vault.vault.name, "payments"),
554 other => panic!("{other:?}"),
555 }
556 let suggested = answer(json!({
557 "schema": MATCH_SCHEMA, "match": "suggested", "matched": "history",
558 "suggestion": {"ns": "acme", "name": "payments"},
559 }));
560 assert!(
561 matches!(step_from_answer(suggested).unwrap(), Step::Suggested(v) if v.ns == "acme")
562 );
563 let create = answer(json!({"schema": MATCH_SCHEMA, "match": "none", "can_create": true}));
564 assert_eq!(step_from_answer(create).unwrap(), Step::Create);
565 let none = answer(json!({"schema": MATCH_SCHEMA, "match": "none"}));
566 assert_eq!(step_from_answer(none).unwrap(), Step::NoVault);
567
568 for broken in [
569 json!({"schema": MATCH_SCHEMA, "match": "bound"}),
570 json!({"schema": MATCH_SCHEMA, "match": "suggested"}),
571 json!({"schema": MATCH_SCHEMA, "match": "maybe"}),
572 json!({"schema": "leanctx.hive.vault-match/v0", "match": "none"}),
573 json!({"schema": MATCH_SCHEMA, "match": "suggested",
574 "suggestion": {"ns": "acme", "name": "../etc"}}),
575 ] {
576 assert!(
577 step_from_answer(answer(broken.clone())).is_err(),
578 "{broken}"
579 );
580 }
581 }
582
583 #[test]
584 fn only_a_missing_route_means_no_match() {
585 assert!(route_missing(&HiveError::NotFound));
586 assert!(route_missing(&HiveError::Server {
587 status: 404,
588 code: "unknown".into()
589 }));
590 assert!(route_missing(&HiveError::Server {
591 status: 405,
592 code: "unknown".into()
593 }));
594 assert!(!route_missing(&HiveError::Forbidden));
595 assert!(!route_missing(&HiveError::Offline("x".into())));
596 assert!(!route_missing(&HiveError::Server {
597 status: 500,
598 code: "internal".into()
599 }));
600 }
601
602 #[test]
603 fn the_match_route_is_asked_on_c0_2_hivees_and_a_404_rests_for_a_day() {
604 let dir = tempfile::tempdir().unwrap();
605 let store = HiveStore::at(dir.path().join("config"), dir.path().join("data"));
606 let now = 1_800_000_000;
607 assert!(!match_available(&store, now), "1.x: never asked");
608 super::super::bus::relay_v2::record_protocol(&store, true).unwrap();
609 assert!(match_available(&store, now));
610 remember_missing(&store, now);
611 assert!(!match_available(&store, now + 60));
612 assert!(match_available(&store, now + REPROBE_SECONDS));
613 assert!(
614 match_available(&store, now - 60),
615 "a clock that moved back asks again"
616 );
617 store.forget(true).unwrap();
618 assert!(!store.config_dir().join(MATCH_FILE).exists());
619 }
620
621 #[test]
622 fn the_consent_subject_names_the_vault_and_stays_on_shape() {
623 let base = tempfile::tempdir().unwrap();
624 let root = base.path().join("Payments Service");
625 std::fs::create_dir_all(root.join(".git")).unwrap();
626 let stable =
627 lean_ctx_protocol::hive::vault::stable_identity("git:github.com/acme/payments");
628 let own = consent_subject(&Target::Own, &stable, &root);
629 consent::check_subject(Kind::LinkVault, &own).unwrap();
630 assert_eq!(own["vault"], "new/payments-service");
631 assert_eq!(own["bound_repo"], "Payments Service");
632 let bind = consent_subject(
633 &Target::Bind(VaultRefV1 {
634 ns: "acme".into(),
635 name: "payments".into(),
636 }),
637 &stable,
638 &root,
639 );
640 consent::check_subject(Kind::LinkVault, &bind).unwrap();
641 assert_eq!(bind["vault"], "acme/payments");
642 assert_ne!(
643 consent::subject_digest(&own).unwrap(),
644 consent::subject_digest(&bind).unwrap(),
645 "a yes for one target never covers another"
646 );
647 assert_eq!(new_vault_name(Path::new("/w/x")), "project");
648 assert_eq!(new_vault_name(Path::new("/w/Über_App")), "ber-app");
649 assert_eq!(new_vault_name(&base.path().join("a".repeat(60))).len(), 40);
650 }
651
652 #[test]
657 fn a_first_share_for_a_mapped_checkout_is_closed_a_move_keeps_waiting() {
658 let dir = tempfile::tempdir().unwrap();
659 let store = HiveStore::at(dir.path().join("config"), dir.path().join("data"));
660 let broker = Broker::open(
661 &store,
662 Trust {
663 presence: None,
664 consent_keys: std::collections::BTreeMap::new(),
665 owner_user_id: None,
666 },
667 );
668 let root = dir.path().join("journey-demo");
669 std::fs::create_dir_all(root.join(".git")).unwrap();
670 let stable =
671 lean_ctx_protocol::hive::vault::stable_identity("git:github.com/acme/journey-demo");
672 let pending = |target: &Target| match broker.require(
673 Kind::LinkVault,
674 &consent_subject(target, &stable, &root),
675 1_792_800_000_000,
676 ) {
677 Err(ConsentError::Required { consent_id, .. }) => broker.get(&consent_id).unwrap(),
678 other => panic!("{other:?}"),
679 };
680 let own = pending(&Target::Own);
681 let team = pending(&Target::Bind(VaultRefV1 {
682 ns: "acme-team".into(),
683 name: "journey-demo".into(),
684 }));
685 let mut map = super::super::vault::VaultMap::default();
686 assert!(!satisfied(&own, &map), "not mapped yet: it waits");
687 map.vaults.insert(
688 stable.clone(),
689 VaultRecord {
690 vault_id: "vlt_1".into(),
691 ns: "ada".into(),
692 name: "journey-demo".into(),
693 sealed: false,
694 roots: vec![root.to_string_lossy().into_owned()],
695 },
696 );
697 assert!(satisfied(&own, &map), "mapped: nothing to answer");
698 assert!(!satisfied(&team, &map), "a move into another vault waits");
699 let mapped = map.vaults[&stable].clone();
700 let closed = broker
701 .close_satisfied(&|r| {
702 r.subject["link_digest"] == stable.as_str() && satisfied_by(r, &mapped)
703 })
704 .unwrap();
705 assert_eq!(closed, vec![own.consent_id.clone()]);
706 assert!(broker.get(&own.consent_id).is_err(), "closed");
707 assert_eq!(
708 broker.get(&team.consent_id).unwrap().state,
709 consent::State::Pending
710 );
711 }
712
713 #[test]
714 fn consent_errors_keep_their_code_for_the_outbox_and_hide_the_id() {
715 let error = MapError::Consent(ConsentError::Required {
716 consent_id: "cns_aaaaaaaaaaaaaaaa".into(),
717 kind: Kind::LinkVault,
718 });
719 let shown = error.to_string();
720 assert!(shown.starts_with("consent_required"), "{shown}");
721 assert!(
722 !shown.contains("cns_"),
723 "the id is never handed to an agent"
724 );
725 assert!(matches!(HiveError::from(error), HiveError::Refused(_)));
726 }
727}