;; lib/relations/federation.sx — cross-instance links + trust + revocation.
;;
;; fed-sx replicates relationship facts between instances; this module models the
;; local side. A peer's link arrives as `peer_rel(Peer, Src, Dst, Kind)` and only
;; becomes an effective edge when a local `trust(Peer)` fact authorises it — the
;; gating is the engine rule (lib/relations/engine.sx), re-checked every query,
;; so revoking trust or a link takes effect on the next saturation. The network
;; transport is fed-sx's job and is mocked here as a dict.
;;
;; Trust is NOT transitive: trusting peer α binds only links α itself asserts;
;; α's own trust in some β does not flow.

;; A federated link asserted by `peer`: peer claims rel(src,dst,kind) holds.
(define
  relations-peer-rel
  (fn (peer src dst kind) (list (quote peer_rel) peer src dst kind)))

;; Local trust in a peer. Gates that peer's links at query time.
(define relations-trust (fn (peer) (list (quote trust) peer)))

;; Mock fed-sx pull: `transport` maps a peer address (its string name) to the
;; list of peer_rel facts that peer asserts. Returns the facts for `addr`, or an
;; empty list if the peer is unknown / unreachable.
(define
  relations-fed-fetch
  (fn
    (transport addr)
    (let
      ((k (if (symbol? addr) (symbol->string addr) addr)))
      (if (has-key? transport k) (get transport k) (list)))))

;; Gather peer_rel facts from every peer in `addrs` via the transport.
(define
  relations-fed-collect
  (fn
    (transport addrs)
    (let
      ((acc (list)))
      (do
        (for-each
          (fn
            (addr)
            (for-each
              (fn (f) (append! acc f))
              (relations-fed-fetch transport addr)))
          addrs)
        acc))))

;; Build a db from local facts plus peer_rel facts pulled from `peers`. Local
;; facts must carry the trust policy (trust(...) facts); replicated links are
;; gated against it by the engine rule at query time.
(define
  relations-fed-build-db
  (fn
    (local-facts transport peers)
    (let
      ((all (list)))
      (do
        (for-each (fn (f) (append! all f)) local-facts)
        (for-each
          (fn (f) (append! all f))
          (relations-fed-collect transport peers))
        (relations-build-db all)))))

;; Ingest a newly replicated fact into a live db (re-saturates).
(define relations-fed-assert! (fn (db fact) (do (dl-assert! db fact) db)))

;; Propagated revocation: retract a replicated link or a local trust fact from a
;; live db. The next query re-saturates and reflects it.
(define relations-revoke! (fn (db fact) (do (dl-retract! db fact) db)))
