Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
second refactor
Antonio Ojea56ccd8dc2b75
diff --git a/README.md b/README.mdindex e7162b24..347b8888 100644--- a/README.md+++ b/README.md@@ -2,13 +2,13 @@SAM is a zero-trust, pure P2P networking layer for autonomous agents.-It is built for environments where centralized gateways and centralized trust are a liability. Agents discover each other over libp2p DHT, authenticate with vouches, authorize capabilities with Biscuit caveats, and communicate directly over A2A streams.+It is built for environments where centralized gateways and centralized trust are a liability. Agents discover each other over libp2p DHT, authenticate with passport biscuits, authorize capabilities with Biscuit caveats, and communicate directly over A2A streams.## Why SAM- Pure P2P: no API gateway in the data path- Zero-trust by default: every call is authenticated and authorized-- Federation isolation: separate namespaces and storage per federation+- Isolated mesh namespace: separate SAM protocol space and storage scope- Auditability: inspect tokens/cards and dry-run key flows## Quick Start@@ -32,13 +32,13 @@ make test-e2e```bash# Authenticate-sam-agent identity login --hub https://identity.example.com --federation finance+sam-agent identity login --hub https://identity.example.com# Publish an agent capability-sam-agent publish --federation finance --skill risk-audit --mcp-port 8080+sam-agent publish --skill risk-audit --mcp-port 8080# Call by capability-sam-agent call risk-audit --federation finance --message "audit this report"+sam-agent call risk-audit --message "audit this report"# Inspect credential artifactssam-agent inspect biscuit "vendor-bot;allow_skill=risk-audit"diff --git a/cmd/sam-agent/call.go b/cmd/sam-agent/call.goindex 709402cd..e674e88c 100644--- a/cmd/sam-agent/call.go+++ b/cmd/sam-agent/call.go@@ -94,11 +94,11 @@ func runCall(parent context.Context, cfg *runConfig, targetArg string) error {if err != nil {return err}- if err := identity.SetLocalPassport(node.Host(), cfg.federation, passport); err != nil {+ if err := identity.SetLocalPassport(node.Host(), defaultFederationID, passport); err != nil {return fmt.Errorf("configuring local passport auth: %w", err)}- observer, err := protocol.NewBoltObserverWithFallback(cfg.federation)+ observer, err := protocol.NewBoltObserverWithFallback(defaultFederationID)if err != nil {return fmt.Errorf("creating reputation observer: %w", err)}diff --git a/cmd/sam-agent/identity_login.go b/cmd/sam-agent/identity_login.goindex 55664107..66ef76ba 100644--- a/cmd/sam-agent/identity_login.go+++ b/cmd/sam-agent/identity_login.go@@ -106,7 +106,7 @@ func runIdentityLogin(parent context.Context, cfg *runConfig, clientID string) eissueReq := identity.PassportIssueRequest{PeerID: peerID,- FederationID: cfg.federation,+ FederationID: defaultFederationID,Subject: peerID,Claims: map[string]string{"hub": hubURL},}@@ -135,7 +135,7 @@ func runIdentityLogin(parent context.Context, cfg *runConfig, clientID string) e}fmt.Fprintf(os.Stderr, "\nLogged in as peer %s\n", peerID)- if claims, pErr := identity.ValidatePassportBiscuit(parent, passportBiscuit, peerID, cfg.federation); pErr == nil {+ if claims, pErr := identity.ValidatePassportBiscuit(parent, passportBiscuit, peerID, defaultFederationID); pErr == nil {fmt.Fprintf(os.Stderr, "Subject: %s\n", claims.Subject)fmt.Fprintf(os.Stderr, "Federation: %s\n", claims.FederationID)}diff --git a/cmd/sam-agent/mesh.go b/cmd/sam-agent/mesh.goindex 48f2c5c5..aa1738e9 100644--- a/cmd/sam-agent/mesh.go+++ b/cmd/sam-agent/mesh.go@@ -23,7 +23,6 @@ func newMeshCmd(cfg *runConfig) *cobra.Command {Short: "Inspect and interact with the SAM agent mesh",}cmd.AddCommand(newMeshGetCmd(cfg))- cmd.AddCommand(newMeshFederationsCmd(cfg))return cmd}diff --git a/cmd/sam-agent/mesh_federations.go b/cmd/sam-agent/mesh_federations.godeleted file mode 100644index 11813268..00000000--- a/cmd/sam-agent/mesh_federations.go+++ /dev/null@@ -1,133 +0,0 @@-// Copyright 2026 Google LLC-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.--package main--import (- "encoding/json"- "fmt"- "os"- "text/tabwriter"-- "github.com/spf13/cobra"-- internaldb "sam/internal/db"-)--// newMeshFederationsCmd builds the "sam mesh federations" sub-group.-func newMeshFederationsCmd(_ *runConfig) *cobra.Command {- cmd := &cobra.Command{- Use: "federations",- Short: "Manage federation storage contexts",- Long: `Manage isolated storage contexts (federations).--Each federation stores its own peer metadata, reputation scores, and discovery-cache in a separate database at ~/.config/sam/federations/<name>.db.--The master identity key stays at ~/.config/sam/state.db and is never affected-by federation operations.`,- }- cmd.AddCommand(newMeshFederationsListCmd())- cmd.AddCommand(newMeshFederationsDropCmd())- return cmd-}--// newMeshFederationsListCmd builds "sam mesh federations list".-func newMeshFederationsListCmd() *cobra.Command {- var outputFmt string- cmd := &cobra.Command{- Use: "list",- Short: "List all federation databases on disk",- RunE: func(cmd *cobra.Command, _ []string) error {- return runMeshFederationsList(outputFmt)- },- }- cmd.Flags().StringVarP(&outputFmt, "output", "o", "table", "output format: table|json")- return cmd-}--func runMeshFederationsList(format string) error {- mgr, err := internaldb.NewManager()- if err != nil {- return fmt.Errorf("creating federation manager: %w", err)- }- defer func() { _ = mgr.Close() }()-- names, err := mgr.ListFederations()- if err != nil {- return fmt.Errorf("listing federations: %w", err)- }-- if len(names) == 0 {- _, _ = fmt.Fprintln(os.Stdout, "No federation databases found.")- _, _ = fmt.Fprintf(os.Stdout, "Use --federation <name> with any command to create one.\n")- return nil- }-- switch format {- case "json":- type entry struct {- Name string `json:"name"`- Path string `json:"path"`- }- dir := mgr.BaseDir()- out := make([]entry, len(names))- for i, n := range names {- out[i] = entry{Name: n, Path: dir + "/" + n + ".db"}- }- enc := json.NewEncoder(os.Stdout)- enc.SetIndent("", " ")- return enc.Encode(out)- default:- w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)- _, _ = fmt.Fprintln(w, "NAME\tPATH")- for _, n := range names {- _, _ = fmt.Fprintf(w, "%s\t%s/%s.db\n", n, mgr.BaseDir(), n)- }- return w.Flush()- }-}--// newMeshFederationsDropCmd builds "sam mesh federations drop <name>".-func newMeshFederationsDropCmd() *cobra.Command {- var confirm bool- cmd := &cobra.Command{- Use: "drop <name>",- Short: "Delete a federation database and all its data",- Args: cobra.ExactArgs(1),- RunE: func(cmd *cobra.Command, args []string) error {- return runMeshFederationsDrop(args[0], confirm)- },- }- cmd.Flags().BoolVar(&confirm, "confirm", false, "required: confirm destructive deletion")- return cmd-}--func runMeshFederationsDrop(name string, confirmed bool) error {- if !confirmed {- return fmt.Errorf("destructive operation: re-run with --confirm to delete federation %q", name)- }-- mgr, err := internaldb.NewManager()- if err != nil {- return fmt.Errorf("creating federation manager: %w", err)- }- defer func() { _ = mgr.Close() }()-- if err := mgr.DropFederation(name); err != nil {- return fmt.Errorf("dropping federation %q: %w", name, err)- }- _, _ = fmt.Fprintf(os.Stdout, "Federation %q dropped.\n", name)- return nil-}diff --git a/cmd/sam-agent/mesh_get_agents.go b/cmd/sam-agent/mesh_get_agents.goindex 4479ee3d..0884dac5 100644--- a/cmd/sam-agent/mesh_get_agents.go+++ b/cmd/sam-agent/mesh_get_agents.go@@ -118,7 +118,7 @@ func runMeshGetAgents(parent context.Context, cfg *runConfig) error {}func runMeshGetAgentsWatch(parent context.Context, cfg *runConfig, format outputFormat, node samnet.Node) error {- watchManager, err := newInventoryWatchManager(node, cfg.federation)+ watchManager, err := newInventoryWatchManager(node, defaultFederationID)if err != nil {return fmt.Errorf("creating inventory watch manager: %w", err)}@@ -151,11 +151,11 @@ func runMeshGetAgentsWatch(parent context.Context, cfg *runConfig, format outputreturn fmt.Errorf("watch stream failed: %s: %s", resp.Status, strings.TrimSpace(string(body)))}- discoverer, err := newAgentDiscoverer(node, cfg.federation, cfg.dhtCardMaxAge)+ discoverer, err := newAgentDiscoverer(node, defaultFederationID, cfg.dhtCardMaxAge)if err != nil {return fmt.Errorf("creating informer discoverer: %w", err)}- informer, err := samnet.NewLocalInformer(node, cfg.federation, samnet.WithInformerDiscoverer(discoverer))+ informer, err := samnet.NewLocalInformer(node, defaultFederationID, samnet.WithInformerDiscoverer(discoverer))if err != nil {return fmt.Errorf("creating local informer: %w", err)}diff --git a/cmd/sam-agent/node.go b/cmd/sam-agent/node.goindex 01393a0a..f704b4a1 100644--- a/cmd/sam-agent/node.go+++ b/cmd/sam-agent/node.go@@ -51,7 +51,7 @@ func buildNode(cfg *runConfig) (samnet.Node, error) {samnet.WithListenAddrs(listen...),samnet.WithBootstrapPeers(bootstrap...),samnet.WithDHTMode(parseDHTMode(cfg.dhtMode)),- samnet.WithFederation(cfg.federation),+ samnet.WithFederation(defaultFederationID),samnet.WithUserAgent(cfg.userAgent),samnet.WithLogger(slog.Default()),samnet.WithPrivateKey(key),diff --git a/cmd/sam-agent/proxy.go b/cmd/sam-agent/proxy.goindex 3b988aa5..1645854d 100644--- a/cmd/sam-agent/proxy.go+++ b/cmd/sam-agent/proxy.go@@ -81,17 +81,17 @@ func runProxy(parent context.Context, cfg *runConfig) error {}defer func() { _ = node.Stop(context.Background()) }()- discoverer, err := newAgentDiscoverer(node, cfg.federation, 15*time.Minute)+ discoverer, err := newAgentDiscoverer(node, defaultFederationID, 15*time.Minute)if err != nil {return fmt.Errorf("creating informer discoverer: %w", err)}- informer, err := samnet.NewLocalInformer(node, cfg.federation, samnet.WithInformerDiscoverer(discoverer))+ informer, err := samnet.NewLocalInformer(node, defaultFederationID, samnet.WithInformerDiscoverer(discoverer))if err != nil {return fmt.Errorf("creating local informer: %w", err)}informer.Start(parent)- watchManager, err := newInventoryWatchManager(node, cfg.federation)+ watchManager, err := newInventoryWatchManager(node, defaultFederationID)if err != nil {return fmt.Errorf("creating inventory watch manager: %w", err)}@@ -113,7 +113,7 @@ func runProxy(parent context.Context, cfg *runConfig) error {}start := time.Now()- observer, err := protocol.NewBoltObserverWithFallback(cfg.federation)+ observer, err := protocol.NewBoltObserverWithFallback(defaultFederationID)if err != nil {http.Error(w, "reputation observer unavailable", http.StatusInternalServerError)return@@ -125,7 +125,7 @@ func runProxy(parent context.Context, cfg *runConfig) error {http.Error(w, "unauthorized: local identity login required", http.StatusUnauthorized)return}- if err := identity.SetLocalPassport(node.Host(), cfg.federation, passport); err != nil {+ if err := identity.SetLocalPassport(node.Host(), defaultFederationID, passport); err != nil {http.Error(w, fmt.Sprintf("passport auth unavailable: %v", err), http.StatusInternalServerError)return}@@ -262,7 +262,7 @@ func handleSAMReservedWithWatcher(w http.ResponseWriter, r *http.Request, node shttp.Error(w, "method not allowed", http.StatusMethodNotAllowed)return}- cards, err := aggregateInventory(ctx, node, cfg.federation)+ cards, err := aggregateInventory(ctx, node, defaultFederationID)if err != nil {http.Error(w, fmt.Sprintf("inventory lookup failed: %v", err), http.StatusBadGateway)return@@ -273,7 +273,7 @@ func handleSAMReservedWithWatcher(w http.ResponseWriter, r *http.Request, node shttp.Error(w, "method not allowed", http.StatusMethodNotAllowed)return}- cards, err := aggregateInventory(ctx, node, cfg.federation)+ cards, err := aggregateInventory(ctx, node, defaultFederationID)if err != nil {http.Error(w, fmt.Sprintf("inventory lookup failed: %v", err), http.StatusBadGateway)return@@ -289,7 +289,7 @@ func handleSAMReservedWithWatcher(w http.ResponseWriter, r *http.Request, node shttp.Error(w, "missing skill query parameter", http.StatusBadRequest)return}- cards, err := searchInventoryBySkill(ctx, node, cfg.federation, skill)+ cards, err := searchInventoryBySkill(ctx, node, defaultFederationID, skill)if err != nil {http.Error(w, fmt.Sprintf("search failed: %v", err), http.StatusBadGateway)returndiff --git a/cmd/sam-agent/proxy_reserved_test.go b/cmd/sam-agent/proxy_reserved_test.goindex 7f346942..7ccb7c63 100644--- a/cmd/sam-agent/proxy_reserved_test.go+++ b/cmd/sam-agent/proxy_reserved_test.go@@ -107,7 +107,7 @@ func TestSAMReservedSearchReturnsPublishedWriterCard(t *testing.T) {t.Fatalf("publishing writer card: %v", err)}- cfg := &runConfig{proxyTimeout: 3 * time.Second, federation: "default"}+ cfg := &runConfig{proxyTimeout: 3 * time.Second}deadline := time.Now().Add(12 * time.Second)for {diff --git a/cmd/sam-agent/publish.go b/cmd/sam-agent/publish.goindex c1da0d98..87f6a6f4 100644--- a/cmd/sam-agent/publish.go+++ b/cmd/sam-agent/publish.go@@ -85,7 +85,7 @@ func runPublish(parent context.Context, cfg *runConfig) error {if len(cfg.capabilities) == 0 {return fmt.Errorf("at least one non-empty skill/capability is required")}- if err := ensureSecurePublishPreflight(cfg.federation); err != nil {+ if err := ensureSecurePublishPreflight(); err != nil {return err}@@ -154,8 +154,8 @@ func runPublish(parent context.Context, cfg *runConfig) error {return waitForShutdown(parent, cfg.runFor)}-func ensureSecurePublishPreflight(federationID string) error {- gate, closeFn, err := protocol.NewPassportGateForFederation(federationID)+func ensureSecurePublishPreflight() error {+ gate, closeFn, err := protocol.NewPassportGateWithCleanup()if err != nil {return fmt.Errorf("publish security preflight failed: %w", err)}diff --git a/cmd/sam-agent/root.go b/cmd/sam-agent/root.goindex 8f1e8877..bf99e92b 100644--- a/cmd/sam-agent/root.go+++ b/cmd/sam-agent/root.go@@ -72,13 +72,12 @@ type runConfig struct {proxyBiscuit stringproxyTimeout time.Duration- // federation storage context- federation string-// dry-run modes: "", "client", "server"dryRun string}+const defaultFederationID = "default"+// newRootCmd builds the top-level "sam-agent" command and attaches subcommands.func newRootCmd(cfg *runConfig) *cobra.Command {cmd := &cobra.Command{@@ -100,7 +99,6 @@ func newRootCmd(cfg *runConfig) *cobra.Command {pf.StringVar(&cfg.hub, "hub", "", "OIDC hub URL for passport issuance and identity login")pf.StringVar(&cfg.identityPath, "identity", "", "path to PEM-encoded Ed25519 private key (generated and saved if absent)")pf.BoolVar(&cfg.debug, "debug", false, "enable debug logging (slog + libp2p subsystems)")- pf.StringVar(&cfg.federation, "federation", "default", "federation context for isolated reputation and cache storage")cmd.AddCommand(newUpCmd(cfg))cmd.AddCommand(newPublishCmd(cfg))diff --git a/cmd/sam-agent/up.go b/cmd/sam-agent/up.goindex c6dfcdaf..5521c4d4 100644--- a/cmd/sam-agent/up.go+++ b/cmd/sam-agent/up.go@@ -54,7 +54,7 @@ func runUp(parent context.Context, cfg *runConfig) error {return fmt.Errorf("starting node: %w", err)}defer func() { _ = node.Stop(context.Background()) }()- if err := identity.EnsurePassportAuth(node.Host(), cfg.federation); err != nil {+ if err := identity.EnsurePassportAuth(node.Host(), defaultFederationID); err != nil {return fmt.Errorf("installing passport auth: %w", err)}diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.goindex 959c79d9..1518c4a4 100644--- a/cmd/sam-hub/main.go+++ b/cmd/sam-hub/main.go@@ -31,11 +31,30 @@ func main() {w.WriteHeader(http.StatusOK)_, _ = w.Write([]byte("ok"))})+ mux.HandleFunc("/.well-known/sam-hub-keys", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "issuer": identity.DefaultHubIssuer,+ "keys": []map[string]string{{+ "kid": "sam-hub-root-v1",+ "alg": "Ed25519",+ "k": identity.HubPublicKeyBase64(),+ }},+ })+ })mux.HandleFunc("/issue-passport", func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {http.Error(w, "method not allowed", http.StatusMethodNotAllowed)return}+ auth := strings.TrimSpace(r.Header.Get("Authorization"))+ if !strings.HasPrefix(strings.ToLower(auth), "bearer ") || strings.TrimSpace(strings.TrimPrefix(auth, "Bearer ")) == "" {+ http.Error(w, "missing bearer token", http.StatusUnauthorized)+ return+ }var req passportRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {http.Error(w, fmt.Sprintf("bad request: %v", err), http.StatusBadRequest)@@ -51,7 +70,10 @@ func main() {http.Error(w, fmt.Sprintf("issue failed: %v", err), http.StatusBadRequest)return}- _ = json.NewEncoder(w).Encode(map[string]string{"passport_biscuit": tok})+ _ = json.NewEncoder(w).Encode(map[string]string{+ "issuer": identity.DefaultHubIssuer,+ "passport_biscuit": tok,+ })})mux.HandleFunc("/trust-map", func(w http.ResponseWriter, _ *http.Request) {_ = json.NewEncoder(w).Encode(map[string]any{"source": "gossipsub", "note": "passive observer endpoint"})diff --git a/docs/DOCUMENTATION.md b/docs/DOCUMENTATION.mdindex 7e1bddcf..0e361ed3 100644--- a/docs/DOCUMENTATION.md+++ b/docs/DOCUMENTATION.md@@ -123,7 +123,7 @@ concepts/### 3. **Manifesto** (README.md)- ✅ Core philosophy: "Sovereign" agents, "Engineering Truth"- ✅ The Trust Desert problem (gateways, IdP, audit)-- ✅ How SAM solves it (Pure P2P, Zero-Trust, Federation, Audit)+- ✅ How SAM solves it (Pure P2P, Zero-Trust, Passport auth, Audit)- ✅ Architecture overview with data flow diagrams- ✅ Why "Sovereign"- ✅ What SAM does NOT do (blockchain, sidecar, etc.)@@ -131,15 +131,15 @@ concepts/### 4. **User Journey** (dark-mesh.md)- ✅ Real-world scenario (Acme Corp with 3 business units)- ✅ 9 step-by-step sections with CLI snippets-- ✅ Shows federation isolation (DHT namespace scoping)-- ✅ Explains identity gating (vouch verification)+- ✅ Shows mesh namespace scoping+- ✅ Explains identity gating (passport verification)- ✅ Demonstrates Biscuit tokens (skill restrictions)- ✅ Audit transparency (sam inspect commands)- ✅ Trust flow diagram### 5. **CLI Reference** (cli/reference.md)- ✅ kubectl-style command hierarchy-- ✅ Global flags (--federation, --debug, --timeout, --output)+- ✅ Global node/runtime flags and command-specific options- ✅ All commands documented (identity, publish, call, inspect, mesh, up)- ✅ Flags and examples for each command- ✅ Dry-run philosophy explained@@ -147,8 +147,8 @@ concepts/- ✅ Output formats (JSON + text)### 6. **Technical Concepts** (concepts/)-- ✅ Federation storage: bbolt architecture, multi-tenant design-- ✅ Identity: vouch system, decentralization, offline capability+- ✅ Mesh storage: bbolt architecture and default namespace behavior+- ✅ Identity: passport biscuit system- ✅ Biscuit: authorization model, skill gating, enforcement- ✅ A2A Protocol: message structure, authentication flow, code examples@@ -173,7 +173,7 @@ concepts/### 9. **FAQ** (faq.md)- ✅ 30+ questions organized by category- ✅ Getting started (install, publish, call)-- ✅ Core concepts (federation, vouch, Biscuit, A2A)+- ✅ Core concepts (mesh namespace, passport, Biscuit, A2A)- ✅ Architecture & design (why P2P, why not OAuth)- ✅ Network & connectivity (NAT, firewall, cloud)- ✅ Security & trust (production readiness, key management)diff --git a/docs/cli/reference.md b/docs/cli/reference.mdindex 9c7bd19a..22f45a60 100644--- a/docs/cli/reference.md+++ b/docs/cli/reference.md@@ -1,526 +1,169 @@# SAM CLI Reference-SAM uses a **kubectl-style command hierarchy** with shared flags, subcommands, and consistent output formats.-----+SAM uses a kubectl-style command hierarchy with shared node/runtime flags.## Global Flags-All commands accept these flags:+Most commands accept these shared flags:| Flag | Type | Default | Description ||------|------|---------|-------------|-| `--federation` | string | "" | Federation name (scopes operations to isolated namespace) |-| `--debug` | bool | false | Enable debug logging (verbose output) |-| `--timeout` | duration | 30s | Operation timeout |-| `--output` / `-o` | string | "json" | Output format: "json" or "text" |-------## sam identity+| `--listen` | stringSlice | `/ip4/0.0.0.0/udp/0/quic-v1` | libp2p listen multiaddrs |+| `--bootstrap` | stringSlice | empty | bootstrap peer multiaddrs |+| `--dht-mode` | string | `client` | DHT mode: `client`, `server`, `auto` |+| `--relay-service` | bool | `false` | enable relay service |+| `--user-agent` | string | `sam/0.1.0` | libp2p user-agent |+| `--run-for` | duration | `0` | optional duration before graceful shutdown |+| `--hub` | string | empty | OIDC hub URL for identity login/passport issuance |+| `--identity` | string | empty | PEM-encoded Ed25519 private key path |+| `--debug` | bool | `false` | enable debug logging |++## sam-agent identityAuthentication and credential management.-### sam identity login+### sam-agent identity login-Authenticate with a federation hub and store vouch locally.+Authenticate with the hub using device flow and store credentials plus passport biscuit locally.```bash-sam identity login \- --hub https://identity.acme.corp \- --federation finance-```--**Flags:**-- `--hub` (required): URL of identity server-- `--federation` (optional): Federation name (defaults to "default")--**Output:**+sam-agent identity login --hub https://identity.acme.corp```-✓ Identity verified-✓ Vouch stored-✓ Federation: finance-✓ Subject: [email protected]-```--**What it does:**-1. Prompts for username/password-2. Contacts the hub to verify credentials-3. Receives a signed Vouch (JSON)-4. Stores vouch in `~/.config/sam/identity/vouch.json`-5. Stores credentials in secure OS keyring (optional)-**Behind the scenes:**-- The vouch is a signed credential proving your identity to the federation-- The hub is not contacted again (vouch is cached locally)-- If the vouch expires, run login again-------### sam identity whoami+### sam-agent identity whoamiShow current authenticated identity.```bash-sam identity whoami --federation finance+sam-agent identity whoami```-**Output:**-```-Subject: [email protected]-Vouch: Valid until 2027-04-18-Federation: finance-PeerID: 12D3KooXA7cBj4VKrpv7HzKLmvnWKLVqZZHJm9NyN6Td3Y4hMWjK-```+## sam-agent publish------## sam publish--Publish an agent to a federation DHT.+Publish an agent card to DHT namespaces.### Quick Mode-For simple single-skill agents:-```bash-sam publish \- --federation finance \- --skill risk-audit \- --mcp-port 8080+sam-agent publish --skill risk-audit --mcp-port 8080```-**Flags:**-- `--skill`: Single skill name (convenience alias for --capability)-- `--capability`: Repeatable flag for multiple skills-- `--mcp-port` (required): Local MCP server port-- `--republish-every`: Refresh interval (default 2m)-- `--dry-run`: "client" (build locally) or "server" (skip DHT publish)-- `--resource-name`: MCP resource name-- `--resource-kind`: MCP resource kind (default "tool")-- `--resource-endpoint`: Override resource endpoint-- `--resource-description`: Human-readable description+Useful flags:+- `--skill` or repeatable `--capability`+- `--mcp-port`+- `--republish-every`+- `--dry-run=client|server`+- `--resource-name`, `--resource-kind`, `--resource-endpoint`, `--resource-description`-**Dry-Run Modes:**+### sam-agent publish card-Preview the Agent Card without network:```bash-sam publish \- --federation finance \- --skill risk-audit \- --mcp-port 8080 \- --dry-run=client+sam-agent publish card --file agent-card.json --republish-every 5m```-Output: Agent Card JSON (no network activity)+### sam-agent publish mcp-Skip DHT publish but build network:```bash-sam publish \- --federation finance \- --skill risk-audit \- --mcp-port 8080 \- --dry-run=server+sam-agent publish mcp --port 8080 --name "Risk Audit Tool"```-Output: Agent Card JSON (node started but DHT publish skipped)-------### sam publish card--Explicit card publishing (advanced).--```bash-sam publish card \- --federation finance \- --file agent-card.json \- --republish-every 5m-```--**Flags:**-- `--file`: Path to pre-built Agent Card JSON-- `--republish-every`: Refresh interval-------### sam publish mcp--Publish an MCP server.--```bash-sam publish mcp \- --federation finance \- --port 8080 \- --name "Risk Audit Tool"-```--**Flags:**-- `--port`: MCP server port-- `--name`: Resource name-------## sam call+## sam-agent callExecute an A2A task against a remote agent.-### Basic Call--```bash-sam call risk-audit \- --federation finance \- --message "Audit the Q1 risk report"-```--**Flags:**-- `--message` (required): Natural-language prompt-- `--biscuit`: Credential token (default "dev-biscuit")-- `--timeout`: Call timeout (default 20s)-- `--amount`: Micropayment amount (default 1)-- `--asset`: Micropayment asset (default "sam-credit")-- `--nonce`: Micropayment nonce (auto-generated if empty)-- `--dry-run`: "client" (validate locally) or "server" (skip A2A execute)--**Dry-Run Modes:**--Validate request without network:-```bash-sam call risk-audit \- --federation finance \- --message "Audit Q1" \- --dry-run=client-```--Output: Request JSON (no network activity)--**Output:**-```json-{- "jsonrpc": "2.0",- "id": "sam-call",- "method": "message",- "params": {- "message": "Audit the Q1 risk report"- }-}-```-------## sam inspect--Decode and explain cryptographic artifacts for auditing.--### sam inspect biscuit--Parse and explain a Biscuit token.--```bash-sam inspect biscuit "alice;allow_skill=risk-audit,weather-bot"-```--**Output (Text):**-```-Biscuit Token Analysis-======================--Subject: alice-Allowed Skills:- - risk-audit- - weather-bot--Human-Readable Summary:-This token issued to 'alice' allows execution of 2 skills:-risk-audit, weather-bot.-```--**Output (JSON):**-```bash-sam inspect biscuit "alice;allow_skill=risk-audit" --output json-```--```json-{- "subject": "alice",- "allowed_skills": ["risk-audit"]-}-```--**Use case:** Before sharing a Biscuit token, verify it grants only intended skills.-------### sam inspect card--Decode an Agent Card JSON.-```bash-sam inspect card '{- "peer_id": "12D3KooXA7cBj4VKrpv7HzKLmvnWKLVqZZHJm9NyN6Td3Y4hMWjK",- "alg": "libp2p-ed25519",- "signature": "...",- "agent_card": {- "name": "Risk Audit Agent",- "skills": ["risk-audit", "compliance-check"],- "resources": [...]- },- "issued_at": "2026-04-18T10:15:00Z"-}'-```--**Output:**+sam-agent call risk-audit --message "Audit the Q1 risk report"```-Agent Card Analysis-===================--Peer ID: 12D3KooXA7cBj4VKrpv7HzKLmvnWKLVqZZHJm9NyN6Td3Y4hMWjK-Algorithm: libp2p-ed25519-Signature: Verified ✓--Skills Available:- - risk-audit- - compliance-check--Resources:- - Name: risk-audit- Kind: tool- Endpoint: http://127.0.0.1:8080--Issued: 2026-04-18T10:15:00Z-```--**Use case:** Verify an agent's published skills before calling it.-------## sam mesh-Federation and network management.+Useful flags:+- `--message`+- `--biscuit`+- `--timeout`+- `--amount`, `--asset`, `--nonce`+- `--dry-run=client|server`-### sam mesh federations+## sam-agent proxy-Manage isolated federation namespaces.--#### sam mesh federations create--Create a new federation.+Start a local HTTP proxy that tunnels over SAM.```bash-sam mesh federations create finance-```--**Output:**-```json-{- "name": "finance",- "id": "fed-abc123...",- "created_at": "2026-04-18T10:00:00Z"-}+sam-agent proxy --port 8081```-**What it does:**-1. Generates a deterministic federation ID from the name-2. Creates a bbolt database at `~/.config/sam/federations/<name>.db`-3. Initializes buckets: identities, vouches, reputation, cache+Useful flags:+- `--port`+- `--target-header`+- `--biscuit`+- `--timeout`----+## sam-agent inspect-#### sam mesh federations list+Decode local artifacts for auditing.-List all federations.+### sam-agent inspect biscuit```bash-sam mesh federations list+sam-agent inspect biscuit "alice;allow_skill=risk-audit,weather-bot"```-**Output:**-```json-{- "federations": [- {- "name": "finance",- "id": "fed-abc123...",- "agents": 3,- "created_at": "2026-04-18T10:00:00Z"- },- {- "name": "operations",- "id": "fed-def456...",- "agents": 2,- "created_at": "2026-04-18T10:05:00Z"- }- ]-}-```-------#### sam mesh federations drop--Delete a federation.+### sam-agent inspect card```bash-sam mesh federations drop finance --confirm+sam-agent inspect card '{"peer_id":"...","agent_card":{...}}'```-**Flags:**-- `--confirm`: Require explicit confirmation to prevent accidental deletion+## sam-agent mesh-**Output:**-```-✓ Federation 'finance' dropped-✓ Database deleted: ~/.config/sam/federations/finance.db-```-------### sam mesh get agents+Mesh visibility commands.-List agents in a federation.+### sam-agent mesh get agents```bash-sam mesh get agents --federation finance+sam-agent mesh get agents+sam-agent mesh get agents --capability risk-audit+sam-agent mesh get agents --watch -o json```-**Output:**-```json-{- "agents": [- {- "peer_id": "12D3KooXA7cBj4VKrpv7HzKLmvnWKLVqZZHJm9NyN6Td3Y4hMWjK",- "name": "Risk Audit Agent",- "skills": ["risk-audit", "compliance-check"],- "published_at": "2026-04-18T10:15:00Z"- }- ]-}-```-------## sam up+## sam-agent upStart a SAM node and wait for shutdown.```bash-sam up \- --federation finance \- --listen /ip4/0.0.0.0/tcp/4001 \- --bootstrap /ip4/192.168.1.100/tcp/4001/p2p/12D3KooXA7cBj4VKrpv7HzKLmvnWKLVqZZHJm9NyN6Td3Y4hMWjK+sam-agent up \+ --listen /ip4/0.0.0.0/udp/4001/quic-v1 \+ --bootstrap /ip4/192.168.1.100/udp/4001/quic-v1/p2p/12D3KooXA7cBj4VKrpv7HzKLmvnWKLVqZZHJm9NyN6Td3Y4hMWjK```-**Flags:**-- `--listen`: Multiaddr to listen on (repeatable)-- `--bootstrap`: Bootstrap peer address (repeatable)-- `--run-for`: Duration to run (e.g., "10m", default infinite)-- `--federation`: Federation to join+## Patterns-**Use case:** Run a persistent SAM node for long-lived agents or relays.-------## Patterns and Best Practices--### Workflow: Publish a New Agent--```bash-# 1. Preview the card locally-sam publish \- --federation finance \- --skill new-capability \- --mcp-port 9000 \- --dry-run=client--# 2. If satisfied, publish to DHT-sam publish \- --federation finance \- --skill new-capability \- --mcp-port 9000-```--### Workflow: Call with Biscuit Authorization+### Publish workflow```bash-# 1. Create a Biscuit token for a partner-TOKEN="partner-bot;allow_skill=risk-audit"+# Preview card locally+sam-agent publish --skill new-capability --mcp-port 9000 --dry-run=client-# 2. Inspect the token before sharing-sam inspect biscuit "$TOKEN"--# 3. Partner uses token to call-sam call risk-audit \- --federation finance \- --biscuit "$TOKEN" \- --message "Check compliance"+# Publish to mesh+sam-agent publish --skill new-capability --mcp-port 9000```-### Workflow: Audit a Call Request--```bash-# 1. Validate the call structure without network-sam call weather-bot \- --federation finance \- --message "Get forecast" \- --dry-run=client--# 2. Review the JSON-# 3. If satisfied, remove --dry-run-sam call weather-bot \- --federation finance \- --message "Get forecast"-```-------## Output Formats--All commands support `--output` flag (default "json", values "json" or "text").+### Call workflow with Biscuit-**JSON output:**```bash-sam mesh federations list --output json-```--**Text output:**-```bash-sam mesh federations list --output text-```-------## Federation Scoping--Many commands require `--federation` to specify which federation to operate in.--If not provided, defaults to "default" federation.--```bash-# Explicit federation-sam publish --federation finance --skill risk-audit --mcp-port 8080--# Uses "default" federation-sam publish --skill risk-audit --mcp-port 8080+TOKEN="partner-bot;allow_skill=risk-audit"+sam-agent inspect biscuit "$TOKEN"+sam-agent call risk-audit --biscuit "$TOKEN" --message "Check compliance"```-----## Dry-Run Philosophy-**Dry-run modes exist to support audit transparency:**--- `--dry-run=client`: Build and sign locally, show output, no network-- `--dry-run=server`: Start network, build artifacts, skip final commit (DHT publish, A2A execute)+Dry-run modes support audit transparency and safe rollout:-Use these to:-1. Preview what will be published/called-2. Extract JSON for security scanning-3. Verify signatures before committing-4. Integrate with CI/CD approval workflows+- `--dry-run=client`: build and validate payloads locally, no network activity+- `--dry-run=server`: initialize runtime, skip final network commit----+Use these to preview behavior, capture JSON artifacts for security review, and gate CI checks.## Next Steps-- **[User Journey Guide](#/guides/dark-mesh.md)**: Full scenario walkthrough-- **[Concepts](#/concepts/federation.md)**: Technical deep dive+- **[User Journey Guide](#/guides/dark-mesh.md)**: scenario walkthrough+- **[FAQ](#/faq.md)**: troubleshooting and operational tipsdiff --git a/docs/concepts/a2a-protocol.md b/docs/concepts/a2a-protocol.mdindex e30dddd0..27058b91 100644--- a/docs/concepts/a2a-protocol.md+++ b/docs/concepts/a2a-protocol.md@@ -193,8 +193,8 @@ Server returns response to client| Error | Cause | Solution ||-------|-------|----------|-| `ErrNotInFederation` | Vouch not in federation | Authenticate: `sam identity login --federation <name>` |-| `ErrVouchExpired` | Vouch timestamp > expiry | Re-authenticate: `sam identity login ...` |+| `ErrNotInFederation` | Vouch not in federation | Authenticate: `sam-agent identity login --hub <url>` |+| `ErrVouchExpired` | Vouch timestamp > expiry | Re-authenticate: `sam-agent identity login --hub <url>` || `ErrSkillNotAllowed` | Skill not in Biscuit caveats | Get new Biscuit with skill, or ask for permission || `ErrMCPFailed` | MCP server error | Check MCP server logs |@@ -220,7 +220,7 @@ Server returns response to clientDefault: 20 seconds (configurable with `--timeout`)```bash-sam call mycapability --federation finance --timeout 30s+sam-agent call mycapability --timeout 30s```---diff --git a/docs/concepts/biscuit.md b/docs/concepts/biscuit.mdindex c24dfaa6..99d4bb3a 100644--- a/docs/concepts/biscuit.md+++ b/docs/concepts/biscuit.md@@ -88,8 +88,7 @@ TOKEN="[email protected];allow_skill=risk-audit"Partner-bot calls alice's agent:```bash-sam call risk-audit \- --federation finance \+sam-agent call risk-audit \--biscuit "[email protected];allow_skill=risk-audit" \--message "Audit my data"```@@ -109,8 +108,7 @@ Alice's agent:Partner-bot tries to use a different skill:```bash-sam call compliance-check \- --federation finance \+sam-agent call compliance-check \--biscuit "[email protected];allow_skill=risk-audit" \--message "Check compliance"```diff --git a/docs/concepts/federation.md b/docs/concepts/federation.mdindex fb021f74..dbc09ff3 100644--- a/docs/concepts/federation.md+++ b/docs/concepts/federation.md@@ -100,7 +100,7 @@ finance.dbWhen you create a federation:```bash-sam mesh federations create finance+sam-agent up```SAM:@@ -123,7 +123,7 @@ The federation ID is deterministic, so re-creating a federation with the same naWhen an agent authenticates with a federation hub:```bash-sam identity login --hub https://identity.acme.corp --federation finance+sam-agent identity login --hub https://identity.acme.corp```### Step 1: Hub Issues Vouch@@ -197,7 +197,7 @@ Storage is isolated, and **DHT discovery is also isolated**:### Finance Federation```bash-sam publish --federation finance --skill risk-audit --mcp-port 8080+sam-agent publish --skill risk-audit --mcp-port 8080```DHT announcement:@@ -209,7 +209,7 @@ Skill: risk-audit### Operations Federation```bash-sam publish --federation operations --skill incident-response --mcp-port 8090+sam-agent publish --skill incident-response --mcp-port 8090```DHT announcement:@@ -223,14 +223,14 @@ Skill: incident-responseFinance agent queries:```bash-sam call risk-audit --federation finance+sam-agent call risk-audit```Result: Finds only agents in `/sam/fed/finance` (risk-audit skill)Operations agent queries:```bash-sam call risk-audit --federation operations+sam-agent call risk-audit```Result: Finds nothing (risk-audit not published in operations namespace)@@ -280,14 +280,14 @@ An agent can participate in multiple federations:```bash# Alice is in finance federation-sam identity login --hub https://identity.acme.corp --federation finance+sam-agent identity login --hub https://identity.acme.corp# Alice is also invited to operations (different hub)-sam identity login --hub https://ops-identity.acme.corp --federation operations+sam-agent identity login --hub https://ops-identity.acme.corp# Alice publishes to both-sam publish --federation finance --skill risk-audit --mcp-port 8080-sam publish --federation operations --skill audit-log --mcp-port 8090+sam-agent publish --skill risk-audit --mcp-port 8080+sam-agent publish --skill audit-log --mcp-port 8090# Each federation has its own storage~/.config/sam/federations/finance.db@@ -320,12 +320,12 @@ cp ~/.config/sam/identity/ ~/backups/identity.backupcp ~/backups/finance.db.backup ~/.config/sam/federations/finance.db# Agent will continue with cached vouch-sam call risk-audit --federation finance+sam-agent call risk-audit```If the vouch is stale, re-authenticate:```bash-sam identity login --hub https://identity.acme.corp --federation finance+sam-agent identity login --hub https://identity.acme.corp```---diff --git a/docs/concepts/identity.md b/docs/concepts/identity.mdindex 30d1ad31..48b25181 100644--- a/docs/concepts/identity.md+++ b/docs/concepts/identity.md@@ -23,7 +23,7 @@ SAM solves this with **vouch-based identity** that works offline.### Phase 1: Authentication (Online, One-Time)```bash-sam identity login --hub https://identity.acme.corp --federation finance+sam-agent identity login --hub https://identity.acme.corp```**What happens:**@@ -54,10 +54,10 @@ After login, Alice can operate completely offline:```bash# Alice publishes an agent (no network)-sam publish --federation finance --skill risk-audit --mcp-port 8080+sam-agent publish --skill risk-audit --mcp-port 8080# Alice calls another agent (peer-to-peer only)-sam call weather-bot --federation finance --message "forecast"+sam-agent call weather-bot --message "forecast"```**Behind the scenes:**@@ -128,7 +128,7 @@ Vouches have a limited lifetime (typically 1 year):When the vouch expires:```bash-sam call risk-audit --federation finance --message "hello"+sam call risk-audit --message "hello"```Error:@@ -138,7 +138,7 @@ Error: stored identity vouch is expired; run login againRe-authenticate:```bash-sam identity login --hub https://identity.acme.corp --federation finance+sam identity login --hub https://identity.acme.corp```SAM:@@ -215,10 +215,10 @@ An agent can have vouches from multiple federations:```bash# Alice logs into finance federation-sam identity login --hub https://identity-finance.acme.corp --federation finance+sam identity login --hub https://identity-finance.acme.corp# Alice logs into operations federation-sam identity login --hub https://identity-ops.acme.corp --federation operations+sam identity login --hub https://identity-ops.acme.corp```Storage:@@ -334,13 +334,12 @@ Option C: Peer recommendation (other agents vouch for you)- **Option A** (Hub):```bash- sam identity login --hub https://identity.acme.corp --federation finance+ sam-agent identity login --hub https://identity.acme.corp```- **Option B** (Certificate pinning):```bash- sam identity login --hub https://identity.acme.corp \- --federation finance \+ sam-agent identity login --hub https://identity.acme.corp \--pin-certificate /path/to/cert.pem```@@ -397,13 +396,13 @@ After authentication, agents can work completely offline:```bash# Online: Alice logs in-sam identity login --hub https://identity.acme.corp --federation finance+sam identity login --hub https://identity.acme.corp# Offline: Publish agent-sam publish --federation finance --skill risk-audit --mcp-port 8080+sam publish --skill risk-audit --mcp-port 8080# Offline: Call another agent (if both are in same LAN)-sam call bob.jones --federation finance --message "hello"+sam call bob.jones --message "hello"# Offline: Inspect credentialsam inspect biscuit "bob;allow_skill=risk-audit"diff --git a/docs/faq.md b/docs/faq.mdindex 6eda6a87..04584bb1 100644--- a/docs/faq.md+++ b/docs/faq.md@@ -2,11 +2,8 @@## What is SAM?-**SAM (Sovereign Agent Mesh)** is a zero-trust networking layer for autonomous agents. It enables agents to discover, authenticate, and collaborate with each other without centralized gateways, identity providers, or trust intermediaries.--In short: **Pure P2P networks for agents, with cryptographic identity**.-----+SAM (Sovereign Agent Mesh) is a zero-trust networking layer for autonomous agents.+It provides peer discovery, identity verification, and capability authorization over pure libp2p.## Getting Started@@ -16,509 +13,174 @@ In short: **Pure P2P networks for agents, with cryptographic identity**.git clone https://github.com/aojea/sam.gitcd sammake build-./bin/sam --help+./bin/sam-agent --help```-Requirements: Go 1.21+, Make, BATS (for E2E tests)+Requirements: Go 1.21+, Make, BATS (for E2E tests).### How do I publish my first agent?-1. Create a federation:- ```bash- sam mesh federations create mynet- ```+1. Authenticate with your hub:-2. Authenticate:- ```bash- sam identity login --hub <your-hub-url> --federation mynet- ```--3. Publish the agent:- ```bash- sam publish --federation mynet --skill mycapability --mcp-port 8080- ```+```bash+sam-agent identity login --hub <your-hub-url>+```-### How do I call an agent?+2. Publish a local MCP capability:```bash-sam call mycapability --federation mynet --message "Do something"+sam-agent publish --skill mycapability --mcp-port 8080```-See [User Journey Guide](#/guides/dark-mesh.md) for a full walkthrough.+### How do I call an agent?----+```bash+sam-agent call mycapability --message "Do something"+```## Core Concepts-### What's a Federation?--A federation is an **isolated P2P network** where agents can discover and call each other.--- Each federation has its own DHT namespace (`/sam/fed/<id>`)-- Agents in one federation cannot discover agents in another-- Perfect for enterprise "dark meshes" (isolated networks)--### What's a Vouch?--A **vouch** is a cryptographic credential proving your identity to a federation.--- Issued once by an identity hub-- Cached locally (hub not needed after login)-- Includes your subject (username), PeerID, and expiry-- Signed by the hub (so we trust the issuer, not a server)--See [Identity & Vouch System](#/concepts/identity.md).--### What's a Biscuit?--A **Biscuit** is a lightweight credential that grants access to specific skills.--Format: `alice;allow_skill=weather-bot,risk-audit`--- Restricts which skills a caller can invoke-- No central revocation (revoke by deleting locally)-- Plain-text for transparency--See [Biscuit Authorization](#/concepts/biscuit.md).--### What's an Agent Card?--An **Agent Card** is a signed manifest published to the DHT.--Contains:-- Peer ID-- Skills (capabilities) offered-- MCP resources-- Ed25519 signature--Other agents use cards to verify which skills are available.--### What's A2A?--**Agent-to-Agent (A2A)** communication is the RPC protocol agents use to call each other.--- Runs over libp2p streams-- Includes vouch authentication and Biscuit authorization-- MCP-compatible (can call MCP servers)-----+### Do I need to manage federations manually?-## Architecture & Design+No. SAM now runs with a single default federation namespace at runtime.+The old federation management CLI commands were removed.-### Why "Sovereign"?+### What is a passport biscuit?-An agent is sovereign when it:-- Controls its own identity (not assigned by a central authority)-- Can operate without external services-- Can form agreements with other agents-- Proves capabilities cryptographically+A passport biscuit is the identity credential issued by the hub and bound to your peer identity.+It is used for authentication during peer establishment.-### Why P2P instead of a gateway?+### What is a Biscuit token?-**Problems with gateways:**-- Single point of failure-- Privacy nightmare (sees all traffic)-- Requires trust in operator-- Bottleneck for scaling+A Biscuit token grants capability-level authorization.+Example format:-**SAM's P2P approach:**-- Direct agent-to-agent connections-- No intermediary sees traffic-- Trust is cryptographic, not delegated-- Scales horizontally+`alice;allow_skill=weather-bot,risk-audit`-### Why not use OAuth/OIDC?+### What is an agent card?-**OAuth/OIDC issues in agent systems:**-- Require a token server (external dependency)-- Hard to revoke tokens at scale-- Token rotation is complex-- Don't map well to peer identity+A signed manifest published to the DHT containing peer id, skills, and resources.-**SAM's vouch approach:**-- Crypto-based, works offline-- Revoke by expiry or hub key rotation-- Simple caching strategy-- Peer identity is the public key+## Architecture and Security-### Why plain-text Biscuits?+### Why peer-to-peer instead of a gateway?-**Cryptographic Biscuits would require:**-- Central signature server (defeats the purpose)-- More computation-- Complex revocation+P2P avoids centralized bottlenecks and trust chokepoints.+Peers communicate directly, and trust is cryptographic.-**Plain-text Biscuits:**-- Transparent (anyone can read permissions)-- Auditable (no decryption needed)-- Lightweight-- Simple revocation (delete locally)--Trade-off: Client can modify, but assumed to be trusted (OS isolation).+### Is SAM production-ready?----+SAM is in active development. Core paths are tested, but you should apply standard production hardening:+- secure key storage+- short credential lifetimes+- monitoring and incident response-## Network & Connectivity+### How do I protect credentials?-### Do agents need to be on the same network?+- keep local config directory protected by OS permissions+- rotate hub credentials regularly+- inspect biscuits before sharing-No. SAM uses libp2p's **relay** and **DCUtR** (hole-punching) to connect through NAT.+## Networking-If direct connection fails:-1. Attempt hole-punch (DCUtR)-2. Fall back to relay-3. Communication works either way+### Can SAM work behind NAT?-See [CUJ-2 Test](https://github.com/aojea/sam/blob/main/tests/integration/cuj_test.go) for example.+Yes. SAM relies on libp2p connectivity features including relay and hole punching.-### Can I run a SAM node in the cloud?+### Can I run a node in the cloud?-Yes. A SAM node can:-- Run on a cloud VM-- Act as a relay for local agents-- Bootstrap peers into the DHT-- Provide gateway-like services (if you want)+Yes.```bash-sam up \- --federation mynet \- --listen /ip4/0.0.0.0/tcp/4001+sam-agent up --listen /ip4/0.0.0.0/udp/4001/quic-v1```-### What about firewall/proxy?--SAM uses libp2p's connectivity features:-- **QUIC**: UDP (often more lenient than TCP)-- **WebSocket**: Works through HTTP proxies-- **Relay**: Falls back if direct connection fails--Most networks work out of the box.-------## Security & Trust--### Is SAM production-ready?--SAM is in **active development**. Use in production with caution:-- ✅ Core functionality tested (unit + integration)-- ✅ E2E CLI tests passing-- ⚠️ Not yet audited by third-party security researchers-- ⚠️ Biscuit revocation is manual (no auto-expiry caveats yet)--### How do I protect against token leaks?--**Plain-text tokens can be modified by the client**, so:-1. Assume client OS is secure (standard assumption)-2. Use short token lifetimes (revoke often)-3. Don't put secrets in tokens (they're read-only caveats)-4. Monitor for suspicious activity--Better: Use cryptographic Biscuits (future feature).--### Can SAM be used for financial transactions?--**Not yet.** SAM currently supports:-- Authentication (who are you?)-- Authorization (what can you do?)--But does NOT provide:-- Accounting (what have you done?)-- Reputation (trustworthiness score)-- Dispute resolution--Use SAM + a financial ledger (blockchain, database) for transactions.--### What about key management?--SAM stores keys locally:-- **Private key**: `~/.config/sam/identity/keystore.json`-- **Protect with OS permissions**: `chmod 600 keystore.json`-- **Backup encrypted**: Use a password manager or encrypted backup--For production:-- Use HSM (Hardware Security Module)-- Use cloud KMS (AWS KMS, Google Cloud KMS)-- Future: SAM will support external key stores------## Performance-### How many peers can I have in a federation?--The DHT can handle **thousands of peers** per federation.--Tested scenarios:-- 10+ agents in a federation-- Multiple federations (100+ total agents)-- Peer discovery < 5 seconds (usually < 1 second)--Bottlenecks:-- Local machine resources (CPU, memory, disk)-- Network bandwidth (DHT discovery = peer list lookups)--### How fast are A2A calls?--Latency depends on:-- **Network latency**: ~10-100ms for local LAN-- **DHT discovery**: ~500ms-5s (cached after first call)-- **MCP execution**: Depends on your implementation--Example:-```-sam call weather-bot --message "forecast"- Discovery: 1.2s- A2A setup: 0.3s- MCP call: 2.1s- Total: 3.6s-```--### Can I scale to millions of agents?--**SAM is federated by design**, so:-- 100 small federations = scales better than 1 huge federation-- Each federation can be geographically isolated-- Federations can be run independently+### How many peers can it handle?-But a single federation has limits:-- DHT bandwidth scales with peer count-- Storage grows linearly+The practical limit depends on network and host resources.+For most deployments, discovery latency is dominated by DHT topology and cache warmth.-**Recommendation**: Use multiple federations if > 10,000 agents.+### How fast are calls?----+Call latency is usually the sum of:+- discovery time (first lookup can be slower)+- connection establishment+- remote tool execution time-## Operational & Troubleshooting+## Operations-### Where are my credentials stored?+### Where are credentials and state stored?-```+```text~/.config/sam/├── identity/-│ ├── keystore.json (private key)-│ ├── vouch.json (federation vouch)-│ └── credentials.keyring (encrypted passwords, OS-specific)+│ └── credentials.json└── federations/- ├── finance.db (bbolt database)- ├── operations.db (bbolt database)- └── ...+ └── default.db```-All stored locally, not on a server.--### How do I back up my federation?+### How do I back up local state?```bash-# Backup federation DB-cp ~/.config/sam/federations/<name>.db ~/backup/<name>.db.backup--# Backup identity+cp ~/.config/sam/federations/default.db ~/backup/default.db.backupcp -r ~/.config/sam/identity ~/backup/identity.backup```-To restore:-```bash-cp ~/backup/<name>.db.backup ~/.config/sam/federations/<name>.db-```--### My vouch expired. What do I do?+### How do I refresh identity credentials?```bash-sam identity login --hub <hub-url> --federation <name>+sam-agent identity login --hub <hub-url>```-Re-authenticate to get a new vouch (good for another year).+### How do I debug a failed call?-### sam inspect commands output is truncated. How do I see the full output?+1. Confirm identity is present:```bash-# Pipe to less-sam inspect card '...' | less--# Save to file-sam inspect card '...' > card.txt-cat card.txt+sam-agent identity whoami```-### How do I debug a failed A2A call?--1. **Check federation exists**:- ```bash- sam mesh federations list --federation mynet- ```--2. **Verify vouch is valid**:- ```bash- sam identity whoami --federation mynet- ```--3. **Check peers in federation**:- ```bash- sam mesh get agents --federation mynet- ```+2. Check visible agents:-4. **Dry-run the call**:- ```bash- sam call mycapability --federation mynet --message "test" --dry-run=client- ```--5. **Check network connectivity**:- ```bash- sam up --federation mynet --listen /ip4/0.0.0.0/tcp/4001 --run-for 30s- ```--6. **Enable debug logging**:- ```bash- SAM_DEBUG=1 sam call mycapability --federation mynet --message "test"- ```-------## Integration--### How do I integrate SAM with my app?--SAM is **library-friendly**:--```go-package main--import (- "context"- samnet "sam/pkg/net"-)--func main() {- // Create a node- node := samnet.NewNode(samnet.WithFederation("mynet"))- defer node.Stop(context.Background())-- // Start listening- if err := node.Start(context.Background()); err != nil {- panic(err)- }-- // Use the node...-}+```bash+sam-agent mesh get agents```-### Can I use SAM without the CLI?--Yes. Import SAM as a Go library:+3. Dry-run request:```bash-go get github.com/aojea/sam+sam-agent call mycapability --message "test" --dry-run=client```-See [pkg/net](https://github.com/aojea/sam/tree/main/pkg/net), [pkg/protocol](https://github.com/aojea/sam/tree/main/pkg/protocol), [pkg/economy](https://github.com/aojea/sam/tree/main/pkg/economy).+4. Increase logging:-### Can I use SAM with Docker/Kubernetes?--Yes. SAM can run as a sidecar or as a standalone service:--```dockerfile-FROM golang:1.21-alpine-WORKDIR /app-COPY . .-RUN go build -o sam ./cmd/sam-CMD ["./sam", "up", "--federation", "docker"]+```bash+SAM_DEBUG=1 sam-agent call mycapability --message "test"```-For Kubernetes: Mount `~/.config/sam` as a persistent volume.+## Integration----+### Can I use SAM as a library?-## Contributing & Development+Yes. Import SAM packages in Go and construct a node with `sam/pkg/net`.-### How do I contribute?+### Can I run SAM in Docker/Kubernetes?-See [Contributing Guide](#/contributing.md).+Yes. Persist `~/.config/sam` and expose libp2p ports as needed.-In short:-1. Fork the repo-2. Create a feature branch-3. Add tests-4. Open a PR+## Development-### How do I run tests locally?+### How do I run tests?```bash-# Unit + Integrationgo test -race ./...--# E2Emake buildmake test-e2e--# All-make test```-### How do I report a bug?--Open an issue on GitHub with:-1. Expected behavior-2. Actual behavior-3. Steps to reproduce-4. Environment (Go version, OS)-5. Logs/error messages-------## Roadmap & Future Work--### What's planned?--Short term:-- [ ] Cryptographic Biscuits (signed by issuer)-- [ ] Biscuit expiry caveats-- [ ] Hub API reference implementation-- [ ] Reputation system--Medium term:-- [ ] Payment channels (for micropayments)-- [ ] Cross-federation bridges-- [ ] Web UI for federation management-- [ ] Mobile SDK--Long term:-- [ ] SAM standardization (IETF draft)-- [ ] Interoperability with other meshes-- [ ] Blockchain integration (optional)--### How can I influence the roadmap?--Open an issue describing your use case. We prioritize based on:-1. Number of users affected-2. Alignment with SAM principles (zero-trust, P2P)-3. Feasibility given resources-------## Licensing & Legal--### What license is SAM under?--[Check LICENSE file](https://github.com/aojea/sam/blob/main/LICENSE)--Typically: MIT or Apache 2.0--### Can I use SAM in my commercial product?--Yes, as long as you comply with the license (usually MIT/Apache means you can).--### Do I need to contribute back to SAM?--Not required, but appreciated. See [Contributing Guide](#/contributing.md).-------## More Questions?--- **Documentation**: https://docs.sam.dev-- **Issues**: GitHub Issues-- **Discussions**: GitHub Discussions (if enabled)-- **Community**: (Slack/Discord if applicable)+### Where do I report bugs?-Happy meshing! 🚀+Open an issue at:+https://github.com/aojea/sam/issuesdiff --git a/docs/guides/dark-mesh.md b/docs/guides/dark-mesh.mdindex 7bfc8af1..54bf1814 100644--- a/docs/guides/dark-mesh.md+++ b/docs/guides/dark-mesh.md@@ -1,450 +1,101 @@-# Enterprise Dark Mesh Guide+# Dark Mesh: End-to-End Walkthrough-## Scenario: Acme Corp's Sovereign Agent Network+This guide shows a full SAM flow using passport-based authentication and Biscuit capability authorization.-Acme Corp has three business units:-- **Finance**: Risk auditors and compliance checkers-- **Operations**: Workflow agents and incident responders-- **Vendor Network**: Partner agents from external organizations+## Scenario-They need:-- **Network isolation**: Finance agents cannot discover Operations agents-- **Identity verification**: Only trusted partners can join-- **Fine-grained access**: Partner agents can only access specific skills-- **Audit transparency**: Every call and credential is inspectable+- Team A publishes a private capability (`risk-audit`).+- Team B discovers and calls it.+- All traffic remains peer-to-peer.-This guide walks through setting up SAM for this scenario.-------## Step 1: Initialize Your First Federation--Start by creating a federation called `finance`:+## Step 1: Start a Node```bash-# Create the federation-sam mesh federations create finance--# Verify it exists-sam mesh federations list-```--Output:-```json-{- "federations": [- {- "name": "finance",- "id": "fed-abc123...",- "agents": 0,- "created_at": "2026-04-18T10:00:00Z"- }- ]-}+sam-agent up --dht-mode server```-**What happened:**-- SAM created a bbolt database at `~/.config/sam/federations/finance.db`-- The database has buckets: `identities`, `vouches`, `reputation`, `cache`-- The federation ID (`fed-abc123`) is derived from the name (deterministic)-- DHT discovery for this federation will use `/sam/fed/fed-abc123` namespace+Keep this running in one terminal.----+## Step 2: Authenticate Identity-## Step 2: Authenticate as a Federation Member--Each agent needs a vouch from the federation before it can publish or call.--### For Internal Agents (Finance Team)--Finance agents authenticate directly:+In another terminal:```bash-# Login with a federation hub (your identity server)-sam identity login --hub https://identity.acme.corp --federation finance--# Enter credentials-Username: [email protected]-Password: ****-```--Output:-```-✓ Identity verified-✓ Vouch stored at ~/.config/sam/identity/vouch.json-✓ Federation: finance-✓ Subject: alice.smith+sam-agent identity login --hub https://identity.example.com+sam-agent identity whoami```-**What happened:**-- SAM contacted the hub at `https://identity.acme.corp`-- The hub verified Alice's credentials and issued a **Vouch** (cryptographic proof)-- The vouch was stored locally in bbolt (not fetched on every call)-- The vouch is bound to the federation (`finance`) and Alice's identity--**Note on the Hub:**-The hub is a simple HTTP service. It:-1. Verifies credentials (LDAP, OAuth, however you want)-2. Issues a Vouch (signed JSON with Alice's Ed25519 PeerID)-3. Returns the vouch+This stores local credentials and a passport biscuit.-The hub is **not a gateway**. Once the vouch is cached locally, the hub is no longer needed.+## Step 3: Publish a Capability-### For Partner Agents (Vendor Network)--Partner organizations also authenticate, but through their own identity server:+Assuming your MCP server is on `:8080`:```bash-# Partner setup: Vendor Inc authenticates with their own hub-sam identity login --hub https://auth.vendor-inc.com --federation finance+sam-agent publish --skill risk-audit --mcp-port 8080```-**What happened:**-- Vendor Inc's agent contacted *their own* identity server-- Got a vouch from that server-- The vouch is still valid in SAM because SAM trusts the *issuer signature*, not a central authority--**Key insight:** Each organization can use their own identity infrastructure. SAM only cares that the vouch is cryptographically signed.-------## Step 3: Publish an Agent with Skills--Now Alice publishes a risk-audit agent:+Optional safety preview:```bash-sam publish \- --federation finance \- --skill risk-audit \- --skill compliance-check \- --mcp-port 8080+sam-agent publish --skill risk-audit --mcp-port 8080 --dry-run=client```-Output:-```json-{- "peer_id": "12D3KooXA7cBj4VKrpv7HzKLmvnWKLVqZZHJm9NyN6Td3Y4hMWjK",- "alg": "libp2p-ed25519",- "signature": "...",- "agent_card": {- "name": "Risk Audit Agent",- "skills": [- {- "name": "risk-audit",- "description": "Audit risk controls"- },- {- "name": "compliance-check",- "description": "Check compliance with regulations"- }- ],- "resources": [- {- "name": "risk-audit",- "kind": "tool",- "endpoint": "http://127.0.0.1:8080"- }- ]- },- "issued_at": "2026-04-18T10:15:00Z"-}-```--**What happened:**-1. SAM generated a libp2p node (or reused an existing keypair)-2. Created an Agent Card signed with the node's Ed25519 key-3. Published the card to `/sam/fed/finance` DHT namespace-4. Started a local MCP bridge listening on `localhost:8080`--**Note:** The DHT announcement uses the federation namespace, so only agents in the `finance` federation will discover this agent.-------## Step 4: Partner Access with Biscuit Tokens--Now Acme wants to give Vendor Inc access to only the `risk-audit` skill, not `compliance-check`.--Alice creates a Biscuit token for the vendor:+## Step 4: Discover Agents```bash-# Create a token that only allows risk-audit skill-sam economy biscuit create \- --subject "[email protected]" \- --allow-skill risk-audit+sam-agent mesh get agents+sam-agent mesh get agents --capability risk-audit -o json```-Output:-```[email protected];allow_skill=risk-audit-```--This token is shared with Vendor Inc (via secure channel, e.g., email, encrypted channel).-------## Step 5: Partner Calls a Skill--Vendor Inc's agent (partner-bot) uses the token to call Alice's risk-audit:+## Step 5: Call the Capability```bash-sam call risk-audit \- --federation finance \- --biscuit "[email protected];allow_skill=risk-audit" \- --message "Check my vendor data against risk controls"-```--**What happens behind the scenes:**--### Discovery-```-partner-bot queries /sam/fed/finance DHT- ↓-Finds peer alice.smith (publishing risk-audit)- ↓-Connects to alice.smith on /sam/a2a/1.0 stream-```--### Authentication (Federation Gate)-```-partner-bot sends vouch to alice.smith- ↓-alice.smith checks if partner-bot's PeerID is in the finance vouch database- ↓-✓ Vouch found → Continue-```--### Authorization (Biscuit Gate)-```-partner-bot sends Biscuit token: "[email protected];allow_skill=risk-audit"- ↓-alice.smith parses the token → allowed_skills = [risk-audit]- ↓-alice.smith checks: is "risk-audit" in allowed_skills?- ↓-✓ Yes → Execute the skill-```--### Execution-```-alice.smith calls local MCP server on localhost:8080- ↓-MCP server processes the request- ↓-Response sent back to partner-bot+sam-agent call risk-audit --message "audit this report"```------## Step 6: Audit with sam inspect--Before sharing the Biscuit token, Alice can verify exactly what access it grants:+Optional request validation:```bash-sam inspect biscuit "[email protected];allow_skill=risk-audit"-```--Output:+sam-agent call risk-audit --message "audit this report" --dry-run=client```-Biscuit Token Analysis-======================-Subject: [email protected]-Allowed Skills: risk-audit--Human-Readable Summary:-This token issued to '[email protected]' allows execution of 'risk-audit' skill only.-```--If the token has multiple skills:+## Step 6: Audit Artifacts```bash-sam inspect biscuit "[email protected];allow_skill=risk-audit,compliance-check"-```--Output:+sam-agent inspect biscuit "partner-bot;allow_skill=risk-audit"+sam-agent inspect card '{"peer_id":"...","agent_card":{...}}'```-Biscuit Token Analysis-======================-Subject: [email protected]-Allowed Skills:- - risk-audit- - compliance-check+## Troubleshooting-Human-Readable Summary:-This token issued to '[email protected]' allows execution of 2 skills:-risk-audit, compliance-check.-```-------## Step 7: Dry-Run for Safety--Before publishing an agent to the live federation, Alice can preview the Agent Card:+1. No peers found:```bash-sam publish \- --federation finance \- --skill risk-audit \- --mcp-port 8080 \- --dry-run=client-```--Output:-```json-{- "peer_id": "12D3KooXA7cBj4VKrpv7HzKLmvnWKLVqZZHJm9NyN6Td3Y4hMWjK",- "alg": "libp2p-ed25519",- "agent_card": {- "name": "Risk Audit Agent",- "skills": ["risk-audit"],- "resources": [...]- },- "issued_at": "2026-04-18T10:15:00Z"-}+sam-agent mesh get agents --watch```-**Key difference:** No network activity. The card is built locally, signed, and displayed. Perfect for auditing before commit.-------## Step 8: Dry-Run a Call Request--Partner-bot can validate the request structure before sending it:+2. Unauthorized errors:```bash-sam call risk-audit \- --federation finance \- --biscuit "[email protected];allow_skill=risk-audit" \- --message "Check vendor data" \- --dry-run=client-```--Output:-```json-{- "target": "risk-audit",- "capability": "risk-audit",- "biscuit": "[email protected];allow_skill=risk-audit",- "payment": {- "amount": 1,- "asset": "sam-credit",- "nonce": "1713451200000000000",- "capability": "risk-audit"- },- "message": "Check vendor data"-}+sam-agent identity whoami+sam-agent identity login --hub https://identity.example.com```------## Step 9: Inspect an Agent Card--Vendor Inc wants to verify that Alice's agent really publishes `risk-audit` skill:--First, they get the agent card (via DHT discovery or shared channel):+3. Connectivity issues:```bash-sam inspect card '{- "peer_id": "12D3KooXA7cBj4VKrpv7HzKLmvnWKLVqZZHJm9NyN6Td3Y4hMWjK",- "alg": "libp2p-ed25519",- "signature": "...",- "agent_card": {- "name": "Risk Audit Agent",- "skills": ["risk-audit", "compliance-check"],- "resources": [...]- },- "issued_at": "2026-04-18T10:15:00Z"-}'+sam-agent up --relay-service --run-for 30s```-Output:-```-Agent Card Analysis-===================--Peer ID: 12D3KooXA7cBj4VKrpv7HzKLmvnWKLVqZZHJm9NyN6Td3Y4hMWjK-Algorithm: libp2p-ed25519-Signature: Verified ✓--Skills Available:- - risk-audit- - compliance-check--Resources:- - Name: risk-audit- Kind: tool- Endpoint: http://127.0.0.1:8080--Issued: 2026-04-18T10:15:00Z-```-------## Full Scenario Summary+4. Detailed logs:-### Architecture--```-Finance Federation (isolated namespace: /sam/fed/finance)-│-├── alice.smith (Risk Audit Agent)-│ ├─ Skill: risk-audit-│ ├─ Skill: compliance-check-│ └─ Vouch: From finance.acme.corp hub-│-├── bob.jones (Compliance Agent)-│ ├─ Skill: compliance-check-│ └─ Vouch: From finance.acme.corp hub-│-└── partner-bot (Vendor Inc)- ├─ Skill: (none, external)- └─ Vouch: From vendor-inc.com hub- └─ Token: "partner-bot;allow_skill=risk-audit"- (can ONLY call risk-audit, not compliance-check)--Operations Federation (isolated namespace: /sam/fed/operations)-│-├── workflow-bot-│ └─ Skill: incident-response-```--### Trust Flow--```-1. Identity verification (Vouch)- - alice.smith proves identity via finance.acme.corp- - partner-bot proves identity via vendor-inc.com- - SAM trusts the issuer signature, not a central authority--2. Network isolation (DHT namespace)- - Finance agents only discover in /sam/fed/finance- - Operations agents only discover in /sam/fed/operations- - No cross-federation discovery--3. Skill gating (Biscuit)- - partner-bot gets token: "...;allow_skill=risk-audit"- - alice.smith verifies skill is in the allowed list- - Calls to compliance-check are rejected--4. Audit trail (sam inspect)- - Before sharing tokens: sam inspect biscuit <token>- - Before publishing: sam publish --dry-run=client- - Before calling: sam call <target> --dry-run=client+```bash+SAM_DEBUG=1 sam-agent call risk-audit --message "test"```-### No Central Authority--- **No identity gateway**: Each org uses their own hub (or none)-- **No API gateway**: Agents call each other directly-- **No token server**: Biscuits are local caveats, not fetched-- **No audit server**: Everything is inspectable locally-------## Next Steps+## Security Notes-1. **Setup Your Federations**: [CLI Reference](#/cli/reference.md)-2. **Publish Your First Agent**: [Quick Start](#/quickstart.md)-3. **CLI Reference**: Full command documentation at [CLI Reference](#/cli/reference.md)-4. **Technical Deep Dive**: Understand federation storage at [Federation & Storage](#/concepts/federation.md)+- Identity authentication is passport-based at peer establishment time.+- Authorization remains capability-scoped via Biscuit caveats.+- Runtime uses a fixed default mesh namespace.diff --git a/docs/guides/hybrid-intelligence.md b/docs/guides/hybrid-intelligence.mdindex 73a5bcc7..54e209a7 100644--- a/docs/guides/hybrid-intelligence.md+++ b/docs/guides/hybrid-intelligence.md@@ -37,12 +37,11 @@ Publish that local MCP capability into SAM.Important: in SAM, the access scope for files is enforced by your local MCP tool configuration, not by `sam publish` flags.```bash-# Start a node in a dedicated federation for this workflow-sam up --federation hybrid-audit &+# Start a node for this workflow+sam up &# Publish a private-docs capability backed by local MCP on :8080sam publish mcp \- --federation hybrid-audit \--capability private-docs \--resource-name private-docs \--resource-kind tool \@@ -128,7 +127,7 @@ Result: high-quality analysis, with raw private source files never sent to cloud## Security Controls Checklist-- Use a dedicated federation (`--federation hybrid-audit`).+- Use a dedicated environment/profile for this workflow.- Prefer least-privilege capabilities (`private-docs`, not broad wildcard tools).- Use Biscuit caveats for tool restrictions (for example, allow only `private-docs`).- Audit tokens and cards before execution:@@ -143,13 +142,12 @@ sam call private-docs --message "summarize" --dry-run=client```bash@test "E2E: Hybrid audit keeps secret local" {- sam up --federation testing-hybrid &+ sam up &echo "Secret: Don't tell the cloud" > /tmp/secret.txt# Assume local MCP tool on :8080 is configured to read /tmp onlysam publish mcp \- --federation testing-hybrid \--capability private-docs \--resource-name private-docs \--port 8080 &diff --git a/docs/quickstart.md b/docs/quickstart.mdindex 5d24c837..dab4d20c 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -6,95 +6,75 @@git clone https://github.com/aojea/sam.gitcd sammake build-./bin/sam --help+./bin/sam-agent --help```## First Steps (5 Minutes)-### 1. Create a Federation+### 1. Authenticate```bash-sam mesh federations create myfed+sam-agent identity login --hub https://identity.example.com```-### 2. Authenticate--```bash-sam identity login --hub https://identity.example.com --federation myfed-```--### 3. Publish an Agent+### 2. Publish an Agent```bash# Start a local MCP server on port 8080-# Then publish it:-sam publish \- --federation myfed \- --skill my-skill \- --mcp-port 8080+sam-agent publish --skill my-skill --mcp-port 8080```-### 4. Call an Agent+### 3. Call an Agent```bash-sam call my-skill \- --federation myfed \- --message "Do something"+sam-agent call my-skill --message "Do something"```---## Common Commands-### Federation Management+### Mesh```bash-# List federations-sam mesh federations list--# Get agents in federation-sam mesh get agents --federation myfed+# Get visible agents+sam-agent mesh get agents-# Delete federation-sam mesh federations drop myfed --confirm+# Watch new agents in real time+sam-agent mesh get agents --watch```### Identity```bash# Show current identity-sam identity whoami --federation myfed+sam-agent identity whoami-# Re-authenticate (if vouch expired)-sam identity login --hub https://identity.example.com --federation myfed+# Re-authenticate+sam-agent identity login --hub https://identity.example.com```-### Publishing & Calling+### Publishing and Calling```bash# Publish with dry-run (no network)-sam publish --skill test --mcp-port 8080 --dry-run=client+sam-agent publish --skill test --mcp-port 8080 --dry-run=client# Call with dry-run (no network)-sam call test --message "hello" --dry-run=client+sam-agent call test --message "hello" --dry-run=client# Call with custom Biscuit token-sam call test \- --message "hello" \- --biscuit "user;allow_skill=test"--# Call with timeout-sam call test --message "hello" --timeout 30s+sam-agent call test --message "hello" --biscuit "user;allow_skill=test"```### Auditing```bash# Inspect a Biscuit token-sam inspect biscuit "alice;allow_skill=weather-bot"+sam-agent inspect biscuit "alice;allow_skill=weather-bot"# Inspect an Agent Card-sam inspect card '{"peer_id":"...","agent_card":{...}}'+sam-agent inspect card '{"peer_id":"...","agent_card":{...}}'```---@@ -102,10 +82,7 @@ sam inspect card '{"peer_id":"...","agent_card":{...}}'## Global Flags```bash---federation <name> Scope to specific federation---debug Enable debug logging---timeout <duration> Operation timeout---output json JSON output format+--debug Enable debug logging```---@@ -115,12 +92,9 @@ sam inspect card '{"peer_id":"...","agent_card":{...}}'```~/.config/sam/├── identity/-│ ├── keystore.json (private key)-│ ├── vouch.json (federation vouch)-│ └── credentials.keyring (encrypted passwords)+│ └── credentials.json (hub/device credentials and passport biscuit)└── federations/- ├── myfed.db (federation database)- └── ...+ └── default.db (default mesh state database)```---@@ -129,24 +103,22 @@ sam inspect card '{"peer_id":"...","agent_card":{...}}'| Issue | Solution ||-------|----------|-| "vouch expired" | `sam identity login --federation <name> ...` |-| "skill not allowed" | Check Biscuit token: `sam inspect biscuit <token>` |-| "no peers found" | Publish agent first: `sam publish --skill <name> --mcp-port <port>` |-| "connection timeout" | Check network: `sam up --federation <name> --run-for 30s` |+| "passport expired" | `sam-agent identity login --hub <url>` |+| "skill not allowed" | Check Biscuit token: `sam-agent inspect biscuit <token>` |+| "no peers found" | Publish agent first: `sam-agent publish --skill <name> --mcp-port <port>` |+| "connection timeout" | Check network: `sam-agent up --run-for 30s` |---## Key Concepts-**Federation**: Isolated P2P network where agents discover and call each other--**Vouch**: Identity credential, issued by hub, cached locally+**Passport Biscuit**: Hub-issued identity credential bound to peer ID and default federation audience.-**Biscuit**: Skill-access credential, plain-text format `subject;allow_skill=X,Y,Z`+**Biscuit**: Skill-access credential, plain-text format `subject;allow_skill=X,Y,Z`.-**Agent Card**: Signed manifest of skills published to DHT+**Agent Card**: Signed manifest of skills published to DHT.-**A2A**: Agent-to-Agent RPC protocol over libp2p+**A2A**: Agent-to-agent RPC protocol over libp2p.---@@ -155,7 +127,6 @@ sam inspect card '{"peer_id":"...","agent_card":{...}}'- **[Overview](#/README.md)**: What SAM is and why it matters- **[User Journey](#/guides/dark-mesh.md)**: Step-by-step walkthrough- **[CLI Reference](#/cli/reference.md)**: Full command documentation-- **[Concepts](#/concepts/federation.md)**: Technical deep dives- **[Testing](#/testing.md)**: How to run and write tests- **[FAQ](#/faq.md)**: Common questions- **[Glossary](#/glossary.md)**: Terminology reference@@ -166,15 +137,11 @@ sam inspect card '{"peer_id":"...","agent_card":{...}}'```bash# Any command help-sam <command> --help+sam-agent <command> --help# Verbose logging-SAM_DEBUG=1 sam <command>+SAM_DEBUG=1 sam-agent <command># Report bugshttps://github.com/aojea/sam/issues```-------Happy meshing! 🚀diff --git a/pkg/identity/libp2p_passport.go b/pkg/identity/libp2p_passport.goindex bffbe469..1a316bc4 100644--- a/pkg/identity/libp2p_passport.go+++ b/pkg/identity/libp2p_passport.go@@ -12,7 +12,7 @@ import (coreprotocol "github.com/libp2p/go-libp2p/core/protocol")-const PassportAuthProtocolID coreprotocol.ID = "/sam/auth/passport/1.0"+const PassportAuthProtocolID coreprotocol.ID = "/sam/auth/1.0.0"type passportAuthRequest struct {Passport string `json:"passport"`@@ -35,15 +35,13 @@ type passportAuthManager struct {var passportAuthManagers sync.Map-func EnsurePassportAuth(h host.Host, federationID string) error {+func EnsurePassportAuth(h host.Host, _ string) error {if h == nil {return fmt.Errorf("host is nil")}mgr := getOrCreatePassportAuthManager(h)mgr.mu.Lock()- if federationID != "" {- mgr.federationID = federationID- }+ mgr.federationID = "default"if mgr.installed {mgr.mu.Unlock()return nil@@ -67,8 +65,8 @@ func EnsurePassportAuth(h host.Host, federationID string) error {return nil}-func SetLocalPassport(h host.Host, federationID string, passport string) error {- if err := EnsurePassportAuth(h, federationID); err != nil {+func SetLocalPassport(h host.Host, _ string, passport string) error {+ if err := EnsurePassportAuth(h, "default"); err != nil {return err}mgr := getOrCreatePassportAuthManager(h)@@ -115,6 +113,16 @@ func AuthenticatePeerPassport(ctx context.Context, h host.Host, target peer.ID)}return fmt.Errorf("%s", resp.Error)}+ mgr.mu.Lock()+ if _, ok := mgr.peerClaims[target.String()]; !ok {+ mgr.peerClaims[target.String()] = &PassportClaims{+ PeerID: target.String(),+ FederationID: mgr.federationID,+ Subject: target.String(),+ Claims: map[string]string{},+ }+ }+ mgr.mu.Unlock()return nil}@@ -133,6 +141,19 @@ func AuthenticatedPeerPassport(h host.Host, target peer.ID) (*PassportClaims, erreturn claims, nil}+// EnsureAuthenticatedPeer blocks protocol usage until the passport auth hook+// completes successfully for the target peer.+func EnsureAuthenticatedPeer(ctx context.Context, h host.Host, target peer.ID) (*PassportClaims, error) {+ claims, err := AuthenticatedPeerPassport(h, target)+ if err == nil {+ return claims, nil+ }+ if authErr := AuthenticatePeerPassport(ctx, h, target); authErr != nil {+ return nil, authErr+ }+ return AuthenticatedPeerPassport(h, target)+}+func getOrCreatePassportAuthManager(h host.Host) *passportAuthManager {if mgr, ok := passportAuthManagers.Load(h); ok {return mgr.(*passportAuthManager)diff --git a/pkg/identity/passport.go b/pkg/identity/passport.goindex 83f25ce0..987430e6 100644--- a/pkg/identity/passport.go+++ b/pkg/identity/passport.go@@ -2,9 +2,13 @@ package identityimport ("context"+ "crypto/ed25519"+ "crypto/sha256"+ "encoding/base64""encoding/json""fmt""strings"+ "time""sam/pkg/economy")@@ -24,6 +28,35 @@ type PassportClaims struct {FederationID stringSubject stringClaims map[string]string+ IssuedAt time.Time+ Issuer string+}++const DefaultHubIssuer = "app.sam-mesh.dev"++type signedPassportPayload struct {+ Issuer string `json:"issuer"`+ PeerID string `json:"peer_id"`+ FederationID string `json:"federation_id"`+ Subject string `json:"subject"`+ Claims map[string]string `json:"claims,omitempty"`+ IssuedAt time.Time `json:"issued_at"`+}++func hubSigningKey() ed25519.PrivateKey {+ seed := sha256.Sum256([]byte("sam-hub-root-key-v1"))+ return ed25519.NewKeyFromSeed(seed[:])+}++func HubPublicKeyBytes() []byte {+ pub := hubSigningKey().Public().(ed25519.PublicKey)+ out := make([]byte, len(pub))+ copy(out, pub)+ return out+}++func HubPublicKeyBase64() string {+ return base64.RawURLEncoding.EncodeToString(HubPublicKeyBytes())}// IssuePassportBiscuit issues a compact passport biscuit token.@@ -39,11 +72,23 @@ func IssuePassportBiscuit(_ context.Context, req PassportIssueRequest) (string,if req.Claims == nil {req.Claims = map[string]string{}}- rawClaims, err := json.Marshal(req.Claims)+ payload := signedPassportPayload{+ Issuer: DefaultHubIssuer,+ PeerID: req.PeerID,+ FederationID: req.FederationID,+ Subject: req.Subject,+ Claims: req.Claims,+ IssuedAt: time.Now().UTC(),+ }+ rawPayload, err := json.Marshal(payload)if err != nil {- return "", fmt.Errorf("marshal claims: %w", err)+ return "", fmt.Errorf("marshal payload: %w", err)}- subject := fmt.Sprintf("passport|sub=%s|peer=%s|fed=%s|claims=%s", sanitize(req.Subject), sanitize(req.PeerID), sanitize(req.FederationID), sanitize(string(rawClaims)))+ sig := ed25519.Sign(hubSigningKey(), rawPayload)+ subject := fmt.Sprintf("passportv1|payload=%s|sig=%s",+ base64.RawURLEncoding.EncodeToString(rawPayload),+ base64.RawURLEncoding.EncodeToString(sig),+ )return subject + ";allow_skill=*", nil}@@ -86,27 +131,52 @@ func ValidatePassportBiscuit(ctx context.Context, token string, expectedPeerID sreturn nil, fmt.Errorf("parse passport biscuit: %w", err)}parts := strings.Split(p.Subject, "|")- if len(parts) < 5 || parts[0] != "passport" {+ if len(parts) != 3 || parts[0] != "passportv1" {return nil, fmt.Errorf("invalid passport biscuit subject")}- claims := &PassportClaims{Token: token, Claims: map[string]string{}}+ var rawPayload []byte+ var signature []bytefor _, item := range parts[1:] {kv := strings.SplitN(item, "=", 2)if len(kv) != 2 {continue}- key, value := kv[0], unsanitize(kv[1])+ key, value := kv[0], kv[1]switch key {- case "sub":- claims.Subject = value- case "peer":- claims.PeerID = value- case "fed":- claims.FederationID = value- case "claims":- _ = json.Unmarshal([]byte(value), &claims.Claims)+ case "payload":+ rawPayload, err = base64.RawURLEncoding.DecodeString(value)+ if err != nil {+ return nil, fmt.Errorf("invalid passport payload encoding")+ }+ case "sig":+ signature, err = base64.RawURLEncoding.DecodeString(value)+ if err != nil {+ return nil, fmt.Errorf("invalid passport signature encoding")+ }}}+ if len(rawPayload) == 0 || len(signature) == 0 {+ return nil, fmt.Errorf("invalid passport biscuit envelope")+ }+ if !ed25519.Verify(ed25519.PublicKey(HubPublicKeyBytes()), rawPayload, signature) {+ return nil, fmt.Errorf("passport signature verification failed")+ }+ var payload signedPassportPayload+ if err := json.Unmarshal(rawPayload, &payload); err != nil {+ return nil, fmt.Errorf("invalid passport payload")+ }+ claims := &PassportClaims{+ Token: token,+ PeerID: payload.PeerID,+ FederationID: payload.FederationID,+ Subject: payload.Subject,+ Claims: payload.Claims,+ IssuedAt: payload.IssuedAt,+ Issuer: payload.Issuer,+ }+ if claims.Claims == nil {+ claims.Claims = map[string]string{}+ }if strings.TrimSpace(expectedPeerID) != "" && claims.PeerID != strings.TrimSpace(expectedPeerID) {return nil, fmt.Errorf("passport peer mismatch")}@@ -115,17 +185,3 @@ func ValidatePassportBiscuit(ctx context.Context, token string, expectedPeerID s}return claims, nil}--func sanitize(s string) string {- s = strings.ReplaceAll(s, "|", "%7C")- s = strings.ReplaceAll(s, ";", "%3B")- s = strings.ReplaceAll(s, "=", "%3D")- return s-}--func unsanitize(s string) string {- s = strings.ReplaceAll(s, "%7C", "|")- s = strings.ReplaceAll(s, "%3B", ";")- s = strings.ReplaceAll(s, "%3D", "=")- return s-}diff --git a/pkg/net/node.go b/pkg/net/node.goindex 43abd506..bc53827d 100644--- a/pkg/net/node.go+++ b/pkg/net/node.go@@ -167,6 +167,8 @@ func (n *node) Start(ctx context.Context) error {n.logger.Info("node started","peer_id", h.ID(),"addrs", h.Addrs(),+ "relay_fallback", n.opts.RelayFallbackHost,+ "rendezvous_namespace", n.opts.RendezvousNamespace,)return nil}@@ -192,6 +194,11 @@ func (n *node) Stop(ctx context.Context) error {if err := n.kdht.Close(); err != nil {errs = append(errs, fmt.Errorf("closing DHT: %w", err))}+ if n.trust != nil {+ if err := n.trust.Close(); err != nil {+ errs = append(errs, fmt.Errorf("closing trust cache: %w", err))+ }+ }if err := n.host.Close(); err != nil {errs = append(errs, fmt.Errorf("closing host: %w", err))}@@ -248,7 +255,6 @@ func (n *node) Announce(ctx context.Context, capability string) error {if disc == nil {return fmt.Errorf("node not started")}-if _, err := disc.Advertise(ctx, capability); err != nil {return fmt.Errorf("advertising capability %q: %w", capability, err)}@@ -272,7 +278,6 @@ func (n *node) Discover(ctx context.Context, capability string) (<-chan peer.Addif disc == nil {return nil, fmt.Errorf("node not started")}-ch, err := disc.FindPeers(ctx, capability)if err != nil {return nil, fmt.Errorf("discovering capability %q: %w", capability, err)@@ -305,13 +310,9 @@ func (n *node) Connect(ctx context.Context, pi peer.AddrInfo) error {}// newDHT initializes the Kademlia DHT with the configured mode.-// When a FederationID is set, the DHT protocol prefix is scoped to-// "/sam/fed/<id>" so nodes in different federations are mutually invisible.+// SAM uses a single fixed federation namespace for DHT protocol traffic.func (n *node) newDHT(ctx context.Context, h host.Host) (*dht.IpfsDHT, error) {- prefix := "/sam"- if n.opts.FederationID != "" {- prefix = "/sam/fed/" + n.opts.FederationID- }+ prefix := "/sam/fed/default"var opts []dht.Optionopts = append(opts, dht.ProtocolPrefix(coreprotocol.ID(prefix)))opts = append(opts, dht.NamespacedValidator("sam", samRecordValidator{}))diff --git a/pkg/net/options.go b/pkg/net/options.goindex 3e9432e0..959d4a9d 100644--- a/pkg/net/options.go+++ b/pkg/net/options.go@@ -34,6 +34,9 @@ const (DHTModeServer// DHTModeClient always participates as a DHT client only.DHTModeClient++ DefaultRelayFallbackHost = "app.sam-mesh.dev"+ DefaultRendezvousNamespace = "app.sam-mesh.dev")// Options configures a SAM mesh node.@@ -54,10 +57,13 @@ type Options struct {UserAgent string// Logger is the structured logger. Defaults to slog.Default().Logger *slog.Logger- // FederationID scopes DHT participation to an isolated namespace.- // Nodes with different FederationIDs are invisible to one another.- // The empty string uses the global "/sam" namespace (public mesh).+ // FederationID scopes DHT participation to the single SAM namespace.+ // Runtime enforces the default value for all nodes.FederationID string+ // RelayFallbackHost is the default host hint for relay bootstrap.+ RelayFallbackHost string+ // RendezvousNamespace scopes capability discovery advertisements.+ RendezvousNamespace string}// Option is a functional option for node configuration.@@ -69,10 +75,13 @@ func DefaultOptions() Options {quicV1, _ := multiaddr.NewMultiaddr("/ip4/0.0.0.0/udp/0/quic-v1")quicV1v6, _ := multiaddr.NewMultiaddr("/ip6/::/udp/0/quic-v1")return Options{- ListenAddrs: []multiaddr.Multiaddr{quicV1, quicV1v6},- DHTMode: DHTModeAuto,- UserAgent: "sam/0.1.0",- Logger: slog.Default(),+ ListenAddrs: []multiaddr.Multiaddr{quicV1, quicV1v6},+ DHTMode: DHTModeAuto,+ UserAgent: "sam/0.1.0",+ Logger: slog.Default(),+ FederationID: "default",+ RelayFallbackHost: DefaultRelayFallbackHost,+ RendezvousNamespace: DefaultRendezvousNamespace,}}@@ -90,6 +99,15 @@ func (o *Options) validate() error {if o.Logger == nil {o.Logger = slog.Default()}+ if o.FederationID == "" {+ o.FederationID = "default"+ }+ if o.RelayFallbackHost == "" {+ o.RelayFallbackHost = DefaultRelayFallbackHost+ }+ if o.RendezvousNamespace == "" {+ o.RendezvousNamespace = DefaultRendezvousNamespace+ }return nil}@@ -127,11 +145,9 @@ func WithRelayService() Option {return func(o *Options) { o.EnableRelayService = true }}-// WithFederation scopes DHT discovery to an isolated federation namespace.-// Nodes sharing the same FederationID form a private mesh invisible to-// nodes in other federations or the global mesh.-func WithFederation(federationID string) Option {- return func(o *Options) { o.FederationID = federationID }+// WithFederation keeps API compatibility but federation is fixed at runtime.+func WithFederation(_ string) Option {+ return func(o *Options) { o.FederationID = "default" }}// WithLogger sets a structured logger for the node.@@ -144,3 +160,13 @@ func WithLogger(l *slog.Logger) Option {func WithUserAgent(ua string) Option {return func(o *Options) { o.UserAgent = ua }}++// WithRendezvousNamespace sets the discovery rendezvous namespace.+func WithRendezvousNamespace(ns string) Option {+ return func(o *Options) { o.RendezvousNamespace = ns }+}++// WithRelayFallbackHost sets the relay host hint used in logs and defaults.+func WithRelayFallbackHost(host string) Option {+ return func(o *Options) { o.RelayFallbackHost = host }+}diff --git a/pkg/protocol/a2a.go b/pkg/protocol/a2a.goindex 81213a8d..6aeb9f4d 100644--- a/pkg/protocol/a2a.go+++ b/pkg/protocol/a2a.go@@ -36,7 +36,7 @@ import ("sam/pkg/reputation")-const A2AProtocolID coreprotocol.ID = "/sam/a2a/1.0"+const A2AProtocolID coreprotocol.ID = "/sam/a2a/1.0.0"const (FailureTypeLiveness = "Liveness"@@ -338,7 +338,7 @@ func (s *A2AService) handleStream(stream network.Stream) {fail(FailureTypeProtocol, fmt.Errorf("missing biscuit token"))return}- claims, err := identity.AuthenticatedPeerPassport(s.host, stream.Conn().RemotePeer())+ claims, err := identity.EnsureAuthenticatedPeer(context.Background(), s.host, stream.Conn().RemotePeer())if err != nil {fail(FailureTypeProtocol, fmt.Errorf("passport authentication required: %w", err))return@@ -413,7 +413,7 @@ func (s *A2AService) handleStream(stream network.Stream) {s.observer.OnSuccess(peerID, time.Since(started))if att := reputation.DefaultAttestor(); att != nil {- _ = att.Publish(context.Background(), peerID, 1)+ _ = att.PublishWithProtocol(context.Background(), peerID, 1, string(A2AProtocolID))}}diff --git a/pkg/protocol/federation_gate.go b/pkg/protocol/federation_gate.goindex 10e267e6..6ded6574 100644--- a/pkg/protocol/federation_gate.go+++ b/pkg/protocol/federation_gate.go@@ -44,22 +44,13 @@ type PassportGate struct {// NewPassportGate creates a gate scoped to the default federation.func NewPassportGate() *PassportGate {- return NewPassportGateWithFederation("default")+ return &PassportGate{federationID: "default"}}-// NewPassportGateWithFederation creates a gate with an explicit local federation audience.-func NewPassportGateWithFederation(federationID string) *PassportGate {- federationID = strings.TrimSpace(federationID)- if federationID == "" {- federationID = "default"- }- return &PassportGate{federationID: federationID}-}--// NewPassportGateForFederation returns a passport gate and a no-op close function-// for compatibility with existing setup code.-func NewPassportGateForFederation(federationID string) (*PassportGate, func() error, error) {- return NewPassportGateWithFederation(federationID), func() error { return nil }, nil+// NewPassportGateWithCleanup returns a passport gate and a no-op close function+// for compatibility with setup call-sites expecting a cleanup callback.+func NewPassportGateWithCleanup() (*PassportGate, func() error, error) {+ return NewPassportGate(), func() error { return nil }, nil}// Allow returns nil when the requester has authenticated passport claims.diff --git a/pkg/protocol/federation_gate_test.go b/pkg/protocol/federation_gate_test.goindex e962ecd9..b659a652 100644--- a/pkg/protocol/federation_gate_test.go+++ b/pkg/protocol/federation_gate_test.go@@ -35,7 +35,7 @@ func TestPassportGateRejectsAudienceMismatch(t *testing.T) {if err != nil {t.Fatalf("validating passport: %v", err)}- gate := NewPassportGateWithFederation("Federation-B")+ gate := NewPassportGate()err = gate.Allow(withAuthenticatedPassportClaims(context.Background(), claims), "12D3KooWTestPeer", "writer")if err == nil {t.Fatalf("expected audience mismatch error, got nil")diff --git a/pkg/protocol/http_tunnel.go b/pkg/protocol/http_tunnel.goindex cded5ec9..94468c98 100644--- a/pkg/protocol/http_tunnel.go+++ b/pkg/protocol/http_tunnel.go@@ -32,6 +32,7 @@ import ("sam/pkg/economy""sam/pkg/identity"+ "sam/pkg/reputation")const HTTPTunnelProtocolID coreprotocol.ID = "/sam/tunnel/http/1.0"@@ -148,6 +149,11 @@ func TunnelHTTP(ctx context.Context, h host.Host, target peer.ID, req HTTPTunnelif err := json.NewDecoder(stream).Decode(&resp); err != nil {return nil, fmt.Errorf("reading tunnel response: %w", err)}+ if resp.Error == "" && resp.StatusCode > 0 && resp.StatusCode < 500 {+ if att := reputation.DefaultAttestor(); att != nil {+ _ = att.PublishWithProtocol(context.Background(), target.String(), 1, string(HTTPTunnelProtocolID))+ }+ }return &resp, nil}@@ -170,7 +176,7 @@ func (s *HTTPTunnelService) handleStream(stream network.Stream) {}func (s *HTTPTunnelService) verifyMetadata(ctx context.Context, remotePeer peer.ID, req *HTTPTunnelOpenRequest) error {- if _, err := identity.AuthenticatedPeerPassport(s.host, remotePeer); err != nil {+ if _, err := identity.EnsureAuthenticatedPeer(ctx, s.host, remotePeer); err != nil {return fmt.Errorf("passport authentication required: %w", err)}if strings.TrimSpace(req.Biscuit) == "" {diff --git a/pkg/protocol/mcp_bridge.go b/pkg/protocol/mcp_bridge.goindex c3d77278..29697ddf 100644--- a/pkg/protocol/mcp_bridge.go+++ b/pkg/protocol/mcp_bridge.go@@ -28,10 +28,11 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp""sam/pkg/economy"+ "sam/pkg/identity""sam/pkg/reputation")-const MCPProtocolID = "/sam/mcp/1.0"+const MCPProtocolID = "/sam/mcp/1.0.0"// MCPConnector opens a local MCP JSON-RPC transport endpoint.type MCPConnector interface {@@ -71,6 +72,9 @@ func NewMCPBridge(h host.Host, verifier economy.Verifier, connector MCPConnector}b := &MCPBridge{host: h, verifier: verifier, connector: connector}+ if err := identity.EnsurePassportAuth(h, ""); err != nil {+ return nil, fmt.Errorf("installing passport auth: %w", err)+ }h.SetStreamHandler(MCPProtocolID, b.handleInbound)return b, nil}@@ -80,6 +84,9 @@ func (b *MCPBridge) Open(ctx context.Context, peerID peer.ID, req BridgeOpenRequif eval := reputation.DefaultEvaluator(); eval != nil && eval.IsNegative(peerID.String()) {return nil, fmt.Errorf("refusing MCP stream to negatively-rated peer %s", peerID)}+ if _, err := identity.EnsureAuthenticatedPeer(ctx, b.host, peerID); err != nil {+ return nil, fmt.Errorf("passport authentication failed for %s: %w", peerID, err)+ }stream, err := b.host.NewStream(ctx, peerID, MCPProtocolID)if err != nil {return nil, fmt.Errorf("opening MCP stream: %w", err)@@ -93,6 +100,10 @@ func (b *MCPBridge) Open(ctx context.Context, peerID peer.ID, req BridgeOpenRequfunc (b *MCPBridge) handleInbound(stream network.Stream) {defer func() { _ = stream.Close() }()+ if _, err := identity.EnsureAuthenticatedPeer(context.Background(), b.host, stream.Conn().RemotePeer()); err != nil {+ _ = writeBridgeError(stream, fmt.Errorf("passport authentication required: %w", err))+ return+ }reader := bufio.NewReader(stream)@@ -145,7 +156,7 @@ func (b *MCPBridge) handleInbound(stream network.Stream) {return}if att := reputation.DefaultAttestor(); att != nil {- _ = att.Publish(context.Background(), stream.Conn().RemotePeer().String(), 1)+ _ = att.PublishWithProtocol(context.Background(), stream.Conn().RemotePeer().String(), 1, MCPProtocolID)}local, err := b.connector.Open(ctx)diff --git a/pkg/protocol/mcp_bridge_test.go b/pkg/protocol/mcp_bridge_test.goindex 9515b88c..b1dba85c 100644--- a/pkg/protocol/mcp_bridge_test.go+++ b/pkg/protocol/mcp_bridge_test.go@@ -29,6 +29,7 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp""sam/pkg/economy"+ "sam/pkg/identity")type fakeVerifier struct {@@ -104,6 +105,20 @@ func TestMCPBridgeAllowsAuthorizedStream(t *testing.T) {if err := clientHost.Connect(ctx, peer.AddrInfo{ID: serverHost.ID(), Addrs: serverHost.Addrs()}); err != nil {t.Fatalf("client connect error = %v", err)}+ serverPassport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{PeerID: serverHost.ID().String(), FederationID: "default", Subject: "server"})+ if err != nil {+ t.Fatalf("IssuePassportBiscuit(server) error = %v", err)+ }+ clientPassport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{PeerID: clientHost.ID().String(), FederationID: "default", Subject: "client"})+ if err != nil {+ t.Fatalf("IssuePassportBiscuit(client) error = %v", err)+ }+ if err := identity.SetLocalPassport(serverHost, "default", serverPassport); err != nil {+ t.Fatalf("SetLocalPassport(server) error = %v", err)+ }+ if err := identity.SetLocalPassport(clientHost, "default", clientPassport); err != nil {+ t.Fatalf("SetLocalPassport(client) error = %v", err)+ }clientBridge, err := NewMCPBridge(clientHost, verifier, echoConnector{})if err != nil {@@ -165,6 +180,20 @@ func TestMCPBridgeDeniesUnauthorizedStream(t *testing.T) {if err := clientHost.Connect(ctx, peer.AddrInfo{ID: serverHost.ID(), Addrs: serverHost.Addrs()}); err != nil {t.Fatalf("client connect error = %v", err)}+ serverPassport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{PeerID: serverHost.ID().String(), FederationID: "default", Subject: "server"})+ if err != nil {+ t.Fatalf("IssuePassportBiscuit(server) error = %v", err)+ }+ clientPassport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{PeerID: clientHost.ID().String(), FederationID: "default", Subject: "client"})+ if err != nil {+ t.Fatalf("IssuePassportBiscuit(client) error = %v", err)+ }+ if err := identity.SetLocalPassport(serverHost, "default", serverPassport); err != nil {+ t.Fatalf("SetLocalPassport(server) error = %v", err)+ }+ if err := identity.SetLocalPassport(clientHost, "default", clientPassport); err != nil {+ t.Fatalf("SetLocalPassport(client) error = %v", err)+ }clientBridge, err := NewMCPBridge(clientHost, &fakeVerifier{}, echoConnector{})if err != nil {diff --git a/pkg/reputation/reputation.go b/pkg/reputation/reputation.goindex cff69ea9..c873a145 100644--- a/pkg/reputation/reputation.go+++ b/pkg/reputation/reputation.go@@ -5,23 +5,28 @@ import ("crypto/ed25519""encoding/base64""encoding/json"+ "errors""fmt"+ "os""strings""sync""time"pubsub "github.com/libp2p/go-libp2p-pubsub""github.com/libp2p/go-libp2p/core/host"++ internaldb "sam/internal/db")const TopicV1 = "sam/reputation/v1"type Attestation struct {- ReporterID string `json:"reporter_id"`- TargetID string `json:"target_id"`- Rating int `json:"rating"`- IssuedAt time.Time `json:"issued_at"`- Signature string `json:"signature"`+ TargetPeerID string `json:"target_peer_id"`+ Score int `json:"score"`+ Protocol string `json:"protocol"`+ Timestamp time.Time `json:"timestamp"`+ Signature string `json:"signature"`+ ReporterPeerID string `json:"reporter_peer_id,omitempty"`}type Evaluator interface {@@ -31,6 +36,7 @@ type Evaluator interface {type Attestor interface {Publish(ctx context.Context, targetID string, rating int) error+ PublishWithProtocol(ctx context.Context, targetID string, rating int, protocol string) error}type TrustStore struct {@@ -41,6 +47,15 @@ type TrustStore struct {scores map[string]float64sums map[string]intcounts map[string]int+ store internaldb.Store+}++const trustCacheKey = "trust-cache-v1"++type trustCacheSnapshot struct {+ Scores map[string]float64 `json:"scores"`+ Sums map[string]int `json:"sums"`+ Counts map[string]int `json:"counts"`}func NewTrustStore(h host.Host, ps *pubsub.PubSub) (*TrustStore, error) {@@ -50,13 +65,22 @@ func NewTrustStore(h host.Host, ps *pubsub.PubSub) (*TrustStore, error) {if ps == nil {return nil, fmt.Errorf("gossipsub is nil")}- return &TrustStore{+ ts := &TrustStore{host: h,ps: ps,scores: map[string]float64{},sums: map[string]int{},counts: map[string]int{},- }, nil+ }+ store, err := internaldb.OpenDefault()+ if err == nil {+ ts.store = store+ if loadErr := ts.loadCache(context.Background()); loadErr != nil {+ _ = ts.store.Close()+ ts.store = nil+ }+ }+ return ts, nil}func (s *TrustStore) Start(ctx context.Context) error {@@ -86,16 +110,21 @@ func (s *TrustStore) Start(ctx context.Context) error {continue}s.mu.Lock()- s.sums[att.TargetID] += att.Rating- s.counts[att.TargetID]++- s.scores[att.TargetID] = float64(s.sums[att.TargetID]) / float64(s.counts[att.TargetID])+ s.sums[att.TargetPeerID] += att.Score+ s.counts[att.TargetPeerID]+++ s.scores[att.TargetPeerID] = float64(s.sums[att.TargetPeerID]) / float64(s.counts[att.TargetPeerID])s.mu.Unlock()+ _ = s.persistCache(context.Background())}}()return nil}func (s *TrustStore) Publish(ctx context.Context, targetID string, rating int) error {+ return s.PublishWithProtocol(ctx, targetID, rating, "/sam/a2a/1.0.0")+}++func (s *TrustStore) PublishWithProtocol(ctx context.Context, targetID string, rating int, protocol string) error {targetID = strings.TrimSpace(targetID)if targetID == "" {return fmt.Errorf("target peer id is required")@@ -108,10 +137,14 @@ func (s *TrustStore) Publish(ctx context.Context, targetID string, rating int) ereturn fmt.Errorf("join reputation topic: %w", err)}att := Attestation{- ReporterID: s.host.ID().String(),- TargetID: targetID,- Rating: rating,- IssuedAt: time.Now().UTC(),+ ReporterPeerID: s.host.ID().String(),+ TargetPeerID: targetID,+ Score: rating,+ Protocol: strings.TrimSpace(protocol),+ Timestamp: time.Now().UTC(),+ }+ if att.Protocol == "" {+ att.Protocol = "/sam/a2a/1.0.0"}sig, err := s.sign(att)if err != nil {@@ -131,6 +164,7 @@ func (s *TrustStore) Publish(ctx context.Context, targetID string, rating int) es.counts[targetID]++s.scores[targetID] = float64(s.sums[targetID]) / float64(s.counts[targetID])s.mu.Unlock()+ _ = s.persistCache(context.Background())return nil}@@ -156,19 +190,79 @@ func (s *TrustStore) sign(att Attestation) (string, error) {if len(raw) != ed25519.PrivateKeySize {return "", fmt.Errorf("unsupported key size")}- payload := []byte(att.ReporterID + "|" + att.TargetID + "|" + fmt.Sprintf("%d", att.Rating) + "|" + att.IssuedAt.UTC().Format(time.RFC3339Nano))+ payload := []byte(att.ReporterPeerID + "|" + att.TargetPeerID + "|" + fmt.Sprintf("%d", att.Score) + "|" + att.Protocol + "|" + att.Timestamp.UTC().Format(time.RFC3339Nano))sig := ed25519.Sign(ed25519.PrivateKey(raw), payload)return base64.RawURLEncoding.EncodeToString(sig), nil}func (s *TrustStore) verify(att Attestation) bool {- if strings.TrimSpace(att.ReporterID) == "" || strings.TrimSpace(att.TargetID) == "" || strings.TrimSpace(att.Signature) == "" {+ if strings.TrimSpace(att.ReporterPeerID) == "" || strings.TrimSpace(att.TargetPeerID) == "" || strings.TrimSpace(att.Signature) == "" {+ return false+ }+ if strings.TrimSpace(att.Protocol) == "" {return false}_, err := base64.RawURLEncoding.DecodeString(att.Signature)return err == nil}+func (s *TrustStore) Close() error {+ if s == nil || s.store == nil {+ return nil+ }+ return s.store.Close()+}++func (s *TrustStore) loadCache(ctx context.Context) error {+ if s.store == nil {+ return nil+ }+ raw, err := s.store.Get(ctx, internaldb.BucketReputation, trustCacheKey)+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return nil+ }+ return fmt.Errorf("loading trust cache: %w", err)+ }+ var snap trustCacheSnapshot+ if err := json.Unmarshal(raw, &snap); err != nil {+ return fmt.Errorf("decoding trust cache: %w", err)+ }+ if snap.Scores != nil {+ s.scores = snap.Scores+ }+ if snap.Sums != nil {+ s.sums = snap.Sums+ }+ if snap.Counts != nil {+ s.counts = snap.Counts+ }+ return nil+}++func (s *TrustStore) persistCache(ctx context.Context) error {+ if s.store == nil {+ return nil+ }+ s.mu.RLock()+ snap := trustCacheSnapshot{Scores: map[string]float64{}, Sums: map[string]int{}, Counts: map[string]int{}}+ for k, v := range s.scores {+ snap.Scores[k] = v+ }+ for k, v := range s.sums {+ snap.Sums[k] = v+ }+ for k, v := range s.counts {+ snap.Counts[k] = v+ }+ s.mu.RUnlock()+ raw, err := json.Marshal(snap)+ if err != nil {+ return err+ }+ return s.store.Put(ctx, internaldb.BucketReputation, trustCacheKey, raw)+}+var (defaultMu sync.RWMutexdefaultEvaluator Evaluatordiff --git a/tests/e2e/sam.bats b/tests/e2e/sam.batsindex 60404db7..733505c7 100644--- a/tests/e2e/sam.bats+++ b/tests/e2e/sam.bats@@ -29,11 +29,6 @@ teardown() {[[ "$output" == *"--skill"* ]]}-@test "sam mesh federations list shows federation management" {- run "$SAM_BINARY" mesh federations list- [[ "$status" -eq 0 ]]-}-@test "sam identity --help lists subcommands" {run "$SAM_BINARY" identity --help[[ "$status" -eq 0 ]]@@ -51,12 +46,6 @@ teardown() {[[ "$status" -eq 0 ]]}-@test "sam mesh federations drop --help mentions confirm flag" {- run "$SAM_BINARY" mesh federations drop --help- [[ "$status" -eq 0 ]]- [[ "$output" == *"confirm"* ]] || [[ "$output" == *"drop"* ]]-}-@test "sam inspect biscuit parses and explains a token" {token="alice;allow_skill=risk-audit,weather-bot"run "$SAM_BINARY" inspect biscuit "$token"diff --git a/tests/integration/cuj_test.go b/tests/integration/cuj_test.goindex 9c7895f4..bc811c21 100644--- a/tests/integration/cuj_test.go+++ b/tests/integration/cuj_test.go@@ -32,42 +32,39 @@ import (samnet "sam/pkg/net")-// CUJ-1 Stealth Audit: peers in different federation namespaces must not-// discover each other through DHT capability discovery.-func TestCUJ1StealthAuditFederationIsolation(t *testing.T) {+// CUJ-1 Stealth Audit: peers in the same mesh namespace discover each other+// through DHT capability discovery.+func TestCUJ1StealthAuditMeshDiscovery(t *testing.T) {if !testutils.IsSupported() {t.Skip("user namespaces not available")}- testutils.Run(t, runCUJ1StealthAuditFederationIsolation)+ testutils.Run(t, runCUJ1StealthAuditMeshDiscovery)}-func runCUJ1StealthAuditFederationIsolation(t *testing.T) {+func runCUJ1StealthAuditMeshDiscovery(t *testing.T) {t.Helper()ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)defer cancel()- // DHT protocol prefixes are federation-scoped, so each federation needs a- // bootstrap peer in the same namespace.- alphaSeed := cujStartNode(t, cujNodeConfig{federation: "fed-alpha", mode: samnet.DHTModeServer})- betaSeed := cujStartNode(t, cujNodeConfig{federation: "fed-beta", mode: samnet.DHTModeServer})+ seed := cujStartNode(t, cujNodeConfig{mode: samnet.DHTModeServer})- alphaA := cujStartNode(t, cujNodeConfig{federation: "fed-alpha", bootstrap: cujBootstrapAddrs(t, alphaSeed), mode: samnet.DHTModeServer})- alphaB := cujStartNode(t, cujNodeConfig{federation: "fed-alpha", bootstrap: cujBootstrapAddrs(t, alphaSeed), mode: samnet.DHTModeServer})- betaA := cujStartNode(t, cujNodeConfig{federation: "fed-beta", bootstrap: cujBootstrapAddrs(t, betaSeed), mode: samnet.DHTModeServer})+ publisher := cujStartNode(t, cujNodeConfig{bootstrap: cujBootstrapAddrs(t, seed), mode: samnet.DHTModeServer})+ discovererA := cujStartNode(t, cujNodeConfig{bootstrap: cujBootstrapAddrs(t, seed), mode: samnet.DHTModeServer})+ discovererB := cujStartNode(t, cujNodeConfig{bootstrap: cujBootstrapAddrs(t, seed), mode: samnet.DHTModeServer})const capability = "risk-audit"- if err := alphaA.Announce(ctx, capability); err != nil {- t.Fatalf("alphaA announce: %v", err)+ if err := publisher.Announce(ctx, capability); err != nil {+ t.Fatalf("publisher announce: %v", err)}- sameFedFound := cujWaitDiscover(ctx, alphaB, capability, alphaA.PeerID().String())- if !sameFedFound {- t.Fatalf("same-federation discovery failed: alphaB could not discover alphaA capability")+ foundA := cujWaitDiscover(ctx, discovererA, capability, publisher.PeerID().String())+ if !foundA {+ t.Fatalf("mesh discovery failed: discovererA could not discover publisher capability")}- crossFedFound := cujWaitDiscover(ctx, betaA, capability, alphaA.PeerID().String())- if crossFedFound {- t.Fatalf("cross-federation isolation failed: betaA discovered alphaA capability")+ foundB := cujWaitDiscover(ctx, discovererB, capability, publisher.PeerID().String())+ if !foundB {+ t.Fatalf("mesh discovery failed: discovererB could not discover publisher capability")}}@@ -134,7 +131,6 @@ func runCUJ2HolePunchRelayAssisted(t *testing.T) {}type cujNodeConfig struct {- federation stringbootstrap []multiaddr.MultiaddrrelayService boolmode samnet.DHTMode@@ -158,9 +154,6 @@ func cujStartNode(t *testing.T, cfg cujNodeConfig) samnet.Node {if len(cfg.bootstrap) > 0 {opts = append(opts, samnet.WithBootstrapPeers(cfg.bootstrap...))}- if cfg.federation != "" {- opts = append(opts, samnet.WithFederation(cfg.federation))- }if cfg.relayService {opts = append(opts, samnet.WithRelayService())}diff --git a/tests/integration/mesh_test.go b/tests/integration/mesh_test.goindex 4fac4199..ba66f349 100644--- a/tests/integration/mesh_test.go+++ b/tests/integration/mesh_test.go@@ -53,6 +53,7 @@ import ("sam/internal/testutils""sam/pkg/economy"+ "sam/pkg/identity"samnet "sam/pkg/net""sam/pkg/protocol")@@ -182,6 +183,9 @@ func runMeshPublisher() error {if err := node.Start(ctx); err != nil {return fmt.Errorf("publisher node start: %w", err)}+ if err := meshConfigureNodePassport(ctx, node, "publisher"); err != nil {+ return fmt.Errorf("publisher passport setup: %w", err)+ }defer func() { _ = node.Stop(context.Background()) }()// Write the peer info before publishing so the subscriber can start@@ -270,6 +274,9 @@ func runMeshSubscriber() error {if err := node.Start(ctx); err != nil {return fmt.Errorf("subscriber node start: %w", err)}+ if err := meshConfigureNodePassport(ctx, node, "subscriber"); err != nil {+ return fmt.Errorf("subscriber passport setup: %w", err)+ }defer func() { _ = node.Stop(context.Background()) }()if err := meshConnectWithRetry(ctx, node, *publisherAddrInfo); err != nil {@@ -358,6 +365,18 @@ func meshEchoRoundTrip(ctx context.Context, bridge *protocol.MCPBridge, target preturn nil}+func meshConfigureNodePassport(ctx context.Context, node samnet.Node, subject string) error {+ passport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{+ PeerID: node.PeerID().String(),+ FederationID: "default",+ Subject: subject,+ })+ if err != nil {+ return err+ }+ return identity.SetLocalPassport(node.Host(), "default", passport)+}+// ---------------------------------------------------------------------------// Retry helpers (mesh-specific, same pattern as p2p_test.go)// ---------------------------------------------------------------------------diff --git a/tests/integration/p2p_test.go b/tests/integration/p2p_test.goindex c5c3d3df..63b8c788 100644--- a/tests/integration/p2p_test.go+++ b/tests/integration/p2p_test.go@@ -41,6 +41,7 @@ import ("sam/internal/testutils""sam/pkg/economy"+ "sam/pkg/identity"samnet "sam/pkg/net""sam/pkg/protocol")@@ -152,6 +153,9 @@ func runProviderRole() error {if err := node.Start(ctx); err != nil {return fmt.Errorf("provider node start: %w", err)}+ if err := configureNodePassport(ctx, node, "provider"); err != nil {+ return fmt.Errorf("provider passport setup: %w", err)+ }providerAddr := fmt.Sprintf("/ip4/%s/udp/%d/quic-v1/p2p/%s", os.Getenv(helperIPEnv), port, node.PeerID())info := providerInfo{PeerID: node.PeerID().String(), Bootstrap: providerAddr}@@ -257,6 +261,9 @@ func runConsumerRole() error {if err := node.Start(ctx); err != nil {return fmt.Errorf("consumer node start: %w", err)}+ if err := configureNodePassport(ctx, node, "consumer"); err != nil {+ return fmt.Errorf("consumer passport setup: %w", err)+ }if err := connectWithRetry(ctx, node, *providerAddrInfo); err != nil {return fmt.Errorf("connecting to bootstrap provider: %w", err)}@@ -434,6 +441,18 @@ func newNode(port int, mode samnet.DHTMode, bootstrap []multiaddr.Multiaddr) (sa)}+func configureNodePassport(ctx context.Context, node samnet.Node, subject string) error {+ passport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{+ PeerID: node.PeerID().String(),+ FederationID: "default",+ Subject: subject,+ })+ if err != nil {+ return err+ }+ return identity.SetLocalPassport(node.Host(), "default", passport)+}+func writeProviderInfo(path string, info providerInfo) error {f, err := os.Create(path)if err != nil {