Skip to main content

hyprstream_core/services/
registry.rs

1//! ZMQ-based registry service for repository management
2//!
3//! This service wraps git2db and provides a ZMQ REQ/REP interface for
4//! repository operations. It uses Cap'n Proto for serialization.
5
6use crate::services::types::{MAX_FDS_GLOBAL, MAX_FDS_PER_CLIENT};
7use crate::services::xet_provenance::XetProvenanceStore;
8use crate::services::{EnvelopeContext, RequestService};
9use anyhow::{anyhow, Result};
10use async_trait::async_trait;
11use dashmap::DashMap;
12use git2db::{CloneBuilder, Git2DB, GitRef, RepoId, TrackedRepository};
13use hyprstream_containedfs::{ContainedFs, FsError, FsHandle};
14use hyprstream_rpc::prelude::*;
15use hyprstream_rpc::transport::TransportConfig;
16use hyprstream_rpc::{StreamChannel, StreamContext};
17use hyprstream_rpc_std::policy_client::PolicyClient;
18use parking_lot::Mutex;
19#[cfg_attr(not(feature = "metrics"), allow(unused_imports))]
20use std::collections::HashMap;
21use std::io::{Read as _, Seek as _, SeekFrom, Write as _};
22use std::path::{Path, PathBuf};
23use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::Relaxed};
24use std::sync::Arc;
25use std::time::{Duration, SystemTime, UNIX_EPOCH};
26use tokio::sync::RwLock;
27use tracing::{debug, error, warn};
28use uuid::Uuid;
29
30// Generated client types (RegistryClient is used in test and metrics-impl code)
31use crate::services::editing::{self, EditingTable};
32use crate::services::generated::registry_client::{
33    dispatch_registry, serialize_response, CtlHandler, RegistryHandler, RepoHandler,
34    WorktreeHandler,
35};
36use automerge::ReadDoc as _;
37use hyprstream_rpc_std::policy_client::PolicyCheck;
38#[allow(unused_imports)]
39use hyprstream_rpc_std::registry_client::{
40    AcceptedAt9pStateInfo, AddRemoteRequest, AmendCommitRequest, At9pCandidateKind,
41    At9pCandidateRequest, BranchRequest, CheckoutRequest, CloneRequest, CommitRequest,
42    CommitWithAuthorRequest, ContinueMergeRequest, CreateTagRequest, CreateWorktreeRequest,
43    CtlCheckoutRequest, CtlDiffRequest, CtlLogRequest, DeleteTagRequest, DetailedStatusInfo,
44    DocFormat, EditApplyRequest, EditOpenRequest, ErrorInfo, FileInfo, FileStatus, GetBlobRequest,
45    GetBlobRequestContent, GetRefRequest, HealthStatus, LogEntry, MergeRequest, NpClunk, NpCreate,
46    NpFlush, NpOpen, NpRead, NpRemove, NpStat as NpStatData, NpStatReq, NpWalk, NpWrite, NpWstat,
47    PushRequest, PutBlobRequest, PutBlobResult, Qid as QidData, ROpen, RRead, RStat, RWalk, RWrite,
48    RegisterRequest, RegistryClient, RegistryResponseVariant, RemoteInfo, RemoveRemoteRequest,
49    RemoveWorktreeRequest, RenameRemoteRequest, SetRemoteUrlRequest, StageFilesRequest, StreamInfo,
50    UpdateRequest, ValidationResult,
51};
52// Conflicting names — use canonical path at usage sites:
53//   registry_client::TrackedRepository, registry_client::RepositoryStatus, registry_client::WorktreeInfo
54
55// ============================================================================
56// Parsing Helper Functions
57// ============================================================================
58
59/// Convert generated variant fields into a TrackedRepository.
60#[cfg(feature = "metrics")]
61fn variant_to_tracked_repository(
62    id: &str,
63    name: &str,
64    url: &str,
65    worktree_path: &str,
66    tracking_ref: &str,
67    current_oid: &str,
68    registered_at: i64,
69) -> Result<TrackedRepository> {
70    let uuid = Uuid::parse_str(id)?;
71    let repo_id = RepoId::from_uuid(uuid);
72    let name_opt = if name.is_empty() {
73        None
74    } else {
75        Some(name.to_owned())
76    };
77    let tracking = if tracking_ref.is_empty() {
78        GitRef::Branch("main".to_owned())
79    } else {
80        GitRef::Branch(tracking_ref.to_owned())
81    };
82    let oid = if current_oid.is_empty() {
83        None
84    } else {
85        Some(current_oid.to_owned())
86    };
87
88    Ok(TrackedRepository {
89        id: repo_id,
90        name: name_opt,
91        url: url.to_owned(),
92        worktree_path: PathBuf::from(worktree_path),
93        tracking_ref: tracking,
94        remotes: Vec::new(),
95        registered_at,
96        current_oid: oid,
97        metadata: HashMap::new(),
98    })
99}
100
101// ============================================================================
102// Registry Service (server-side)
103// ============================================================================
104
105// ============================================================================
106// 9P Fid Table for Filesystem Operations
107// ============================================================================
108
109// FsHandle imported from hyprstream_containedfs above
110use crate::services::types::{DEFAULT_IOUNIT, DMDIR, ORDWR, OTRUNC, OWRITE, QTDIR, QTFILE};
111
112/// 9P Qid — uniquely identifies a file version.
113#[derive(Clone, Debug)]
114struct Qid {
115    qtype: u8,
116    version: u32,
117    path: u64,
118}
119
120/// State of a fid in the 9P table.
121enum FidState {
122    /// After walk: handle for metadata/open, not yet opened for I/O.
123    Walked { walk_handle: FsHandle, qid: Qid },
124    /// After open: real fd for I/O.
125    Opened {
126        file: Mutex<std::fs::File>,
127        qid: Qid,
128        iounit: u32,
129        mode: u8,
130        /// Relative path within the worktree (needed for directory reads).
131        rel_path: String,
132    },
133}
134
135/// Entry in the fid table.
136struct FidEntry {
137    state: FidState,
138    /// Identity of the client that owns this fid (for owner verification).
139    owner_identity: String,
140    /// Epoch seconds of last access (for idle timeout reaping).
141    last_accessed: AtomicU64,
142}
143
144/// Process-global fid table for 9P filesystem operations.
145///
146/// Uses `DashMap` for lock-free concurrent access. Fids are allocated with
147/// a simple atomic counter with collision retry.
148struct FidTable {
149    next_fid: AtomicU32,
150    fids: DashMap<u32, FidEntry>,
151    /// Per-client fid count for resource limiting.
152    client_fid_counts: DashMap<String, AtomicU32>,
153}
154
155/// Idle timeout for fids (5 minutes).
156const FID_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
157
158/// Hard cap on the inline `putBlob` upload path (DoS guard for unbounded `Data`).
159/// Model-weight-scale blobs are NOT intended for the inline path; a streaming
160/// upload channel (additive schema follow-up) will carry those. 64 MiB.
161const MAX_INLINE_UPLOAD: u64 = 64 * 1024 * 1024;
162const MAX_AT9P_CANDIDATE_BYTES: usize = 4 * 1024 * 1024;
163
164fn now_epoch_secs() -> u64 {
165    SystemTime::now()
166        .duration_since(UNIX_EPOCH)
167        .unwrap_or_default()
168        .as_secs()
169}
170
171/// Build a Qid from filesystem metadata.
172///
173/// Advisory identity hint only — see the qid-soundness invariant on
174/// `hyprstream_vfs::Stat`. `path = inode` is rename-stable but subject to
175/// inode reuse; `version = ctime` is truncated. No authz may key on this. The
176/// content-CID-derived qid lands in #387.
177#[cfg(unix)]
178fn qid_from_metadata(meta: &std::fs::Metadata) -> Qid {
179    use std::os::unix::fs::MetadataExt;
180    Qid {
181        qtype: if meta.is_dir() { QTDIR } else { QTFILE },
182        version: meta.ctime() as u32,
183        path: meta.ino(),
184    }
185}
186
187/// Build a Qid from metadata (non-Unix fallback).
188///
189/// `path = 0` by the "0 = unknown" convention (no inode available); this qid
190/// is NOT a usable identity. See `hyprstream_vfs::Stat`.
191#[cfg(not(unix))]
192fn qid_from_metadata(meta: &std::fs::Metadata) -> Qid {
193    Qid {
194        qtype: if meta.is_dir() { QTDIR } else { QTFILE },
195        version: meta
196            .modified()
197            .ok()
198            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
199            .map(|d| d.as_secs() as u32)
200            .unwrap_or(0),
201        path: 0, // No inode on non-Unix — "0 = unknown" per vfs::Stat convention
202    }
203}
204
205impl FidTable {
206    fn new() -> Self {
207        Self {
208            next_fid: AtomicU32::new(1), // 0 is reserved for root
209            fids: DashMap::new(),
210            client_fid_counts: DashMap::new(),
211        }
212    }
213
214    /// Allocate a new fid for a client, checking per-client and global limits.
215    fn alloc_fid(&self, client_id: &str) -> Result<u32, FsError> {
216        let count = self
217            .client_fid_counts
218            .entry(client_id.to_owned())
219            .or_insert_with(|| AtomicU32::new(0));
220        if count.load(Relaxed) >= MAX_FDS_PER_CLIENT {
221            return Err(FsError::ResourceLimit(
222                "too many open fids for client".into(),
223            ));
224        }
225        if self.fids.len() >= MAX_FDS_GLOBAL as usize {
226            return Err(FsError::ResourceLimit("too many open fids globally".into()));
227        }
228        for _ in 0..1000 {
229            let fid = self.next_fid.fetch_add(1, Relaxed);
230            if fid >= 1 && !self.fids.contains_key(&fid) {
231                count.fetch_add(1, Relaxed);
232                return Ok(fid);
233            }
234        }
235        Err(FsError::ResourceLimit(
236            "failed to allocate fid after retries".into(),
237        ))
238    }
239
240    /// Insert a fid entry (does NOT increment client count — use insert_counted for that).
241    fn insert(&self, fid: u32, entry: FidEntry) {
242        self.fids.insert(fid, entry);
243    }
244
245    /// Insert a fid entry AND increment the client's fid count.
246    /// Use this when inserting a fid that wasn't allocated via alloc_fid
247    /// (e.g., client-specified newfid in walk).
248    fn insert_counted(&self, fid: u32, entry: FidEntry, client_id: &str) {
249        let count = self
250            .client_fid_counts
251            .entry(client_id.to_owned())
252            .or_insert_with(|| AtomicU32::new(0));
253        count.fetch_add(1, Relaxed);
254        self.fids.insert(fid, entry);
255    }
256
257    /// Replace a fid entry in-place without touching the client count.
258    /// Use this for state transitions (Walked → Opened) where the fid
259    /// already exists and the count should stay the same.
260    fn replace(&self, fid: u32, entry: FidEntry) {
261        self.fids.insert(fid, entry);
262    }
263
264    /// Take a fid entry WITHOUT decrementing the client's count.
265    /// Use this when the fid will be re-inserted (state transition).
266    /// The caller is responsible for re-inserting via `replace` or `insert`.
267    fn take(&self, fid: u32) -> Option<FidEntry> {
268        self.fids.remove(&fid).map(|(_, v)| v)
269    }
270
271    /// Remove a fid and decrement the client's count.
272    fn remove(&self, fid: u32, client_id: &str) -> Option<FidEntry> {
273        let removed = self.fids.remove(&fid).map(|(_, v)| v);
274        if removed.is_some() {
275            if let Some(count) = self.client_fid_counts.get(client_id) {
276                count.fetch_sub(1, Relaxed);
277            }
278        }
279        removed
280    }
281
282    /// Get a reference to a fid entry, verifying ownership.
283    fn get_verified(
284        &self,
285        fid: u32,
286        client_id: &str,
287    ) -> Result<dashmap::mapref::one::Ref<'_, u32, FidEntry>, FsError> {
288        let entry = self
289            .fids
290            .get(&fid)
291            .ok_or_else(|| FsError::NotFound(format!("bad fid: {}", fid)))?;
292        if entry.owner_identity != client_id {
293            return Err(FsError::PermissionDenied("fid not owned by caller".into()));
294        }
295        entry.last_accessed.store(now_epoch_secs(), Relaxed);
296        Ok(entry)
297    }
298}
299
300/// ZMQ-based registry service
301///
302/// Wraps git2db::Git2DB and provides a Cap'n Proto interface over ZMQ.
303///
304/// ## Streaming Support
305///
306/// Streaming clone uses the Continuation pipeline (same as inference streaming):
307/// 1. Handler performs DH key exchange and returns (StreamInfo, Continuation)
308/// 2. Dispatch serializes StreamInfo as the REP response
309/// 3. RequestLoop spawns the Continuation after REP is sent
310/// 4. Continuation publishes clone progress via PUB/SUB
311///
312/// The registry is wrapped in RwLock for interior mutability since some operations
313/// (like clone) require mutable access but RequestService::handle_request takes &self.
314pub struct RegistryService {
315    // Business logic
316    registry: Arc<RwLock<Git2DB>>,
317    #[allow(dead_code)] // Future: base directory for relative path operations
318    base_dir: PathBuf,
319    /// Policy client for authorization checks (uses ZMQ to PolicyService)
320    policy_client: PolicyClient,
321    /// No runtime installer in this slice; reserved Federate JWTs still deny.
322    #[cfg(feature = "postgres")]
323    federate_dispatch: Option<Arc<crate::services::oauth::federate_proof::DispatchAdapter>>,
324    // Infrastructure (for Spawnable)
325    transport: TransportConfig,
326    signing_key: SigningKey,
327    reach_config: hyprstream_rpc::moq_stream::ProducerReachConfigHandle,
328    moq_origin: hyprstream_rpc::moq_stream::MoqStreamOriginHandle,
329    /// 9P fid table for filesystem operations.
330    fid_table: Arc<FidTable>,
331    /// Cached contained roots for worktrees: (repo_id, worktree_name) → ContainedFs.
332    contained_roots: DashMap<(String, String), Arc<dyn ContainedFs>>,
333    /// CRDT editing sessions for collaborative file editing.
334    editing_table: Arc<EditingTable>,
335    /// Expected JWT audience for token validation (RFC 8707).
336    expected_audience: Option<String>,
337    /// Present only for an explicitly configured canonical 9P read export.
338    /// Relay admission additionally requires the relay's live registered
339    /// `mcp` service-key grant — the MCP service is the relay for the
340    /// MCP-driven 9P read path (same pattern as Model's `oai`/`mcp` relay
341    /// checks, model.rs accept_delegated_bearer).
342    ninep_canonical_read: Option<crate::config::NinepCanonicalReadConfig>,
343    delegated_ninep_audience: Option<String>,
344    /// JWT key source for token verification.
345    jwt_key_source: Option<std::sync::Arc<dyn hyprstream_rpc::auth::JwtKeySource>>,
346    /// Server-side `(merkle_hex → repo_id)` provenance store backing the
347    /// fail-closed XET `getBlob` gate (#436 / #509). Pointer presence is
348    /// necessary-but-not-sufficient: entitlement requires a provenance record.
349    xet_provenance: Arc<XetProvenanceStore>,
350    /// Per-read CAS MAC PEP, production-wired to verified subject contexts and
351    /// a signed WAL.
352    cas_pep: Arc<crate::mac::CasPep>,
353    /// Publishes/advances a repo's `ai.hyprstream.model` PDS record on
354    /// register + commit (#910a). `None` means this node has no PDS
355    /// configured — register/commit proceed exactly as before.
356    #[cfg(feature = "rocksdb")]
357    pds_publisher: Option<Arc<crate::services::discovery::PdsPublisher>>,
358}
359
360/// Progress reporter that sends updates via a tokio mpsc channel.
361///
362/// Implements `git2db::callback_config::ProgressReporter` to bridge git2db's
363/// progress callbacks to hyprstream's stream publishing system.
364///
365/// Uses `blocking_send` since this is called from a sync context (spawn_blocking).
366struct CloneProgressReporter {
367    sender: tokio::sync::mpsc::Sender<hyprstream_rpc::streaming::ProgressUpdate>,
368}
369
370impl CloneProgressReporter {
371    fn new(sender: tokio::sync::mpsc::Sender<hyprstream_rpc::streaming::ProgressUpdate>) -> Self {
372        Self { sender }
373    }
374}
375
376impl git2db::callback_config::ProgressReporter for CloneProgressReporter {
377    fn report(&self, stage: &str, current: usize, total: usize) {
378        // Use try_send to avoid deadlocking the single-threaded runtime
379        // when called from async context (e.g., LFS progress). Progress is best-effort.
380        match self
381            .sender
382            .try_send(hyprstream_rpc::streaming::ProgressUpdate::Progress {
383                stage: stage.to_owned(),
384                current,
385                total,
386            }) {
387            Ok(()) => {}
388            Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
389                tracing::trace!("Progress channel full, dropping update");
390            }
391            Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
392                tracing::trace!("Progress channel closed");
393            }
394        }
395    }
396}
397
398impl RegistryService {
399    /// Create a new registry service with infrastructure
400    ///
401    /// Must be called from within a tokio runtime context.
402    pub async fn new(
403        base_dir: impl AsRef<Path>,
404        policy_client: PolicyClient,
405        transport: TransportConfig,
406        signing_key: SigningKey,
407    ) -> Result<Self> {
408        let base_dir = base_dir.as_ref().to_path_buf();
409        let registry = Git2DB::open(&base_dir).await?;
410
411        // Load the XET provenance store (lives alongside registry metadata).
412        // Missing file → empty store → fail-closed XET getBlob (secure default).
413        let xet_provenance = Arc::new(XetProvenanceStore::load(&base_dir).await?);
414
415        let worker_registry = Arc::new(RwLock::new(registry));
416
417        // Create fid table and editing table, spawn reaper
418        let fid_table = Arc::new(FidTable::new());
419        let editing_table = Arc::new(EditingTable::new());
420        let reaper_fid_table = Arc::clone(&fid_table);
421        let reaper_editing_table = Arc::clone(&editing_table);
422        tokio::spawn(async move {
423            Self::fid_reaper(reaper_fid_table, reaper_editing_table).await;
424        });
425
426        let service = Self {
427            registry: worker_registry,
428            base_dir,
429            policy_client,
430            #[cfg(feature = "postgres")]
431            federate_dispatch: None,
432            transport,
433            signing_key,
434            reach_config: Arc::new(parking_lot::RwLock::new(
435                hyprstream_rpc::moq_stream::ProducerReachConfig::default(),
436            )),
437            moq_origin: Arc::new(parking_lot::RwLock::new(None)),
438            fid_table,
439            contained_roots: DashMap::new(),
440            editing_table,
441            expected_audience: None,
442            ninep_canonical_read: None,
443            delegated_ninep_audience: None,
444            jwt_key_source: None,
445            xet_provenance,
446            cas_pep: Arc::new(crate::mac::CasPep::fail_closed()),
447            #[cfg(feature = "rocksdb")]
448            pds_publisher: None,
449        };
450
451        Ok(service)
452    }
453
454    /// Set the expected JWT audience for token validation.
455    pub fn with_expected_audience(mut self, audience: String) -> Self {
456        self.expected_audience = Some(audience);
457        self
458    }
459
460    /// Admit only an operator-selected repository/worktree through a separate
461    /// live relay grant. This does not grant the OAI service a Registry scope.
462    pub fn with_ninep_canonical_read(
463        mut self,
464        export: crate::config::NinepCanonicalReadConfig,
465        issuer: String,
466    ) -> anyhow::Result<Self> {
467        export.validate()?;
468        anyhow::ensure!(!issuer.is_empty(), "9P issuer audience required");
469        self.ninep_canonical_read = Some(export);
470        self.delegated_ninep_audience = Some(issuer);
471        Ok(self)
472    }
473
474    /// Wire in the PDS publisher (#910a). Registration and
475    /// `commitWithAuthor` (the RPC promote also drives) will publish/advance
476    /// the repo's `ai.hyprstream.model` record through it.
477    #[cfg(feature = "rocksdb")]
478    pub fn with_pds_publisher(
479        mut self,
480        publisher: crate::services::discovery::PdsPublisher,
481    ) -> Self {
482        self.pds_publisher = Some(Arc::new(publisher));
483        self
484    }
485
486    /// Like [`Self::with_pds_publisher`] but takes an already-`Arc`'d publisher,
487    /// so the caller can retain a weak clone for the ES256 promotion hook (#918).
488    #[cfg(feature = "rocksdb")]
489    pub fn with_pds_publisher_arc(
490        mut self,
491        publisher: Arc<crate::services::discovery::PdsPublisher>,
492    ) -> Self {
493        self.pds_publisher = Some(publisher);
494        self
495    }
496
497    /// Best-effort publish/advance of `repo_id`'s PDS record (#910a).
498    ///
499    /// Failures are logged and swallowed, never surfaced to the RPC caller:
500    /// the git commit/registration that triggered this already succeeded and
501    /// is the durable source of truth, matching the eventual-consistency
502    /// contract `git::promote` documents for the (still-stubbed, cross-node)
503    /// pointer-advance path. A missed local publish is caught up by the next
504    /// successful register/commit on the same repo.
505    #[cfg(feature = "rocksdb")]
506    fn publish_pds_record(&self, repo_id: &RepoId, current_oid: &str) {
507        let Some(publisher) = &self.pds_publisher else {
508            return;
509        };
510        if let Err(e) = publisher.publish(&repo_id.to_string(), current_oid) {
511            warn!(
512                repo_id = %repo_id, current_oid, error = %e,
513                "PDS record publish failed; local state is durable, record is stale until next publish"
514            );
515        }
516    }
517
518    /// No-PDS twin: `None` means register/commit proceed exactly as before.
519    #[cfg(not(feature = "rocksdb"))]
520    fn publish_pds_record(&self, _repo_id: &RepoId, _current_oid: &str) {}
521
522    /// Set the JWT key source for token verification.
523    pub fn with_jwt_key_source(
524        mut self,
525        src: std::sync::Arc<dyn hyprstream_rpc::auth::JwtKeySource>,
526    ) -> Self {
527        self.jwt_key_source = Some(src);
528        self
529    }
530
531    #[cfg(feature = "postgres")]
532    pub(crate) fn with_federate_dispatch(
533        mut self,
534        adapter: Arc<crate::services::oauth::federate_proof::DispatchAdapter>,
535    ) -> Self {
536        self.federate_dispatch = Some(adapter);
537        self
538    }
539
540    /// Install the production CAS PEP used by streaming continuations.
541    pub fn with_cas_pep(mut self, pep: Arc<crate::mac::CasPep>) -> Self {
542        self.cas_pep = pep;
543        self
544    }
545
546    /// Validate that a path is within the base directory (I5/I6 fix).
547    fn validate_path_within_base(&self, path: &Path) -> Result<()> {
548        // If path exists, use canonical check
549        if path.exists() {
550            let canonical_path = path
551                .canonicalize()
552                .map_err(|e| anyhow!("Failed to canonicalize path: {}", e))?;
553            let canonical_base = self
554                .base_dir
555                .canonicalize()
556                .map_err(|e| anyhow!("Failed to canonicalize base dir: {}", e))?;
557            if !canonical_path.starts_with(&canonical_base) {
558                return Err(anyhow!(
559                    "Path {:?} is outside base directory {:?}",
560                    canonical_path,
561                    canonical_base
562                ));
563            }
564        } else {
565            // Path doesn't exist yet — use contained_join for validation
566            let _ = hyprstream_containedfs::contained_join(&self.base_dir, &path.to_string_lossy())
567                .map_err(|e| anyhow!("Path validation failed: {}", e))?;
568        }
569        Ok(())
570    }
571
572    /// Background task that reaps idle fids.
573    async fn fid_reaper(fid_table: Arc<FidTable>, editing_table: Arc<EditingTable>) {
574        let mut interval = tokio::time::interval(Duration::from_secs(60));
575        loop {
576            interval.tick().await;
577            let now = now_epoch_secs();
578            fid_table.fids.retain(|fid, entry| {
579                let idle = now.saturating_sub(entry.last_accessed.load(Relaxed));
580                if idle > FID_IDLE_TIMEOUT.as_secs() {
581                    // Clean up any editing sessions associated with this fid
582                    editing_table.on_reap(&entry.owner_identity, *fid);
583                    // Decrement client fid count
584                    if let Some(count) = fid_table.client_fid_counts.get(&entry.owner_identity) {
585                        count.fetch_sub(1, Relaxed);
586                    }
587                    debug!("Reaped idle fid (idle {}s)", idle);
588                    false // remove
589                } else {
590                    true // keep
591                }
592            });
593        }
594    }
595
596    /// Execute a streaming clone with real-time progress via Continuation.
597    ///
598    /// Uses git2db's callback_config to receive progress updates during clone,
599    /// which are forwarded to the client via StreamChannel in real-time.
600    /// Called as a Continuation after the REP response is sent.
601    #[allow(clippy::too_many_arguments)]
602    async fn execute_clone_stream(
603        stream_channel: StreamChannel,
604        registry: Arc<RwLock<Git2DB>>,
605        stream_ctx: StreamContext,
606        url: String,
607        name: Option<String>,
608        shallow: bool,
609        depth: Option<u32>,
610        branch: Option<String>,
611    ) {
612        use hyprstream_rpc::streaming::ProgressUpdate;
613
614        debug!(
615            stream_id = %stream_ctx.stream_id(),
616            url = %url,
617            "Starting streaming clone with progress reporting"
618        );
619
620        // Create tokio channel for receiving updates from git2db
621        let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel::<ProgressUpdate>(100);
622
623        // Create reporter that implements git2db::ProgressReporter
624        let reporter = Arc::new(CloneProgressReporter::new(progress_tx.clone()));
625
626        // Build callback config with progress reporter
627        let callback_config = git2db::callback_config::CallbackConfig::new()
628            .with_progress(git2db::callback_config::ProgressConfig::Channel(reporter));
629
630        // Execute clone and stream progress concurrently
631        let result = stream_channel
632            .run_stream(&stream_ctx, |mut publisher| async move {
633                // Spawn clone task - runs concurrently with progress streaming
634                let registry_clone = Arc::clone(&registry);
635
636                let clone_handle = tokio::spawn(async move {
637                    // CloneBuilder manages locks internally for optimal performance
638                    // (read lock for config, no lock during network I/O, write lock for registration)
639                    Self::clone_repo_inner(
640                        registry_clone,
641                        &url,
642                        name.as_deref(),
643                        shallow,
644                        depth,
645                        branch.as_deref(),
646                        Some(callback_config),
647                    )
648                    .await
649                });
650
651                // Drop sender after spawning so receiver knows when clone finishes
652                drop(progress_tx);
653
654                // Stream progress updates in real-time as they arrive
655                // (Ignore Complete/Error from channel - we'll send our own based on clone_result)
656                while let Some(update) = progress_rx.recv().await {
657                    if let ProgressUpdate::Progress {
658                        stage,
659                        current,
660                        total,
661                    } = update
662                    {
663                        if let Err(e) = publisher.publish_progress(&stage, current, total).await {
664                            return (publisher, Err(e));
665                        }
666                    }
667                }
668
669                // Wait for clone to complete and send final status
670                let result = match clone_handle.await {
671                    Ok(Ok(repo)) => {
672                        let metadata = serde_json::json!({
673                            "repo_id": repo.id.to_string(),
674                            "name": repo.name,
675                            "url": repo.url,
676                        });
677                        publisher
678                            .complete_ref(metadata.to_string().as_bytes())
679                            .await
680                    }
681                    Ok(Err(e)) => Err(e), // framework sends Error frame automatically
682                    Err(e) => Err(anyhow!("Clone task panicked: {}", e)), // framework sends Error frame
683                };
684                (publisher, result)
685            })
686            .await;
687
688        if let Err(e) = result {
689            error!(
690                stream_id = %stream_ctx.stream_id(),
691                error = %e,
692                "Clone stream failed"
693            );
694        }
695    }
696
697    /// Parse a RepoId from string
698    fn parse_repo_id(id_str: &str) -> Result<RepoId> {
699        let uuid =
700            Uuid::parse_str(id_str).map_err(|e| anyhow!("invalid repo id '{}': {}", id_str, e))?;
701        Ok(RepoId::from_uuid(uuid))
702    }
703
704    /// Internal clone logic shared by sync and streaming clone operations.
705    ///
706    /// Builds clone request, executes it, and returns the cloned repository.
707    /// CloneBuilder manages locks internally for optimal performance.
708    ///
709    /// # Arguments
710    /// * `callback_config` - Optional callback configuration for progress reporting
711    async fn clone_repo_inner(
712        registry: Arc<RwLock<Git2DB>>,
713        url: &str,
714        name: Option<&str>,
715        shallow: bool,
716        depth: Option<u32>,
717        branch: Option<&str>,
718        callback_config: Option<git2db::callback_config::CallbackConfig>,
719    ) -> Result<TrackedRepository> {
720        let mut clone_builder = CloneBuilder::new(Arc::clone(&registry), url);
721
722        if let Some(n) = name {
723            clone_builder = clone_builder.name(n);
724        }
725
726        // depth > 0 implies shallow clone
727        // if shallow is explicitly set but depth is 0, use depth=1
728        if let Some(d) = depth.filter(|&d| d > 0) {
729            clone_builder = clone_builder.depth(d);
730        } else if shallow {
731            clone_builder = clone_builder.depth(1);
732        }
733
734        if let Some(b) = branch.filter(|b| !b.is_empty()) {
735            clone_builder = clone_builder.branch(b);
736        }
737
738        // Add callback config for progress reporting if provided
739        if let Some(config) = callback_config {
740            clone_builder = clone_builder.callback_config(config);
741        }
742
743        let repo_id = clone_builder.exec().await?;
744
745        // Get the tracked repository to return
746        let registry_guard = registry.read().await;
747        let result = registry_guard
748            .list()
749            .find(|r| r.id == repo_id)
750            .cloned()
751            .ok_or_else(|| anyhow!("Failed to find cloned repository"));
752        drop(registry_guard);
753        result
754    }
755
756    /// Handle a list repositories request
757    async fn handle_list(&self) -> Result<Vec<TrackedRepository>> {
758        let registry = self.registry.read().await;
759        Ok(registry.list().cloned().collect())
760    }
761
762    /// Handle get repository by ID
763    async fn handle_get(&self, repo_id: &str) -> Result<Option<TrackedRepository>> {
764        let id = Self::parse_repo_id(repo_id)?;
765        let registry = self.registry.read().await;
766        let result = registry.list().find(|r| r.id == id).cloned();
767        Ok(result)
768    }
769
770    /// Handle get repository by name
771    async fn handle_get_by_name(&self, name: &str) -> Result<Option<TrackedRepository>> {
772        let registry = self.registry.read().await;
773        let result = registry
774            .list()
775            .find(|r| r.name.as_ref() == Some(&name.to_owned()))
776            .cloned();
777        Ok(result)
778    }
779
780    /// Handle list branches
781    async fn handle_list_branches(&self, repo_id: &str) -> Result<Vec<String>> {
782        let id = Self::parse_repo_id(repo_id)?;
783        let registry = self.registry.read().await;
784        let handle = registry.repo(&id)?;
785        let branches = handle.branch().list().await?;
786        Ok(branches.into_iter().map(|b| b.name).collect())
787    }
788
789    /// Handle create branch
790    async fn handle_create_branch(
791        &self,
792        repo_id: &str,
793        branch_name: &str,
794        start_point: Option<&str>,
795    ) -> Result<()> {
796        let id = Self::parse_repo_id(repo_id)?;
797        let registry = self.registry.read().await;
798        let handle = registry.repo(&id)?;
799        handle.branch().create(branch_name, start_point).await?;
800        Ok(())
801    }
802
803    /// Handle status
804    async fn handle_status(&self, repo_id: &str) -> Result<git2db::RepositoryStatus> {
805        let id = Self::parse_repo_id(repo_id)?;
806
807        // Use with_repo_blocking to properly resolve worktree path for bare repos
808        self.with_repo_blocking(&id, |repo| {
809            let head = repo.head().ok();
810            let branch = head.as_ref().and_then(|h| h.shorthand().map(String::from));
811            let head_oid = head.as_ref().and_then(git2::Reference::target);
812
813            let statuses = repo
814                .statuses(None)
815                .map_err(|e| anyhow!("Failed to get statuses: {}", e))?;
816            let is_clean = statuses.is_empty();
817            let modified_files: Vec<std::path::PathBuf> = statuses
818                .iter()
819                .filter_map(|e| e.path().map(std::path::PathBuf::from))
820                .collect();
821
822            // Compute ahead/behind
823            let (ahead, behind) = if let Ok(ref head_ref) = repo.head() {
824                if let Some(branch_name) = head_ref.shorthand() {
825                    let upstream_name = format!("origin/{}", branch_name);
826                    if let Ok(upstream) = repo.revparse_single(&upstream_name) {
827                        if let (Ok(local), Ok(remote)) =
828                            (head_ref.peel_to_commit(), upstream.peel_to_commit())
829                        {
830                            repo.graph_ahead_behind(local.id(), remote.id())
831                                .unwrap_or((0, 0))
832                        } else {
833                            (0, 0)
834                        }
835                    } else {
836                        (0, 0)
837                    }
838                } else {
839                    (0, 0)
840                }
841            } else {
842                (0, 0)
843            };
844
845            Ok(git2db::RepositoryStatus {
846                branch,
847                head: head_oid,
848                ahead,
849                behind,
850                is_clean,
851                modified_files,
852            })
853        })
854        .await
855    }
856
857    /// Handle clone operation
858    async fn handle_clone(
859        &self,
860        url: &str,
861        name: Option<&str>,
862        shallow: bool,
863        depth: Option<u32>,
864        branch: Option<&str>,
865    ) -> Result<TrackedRepository> {
866        Self::clone_repo_inner(
867            Arc::clone(&self.registry),
868            url,
869            name,
870            shallow,
871            depth,
872            branch,
873            None,
874        )
875        .await
876    }
877
878    // ========================================================================
879    // Streaming Clone Support
880    // ========================================================================
881
882    /// Prepare a streaming clone operation and return (StreamInfo, Continuation).
883    ///
884    /// Creates a StreamChannel for DH key exchange and pre-authorization.
885    /// The continuation contains the clone work, executed by RequestLoop after REP is sent.
886    async fn prepare_clone_stream(
887        &self,
888        url: &str,
889        name: Option<&str>,
890        shallow: bool,
891        depth: Option<u32>,
892        branch: Option<&str>,
893        client_ephemeral_pubkey: Option<&[u8]>,
894    ) -> Result<(StreamInfo, hyprstream_rpc::service::Continuation)> {
895        // DH key derivation is required
896        let client_pub_bytes = client_ephemeral_pubkey.ok_or_else(|| {
897            anyhow!("Streaming requires client ephemeral pubkey for E2E authentication")
898        })?;
899
900        // Create StreamChannel for DH key exchange and publishing
901        let stream_channel = StreamChannel::new(self.signing_key.clone())
902            .with_reach_config(hyprstream_rpc::moq_stream::ProducerReachConfig::default())
903            .with_reach_config_handle(self.reach_config.clone())
904            .with_moq_origin_handle(self.moq_origin.clone());
905
906        // 10 minutes expiry for clone operations
907        let stream_ctx = stream_channel
908            .prepare_third_party_interop_stream(client_pub_bytes, 600)
909            .await?;
910
911        debug!(
912            stream_id = %stream_ctx.stream_id(),
913            topic = %stream_ctx.topic(),
914            "Clone stream prepared (DH + pre-authorization via StreamChannel)"
915        );
916
917        let broadcast_path = hyprstream_rpc::moq_stream::global_moq_origin()
918            .map(|o| o.broadcast_path(stream_ctx.topic()))
919            .unwrap_or_default();
920        let stream_info = StreamInfo {
921            stream_id: stream_ctx.stream_id().to_owned(),
922            dh_public: *stream_ctx.server_pubkey(),
923            broadcast_path,
924            announced_at: stream_ctx.reach(), // #384: per-stream reach via ctx
925            moql_server_identity: stream_ctx.moql_server_identity(),
926            ..Default::default()
927        };
928
929        // Build continuation that executes the clone and streams progress
930        let registry = Arc::clone(&self.registry);
931        let url = url.to_owned();
932        let name = name.map(std::borrow::ToOwned::to_owned);
933        let branch = branch.map(std::borrow::ToOwned::to_owned);
934
935        let continuation: hyprstream_rpc::service::Continuation = Box::pin(async move {
936            Self::execute_clone_stream(
937                stream_channel,
938                registry,
939                stream_ctx,
940                url,
941                name,
942                shallow,
943                depth,
944                branch,
945            )
946            .await;
947        });
948
949        Ok((stream_info, continuation))
950    }
951
952    // ========================================================================
953    // Content-addressed blob fetch (getBlob, #432)
954    // ========================================================================
955
956    /// Resolve a grantRepo identifier (at-uri / id / name / url) to a tracked
957    /// repository. Federation-portable at-uris are matched by their trailing
958    /// component against the repo name; we also accept an exact UUID, name, or
959    /// URL match so callers can use whichever they resolved.
960    async fn resolve_grant_repo(&self, grant_repo: &str) -> Option<TrackedRepository> {
961        let registry = self.registry.read().await;
962        // at-uri form: take the trailing path segment as the repo name candidate.
963        let name_candidate = grant_repo.rsplit('/').next().unwrap_or(grant_repo);
964        let found = registry
965            .list()
966            .find(|r| {
967                r.id.to_string() == grant_repo
968                    || r.url == grant_repo
969                    || r.name.as_deref() == Some(grant_repo)
970                    || r.name.as_deref() == Some(name_candidate)
971            })
972            .cloned();
973        found
974    }
975
976    /// Authorize a getBlob request, HuggingFace-Xet-compatible. The CAS is GLOBAL
977    /// and content-addressed (cross-repo dedup preserved); isolation is enforced
978    /// at the READ-AUTHORIZATION layer per HF's rule — "you can only read chunks
979    /// required to reproduce files you have access to, and no more." Enforces BOTH:
980    ///   (a) the authenticated caller may access `grant_repo` (Casbin query on
981    ///       `model:{name}`), AND
982    ///   (b) the requested content address is the **reconstruction target of a
983    ///       file in `grant_repo`** — for git OIDs, the object exists in the repo;
984    ///       for XET merkles, a tracked git-xet/lfs file's content-OID equals the
985    ///       merkle (file-level entitlement-by-reconstruction; see
986    ///       `repo_contains_xet_merkle`). Merely naming the hash in a checked-in
987    ///       blob does NOT authorize it.
988    /// The content hash is NEVER a capability — possessing the hash grants
989    /// nothing; entitlement keys on `grant_repo` access AND the content being a
990    /// reconstruction target there. `Err` denies (no bytes).
991    ///
992    /// Returns the resolved content address string for downstream reconstruction.
993    async fn authorize_get_blob(
994        &self,
995        ctx: &EnvelopeContext,
996        data: &GetBlobRequest,
997    ) -> Result<String> {
998        // Extract the content address from the union.
999        let address = match &data.content {
1000            GetBlobRequestContent::GitOid(oid) => oid.clone(),
1001            GetBlobRequestContent::XetMerkle(m) => m.clone(),
1002        };
1003        let is_git_oid = matches!(&data.content, GetBlobRequestContent::GitOid(_));
1004
1005        if data.grant_repo.trim().is_empty() {
1006            anyhow::bail!("getBlob denied: grantRepo is required (the hash is not a capability)");
1007        }
1008        if address.trim().is_empty() {
1009            anyhow::bail!("getBlob denied: empty content address");
1010        }
1011
1012        // Resolve grantRepo → tracked repo. Unknown repo = deny.
1013        let repo = self
1014            .resolve_grant_repo(&data.grant_repo)
1015            .await
1016            .ok_or_else(|| anyhow!("getBlob denied: grantRepo '{}' not found", data.grant_repo))?;
1017        let repo_name = repo.name.clone().unwrap_or_default();
1018        if repo_name.is_empty() {
1019            anyhow::bail!("getBlob denied: grantRepo has no name for authz");
1020        }
1021
1022        // ── Condition (a): caller may access grantRepo (registry/model scope). ──
1023        // Reuse the standard Casbin query gate used elsewhere in this service.
1024        RegistryHandler::authorize(self, ctx, &format!("model:{}", repo_name), "query")
1025            .await
1026            .map_err(|e| anyhow!("getBlob denied: {}", e))?;
1027
1028        // ── Condition (b): the address is a reconstruction target in grantRepo. ──
1029        // HF-compatible read-authorization over global dedup: permit iff a file in
1030        // grantRepo genuinely reconstructs FROM this address (git OID exists, or a
1031        // tracked xet/lfs pointer's content-OID equals the merkle). Prevents both
1032        // naming an unrelated repo to fish bytes AND planting a bare hex reference
1033        // to borrow read access to content the caller isn't entitled to reproduce.
1034        let contained = if is_git_oid {
1035            self.repo_contains_git_oid(&repo.id, &address).await?
1036        } else {
1037            self.repo_contains_xet_merkle(&repo.id, &address).await?
1038        };
1039        if !contained {
1040            anyhow::bail!(
1041                "getBlob denied: grantRepo '{}' does not contain address '{}'",
1042                data.grant_repo,
1043                address
1044            );
1045        }
1046
1047        Ok(address)
1048    }
1049
1050    /// Condition-(b) check for a git OID: the object must exist in grantRepo's
1051    /// object database.
1052    async fn repo_contains_git_oid(&self, repo_id: &git2db::RepoId, oid_hex: &str) -> Result<bool> {
1053        let oid_hex = oid_hex.to_owned();
1054        self.with_repo_blocking(repo_id, move |repo| {
1055            let oid = match git2::Oid::from_str(&oid_hex) {
1056                Ok(o) => o,
1057                Err(_) => return Ok(false), // malformed OID → not contained
1058            };
1059            Ok(repo.odb().map(|odb| odb.exists(oid)).unwrap_or(false))
1060        })
1061        .await
1062    }
1063
1064    // (helper `xet_pointer_references_merkle` defined at module scope below)
1065
1066    /// Condition-(b) check for a XET merkle root — **provenance-gated and
1067    /// fail-closed** (the #436 / #509 fix).
1068    ///
1069    /// Entitlement requires BOTH:
1070    ///   1. a **server-side provenance record** binding this merkle to
1071    ///      `repo_id` (i.e. this repo actually *uploaded* the bytes); AND
1072    ///   2. (defense-in-depth) the repo's current HEAD tree still **references**
1073    ///      the merkle via a checked-in git-xet / git-lfs pointer whose merkle
1074    ///      field EXACTLY equals the requested hash.
1075    ///
1076    /// The provenance record is the authoritative gate. Pointer presence is
1077    /// **necessary-but-not-sufficient**: because the CAS is global and
1078    /// non-namespaced, a pointer blob is caller-committed and therefore
1079    /// *forgeable* — Tenant B can plant `oid sha256:<Tenant A's private merkle>`
1080    /// in their own repo. We therefore **deny when no provenance record exists**
1081    /// and NEVER fall back to the pointer-only check. See
1082    /// [`crate::services::xet_provenance`] for the trust boundary and #509 for
1083    /// the authenticated upload-binding that populates provenance.
1084    async fn repo_contains_xet_merkle(
1085        &self,
1086        repo_id: &git2db::RepoId,
1087        merkle_hex: &str,
1088    ) -> Result<bool> {
1089        // ── Authoritative gate: fail-closed provenance check. ──
1090        // No record binding (merkle → repo) ⇒ deny, regardless of any pointer.
1091        if !self
1092            .xet_provenance
1093            .is_bound(merkle_hex, &repo_id.0.to_string())
1094            .await
1095        {
1096            return Ok(false);
1097        }
1098
1099        // ── Defense-in-depth: the repo must still reference the merkle. ──
1100        let merkle_hex = merkle_hex.to_owned();
1101        self.with_repo_blocking(repo_id, move |repo| {
1102            let head = match repo.head().ok().and_then(|h| h.peel_to_tree().ok()) {
1103                Some(t) => t,
1104                None => return Ok(false),
1105            };
1106            let mut found = false;
1107            // Walk the HEAD tree; for each pointer-sized blob, parse it as a
1108            // git-xet / git-lfs pointer and match the merkle/oid field EXACTLY.
1109            head.walk(git2::TreeWalkMode::PreOrder, |_dir, entry| {
1110                if entry.kind() == Some(git2::ObjectType::Blob) {
1111                    if let Ok(obj) = entry.to_object(&repo) {
1112                        if let Some(blob) = obj.as_blob() {
1113                            // Pointers are small text files; bound the read.
1114                            if blob.size() <= 4096 {
1115                                if let Ok(text) = std::str::from_utf8(blob.content()) {
1116                                    if xet_pointer_references_merkle(text, &merkle_hex) {
1117                                        found = true;
1118                                        return git2::TreeWalkResult::Abort;
1119                                    }
1120                                }
1121                            }
1122                        }
1123                    }
1124                }
1125                git2::TreeWalkResult::Ok
1126            })
1127            .ok();
1128            Ok(found)
1129        })
1130        .await
1131    }
1132
1133    /// Prepare a streaming getBlob: DH key exchange + a continuation that
1134    /// reconstructs the content-addressed bytes via the shared cas-serve store
1135    /// (CDC→xorbs→mdb_shard→bytes) and publishes them over the moq plane.
1136    /// Mirrors `prepare_clone_stream`'s StreamInfo production path.
1137    async fn prepare_get_blob_stream(
1138        &self,
1139        address: String,
1140        client_ephemeral_pubkey: Option<&[u8]>,
1141        subject_id: String,
1142        verified_tenant: Option<String>,
1143    ) -> Result<(StreamInfo, hyprstream_rpc::service::Continuation)> {
1144        let client_pub_bytes = client_ephemeral_pubkey.ok_or_else(|| {
1145            anyhow!("Streaming requires client ephemeral pubkey for E2E authentication")
1146        })?;
1147
1148        let stream_channel = StreamChannel::new(self.signing_key.clone())
1149            .with_reach_config(hyprstream_rpc::moq_stream::ProducerReachConfig::default())
1150            .with_reach_config_handle(self.reach_config.clone())
1151            .with_moq_origin_handle(self.moq_origin.clone());
1152        // 10 minutes expiry — weights are GB-scale.
1153        let stream_ctx = stream_channel
1154            .prepare_third_party_interop_stream(client_pub_bytes, 600)
1155            .await?;
1156
1157        debug!(
1158            stream_id = %stream_ctx.stream_id(),
1159            topic = %stream_ctx.topic(),
1160            "getBlob stream prepared (DH + pre-authorization via StreamChannel)"
1161        );
1162
1163        let broadcast_path = hyprstream_rpc::moq_stream::global_moq_origin()
1164            .map(|o| o.broadcast_path(stream_ctx.topic()))
1165            .unwrap_or_default();
1166        let stream_info = StreamInfo {
1167            stream_id: stream_ctx.stream_id().to_owned(),
1168            dh_public: *stream_ctx.server_pubkey(),
1169            broadcast_path,
1170            announced_at: stream_ctx.reach(),
1171            moql_server_identity: stream_ctx.moql_server_identity(),
1172            ..Default::default()
1173        };
1174        let cas_pep = Arc::clone(&self.cas_pep);
1175
1176        let continuation: hyprstream_rpc::service::Continuation = Box::pin(async move {
1177            Self::execute_get_blob_stream(
1178                stream_channel,
1179                stream_ctx,
1180                address,
1181                subject_id,
1182                verified_tenant,
1183                cas_pep,
1184            )
1185            .await;
1186        });
1187
1188        Ok((stream_info, continuation))
1189    }
1190
1191    /// Continuation body: reconstruct bytes and stream them. Reuses
1192    /// `cas_serve::CasStore` for reconstruction (no reimplementation).
1193    ///
1194    /// #1270: performs a MAC `can_access` recheck at the point of use (before
1195    /// any bytes are read from the substrate). The subject identity was captured
1196    /// from the verified `EnvelopeContext` at handler time. The explicitly
1197    /// installed fail-closed [`CasPep`] denies when no CAS clearance adapter is
1198    /// configured. There is no permissive mode inside the installed PEP.
1199    async fn execute_get_blob_stream(
1200        stream_channel: StreamChannel,
1201        stream_ctx: StreamContext,
1202        address: String,
1203        subject_id: String,
1204        verified_tenant: Option<String>,
1205        cas_pep: Arc<crate::mac::CasPep>,
1206    ) {
1207        // 64 KiB publish frames — bound per-message size for GB-scale weights.
1208        const CHUNK: usize = 64 * 1024;
1209
1210        let result = stream_channel
1211            .run_stream(&stream_ctx, |mut publisher| async move {
1212                // L1 CAS substrate, default (untenanted, BLAKE3, local) domain —
1213                // layout-compatible with the legacy CasStore root (#812).
1214                let substrate = crate::storage::CasSubstrate::from_env();
1215                let domain = crate::storage::DedupDomain::local_default();
1216
1217                // #1270 MAC PEP recheck at point of use: derive the trusted
1218                // content-bound label from the domain and check the subject's
1219                // clearance BEFORE reading any bytes. Fail-closed: a deny
1220                // produces zero bytes of output.
1221                let resolver = crate::mac::CasObjectLabelResolver::from_domain(&domain);
1222                let decision = cas_pep
1223                    .check_read(&subject_id, verified_tenant.as_deref(), &resolver)
1224                    .await;
1225                if !decision.is_permit() {
1226                    tracing::warn!(
1227                        target: "hyprstream.mac.cas_pep",
1228                        %subject_id,
1229                        verified_tenant = ?verified_tenant,
1230                        %address,
1231                        ?decision,
1232                        "getBlob MAC PEP denied at continuation; no bytes streamed (#1270)"
1233                    );
1234                    return (
1235                        publisher,
1236                        Err(anyhow!(
1237                            "getBlob denied: MAC clearance check failed at point of use: \
1238                         {decision:?} (#1270)"
1239                        )),
1240                    );
1241                }
1242
1243                let bytes = match substrate.get(&domain, &address).await {
1244                    Ok(b) => b,
1245                    Err(e) => {
1246                        return (
1247                            publisher,
1248                            Err(anyhow!("getBlob reconstruction failed: {}", e)),
1249                        )
1250                    }
1251                };
1252                for frame in bytes.chunks(CHUNK) {
1253                    if let Err(e) = publisher.publish_data(frame).await {
1254                        return (publisher, Err(e));
1255                    }
1256                }
1257                let result = publisher.complete_ref(b"").await;
1258                (publisher, result)
1259            })
1260            .await;
1261
1262        if let Err(e) = result {
1263            error!(
1264                stream_id = %stream_ctx.stream_id(),
1265                error = %e,
1266                "getBlob stream failed"
1267            );
1268        }
1269    }
1270
1271    /// Handle list worktrees
1272    async fn handle_list_worktrees(
1273        &self,
1274        repo_id: &str,
1275    ) -> Result<Vec<hyprstream_rpc_std::registry_client::WorktreeInfo>> {
1276        let id = Self::parse_repo_id(repo_id)?;
1277        let registry = self.registry.read().await;
1278        let handle = registry.repo(&id)?;
1279        let mut worktrees = handle.get_worktrees().await?;
1280
1281        let archetype_registry = crate::archetypes::global_registry();
1282        let mut result = Vec::with_capacity(worktrees.len());
1283        for wt in &mut worktrees {
1284            // Extract branch name from worktree path (last component)
1285            let branch_name = wt
1286                .path()
1287                .file_name()
1288                .and_then(|s| s.to_str())
1289                .map(std::borrow::ToOwned::to_owned)
1290                .unwrap_or_default();
1291
1292            // Use WorktreeHandle::status() - single source of truth for dirty status
1293            let status = wt.status().await.ok();
1294            let is_dirty = status.as_ref().map(|s| !s.is_clean).unwrap_or(false);
1295            let head_oid = status
1296                .and_then(|s| s.head.map(|h| h.to_string()))
1297                .unwrap_or_default();
1298
1299            // Detect capabilities from worktree path (server-side, same machine as files)
1300            let capabilities: Vec<String> = archetype_registry
1301                .detect(wt.path())
1302                .to_detected_domains()
1303                .capabilities
1304                .to_ids()
1305                .into_iter()
1306                .map(std::borrow::ToOwned::to_owned)
1307                .collect();
1308
1309            result.push(hyprstream_rpc_std::registry_client::WorktreeInfo {
1310                path_removed: (), // field removed from schema
1311                branch_name,
1312                head_oid,
1313                is_locked: false,
1314                is_dirty,
1315                capabilities,
1316            });
1317        }
1318        Ok(result)
1319    }
1320
1321    /// Handle create worktree (idempotent — no-op if worktree already exists)
1322    async fn handle_create_worktree(&self, repo_id: &str, branch: &str) -> Result<()> {
1323        // Validate branch name (rejects .., control chars, path traversal)
1324        hyprstream_containedfs::validate_ref_name(branch)
1325            .map_err(|e| anyhow!("Invalid branch name: {}", e))?;
1326
1327        let id = Self::parse_repo_id(repo_id)?;
1328        let registry = self.registry.read().await;
1329        let handle = registry.repo(&id)?;
1330
1331        // Check if worktree already exists (idempotent)
1332        // Use status().branch instead of file_name() to handle hierarchical
1333        // branch names like "feature/my-branch" correctly.
1334        let mut worktrees = handle.get_worktrees().await?;
1335        for wt in &mut worktrees {
1336            let wt_branch = wt.status().await.ok().and_then(|s| s.branch);
1337            if wt_branch.as_deref() == Some(branch) {
1338                return Ok(());
1339            }
1340        }
1341
1342        // Create — empty path lets git2db derive safe worktrees/{branch} path
1343        handle.create_worktree(Path::new(""), branch).await?;
1344        Ok(())
1345    }
1346
1347    /// Handle register operation
1348    async fn handle_register(
1349        &self,
1350        path: &str,
1351        name: Option<&str>,
1352        tracking_ref: Option<&str>,
1353    ) -> Result<TrackedRepository> {
1354        let path = PathBuf::from(path);
1355        // I5: Validate path is within base_dir
1356        self.validate_path_within_base(&path)?;
1357        let name = name.map(std::borrow::ToOwned::to_owned);
1358
1359        // Register requires write lock
1360        let mut registry = self.registry.write().await;
1361
1362        // Name lookup is otherwise ambiguous when two registrations share a
1363        // label. Check under the same write lock held through builder.exec(),
1364        // so concurrent Register calls cannot both pass this guard.
1365        if let Some(name) = name.as_deref() {
1366            anyhow::ensure!(
1367                registry.get_by_name(name).is_none(),
1368                "Repository name is already registered"
1369            );
1370        }
1371
1372        // Generate a new repo ID
1373        let repo_id = RepoId::new();
1374
1375        // Derive URL from path (local file URL)
1376        let url = format!("file://{}", path.display());
1377
1378        // Use the non-deprecated registry.register(repo_id) builder so the
1379        // caller-supplied path is honored, rather than register_repository's
1380        // hard-coded base_dir/<uuid> location.
1381        let mut builder = registry
1382            .register(repo_id.clone())
1383            .url(url)
1384            .worktree_path(path);
1385        if let Some(name) = name {
1386            builder = builder.name(name);
1387        }
1388        if let Some(tracking_ref) = tracking_ref {
1389            builder = builder.tracking_ref(GitRef::Branch(tracking_ref.to_owned()));
1390        }
1391        builder.exec().await?;
1392
1393        // Get the tracked repository to return
1394        let repo = registry
1395            .list()
1396            .find(|r| r.id == repo_id)
1397            .cloned()
1398            .ok_or_else(|| anyhow!("Failed to find registered repository"))?;
1399        drop(registry);
1400
1401        // #910a — publish an initial PDS record if the newly-registered repo
1402        // already has a HEAD (e.g. registering an existing on-disk repo).
1403        // A freshly-initialized repo with no commits yet has no `current_oid`
1404        // to publish; its first `commitWithAuthor` will do so instead.
1405        if let Some(current_oid) = repo.current_oid.as_deref() {
1406            self.publish_pds_record(&repo_id, current_oid);
1407        }
1408
1409        Ok(repo)
1410    }
1411
1412    /// Handle remove operation
1413    async fn handle_remove(&self, repo_id: &str) -> Result<()> {
1414        let id = Self::parse_repo_id(repo_id)?;
1415
1416        // Remove requires write lock
1417        let mut registry = self.registry.write().await;
1418        registry.remove_repository(&id).await?;
1419        Ok(())
1420    }
1421
1422    /// Handle remove worktree operation (accepts branch name, resolves path internally)
1423    async fn handle_remove_worktree(&self, repo_id: &str, branch: &str) -> Result<()> {
1424        hyprstream_containedfs::validate_ref_name(branch)
1425            .map_err(|e| anyhow!("Invalid branch name: {}", e))?;
1426        let id = Self::parse_repo_id(repo_id)?;
1427        let registry = self.registry.read().await;
1428        let handle = registry.repo(&id)?;
1429
1430        // Find worktree by branch name using status().branch
1431        let mut worktrees = handle.get_worktrees().await?;
1432        let mut found = None;
1433        for wt in &mut worktrees {
1434            let wt_branch = wt.status().await.ok().and_then(|s| s.branch);
1435            if wt_branch.as_deref() == Some(branch) {
1436                found = Some(wt.path().to_path_buf());
1437                break;
1438            }
1439        }
1440        let matched_wt = found.ok_or_else(|| anyhow!("No worktree for branch '{}'", branch))?;
1441
1442        let worktree_name = matched_wt
1443            .file_name()
1444            .and_then(|s| s.to_str())
1445            .ok_or_else(|| anyhow!("Invalid worktree path"))?;
1446
1447        // Get base repo path
1448        let repo_path = handle.worktree()?;
1449
1450        // Use GitManager to remove worktree
1451        git2db::GitManager::global().remove_worktree(repo_path, worktree_name, None)?;
1452        Ok(())
1453    }
1454
1455    /// Handle get HEAD operation
1456    async fn handle_get_head(&self, repo_id: &str) -> Result<String> {
1457        let id = Self::parse_repo_id(repo_id)?;
1458        let registry = self.registry.read().await;
1459        let handle = registry.repo(&id)?;
1460
1461        // Get HEAD ref (DefaultBranch resolves to HEAD)
1462        let oid = handle.resolve_git_ref(&GitRef::DefaultBranch).await?;
1463        Ok(oid.to_string())
1464    }
1465
1466    /// Handle get ref operation
1467    async fn handle_get_ref(&self, repo_id: &str, ref_name: &str) -> Result<String> {
1468        let id = Self::parse_repo_id(repo_id)?;
1469        let ref_name = ref_name.to_owned();
1470        let registry = self.registry.read().await;
1471        let handle = registry.repo(&id)?;
1472
1473        // Try to resolve as a revspec
1474        let oid = handle.resolve_revspec(&ref_name).await?;
1475        Ok(oid.to_string())
1476    }
1477
1478    /// Resolve a worktree path from a repository handle.
1479    ///
1480    /// For bare repositories (cloned models), `handle.worktree()` returns the bare
1481    /// repo path (e.g. `models/name/name.git`), which can't be used for operations
1482    /// that require a working tree (status, staging, etc.). This method finds the
1483    /// actual worktree for the tracking ref.
1484    async fn resolve_worktree_path(
1485        handle: &git2db::RepositoryHandle<'_>,
1486    ) -> Result<std::path::PathBuf> {
1487        let base_path = handle.worktree()?.to_path_buf();
1488
1489        // Detect bare repository: path ends in .git or has HEAD but no .git subdir
1490        let is_bare = base_path.extension().is_some_and(|ext| ext == "git")
1491            || (base_path.join("HEAD").exists() && !base_path.join(".git").exists());
1492
1493        if !is_bare {
1494            return Ok(base_path);
1495        }
1496
1497        // Try the tracking ref's worktree first
1498        let tracked = handle.metadata()?;
1499        let branch = match &tracked.tracking_ref {
1500            git2db::GitRef::Branch(b) => Some(b.as_str()),
1501            _ => None,
1502        };
1503
1504        if let Some(branch) = branch {
1505            if let Ok(Some(wt)) = handle.get_worktree(branch).await {
1506                return Ok(wt.path().to_path_buf());
1507            }
1508        }
1509
1510        // Fallback: try any available worktree
1511        if let Ok(worktrees) = handle.get_worktrees().await {
1512            if let Some(wt) = worktrees.into_iter().next() {
1513                return Ok(wt.path().to_path_buf());
1514            }
1515        }
1516
1517        Err(anyhow!(
1518            "No worktrees found for bare repository: {:?}",
1519            base_path
1520        ))
1521    }
1522
1523    /// Execute a blocking git2 operation on a repository.
1524    ///
1525    /// Handles the boilerplate of: read registry → get handle → resolve worktree →
1526    /// spawn_blocking → Repository::open → operation.
1527    async fn with_repo_blocking<F, T>(&self, id: &git2db::RepoId, f: F) -> Result<T>
1528    where
1529        F: FnOnce(git2::Repository) -> Result<T> + Send + 'static,
1530        T: Send + 'static,
1531    {
1532        let registry = self.registry.read().await;
1533        let handle = registry.repo(id)?;
1534        let repo_path = Self::resolve_worktree_path(&handle).await?;
1535        tokio::task::spawn_blocking(move || {
1536            let repo = git2::Repository::open(&repo_path)
1537                .map_err(|e| anyhow!("Failed to open repository: {}", e))?;
1538            f(repo)
1539        })
1540        .await
1541        .map_err(|e| anyhow!("Task join error: {}", e))?
1542    }
1543
1544    /// Execute a blocking git2 operation on a specific worktree (by branch name).
1545    ///
1546    /// Unlike `with_repo_blocking` which guesses the worktree via `resolve_worktree_path`,
1547    /// this takes an explicit branch/worktree name.
1548    async fn with_worktree_blocking<F, T>(
1549        &self,
1550        id: &git2db::RepoId,
1551        branch: &str,
1552        f: F,
1553    ) -> Result<T>
1554    where
1555        F: FnOnce(git2::Repository) -> Result<T> + Send + 'static,
1556        T: Send + 'static,
1557    {
1558        let registry = self.registry.read().await;
1559        let handle = registry.repo(id)?;
1560        let wt = handle
1561            .get_worktree(branch)
1562            .await
1563            .map_err(|e| anyhow!("Worktree '{}' not found: {}", branch, e))?
1564            .ok_or_else(|| anyhow!("Worktree '{}' not found", branch))?;
1565        let wt_path = wt.path().to_path_buf();
1566        tokio::task::spawn_blocking(move || {
1567            let repo = git2::Repository::open(&wt_path)
1568                .map_err(|e| anyhow!("Failed to open worktree: {}", e))?;
1569            f(repo)
1570        })
1571        .await
1572        .map_err(|e| anyhow!("Task join error: {}", e))?
1573    }
1574
1575    /// Handle update operation (fetch from remote)
1576    async fn handle_update(&self, repo_id: &str, refspec: Option<&str>) -> Result<()> {
1577        let id = Self::parse_repo_id(repo_id)?;
1578        let refspec = refspec.map(std::borrow::ToOwned::to_owned);
1579        self.with_repo_blocking(&id, move |repo| {
1580            crate::git::ops::fetch(&repo, "origin", refspec.as_deref())
1581        })
1582        .await
1583    }
1584
1585    /// Handle health check
1586    async fn handle_health_check(&self) -> Result<HealthStatus> {
1587        let registry = self.registry.read().await;
1588        let repo_count = registry.list().count() as u32;
1589        Ok(HealthStatus {
1590            status: "healthy".to_owned(),
1591            repository_count: repo_count,
1592            worktree_count: 0,
1593            cache_hits: 0,
1594            cache_misses: 0,
1595        })
1596    }
1597
1598    /// Handle list remotes operation
1599    async fn handle_list_remotes(&self, repo_id: &str) -> Result<Vec<RemoteInfo>> {
1600        let id = Self::parse_repo_id(repo_id)?;
1601        let registry = self.registry.read().await;
1602        let handle = registry.repo(&id)?;
1603
1604        let remotes = handle.remote().list().await?;
1605        let result = remotes
1606            .into_iter()
1607            .map(|remote| RemoteInfo {
1608                name: remote.name,
1609                url: remote.url,
1610                push_url: remote.push_url.unwrap_or_default(),
1611            })
1612            .collect();
1613        Ok(result)
1614    }
1615
1616    /// Handle add remote operation
1617    async fn handle_add_remote(&self, repo_id: &str, name: &str, url: &str) -> Result<()> {
1618        let id = Self::parse_repo_id(repo_id)?;
1619        let name = name.to_owned();
1620        let url = url.to_owned();
1621        let registry = self.registry.read().await;
1622        let handle = registry.repo(&id)?;
1623        handle.remote().add(&name, &url).await?;
1624        Ok(())
1625    }
1626
1627    /// Handle remove remote operation
1628    async fn handle_remove_remote(&self, repo_id: &str, name: &str) -> Result<()> {
1629        let id = Self::parse_repo_id(repo_id)?;
1630        let name = name.to_owned();
1631        let registry = self.registry.read().await;
1632        let handle = registry.repo(&id)?;
1633        handle.remote().remove(&name).await?;
1634        Ok(())
1635    }
1636
1637    /// Handle set remote URL operation
1638    async fn handle_set_remote_url(&self, repo_id: &str, name: &str, url: &str) -> Result<()> {
1639        let id = Self::parse_repo_id(repo_id)?;
1640        let name = name.to_owned();
1641        let url = url.to_owned();
1642        let registry = self.registry.read().await;
1643        let handle = registry.repo(&id)?;
1644        handle.remote().set_url(&name, &url).await?;
1645        Ok(())
1646    }
1647
1648    /// Handle rename remote operation
1649    async fn handle_rename_remote(
1650        &self,
1651        repo_id: &str,
1652        old_name: &str,
1653        new_name: &str,
1654    ) -> Result<()> {
1655        let id = Self::parse_repo_id(repo_id)?;
1656        let old_name = old_name.to_owned();
1657        let new_name = new_name.to_owned();
1658        let registry = self.registry.read().await;
1659        let handle = registry.repo(&id)?;
1660        handle.remote().rename(&old_name, &new_name).await?;
1661        Ok(())
1662    }
1663
1664    // ========================================================================
1665    // Push Operations
1666    // ========================================================================
1667
1668    /// Handle push operation
1669    async fn handle_push(
1670        &self,
1671        repo_id: &str,
1672        remote: &str,
1673        refspec: &str,
1674        force: bool,
1675    ) -> Result<()> {
1676        let id = Self::parse_repo_id(repo_id)?;
1677        let remote = remote.to_owned();
1678        let refspec = refspec.to_owned();
1679        self.with_repo_blocking(&id, move |repo| {
1680            crate::git::ops::push(&repo, &remote, &refspec, force)
1681        })
1682        .await
1683    }
1684
1685    // ========================================================================
1686    // Tag Operations
1687    // ========================================================================
1688
1689    /// Handle list tags operation
1690    async fn handle_list_tags(&self, repo_id: &str) -> Result<Vec<String>> {
1691        let id = Self::parse_repo_id(repo_id)?;
1692        self.with_repo_blocking(&id, |repo| crate::git::ops::list_tags(&repo))
1693            .await
1694    }
1695
1696    /// Handle create tag operation
1697    async fn handle_create_tag(
1698        &self,
1699        repo_id: &str,
1700        name: &str,
1701        target: Option<&str>,
1702    ) -> Result<()> {
1703        let id = Self::parse_repo_id(repo_id)?;
1704        let name = name.to_owned();
1705        let target = target.map(std::borrow::ToOwned::to_owned);
1706        self.with_repo_blocking(&id, move |repo| {
1707            crate::git::ops::create_tag(&repo, &name, target.as_deref(), false)
1708        })
1709        .await
1710    }
1711
1712    /// Handle delete tag operation
1713    async fn handle_delete_tag(&self, repo_id: &str, name: &str) -> Result<()> {
1714        let id = Self::parse_repo_id(repo_id)?;
1715        let name = name.to_owned();
1716        self.with_repo_blocking(&id, move |repo| crate::git::ops::delete_tag(&repo, &name))
1717            .await
1718    }
1719
1720    // ========================================================================
1721    // Detailed Status
1722    // ========================================================================
1723
1724    /// Handle detailed status operation
1725    async fn handle_detailed_status(&self, repo_id: &str) -> Result<DetailedStatusInfo> {
1726        let id = Self::parse_repo_id(repo_id)?;
1727        self.with_repo_blocking(&id, |repo| crate::git::ops::detailed_status(&repo))
1728            .await
1729    }
1730
1731    // ========================================================================
1732    // Filesystem Operations
1733    // ========================================================================
1734
1735    /// Get or create a ContainedFs for a (repo_id, worktree) pair.
1736    async fn get_contained_root(
1737        &self,
1738        repo_id: &str,
1739        worktree: &str,
1740    ) -> Result<Arc<dyn ContainedFs>, FsError> {
1741        let key = (repo_id.to_owned(), worktree.to_owned());
1742        if let Some(root) = self.contained_roots.get(&key) {
1743            return Ok(Arc::clone(&root));
1744        }
1745
1746        // Resolve worktree path from repo
1747        let id = Self::parse_repo_id(repo_id).map_err(|e| FsError::NotFound(e.to_string()))?;
1748
1749        let registry = self.registry.read().await;
1750        let handle = registry
1751            .repo(&id)
1752            .map_err(|e| FsError::NotFound(e.to_string()))?;
1753        let worktrees = handle
1754            .get_worktrees()
1755            .await
1756            .map_err(|e| FsError::Io(std::io::Error::other(e.to_string())))?;
1757
1758        // Find the worktree matching the requested name
1759        let mut worktree_path = None;
1760        for wt in &worktrees {
1761            let wt_name = wt.path().file_name().and_then(|s| s.to_str()).unwrap_or("");
1762            if wt_name == worktree {
1763                worktree_path = Some(wt.path().to_path_buf());
1764                break;
1765            }
1766        }
1767
1768        // If worktree name is "." or empty, use the repo's base worktree path
1769        let worktree_path = if let Some(p) = worktree_path {
1770            p
1771        } else if worktree == "." || worktree.is_empty() {
1772            handle
1773                .resolve_worktree_path()
1774                .await
1775                .map_err(|e| FsError::NotFound(e.to_string()))?
1776        } else {
1777            return Err(FsError::NotFound(format!(
1778                "worktree '{}' not found for repo '{}'",
1779                worktree, repo_id
1780            )));
1781        };
1782
1783        let root = hyprstream_containedfs::open(&worktree_path)?;
1784        self.contained_roots.insert(key, Arc::clone(&root));
1785        Ok(root)
1786    }
1787
1788    // ========================================================================
1789    // 9P Helper: Convert internal Qid to generated QidData
1790    // ========================================================================
1791
1792    fn qid_to_data(qid: &Qid) -> QidData {
1793        QidData {
1794            qtype: qid.qtype,
1795            version: qid.version,
1796            path: qid.path,
1797        }
1798    }
1799
1800    /// Extract a file's own name (the final path component) from a fid's
1801    /// tracked `rel_path` (relative to the contained root). Returns `""` for
1802    /// the contained root itself (`"."` / empty) — a synthetic entry with no
1803    /// name of its own — which callers may leave empty in `Tstat`.
1804    fn rel_path_file_name(rel_path: &str) -> &str {
1805        if rel_path.is_empty() || rel_path == "." {
1806            ""
1807        } else {
1808            rel_path.rsplit('/').next().unwrap_or(rel_path)
1809        }
1810    }
1811
1812    /// Build NpStatData from filesystem metadata.
1813    fn metadata_to_np_stat(name: &str, meta: &std::fs::Metadata) -> NpStatData {
1814        let qid = qid_from_metadata(meta);
1815        #[cfg(unix)]
1816        let (mode, atime, mtime, uid, gid) = {
1817            use std::os::unix::fs::MetadataExt;
1818            (
1819                meta.mode(),
1820                meta.atime() as u32,
1821                meta.mtime() as u32,
1822                meta.uid().to_string(),
1823                meta.gid().to_string(),
1824            )
1825        };
1826        #[cfg(not(unix))]
1827        let (mode, atime, mtime, uid, gid) = {
1828            let mtime_val = meta
1829                .modified()
1830                .ok()
1831                .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
1832                .map(|d| d.as_secs() as u32)
1833                .unwrap_or(0);
1834            (
1835                if meta.is_dir() { 0o40755 } else { 0o100644 },
1836                mtime_val,
1837                mtime_val,
1838                String::new(),
1839                String::new(),
1840            )
1841        };
1842        NpStatData {
1843            qid: Self::qid_to_data(&qid),
1844            mode,
1845            atime,
1846            mtime,
1847            length: meta.len(),
1848            name: name.to_owned(),
1849            uid,
1850            gid,
1851            muid: String::new(),
1852        }
1853    }
1854}
1855
1856// ============================================================================
1857// Generated Handler Helpers
1858// ============================================================================
1859
1860fn tracked_repo_to_data(
1861    repo: &TrackedRepository,
1862) -> hyprstream_rpc_std::registry_client::TrackedRepository {
1863    tracked_repo_to_data_with_worktrees(repo, vec![])
1864}
1865
1866fn tracked_repo_to_data_with_worktrees(
1867    repo: &TrackedRepository,
1868    worktrees: Vec<hyprstream_rpc_std::registry_client::WorktreeInfo>,
1869) -> hyprstream_rpc_std::registry_client::TrackedRepository {
1870    hyprstream_rpc_std::registry_client::TrackedRepository {
1871        id: repo.id.to_string(),
1872        name: repo.name.clone().unwrap_or_default(),
1873        url: repo.url.clone(),
1874        worktree_path_removed: (), // field removed from schema
1875        tracking_ref: match &repo.tracking_ref {
1876            GitRef::Branch(b) => b.clone(),
1877            _ => String::new(),
1878        },
1879        current_oid: repo.current_oid.clone().unwrap_or_default(),
1880        registered_at: repo.registered_at,
1881        worktrees,
1882    }
1883}
1884
1885macro_rules! tracked_variant {
1886    ($variant:ident, $repo:expr) => {{
1887        let d = tracked_repo_to_data($repo);
1888        RegistryResponseVariant::$variant(d)
1889    }};
1890}
1891
1892fn reg_error(msg: &str) -> RegistryResponseVariant {
1893    RegistryResponseVariant::Error(ErrorInfo {
1894        message: msg.to_owned(),
1895        code: "INTERNAL".to_owned(),
1896        details: String::new(),
1897    })
1898}
1899
1900// ============================================================================
1901// Generated RegistryHandler Implementation
1902// ============================================================================
1903
1904#[async_trait::async_trait(?Send)]
1905impl RegistryHandler for RegistryService {
1906    async fn authorize(
1907        &self,
1908        ctx: &EnvelopeContext,
1909        resource: &str,
1910        operation: &str,
1911    ) -> Result<()> {
1912        // Pass the operation string as-is to the policy check rather than
1913        // round-tripping through Operation enum (which maps "query" → "query.status").
1914        let subject = ctx.subject();
1915        // The registry and its worktree namespace are node-global: repository
1916        // metadata and paths carry no tenant key. Keep this authorization in
1917        // the global policy domain rather than claiming storage isolation that
1918        // the registry does not provide.
1919        let request = PolicyCheck {
1920            subject: subject.to_string(),
1921            domain: if ctx.is_federate_admitted() {
1922                ctx.domain()?
1923            } else {
1924                "*".to_owned()
1925            },
1926            resource: resource.to_owned(),
1927            operation: operation.to_owned(),
1928        };
1929        if ctx.is_federate_admitted() {
1930            anyhow::ensure!(
1931                ctx.admitted_federate_operation(resource, operation),
1932                "Federate request-local operation mismatch"
1933            );
1934            // H2 already performed a fresh Policy check for the original
1935            // holder's exact Registry.list action. Generic Policy.check would
1936            // instead check this service's own identity.
1937            return Ok(());
1938        }
1939        let allowed = crate::services::policy::check_with_holder_evidence(
1940            &self.policy_client,
1941            &request,
1942            ctx.jwt_token(),
1943            &ctx.subject(),
1944            ctx.original_holder_evidence(),
1945        )
1946        .await
1947        .unwrap_or_else(|e| {
1948            warn!(
1949                "Policy check RPC error: sub={} obj={} act={} err={} - denying access",
1950                subject, resource, operation, e
1951            );
1952            false
1953        });
1954        if allowed {
1955            Ok(())
1956        } else {
1957            anyhow::bail!(
1958                "Unauthorized: {} cannot {} on {}",
1959                subject,
1960                operation,
1961                resource
1962            )
1963        }
1964    }
1965
1966    async fn handle_list(
1967        &self,
1968        ctx: &EnvelopeContext,
1969        _request_id: u64,
1970    ) -> Result<RegistryResponseVariant> {
1971        if ctx.is_federate_admitted() {
1972            // H2 admits Registry.list but cannot check each entry under the
1973            // original holder. Keep catalog browsing empty until Policy has
1974            // an authenticated per-entry query. The staging acceptance path
1975            // uses exact-pin getByName with its own fresh request admission.
1976            return Ok(RegistryResponseVariant::ListResult(Vec::new()));
1977        }
1978        let repos = match self.handle_list().await {
1979            Ok(r) => r,
1980            Err(e) => return Ok(reg_error(&e.to_string())),
1981        };
1982
1983        let subject = ctx.subject().to_string();
1984        // Registry is node-global (as in authorize above). A verified local
1985        // service WIT is not a hosted-account tenant. Tenant-bound callers
1986        // still require their verified tenant; never widen a user to '*'.
1987        let caller = ctx.subject();
1988        let domain = if ctx.verified_tenant().is_none()
1989            && ctx.claims().is_some()
1990            && !caller.is_federated()
1991            && caller
1992                .name()
1993                .is_some_and(|name| name.starts_with("service:"))
1994        {
1995            "*".to_owned()
1996        } else {
1997            ctx.domain()?
1998        };
1999        let mut result = Vec::with_capacity(repos.len());
2000
2001        for repo in &repos {
2002            let name = repo.name.clone().unwrap_or_default();
2003            if name.is_empty() {
2004                continue;
2005            }
2006
2007            // Policy gate: only include repos the caller has at least query access to
2008            let resource = format!("model:{}", name);
2009            let request = PolicyCheck {
2010                subject: subject.clone(),
2011                domain: domain.clone(),
2012                resource: resource.clone(),
2013                operation: "query".to_owned(),
2014            };
2015            let permitted = crate::services::policy::check_with_holder_evidence(
2016                &self.policy_client,
2017                &request,
2018                ctx.jwt_token(),
2019                &ctx.subject(),
2020                ctx.original_holder_evidence(),
2021            )
2022            .await
2023            .unwrap_or_else(|e| {
2024                warn!(
2025                    "Policy check RPC error while filtering {}: {} - denying access",
2026                    resource, e
2027                );
2028                false
2029            });
2030            if !permitted {
2031                continue;
2032            }
2033
2034            // Collect worktrees with capabilities (holds registry read lock internally)
2035            let worktrees = match self.handle_list_worktrees(&repo.id.to_string()).await {
2036                Ok(wts) => wts,
2037                Err(e) => {
2038                    warn!("Failed to list worktrees for '{}': {}", name, e);
2039                    vec![]
2040                }
2041            };
2042
2043            result.push(tracked_repo_to_data_with_worktrees(repo, worktrees));
2044        }
2045
2046        Ok(RegistryResponseVariant::ListResult(result))
2047    }
2048
2049    async fn handle_get(
2050        &self,
2051        _ctx: &EnvelopeContext,
2052        _request_id: u64,
2053        value: &str,
2054    ) -> Result<RegistryResponseVariant> {
2055        match self.handle_get(value).await {
2056            Ok(Some(repo)) => Ok(tracked_variant!(GetResult, &repo)),
2057            Ok(None) => Ok(reg_error("Repository not found")),
2058            Err(e) => Ok(reg_error(&e.to_string())),
2059        }
2060    }
2061
2062    async fn handle_get_by_name(
2063        &self,
2064        _ctx: &EnvelopeContext,
2065        _request_id: u64,
2066        value: &str,
2067    ) -> Result<RegistryResponseVariant> {
2068        match self.handle_get_by_name(value).await {
2069            Ok(Some(repo)) => Ok(tracked_variant!(GetByNameResult, &repo)),
2070            Ok(None) => Ok(reg_error("Repository not found")),
2071            Err(e) => Ok(reg_error(&e.to_string())),
2072        }
2073    }
2074
2075    async fn handle_clone(
2076        &self,
2077        _ctx: &EnvelopeContext,
2078        _request_id: u64,
2079        data: &CloneRequest,
2080    ) -> Result<RegistryResponseVariant> {
2081        let name_opt = if data.name.is_empty() {
2082            None
2083        } else {
2084            Some(data.name.as_str())
2085        };
2086        let branch_opt = if data.branch.is_empty() {
2087            None
2088        } else {
2089            Some(data.branch.as_str())
2090        };
2091        match self
2092            .handle_clone(
2093                &data.url,
2094                name_opt,
2095                data.shallow,
2096                Some(data.depth),
2097                branch_opt,
2098            )
2099            .await
2100        {
2101            Ok(repo) => Ok(tracked_variant!(CloneResult, &repo)),
2102            Err(e) => Ok(reg_error(&e.to_string())),
2103        }
2104    }
2105
2106    async fn handle_clone_stream(
2107        &self,
2108        ctx: &EnvelopeContext,
2109        _request_id: u64,
2110        data: &CloneRequest,
2111    ) -> Result<(StreamInfo, hyprstream_rpc::service::Continuation)> {
2112        let name_opt = if data.name.is_empty() {
2113            None
2114        } else {
2115            Some(data.name.as_str())
2116        };
2117        let branch_opt = if data.branch.is_empty() {
2118            None
2119        } else {
2120            Some(data.branch.as_str())
2121        };
2122        let client_ephemeral_pubkey = ctx.ephemeral_pubkey();
2123        self.prepare_clone_stream(
2124            &data.url,
2125            name_opt,
2126            data.shallow,
2127            Some(data.depth),
2128            branch_opt,
2129            client_ephemeral_pubkey.as_ref().map(<[u8; 32]>::as_slice),
2130        )
2131        .await
2132    }
2133
2134    async fn handle_get_blob(
2135        &self,
2136        ctx: &EnvelopeContext,
2137        _request_id: u64,
2138        data: &GetBlobRequest,
2139    ) -> Result<(StreamInfo, hyprstream_rpc::service::Continuation)> {
2140        // SECURITY: enforce BOTH conditions (caller-may-access-grantRepo AND
2141        // grantRepo-contains-address) BEFORE any bytes are served. The hash is
2142        // not a capability. A denial returns Err → the request loop emits an
2143        // error response (no StreamInfo, no continuation, no bytes).
2144        let address = self.authorize_get_blob(ctx, data).await?;
2145        let client_ephemeral_pubkey = ctx.ephemeral_pubkey();
2146        // #1270: capture the verified subject for the post-RPC MAC recheck in
2147        // the streaming continuation. The continuation runs after the RPC
2148        // returns; the PEP re-evaluates clearance at the point of use (before
2149        // any bytes are read from the substrate).
2150        let subject_id = ctx.subject().to_string();
2151        let verified_tenant = ctx.verified_tenant().map(str::to_owned);
2152        self.prepare_get_blob_stream(
2153            address,
2154            client_ephemeral_pubkey.as_ref().map(<[u8; 32]>::as_slice),
2155            subject_id,
2156            verified_tenant,
2157        )
2158        .await
2159    }
2160
2161    async fn handle_register(
2162        &self,
2163        _ctx: &EnvelopeContext,
2164        _request_id: u64,
2165        data: &RegisterRequest,
2166    ) -> Result<RegistryResponseVariant> {
2167        let name_opt = if data.name.is_empty() {
2168            None
2169        } else {
2170            Some(data.name.as_str())
2171        };
2172        let tracking_ref_opt = if data.tracking_ref.is_empty() {
2173            None
2174        } else {
2175            Some(data.tracking_ref.as_str())
2176        };
2177        match self
2178            .handle_register(&data.path, name_opt, tracking_ref_opt)
2179            .await
2180        {
2181            Ok(repo) => Ok(tracked_variant!(RegisterResult, &repo)),
2182            Err(e) => Ok(reg_error(&e.to_string())),
2183        }
2184    }
2185
2186    async fn handle_remove(
2187        &self,
2188        _ctx: &EnvelopeContext,
2189        _request_id: u64,
2190        value: &str,
2191    ) -> Result<RegistryResponseVariant> {
2192        match self.handle_remove(value).await {
2193            Ok(()) => Ok(RegistryResponseVariant::RemoveResult),
2194            Err(e) => Ok(reg_error(&e.to_string())),
2195        }
2196    }
2197
2198    async fn handle_health_check(
2199        &self,
2200        _ctx: &EnvelopeContext,
2201        _request_id: u64,
2202    ) -> Result<RegistryResponseVariant> {
2203        match self.handle_health_check().await {
2204            Ok(status) => Ok(RegistryResponseVariant::HealthCheckResult(status)),
2205            Err(e) => Ok(reg_error(&e.to_string())),
2206        }
2207    }
2208
2209    /// Authenticated in-band XET write (epic #654) — the symmetric write half of
2210    /// `getBlob` and what populates the provenance store the `#509` read-gate
2211    /// consults. The caller supplies bytes only; the server computes the merkle
2212    /// from those bytes (never caller-supplied — this is what closes the #436
2213    /// OID-planting vector by construction) and binds `(merkle → grantRepo)`
2214    /// provenance from the verified identity.
2215    ///
2216    /// The coarse `$scope(write)` gate runs in dispatch before this handler (as
2217    /// `$scope(query)` does for `handle_get_blob`; neither carries `#[authorize]`).
2218    /// A failure returns a fail-closed error response — no bytes are persisted and
2219    /// no provenance is recorded unless the caller is authorized.
2220    async fn handle_put_blob(
2221        &self,
2222        ctx: &EnvelopeContext,
2223        _request_id: u64,
2224        data: &PutBlobRequest,
2225    ) -> Result<RegistryResponseVariant> {
2226        match self.put_blob_inner(ctx, data).await {
2227            Ok(variant) => Ok(variant),
2228            // Fail-closed: any deny/error → error response, nothing stored.
2229            Err(e) => Ok(reg_error(&format!("putBlob denied: {e}"))),
2230        }
2231    }
2232
2233    async fn handle_ingest_at9p_candidate(
2234        &self,
2235        _ctx: &EnvelopeContext,
2236        _request_id: u64,
2237        data: &At9pCandidateRequest,
2238    ) -> Result<RegistryResponseVariant> {
2239        // Fail closed: accepted-state ingest requires the concrete publisher.
2240        #[cfg(not(feature = "rocksdb"))]
2241        {
2242            let _ = (_ctx, _request_id, data);
2243            return Ok(reg_error(
2244                "accepted did:at9p ingest requires the `rocksdb` feature",
2245            ));
2246        }
2247        #[cfg(feature = "rocksdb")]
2248        {
2249            let result = async {
2250                anyhow::ensure!(!data.did.is_empty(), "did is required");
2251                anyhow::ensure!(
2252                    !data.record_bytes.is_empty(),
2253                    "candidate bytes are required"
2254                );
2255                anyhow::ensure!(
2256                    data.record_bytes.len() <= MAX_AT9P_CANDIDATE_BYTES,
2257                    "candidate exceeds ingest cap"
2258                );
2259                let publisher = self
2260                    .pds_publisher
2261                    .as_ref()
2262                    .ok_or_else(|| anyhow!("accepted did:at9p ingest is not configured"))?;
2263                let publisher = Arc::clone(publisher);
2264                let did = data.did.clone();
2265                let record_bytes = data.record_bytes.clone();
2266                let kind = data.kind;
2267                let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
2268                let state = tokio::task::spawn_blocking(move || match kind {
2269                    At9pCandidateKind::Genesis => {
2270                        publisher.ingest_at9p_genesis(&did, &record_bytes)
2271                    }
2272                    At9pCandidateKind::Successor => {
2273                        publisher.ingest_at9p_successor(&did, &record_bytes, &now)
2274                    }
2275                })
2276                .await
2277                .map_err(|error| anyhow!("at9p candidate worker failed: {error}"))??;
2278                Ok::<_, anyhow::Error>(AcceptedAt9pStateInfo {
2279                    did: state.did,
2280                    epoch: state.epoch,
2281                    head_digest: state.head_digest.to_vec(),
2282                    terminal: state.terminal,
2283                })
2284            }
2285            .await;
2286            Ok(match result {
2287                Ok(info) => RegistryResponseVariant::IngestAt9pCandidateResult(info),
2288                Err(error) => reg_error(&format!("at9p candidate rejected: {error}")),
2289            })
2290        }
2291    }
2292}
2293
2294impl RegistryService {
2295    /// Core of [`RegistryHandler::handle_put_blob`], split out for `?` ergonomics.
2296    /// Every early return here is a hard deny (no bytes stored, no provenance
2297    /// recorded); the caller maps `Err` → a fail-closed error response.
2298    async fn put_blob_inner(
2299        &self,
2300        ctx: &EnvelopeContext,
2301        data: &PutBlobRequest,
2302    ) -> Result<RegistryResponseVariant> {
2303        // ── Input validation ──
2304        if data.grant_repo.trim().is_empty() {
2305            anyhow::bail!("grantRepo is required (provenance binds the bytes to a repo)");
2306        }
2307        if data.bytes.is_empty() {
2308            anyhow::bail!("empty upload");
2309        }
2310        // DoS guard: the inline path is hard-capped. Larger blobs will use the
2311        // streaming upload channel (additive schema follow-up field).
2312        if data.bytes.len() as u64 > MAX_INLINE_UPLOAD {
2313            anyhow::bail!(
2314                "upload exceeds inline cap ({} > {MAX_INLINE_UPLOAD} bytes); \
2315                 streaming upload not yet available",
2316                data.bytes.len()
2317            );
2318        }
2319
2320        // ── Resolve grantRepo → tracked repo (unknown repo = deny) ──
2321        let repo = self
2322            .resolve_grant_repo(&data.grant_repo)
2323            .await
2324            .ok_or_else(|| anyhow!("grantRepo '{}' not found", data.grant_repo))?;
2325        let repo_name = repo.name.clone().unwrap_or_default();
2326        if repo_name.is_empty() {
2327            anyhow::bail!("grantRepo has no name for authz");
2328        }
2329
2330        // ── Authorize WRITE on grantRepo. Mirrors `authorize_get_blob`'s per-repo
2331        //    Casbin check, one verb up: a read (`query`) grant never implies
2332        //    `write`. There is no condition-(b) "reconstruction target" check on
2333        //    the write side — the upload is precisely what CREATES the binding. ──
2334        RegistryHandler::authorize(self, ctx, &format!("model:{}", repo_name), "write")
2335            .await
2336            .map_err(|e| anyhow!("write not authorized on '{}': {}", data.grant_repo, e))?;
2337
2338        // ── Chunk + seal a labeled manifest + SERVER-SIDE merkle ────────────
2339        // An uploader without a verified MAC clearance cannot create a CAS
2340        // object. The verified clearance is a trusted restrict-only hint; the
2341        // substrate joins it with the node-global CAS domain floor and binds
2342        // the effective label into the manifest CID.
2343        let security_label = *ctx
2344            .security_context()
2345            .ok_or_else(|| anyhow!("putBlob requires a verified security clearance label"))?
2346            .clearance();
2347        let substrate = crate::storage::CasSubstrate::from_env();
2348        // Registry CAS/provenance paths are node-global and carry no tenant key;
2349        // preserve #1196's global-domain boundary rather than deriving a tenant
2350        // domain from `EnvelopeContext::verified_tenant()`.
2351        let domain = crate::storage::DedupDomain::local_default();
2352        let put = substrate
2353            .put(&domain, &data.bytes, Some(security_label))
2354            .await
2355            .map_err(|e| anyhow!("CAS ingest failed: {e}"))?;
2356
2357        // ── Bind provenance: THIS repo uploaded THIS merkle. Key on the SAME
2358        //    `repo_id.0.to_string()` form the read-gate's `is_bound` uses, or the
2359        //    later read would never match this binding. ──
2360        self.xet_provenance
2361            .record(&put.merkle, &repo.id.0.to_string())
2362            .await
2363            .map_err(|e| anyhow!("provenance record failed: {e}"))?;
2364
2365        Ok(RegistryResponseVariant::PutBlobResult(PutBlobResult {
2366            merkle: put.merkle,
2367            xorb_hashes: put.xorb_hashes,
2368            bytes_stored: put.bytes_stored,
2369        }))
2370    }
2371}
2372
2373// ============================================================================
2374// Generated RepoHandler Implementation (repo-scoped operations)
2375// ============================================================================
2376//
2377// Auth is handled by the generated dispatch_repo() function via authorize().
2378// Each method delegates to the corresponding internal method on RegistryService.
2379
2380#[async_trait::async_trait(?Send)]
2381impl RepoHandler for RegistryService {
2382    async fn handle_create_worktree(
2383        &self,
2384        _ctx: &EnvelopeContext,
2385        _request_id: u64,
2386        repo_id: &str,
2387        data: &CreateWorktreeRequest,
2388    ) -> Result<()> {
2389        self.handle_create_worktree(repo_id, &data.branch).await
2390    }
2391
2392    async fn handle_list_worktrees(
2393        &self,
2394        _ctx: &EnvelopeContext,
2395        _request_id: u64,
2396        repo_id: &str,
2397    ) -> Result<Vec<hyprstream_rpc_std::registry_client::WorktreeInfo>> {
2398        self.handle_list_worktrees(repo_id).await
2399    }
2400
2401    async fn handle_remove_worktree(
2402        &self,
2403        _ctx: &EnvelopeContext,
2404        _request_id: u64,
2405        repo_id: &str,
2406        data: &RemoveWorktreeRequest,
2407    ) -> Result<()> {
2408        self.handle_remove_worktree(repo_id, &data.branch).await
2409    }
2410
2411    async fn handle_create_branch(
2412        &self,
2413        _ctx: &EnvelopeContext,
2414        _request_id: u64,
2415        repo_id: &str,
2416        data: &BranchRequest,
2417    ) -> Result<()> {
2418        let sp = if data.start_point.is_empty() {
2419            None
2420        } else {
2421            Some(data.start_point.as_str())
2422        };
2423        self.handle_create_branch(repo_id, &data.branch_name, sp)
2424            .await
2425    }
2426
2427    async fn handle_list_branches(
2428        &self,
2429        _ctx: &EnvelopeContext,
2430        _request_id: u64,
2431        repo_id: &str,
2432    ) -> Result<Vec<String>> {
2433        self.handle_list_branches(repo_id).await
2434    }
2435
2436    // DEPRECATED — these operations moved to WorktreeRequest scope.
2437    // Kept for wire compatibility; return errors directing callers to the new API.
2438    async fn handle_checkout(
2439        &self,
2440        _ctx: &EnvelopeContext,
2441        _request_id: u64,
2442        _repo_id: &str,
2443        _data: &CheckoutRequest,
2444    ) -> Result<()> {
2445        Err(anyhow!(
2446            "checkout moved to worktree scope — use worktree(branch).checkout()"
2447        ))
2448    }
2449
2450    async fn handle_stage_all(
2451        &self,
2452        _ctx: &EnvelopeContext,
2453        _request_id: u64,
2454        _repo_id: &str,
2455    ) -> Result<()> {
2456        Err(anyhow!(
2457            "stageAll moved to worktree scope — use worktree(branch).stageAll()"
2458        ))
2459    }
2460
2461    async fn handle_stage_files(
2462        &self,
2463        _ctx: &EnvelopeContext,
2464        _request_id: u64,
2465        _repo_id: &str,
2466        _data: &StageFilesRequest,
2467    ) -> Result<()> {
2468        Err(anyhow!(
2469            "stageFiles moved to worktree scope — use worktree(branch).stageFiles()"
2470        ))
2471    }
2472
2473    async fn handle_commit(
2474        &self,
2475        _ctx: &EnvelopeContext,
2476        _request_id: u64,
2477        _repo_id: &str,
2478        _data: &CommitRequest,
2479    ) -> Result<String> {
2480        Err(anyhow!(
2481            "commit moved to worktree scope — use worktree(branch).commit()"
2482        ))
2483    }
2484
2485    async fn handle_merge(
2486        &self,
2487        _ctx: &EnvelopeContext,
2488        _request_id: u64,
2489        _repo_id: &str,
2490        _data: &MergeRequest,
2491    ) -> Result<()> {
2492        Err(anyhow!(
2493            "merge moved to worktree scope — use worktree(branch).merge()"
2494        ))
2495    }
2496
2497    async fn handle_abort_merge(
2498        &self,
2499        _ctx: &EnvelopeContext,
2500        _request_id: u64,
2501        _repo_id: &str,
2502    ) -> Result<()> {
2503        Err(anyhow!(
2504            "abortMerge moved to worktree scope — use worktree(branch).abortMerge()"
2505        ))
2506    }
2507
2508    async fn handle_continue_merge(
2509        &self,
2510        _ctx: &EnvelopeContext,
2511        _request_id: u64,
2512        _repo_id: &str,
2513        _data: &ContinueMergeRequest,
2514    ) -> Result<()> {
2515        Err(anyhow!(
2516            "continueMerge moved to worktree scope — use worktree(branch).continueMerge()"
2517        ))
2518    }
2519
2520    async fn handle_quit_merge(
2521        &self,
2522        _ctx: &EnvelopeContext,
2523        _request_id: u64,
2524        _repo_id: &str,
2525    ) -> Result<()> {
2526        Err(anyhow!(
2527            "quitMerge moved to worktree scope — use worktree(branch).quitMerge()"
2528        ))
2529    }
2530
2531    async fn handle_get_head(
2532        &self,
2533        _ctx: &EnvelopeContext,
2534        _request_id: u64,
2535        repo_id: &str,
2536    ) -> Result<String> {
2537        self.handle_get_head(repo_id).await
2538    }
2539
2540    async fn handle_get_ref(
2541        &self,
2542        _ctx: &EnvelopeContext,
2543        _request_id: u64,
2544        repo_id: &str,
2545        data: &GetRefRequest,
2546    ) -> Result<String> {
2547        self.handle_get_ref(repo_id, &data.ref_name).await
2548    }
2549
2550    async fn handle_status(
2551        &self,
2552        _ctx: &EnvelopeContext,
2553        _request_id: u64,
2554        repo_id: &str,
2555    ) -> Result<hyprstream_rpc_std::registry_client::RepositoryStatus> {
2556        let status = self.handle_status(repo_id).await?;
2557        Ok(hyprstream_rpc_std::registry_client::RepositoryStatus {
2558            branch: status.branch.unwrap_or_default(),
2559            head_oid: status.head.map(|h| h.to_string()).unwrap_or_default(),
2560            ahead: status.ahead as u32,
2561            behind: status.behind as u32,
2562            is_clean: status.is_clean,
2563            modified_files: status
2564                .modified_files
2565                .iter()
2566                .map(|p| p.to_string_lossy().to_string())
2567                .collect(),
2568        })
2569    }
2570
2571    async fn handle_detailed_status(
2572        &self,
2573        _ctx: &EnvelopeContext,
2574        _request_id: u64,
2575        repo_id: &str,
2576    ) -> Result<DetailedStatusInfo> {
2577        self.handle_detailed_status(repo_id).await
2578    }
2579
2580    async fn handle_list_remotes(
2581        &self,
2582        _ctx: &EnvelopeContext,
2583        _request_id: u64,
2584        repo_id: &str,
2585    ) -> Result<Vec<RemoteInfo>> {
2586        self.handle_list_remotes(repo_id).await
2587    }
2588
2589    async fn handle_add_remote(
2590        &self,
2591        _ctx: &EnvelopeContext,
2592        _request_id: u64,
2593        repo_id: &str,
2594        data: &AddRemoteRequest,
2595    ) -> Result<()> {
2596        self.handle_add_remote(repo_id, &data.name, &data.url).await
2597    }
2598
2599    async fn handle_remove_remote(
2600        &self,
2601        _ctx: &EnvelopeContext,
2602        _request_id: u64,
2603        repo_id: &str,
2604        data: &RemoveRemoteRequest,
2605    ) -> Result<()> {
2606        self.handle_remove_remote(repo_id, &data.name).await
2607    }
2608
2609    async fn handle_set_remote_url(
2610        &self,
2611        _ctx: &EnvelopeContext,
2612        _request_id: u64,
2613        repo_id: &str,
2614        data: &SetRemoteUrlRequest,
2615    ) -> Result<()> {
2616        self.handle_set_remote_url(repo_id, &data.name, &data.url)
2617            .await
2618    }
2619
2620    async fn handle_rename_remote(
2621        &self,
2622        _ctx: &EnvelopeContext,
2623        _request_id: u64,
2624        repo_id: &str,
2625        data: &RenameRemoteRequest,
2626    ) -> Result<()> {
2627        self.handle_rename_remote(repo_id, &data.old_name, &data.new_name)
2628            .await
2629    }
2630
2631    async fn handle_push(
2632        &self,
2633        _ctx: &EnvelopeContext,
2634        _request_id: u64,
2635        repo_id: &str,
2636        data: &PushRequest,
2637    ) -> Result<()> {
2638        self.handle_push(repo_id, &data.remote, &data.refspec, data.force)
2639            .await
2640    }
2641
2642    // DEPRECATED — moved to WorktreeRequest scope.
2643    async fn handle_amend_commit(
2644        &self,
2645        _ctx: &EnvelopeContext,
2646        _request_id: u64,
2647        _repo_id: &str,
2648        _data: &AmendCommitRequest,
2649    ) -> Result<String> {
2650        Err(anyhow!(
2651            "amendCommit moved to worktree scope — use worktree(branch).amendCommit()"
2652        ))
2653    }
2654
2655    async fn handle_commit_with_author(
2656        &self,
2657        _ctx: &EnvelopeContext,
2658        _request_id: u64,
2659        _repo_id: &str,
2660        _data: &CommitWithAuthorRequest,
2661    ) -> Result<String> {
2662        Err(anyhow!(
2663            "commitWithAuthor moved to worktree scope — use worktree(branch).commitWithAuthor()"
2664        ))
2665    }
2666
2667    async fn handle_stage_all_including_untracked(
2668        &self,
2669        _ctx: &EnvelopeContext,
2670        _request_id: u64,
2671        _repo_id: &str,
2672    ) -> Result<()> {
2673        Err(anyhow!("stageAllIncludingUntracked moved to worktree scope — use worktree(branch).stageAllIncludingUntracked()"))
2674    }
2675
2676    async fn handle_list_tags(
2677        &self,
2678        _ctx: &EnvelopeContext,
2679        _request_id: u64,
2680        repo_id: &str,
2681    ) -> Result<Vec<String>> {
2682        self.handle_list_tags(repo_id).await
2683    }
2684
2685    async fn handle_create_tag(
2686        &self,
2687        _ctx: &EnvelopeContext,
2688        _request_id: u64,
2689        repo_id: &str,
2690        data: &CreateTagRequest,
2691    ) -> Result<()> {
2692        let t = if data.target.is_empty() {
2693            None
2694        } else {
2695            Some(data.target.as_str())
2696        };
2697        self.handle_create_tag(repo_id, &data.name, t).await
2698    }
2699
2700    async fn handle_delete_tag(
2701        &self,
2702        _ctx: &EnvelopeContext,
2703        _request_id: u64,
2704        repo_id: &str,
2705        data: &DeleteTagRequest,
2706    ) -> Result<()> {
2707        self.handle_delete_tag(repo_id, &data.name).await
2708    }
2709
2710    async fn handle_update(
2711        &self,
2712        _ctx: &EnvelopeContext,
2713        _request_id: u64,
2714        repo_id: &str,
2715        data: &UpdateRequest,
2716    ) -> Result<()> {
2717        let r = if data.refspec.is_empty() {
2718            None
2719        } else {
2720            Some(data.refspec.as_str())
2721        };
2722        self.handle_update(repo_id, r).await
2723    }
2724}
2725
2726// ============================================================================
2727// Generated CtlHandler Implementation — per-file git introspection + CRDT editing
2728// ============================================================================
2729
2730impl RegistryService {
2731    /// Resolve a fid to its relative path within the worktree.
2732    fn fid_rel_path(&self, fid: u32, client_id: &str) -> Result<String> {
2733        let entry = self
2734            .fid_table
2735            .get_verified(fid, client_id)
2736            .map_err(|e| anyhow!("{}", e))?;
2737        match &entry.state {
2738            FidState::Walked { walk_handle, .. } => Ok(walk_handle.rel_path().to_owned()),
2739            FidState::Opened { .. } => {
2740                // Opened fids don't carry the path — walk_handle was consumed.
2741                // For ctl operations, the fid should be in Walked state.
2742                anyhow::bail!(
2743                    "fid {} is opened for I/O; ctl operations require a walked (not opened) fid",
2744                    fid
2745                )
2746            }
2747        }
2748    }
2749
2750    /// Read file content via contained root for a given fid's path.
2751    async fn read_fid_content(
2752        &self,
2753        repo_id: &str,
2754        worktree: &str,
2755        fid: u32,
2756        client_id: &str,
2757    ) -> Result<String> {
2758        let rel_path = self.fid_rel_path(fid, client_id)?;
2759        let root = self
2760            .get_contained_root(repo_id, worktree)
2761            .await
2762            .map_err(|e| anyhow!("{}", e))?;
2763        let file = root
2764            .open(&rel_path, hyprstream_containedfs::OpenMode::OREAD)
2765            .map_err(|e| anyhow!("{}", e))?;
2766        let mut content = String::new();
2767        std::io::BufReader::new(file).read_to_string(&mut content)?;
2768        Ok(content)
2769    }
2770}
2771
2772#[async_trait::async_trait(?Send)]
2773impl CtlHandler for RegistryService {
2774    /// Git status of this file.
2775    async fn handle_status(
2776        &self,
2777        ctx: &EnvelopeContext,
2778        _request_id: u64,
2779        repo_id: &str,
2780        _name: &str,
2781        fid: u32,
2782    ) -> Result<FileStatus> {
2783        let subject = ctx.subject().to_string();
2784        let rel_path = self.fid_rel_path(fid, &subject)?;
2785
2786        let id = Self::parse_repo_id(repo_id)?;
2787        let state = self
2788            .with_repo_blocking(&id, move |repo| {
2789                let status = repo.status_file(std::path::Path::new(&rel_path))?;
2790                Ok(format!("{:?}", status))
2791            })
2792            .await?;
2793        Ok(FileStatus { state })
2794    }
2795
2796    /// Commits touching this file.
2797    async fn handle_log(
2798        &self,
2799        ctx: &EnvelopeContext,
2800        _request_id: u64,
2801        repo_id: &str,
2802        _name: &str,
2803        fid: u32,
2804        data: &CtlLogRequest,
2805    ) -> Result<Vec<LogEntry>> {
2806        let subject = ctx.subject().to_string();
2807        let rel_path = self.fid_rel_path(fid, &subject)?;
2808
2809        let id = Self::parse_repo_id(repo_id)?;
2810        let ref_name = data.ref_name.clone();
2811        let max_count = if data.max_count == 0 {
2812            20
2813        } else {
2814            data.max_count as usize
2815        };
2816
2817        self.with_repo_blocking(&id, move |repo| {
2818            let mut revwalk = repo.revwalk()?;
2819            if ref_name.is_empty() {
2820                revwalk.push_head()?;
2821            } else {
2822                let obj = repo.revparse_single(&ref_name)?;
2823                revwalk.push(obj.id())?;
2824            }
2825            revwalk.set_sorting(git2::Sort::TIME)?;
2826
2827            let mut entries = Vec::new();
2828            for oid_result in revwalk {
2829                if entries.len() >= max_count {
2830                    break;
2831                }
2832                let oid = oid_result?;
2833                let commit = repo.find_commit(oid)?;
2834
2835                let dominated = if commit.parent_count() == 0 {
2836                    commit
2837                        .tree()?
2838                        .get_path(std::path::Path::new(&rel_path))
2839                        .is_ok()
2840                } else {
2841                    let parent = commit.parent(0)?;
2842                    let diff =
2843                        repo.diff_tree_to_tree(Some(&parent.tree()?), Some(&commit.tree()?), None)?;
2844                    diff.deltas().any(|d| {
2845                        d.new_file()
2846                            .path()
2847                            .is_some_and(|p| p == std::path::Path::new(&rel_path))
2848                            || d.old_file()
2849                                .path()
2850                                .is_some_and(|p| p == std::path::Path::new(&rel_path))
2851                    })
2852                };
2853
2854                if dominated {
2855                    let author = commit.author();
2856                    entries.push(LogEntry {
2857                        oid: oid.to_string(),
2858                        message: commit.message().unwrap_or("").to_owned(),
2859                        author: author.name().unwrap_or("").to_owned(),
2860                        timestamp: commit.time().seconds() as u64,
2861                    });
2862                }
2863            }
2864            Ok(entries)
2865        })
2866        .await
2867    }
2868
2869    /// Diff this file against a ref.
2870    async fn handle_diff(
2871        &self,
2872        ctx: &EnvelopeContext,
2873        _request_id: u64,
2874        repo_id: &str,
2875        _name: &str,
2876        fid: u32,
2877        data: &CtlDiffRequest,
2878    ) -> Result<String> {
2879        let subject = ctx.subject().to_string();
2880        let rel_path = self.fid_rel_path(fid, &subject)?;
2881
2882        let id = Self::parse_repo_id(repo_id)?;
2883        let ref_name = if data.ref_name.is_empty() {
2884            "HEAD".to_owned()
2885        } else {
2886            data.ref_name.clone()
2887        };
2888
2889        self.with_repo_blocking(&id, move |repo| {
2890            let obj = repo.revparse_single(&ref_name)?;
2891            let commit = obj.peel_to_commit()?;
2892            let tree = commit.tree()?;
2893
2894            let mut diff_opts = git2::DiffOptions::new();
2895            diff_opts.pathspec(&rel_path);
2896
2897            let diff = repo.diff_tree_to_workdir_with_index(Some(&tree), Some(&mut diff_opts))?;
2898
2899            let mut output = String::new();
2900            diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
2901                let origin = line.origin();
2902                if origin == '+' || origin == '-' || origin == ' ' {
2903                    output.push(origin);
2904                }
2905                if let Ok(s) = std::str::from_utf8(line.content()) {
2906                    output.push_str(s);
2907                }
2908                true
2909            })?;
2910
2911            Ok(output)
2912        })
2913        .await
2914    }
2915
2916    /// Git blame for this file.
2917    async fn handle_blame(
2918        &self,
2919        ctx: &EnvelopeContext,
2920        _request_id: u64,
2921        repo_id: &str,
2922        _name: &str,
2923        fid: u32,
2924    ) -> Result<String> {
2925        let subject = ctx.subject().to_string();
2926        let rel_path = self.fid_rel_path(fid, &subject)?;
2927
2928        let id = Self::parse_repo_id(repo_id)?;
2929
2930        self.with_repo_blocking(&id, move |repo| {
2931            let blame = repo.blame_file(std::path::Path::new(&rel_path), None)?;
2932
2933            let mut output = String::new();
2934            for i in 0..blame.len() {
2935                if let Some(hunk) = blame.get_index(i) {
2936                    let sig = hunk.final_signature();
2937                    let name = sig.name().unwrap_or("?");
2938                    let oid = hunk.final_commit_id();
2939                    let line_start = hunk.final_start_line();
2940                    let line_count = hunk.lines_in_hunk();
2941                    use std::fmt::Write;
2942                    writeln!(
2943                        output,
2944                        "{:.8} ({} L{}-{}) ",
2945                        oid,
2946                        name,
2947                        line_start,
2948                        line_start + line_count - 1
2949                    )?;
2950                }
2951            }
2952            Ok(output)
2953        })
2954        .await
2955    }
2956
2957    /// Restore file content from a ref.
2958    async fn handle_checkout(
2959        &self,
2960        ctx: &EnvelopeContext,
2961        _request_id: u64,
2962        repo_id: &str,
2963        name: &str,
2964        fid: u32,
2965        data: &CtlCheckoutRequest,
2966    ) -> Result<()> {
2967        let subject = ctx.subject().to_string();
2968        let rel_path = self.fid_rel_path(fid, &subject)?;
2969
2970        let id = Self::parse_repo_id(repo_id)?;
2971        let ref_name = if data.ref_name.is_empty() {
2972            "HEAD".to_owned()
2973        } else {
2974            data.ref_name.clone()
2975        };
2976        let rel_path_clone = rel_path.clone();
2977
2978        let blob_content = self
2979            .with_repo_blocking(&id, move |repo| {
2980                let obj = repo.revparse_single(&ref_name)?;
2981                let commit = obj.peel_to_commit()?;
2982                let tree = commit.tree()?;
2983                let entry = tree.get_path(std::path::Path::new(&rel_path_clone))?;
2984                let blob = repo.find_blob(entry.id())?;
2985                Ok(blob.content().to_vec())
2986            })
2987            .await?;
2988
2989        // Write blob content to the worktree file (no registry lock held)
2990        let root = self
2991            .get_contained_root(repo_id, name)
2992            .await
2993            .map_err(|e| anyhow!("{}", e))?;
2994        let mut file = root
2995            .open(
2996                &rel_path,
2997                hyprstream_containedfs::OpenMode::OWRITE | hyprstream_containedfs::OpenMode::OTRUNC,
2998            )
2999            .map_err(|e| anyhow!("{}", e))?;
3000        use std::io::Write as _;
3001        file.write_all(&blob_content)?;
3002        file.flush()?;
3003
3004        Ok(())
3005    }
3006
3007    /// Validate file format.
3008    async fn handle_validate(
3009        &self,
3010        ctx: &EnvelopeContext,
3011        _request_id: u64,
3012        repo_id: &str,
3013        name: &str,
3014        fid: u32,
3015    ) -> Result<ValidationResult> {
3016        let subject = ctx.subject().to_string();
3017        let rel_path = self.fid_rel_path(fid, &subject)?;
3018
3019        // Read the file content
3020        let content = self.read_fid_content(repo_id, name, fid, &subject).await?;
3021
3022        // Detect format from extension
3023        let ext = std::path::Path::new(&rel_path)
3024            .extension()
3025            .and_then(|s| s.to_str())
3026            .unwrap_or("");
3027
3028        let mut errors = Vec::new();
3029        match ext {
3030            "toml" => {
3031                if let Err(e) = content.parse::<toml::Value>() {
3032                    errors.push(e.to_string());
3033                }
3034            }
3035            "json" => {
3036                if let Err(e) = serde_json::from_str::<serde_json::Value>(&content) {
3037                    errors.push(e.to_string());
3038                }
3039            }
3040            "yaml" | "yml" => {
3041                if let Err(e) = serde_yaml::from_str::<serde_yaml::Value>(&content) {
3042                    errors.push(e.to_string());
3043                }
3044            }
3045            _ => {
3046                // Text files are always valid
3047            }
3048        }
3049
3050        Ok(ValidationResult {
3051            valid: errors.is_empty(),
3052            errors,
3053        })
3054    }
3055
3056    /// File metadata and git state.
3057    async fn handle_info(
3058        &self,
3059        ctx: &EnvelopeContext,
3060        _request_id: u64,
3061        _repo_id: &str,
3062        _name: &str,
3063        fid: u32,
3064    ) -> Result<FileInfo> {
3065        let subject = ctx.subject().to_string();
3066        let rel_path = self.fid_rel_path(fid, &subject)?;
3067
3068        let entry = self
3069            .fid_table
3070            .get_verified(fid, &subject)
3071            .map_err(|e| anyhow!("{}", e))?;
3072        let meta = match &entry.state {
3073            FidState::Walked { walk_handle, .. } => {
3074                walk_handle.metadata().map_err(|e| anyhow!("{}", e))?
3075            }
3076            FidState::Opened { file, .. } => file.lock().metadata()?,
3077        };
3078
3079        let ext = std::path::Path::new(&rel_path)
3080            .extension()
3081            .and_then(|s| s.to_str())
3082            .unwrap_or("");
3083        let format = match ext {
3084            "toml" => DocFormat::Toml,
3085            "json" => DocFormat::Json,
3086            "yaml" | "yml" => DocFormat::Yaml,
3087            "csv" => DocFormat::Csv,
3088            _ => DocFormat::Text,
3089        };
3090
3091        let editing = self.editing_table.fid_has_session(&subject, fid);
3092        let dirty = if editing {
3093            if let Some(shared) = self.editing_table.get_session(&subject, fid) {
3094                shared.lock().dirty
3095            } else {
3096                false
3097            }
3098        } else {
3099            false
3100        };
3101
3102        Ok(FileInfo {
3103            path: rel_path,
3104            size: meta.len(),
3105            format,
3106            editing,
3107            dirty,
3108        })
3109    }
3110
3111    /// Open file for CRDT editing.
3112    async fn handle_edit_open(
3113        &self,
3114        ctx: &EnvelopeContext,
3115        _request_id: u64,
3116        repo_id: &str,
3117        name: &str,
3118        fid: u32,
3119        data: &EditOpenRequest,
3120    ) -> Result<()> {
3121        let subject = ctx.subject().to_string();
3122        let rel_path = self.fid_rel_path(fid, &subject)?;
3123        let content = self.read_fid_content(repo_id, name, fid, &subject).await?;
3124        let format = data.format;
3125
3126        self.editing_table
3127            .open(&subject, fid, repo_id, name, &rel_path, format, &content)
3128            .map_err(|e| anyhow!("{}", e))?;
3129
3130        Ok(())
3131    }
3132
3133    /// Get current CRDT document state.
3134    async fn handle_edit_state(
3135        &self,
3136        ctx: &EnvelopeContext,
3137        _request_id: u64,
3138        _repo_id: &str,
3139        _name: &str,
3140        fid: u32,
3141    ) -> Result<String> {
3142        let subject = ctx.subject().to_string();
3143        let shared = self
3144            .editing_table
3145            .get_session(&subject, fid)
3146            .ok_or_else(|| anyhow!("no active editing session for fid {}", fid))?;
3147
3148        let sd = shared.lock();
3149        // Get the content value from the automerge document
3150        let content = sd
3151            .doc
3152            .get(automerge::ROOT, "content")
3153            .ok()
3154            .flatten()
3155            .map(|(val, _)| match val {
3156                automerge::Value::Scalar(s) => match s.as_ref() {
3157                    automerge::ScalarValue::Str(s) => s.to_string(),
3158                    _ => String::new(),
3159                },
3160                _ => String::new(),
3161            })
3162            .unwrap_or_default();
3163
3164        Ok(content)
3165    }
3166
3167    /// Apply automerge CRDT change.
3168    async fn handle_edit_apply(
3169        &self,
3170        ctx: &EnvelopeContext,
3171        _request_id: u64,
3172        _repo_id: &str,
3173        _name: &str,
3174        fid: u32,
3175        data: &EditApplyRequest,
3176    ) -> Result<()> {
3177        let subject = ctx.subject().to_string();
3178        let shared = self
3179            .editing_table
3180            .get_session(&subject, fid)
3181            .ok_or_else(|| anyhow!("no active editing session for fid {}", fid))?;
3182
3183        let mut sd = shared.lock();
3184        sd.doc.load_incremental(&data.change_bytes)?;
3185        sd.dirty = true;
3186
3187        Ok(())
3188    }
3189
3190    /// Close CRDT editing session.
3191    async fn handle_edit_close(
3192        &self,
3193        ctx: &EnvelopeContext,
3194        _request_id: u64,
3195        _repo_id: &str,
3196        _name: &str,
3197        fid: u32,
3198    ) -> Result<()> {
3199        let subject = ctx.subject().to_string();
3200        if !self.editing_table.close(&subject, fid) {
3201            anyhow::bail!("no active editing session for fid {}", fid);
3202        }
3203        Ok(())
3204    }
3205
3206    /// Write CRDT state to disk file.
3207    async fn handle_ctl_flush(
3208        &self,
3209        ctx: &EnvelopeContext,
3210        _request_id: u64,
3211        repo_id: &str,
3212        name: &str,
3213        fid: u32,
3214    ) -> Result<()> {
3215        let subject = ctx.subject().to_string();
3216        let rel_path = self.fid_rel_path(fid, &subject)?;
3217        let shared = self
3218            .editing_table
3219            .get_session(&subject, fid)
3220            .ok_or_else(|| anyhow!("no active editing session for fid {}", fid))?;
3221
3222        // Read current file hash and compare with stored hash
3223        let root = self
3224            .get_contained_root(repo_id, name)
3225            .await
3226            .map_err(|e| anyhow!("{}", e))?;
3227        let current_hash = {
3228            let file = root
3229                .open(&rel_path, hyprstream_containedfs::OpenMode::OREAD)
3230                .map_err(|e| anyhow!("{}", e))?;
3231            let mut data = Vec::new();
3232            std::io::BufReader::new(file).read_to_end(&mut data)?;
3233            editing::sha256_hash(&data)
3234        };
3235
3236        let mut sd = shared.lock();
3237
3238        // Check for external modifications
3239        if current_hash != sd.file_hash {
3240            anyhow::bail!("file modified externally since editOpen; cannot flush");
3241        }
3242
3243        // Get content from CRDT doc
3244        let content = sd
3245            .doc
3246            .get(automerge::ROOT, "content")
3247            .ok()
3248            .flatten()
3249            .map(|(val, _)| match val {
3250                automerge::Value::Scalar(s) => match s.as_ref() {
3251                    automerge::ScalarValue::Str(s) => s.to_string(),
3252                    _ => String::new(),
3253                },
3254                _ => String::new(),
3255            })
3256            .unwrap_or_default();
3257
3258        // Write to disk (write=true, truncate=true)
3259        let mut file = root
3260            .open(
3261                &rel_path,
3262                hyprstream_containedfs::OpenMode::OWRITE | hyprstream_containedfs::OpenMode::OTRUNC,
3263            )
3264            .map_err(|e| anyhow!("{}", e))?;
3265        use std::io::Write as _;
3266        file.write_all(content.as_bytes())?;
3267        file.flush()?;
3268
3269        // Update stored hash and clear dirty flag
3270        sd.file_hash = editing::sha256_hash(content.as_bytes());
3271        sd.dirty = false;
3272
3273        Ok(())
3274    }
3275}
3276
3277// Generated WorktreeHandler Implementation — 9P2000-inspired protocol
3278// ============================================================================
3279
3280#[async_trait::async_trait(?Send)]
3281impl WorktreeHandler for RegistryService {
3282    /// Walk: resolve path components to get a fid.
3283    async fn handle_walk(
3284        &self,
3285        ctx: &EnvelopeContext,
3286        _request_id: u64,
3287        repo_id: &str,
3288        name: &str,
3289        data: &NpWalk,
3290    ) -> Result<RWalk> {
3291        let root = self
3292            .get_contained_root(repo_id, name)
3293            .await
3294            .map_err(|e| anyhow!("{}", e))?;
3295
3296        // Validate each wname is a single safe path component (defense-in-depth;
3297        // pathrs also enforces containment at the kernel level via openat2).
3298        for wname in &data.wnames {
3299            if wname.is_empty() {
3300                anyhow::bail!("wname must not be empty");
3301            }
3302            if wname == ".." {
3303                anyhow::bail!("path traversal via '..' rejected");
3304            }
3305            if wname.contains('/') {
3306                anyhow::bail!(
3307                    "wname {:?} contains slash (must be a single component)",
3308                    wname
3309                );
3310            }
3311            if wname.as_bytes().contains(&0) {
3312                anyhow::bail!("wname contains NUL byte");
3313            }
3314        }
3315
3316        // Join wnames into a path (empty wnames = root)
3317        let path = if data.wnames.is_empty() {
3318            ".".to_owned()
3319        } else {
3320            data.wnames.join("/")
3321        };
3322
3323        let walk_handle = root.walk(&path).map_err(|e| anyhow!("{}", e))?;
3324        let meta = walk_handle.metadata().map_err(|e| anyhow!("{}", e))?;
3325        let qid = qid_from_metadata(&meta);
3326
3327        let subject = ctx.subject().to_string();
3328        // Use client-specified newfid, or auto-allocate
3329        let fid = if data.newfid > 0 {
3330            // Reject if the fid is already in use (prevents overwriting another client's fid)
3331            if self.fid_table.fids.contains_key(&data.newfid) {
3332                anyhow::bail!("fid {} is already in use", data.newfid);
3333            }
3334            data.newfid
3335        } else {
3336            self.fid_table
3337                .alloc_fid(&subject)
3338                .map_err(|e| anyhow!("{}", e))?
3339        };
3340
3341        let entry = FidEntry {
3342            state: FidState::Walked {
3343                walk_handle,
3344                qid: qid.clone(),
3345            },
3346            owner_identity: subject.clone(),
3347            last_accessed: AtomicU64::new(now_epoch_secs()),
3348        };
3349        if data.newfid > 0 {
3350            // Client-specified fid: must increment count (alloc_fid wasn't called)
3351            self.fid_table.insert_counted(fid, entry, &subject);
3352        } else {
3353            // Auto-allocated fid: count was already incremented by alloc_fid
3354            self.fid_table.insert(fid, entry);
3355        }
3356
3357        Ok(RWalk {
3358            qid: Self::qid_to_data(&qid),
3359            fid,
3360        })
3361    }
3362
3363    /// Query-scoped read-only open; the wire request has no mode field.
3364    async fn handle_open_read(
3365        &self,
3366        ctx: &EnvelopeContext,
3367        request_id: u64,
3368        repo_id: &str,
3369        name: &str,
3370        data: &NpStatReq,
3371    ) -> Result<ROpen> {
3372        self.handle_open(
3373            ctx,
3374            request_id,
3375            repo_id,
3376            name,
3377            &NpOpen {
3378                fid: data.fid,
3379                mode: 0,
3380            },
3381        )
3382        .await
3383    }
3384
3385    /// Open: open a walked fid for I/O, returns iounit.
3386    async fn handle_open(
3387        &self,
3388        ctx: &EnvelopeContext,
3389        _request_id: u64,
3390        _repo_id: &str,
3391        _name: &str,
3392        data: &NpOpen,
3393    ) -> Result<ROpen> {
3394        let subject = ctx.subject().to_string();
3395
3396        // Take the fid to transition Walked → Opened (no count change)
3397        let entry = self
3398            .fid_table
3399            .take(data.fid)
3400            .ok_or_else(|| anyhow!("fid {} not found", data.fid))?;
3401        if entry.owner_identity != subject {
3402            // Put it back and bail
3403            self.fid_table.replace(data.fid, entry);
3404            anyhow::bail!("fid {} not owned by caller", data.fid);
3405        }
3406
3407        let (walk_handle, qid) = match entry.state {
3408            FidState::Walked { walk_handle, qid } => (walk_handle, qid),
3409            other => {
3410                // Put it back and bail
3411                self.fid_table.replace(
3412                    data.fid,
3413                    FidEntry {
3414                        state: other,
3415                        owner_identity: entry.owner_identity,
3416                        last_accessed: entry.last_accessed,
3417                    },
3418                );
3419                anyhow::bail!("fid {} is already opened", data.fid);
3420            }
3421        };
3422
3423        // Extract rel_path before consuming the walk_handle
3424        let rel_path = walk_handle.rel_path().to_owned();
3425
3426        let write = (data.mode & OWRITE) != 0 || (data.mode & ORDWR) != 0;
3427        let file = walk_handle.open_file(write).map_err(|e| anyhow!("{}", e))?;
3428
3429        // If OTRUNC, truncate the file
3430        if (data.mode & OTRUNC) != 0 && write {
3431            file.set_len(0)?;
3432        }
3433
3434        let iounit = DEFAULT_IOUNIT;
3435
3436        // Re-insert as Opened (no count change — take didn't decrement)
3437        self.fid_table.replace(
3438            data.fid,
3439            FidEntry {
3440                state: FidState::Opened {
3441                    file: Mutex::new(file),
3442                    qid: qid.clone(),
3443                    iounit,
3444                    mode: data.mode,
3445                    rel_path,
3446                },
3447                owner_identity: subject,
3448                last_accessed: AtomicU64::new(now_epoch_secs()),
3449            },
3450        );
3451
3452        Ok(ROpen {
3453            qid: Self::qid_to_data(&qid),
3454            iounit,
3455        })
3456    }
3457
3458    /// Create: create a file/dir under a walked directory fid.
3459    async fn handle_create(
3460        &self,
3461        ctx: &EnvelopeContext,
3462        _request_id: u64,
3463        repo_id: &str,
3464        name: &str,
3465        data: &NpCreate,
3466    ) -> Result<ROpen> {
3467        let subject = ctx.subject().to_string();
3468
3469        // Validate the name is a single safe path component (defense-in-depth)
3470        if data.name.is_empty() {
3471            anyhow::bail!("create name must not be empty");
3472        }
3473        if data.name == "." || data.name == ".." {
3474            anyhow::bail!("create name {:?} is not a valid file name", data.name);
3475        }
3476        if data.name.contains('/') {
3477            anyhow::bail!(
3478                "create name {:?} must be a single component (no slashes)",
3479                data.name
3480            );
3481        }
3482        if data.name.as_bytes().contains(&0) {
3483            anyhow::bail!("create name contains NUL byte");
3484        }
3485
3486        // Take the fid to get ownership of the WalkHandle (directory we're creating in)
3487        let entry = self
3488            .fid_table
3489            .take(data.fid)
3490            .ok_or_else(|| anyhow!("fid {} not found", data.fid))?;
3491        if entry.owner_identity != subject {
3492            self.fid_table.replace(data.fid, entry);
3493            anyhow::bail!("fid {} not owned by caller", data.fid);
3494        }
3495
3496        let (dir_handle, _dir_qid) = match entry.state {
3497            FidState::Walked { walk_handle, qid } => {
3498                if qid.qtype & QTDIR == 0 {
3499                    // Put it back and bail
3500                    self.fid_table.replace(
3501                        data.fid,
3502                        FidEntry {
3503                            state: FidState::Walked { walk_handle, qid },
3504                            owner_identity: entry.owner_identity,
3505                            last_accessed: entry.last_accessed,
3506                        },
3507                    );
3508                    anyhow::bail!("fid {} is not a directory", data.fid);
3509                }
3510                (walk_handle, qid)
3511            }
3512            other => {
3513                self.fid_table.replace(
3514                    data.fid,
3515                    FidEntry {
3516                        state: other,
3517                        owner_identity: entry.owner_identity,
3518                        last_accessed: entry.last_accessed,
3519                    },
3520                );
3521                anyhow::bail!("fid {} must be a walked (not opened) directory", data.fid);
3522            }
3523        };
3524
3525        let is_dir = (data.perm & DMDIR) != 0;
3526
3527        // Compute the child's path relative to the contained root
3528        let child_path = dir_handle.child_rel_path(&data.name);
3529        let root = self
3530            .get_contained_root(repo_id, name)
3531            .await
3532            .map_err(|e| anyhow!("{}", e))?;
3533
3534        if is_dir {
3535            // Create child directory via ContainedFs (kernel-enforced containment)
3536            root.mkdir(&child_path).map_err(|e| anyhow!("{}", e))?;
3537
3538            // Resolve a handle to the new child directory
3539            let child_handle = root.walk(&child_path).map_err(|e| anyhow!("{}", e))?;
3540            let meta = child_handle.metadata().map_err(|e| anyhow!("{}", e))?;
3541            let qid = qid_from_metadata(&meta);
3542
3543            // Replace the fid with the new directory as Walked (no count change)
3544            self.fid_table.replace(
3545                data.fid,
3546                FidEntry {
3547                    state: FidState::Walked {
3548                        walk_handle: child_handle,
3549                        qid: qid.clone(),
3550                    },
3551                    owner_identity: subject,
3552                    last_accessed: AtomicU64::new(now_epoch_secs()),
3553                },
3554            );
3555
3556            Ok(ROpen {
3557                qid: Self::qid_to_data(&qid),
3558                iounit: DEFAULT_IOUNIT,
3559            })
3560        } else {
3561            // Create file via ContainedFs (kernel-enforced containment)
3562            let file = root
3563                .create(
3564                    &child_path,
3565                    hyprstream_containedfs::OpenMode::OWRITE
3566                        | hyprstream_containedfs::OpenMode::OTRUNC,
3567                )
3568                .map_err(|e| anyhow!("{}", e))?;
3569
3570            let meta = file.metadata()?;
3571            let qid = qid_from_metadata(&meta);
3572            let iounit = DEFAULT_IOUNIT;
3573
3574            // Force ORDWR since create always opens writable
3575            let mode = data.mode | ORDWR;
3576
3577            // Replace the fid with the opened file (no count change)
3578            self.fid_table.replace(
3579                data.fid,
3580                FidEntry {
3581                    state: FidState::Opened {
3582                        file: Mutex::new(file),
3583                        qid: qid.clone(),
3584                        iounit,
3585                        mode,
3586                        rel_path: child_path,
3587                    },
3588                    owner_identity: subject,
3589                    last_accessed: AtomicU64::new(now_epoch_secs()),
3590                },
3591            );
3592
3593            Ok(ROpen {
3594                qid: Self::qid_to_data(&qid),
3595                iounit,
3596            })
3597        }
3598    }
3599
3600    /// Read: offset+count read, bounded by iounit. This is THE fix for the
3601    /// readFile bug — no unbounded allocation possible.
3602    /// For directories, returns entries in wire format: name_len(u32le) + name(utf8) + is_dir(u8) + size(u64le).
3603    async fn handle_read(
3604        &self,
3605        ctx: &EnvelopeContext,
3606        _request_id: u64,
3607        repo_id: &str,
3608        name: &str,
3609        data: &NpRead,
3610    ) -> Result<RRead> {
3611        let subject = ctx.subject().to_string();
3612        let entry = self
3613            .fid_table
3614            .get_verified(data.fid, &subject)
3615            .map_err(|e| anyhow!("{}", e))?;
3616
3617        match &entry.state {
3618            FidState::Opened {
3619                file,
3620                qid,
3621                iounit,
3622                rel_path,
3623                ..
3624            } => {
3625                if qid.qtype & QTDIR != 0 {
3626                    // Directory read: encode entries as wire format
3627                    let root = self
3628                        .get_contained_root(repo_id, name)
3629                        .await
3630                        .map_err(|e| anyhow!("{}", e))?;
3631                    let entries = root.readdir(rel_path).map_err(|e| anyhow!("{}", e))?;
3632
3633                    // Serialize all entries into wire format:
3634                    // name_len(u32le) + name(utf8) + is_dir(u8) + size(u64le)
3635                    //
3636                    // Directory listings are served only at offset=0 to prevent
3637                    // mid-record splits. The client reads in a loop and stops
3638                    // on empty response, so returning empty for offset>0 signals EOF.
3639                    if data.offset != 0 {
3640                        return Ok(RRead { data: vec![] });
3641                    }
3642
3643                    let mut wire = Vec::new();
3644                    for entry in &entries {
3645                        let name_bytes = entry.name.as_bytes();
3646                        wire.extend_from_slice(&(name_bytes.len() as u32).to_le_bytes());
3647                        wire.extend_from_slice(name_bytes);
3648                        wire.push(if entry.is_dir { 1 } else { 0 });
3649                        wire.extend_from_slice(&entry.size.to_le_bytes());
3650                    }
3651
3652                    let count = std::cmp::min(data.count, *iounit) as usize;
3653                    let end = std::cmp::min(count, wire.len());
3654                    Ok(RRead {
3655                        data: wire[..end].to_vec(),
3656                    })
3657                } else {
3658                    // Regular file read
3659                    let count = std::cmp::min(data.count, *iounit) as usize;
3660                    let mut buf = vec![0u8; count];
3661                    let mut f = file.lock();
3662                    f.seek(SeekFrom::Start(data.offset))?;
3663                    let n = f.read(&mut buf)?;
3664                    buf.truncate(n);
3665                    Ok(RRead { data: buf })
3666                }
3667            }
3668            _ => anyhow::bail!("fid {} is not opened for I/O", data.fid),
3669        }
3670    }
3671
3672    /// Write: offset+data write, rejects if data > iounit.
3673    async fn handle_write(
3674        &self,
3675        ctx: &EnvelopeContext,
3676        _request_id: u64,
3677        _repo_id: &str,
3678        _name: &str,
3679        data: &NpWrite,
3680    ) -> Result<RWrite> {
3681        let subject = ctx.subject().to_string();
3682        // Guard: reject direct writes to files with active CRDT editing sessions
3683        if self.editing_table.fid_has_session(&subject, data.fid) {
3684            anyhow::bail!(
3685                "fid {} is open for CRDT editing, use ctl edit-apply instead",
3686                data.fid
3687            );
3688        }
3689        let entry = self
3690            .fid_table
3691            .get_verified(data.fid, &subject)
3692            .map_err(|e| anyhow!("{}", e))?;
3693
3694        match &entry.state {
3695            FidState::Opened {
3696                file, iounit, mode, ..
3697            } => {
3698                if (*mode & OWRITE) == 0 && (*mode & ORDWR) == 0 {
3699                    anyhow::bail!("fid {} not opened for writing", data.fid);
3700                }
3701                if data.data.len() as u32 > *iounit {
3702                    anyhow::bail!(
3703                        "write data ({} bytes) exceeds iounit ({})",
3704                        data.data.len(),
3705                        iounit
3706                    );
3707                }
3708                let mut f = file.lock();
3709                f.seek(SeekFrom::Start(data.offset))?;
3710                let n = f.write(&data.data)?;
3711                Ok(RWrite { count: n as u32 })
3712            }
3713            _ => anyhow::bail!("fid {} is not opened for I/O", data.fid),
3714        }
3715    }
3716
3717    /// Clunk: release a fid, close any open file.
3718    async fn handle_clunk(
3719        &self,
3720        ctx: &EnvelopeContext,
3721        _request_id: u64,
3722        _repo_id: &str,
3723        _name: &str,
3724        data: &NpClunk,
3725    ) -> Result<()> {
3726        let subject = ctx.subject().to_string();
3727        // Clean up any CRDT editing session for this fid
3728        self.editing_table.on_clunk(&subject, data.fid);
3729        let _entry = self
3730            .fid_table
3731            .remove(data.fid, &subject)
3732            .ok_or_else(|| anyhow!("fid {} not found or not owned", data.fid))?;
3733        // File is dropped here, closing the fd
3734        Ok(())
3735    }
3736
3737    /// Remove: clunk + delete the file/directory.
3738    async fn handle_remove(
3739        &self,
3740        ctx: &EnvelopeContext,
3741        _request_id: u64,
3742        repo_id: &str,
3743        name: &str,
3744        data: &NpRemove,
3745    ) -> Result<()> {
3746        let subject = ctx.subject().to_string();
3747        let entry = self
3748            .fid_table
3749            .remove(data.fid, &subject)
3750            .ok_or_else(|| anyhow!("fid {} not found or not owned", data.fid))?;
3751
3752        // Determine what to remove based on the qid type
3753        let qid = match &entry.state {
3754            FidState::Walked { qid, .. } | FidState::Opened { qid, .. } => qid,
3755        };
3756
3757        // We need the path to remove — for now, we can use the contained root
3758        // The walk_handle carries enough info, but we need the path.
3759        // Since 9P remove operates on the fid (not a path), and we have
3760        // the WalkHandle, we use the metadata to identify what we're removing.
3761        // For a proper implementation, we'd need to track the path in the fid.
3762        let _ = (repo_id, name, qid);
3763        warn!(
3764            "9P remove: fid {} clunked but path-based removal requires path tracking",
3765            data.fid
3766        );
3767        // The fid is already removed (clunked) — file handle dropped
3768        Ok(())
3769    }
3770
3771    /// Stat: get file metadata for a fid.
3772    async fn handle_np_stat(
3773        &self,
3774        ctx: &EnvelopeContext,
3775        _request_id: u64,
3776        _repo_id: &str,
3777        _name: &str,
3778        data: &NpStatReq,
3779    ) -> Result<RStat> {
3780        let subject = ctx.subject().to_string();
3781        let entry = self
3782            .fid_table
3783            .get_verified(data.fid, &subject)
3784            .map_err(|e| anyhow!("{}", e))?;
3785
3786        let (meta, rel_path) = match &entry.state {
3787            FidState::Walked { walk_handle, .. } => (
3788                walk_handle.metadata().map_err(|e| anyhow!("{}", e))?,
3789                walk_handle.rel_path().to_owned(),
3790            ),
3791            FidState::Opened { file, rel_path, .. } => (file.lock().metadata()?, rel_path.clone()),
3792        };
3793
3794        let stat = Self::metadata_to_np_stat(Self::rel_path_file_name(&rel_path), &meta);
3795        Ok(RStat { stat })
3796    }
3797
3798    /// Wstat: modify file metadata (rename, truncate, etc).
3799    async fn handle_wstat(
3800        &self,
3801        ctx: &EnvelopeContext,
3802        _request_id: u64,
3803        _repo_id: &str,
3804        _name: &str,
3805        data: &NpWstat,
3806    ) -> Result<()> {
3807        let subject = ctx.subject().to_string();
3808        let entry = self
3809            .fid_table
3810            .get_verified(data.fid, &subject)
3811            .map_err(|e| anyhow!("{}", e))?;
3812
3813        // Handle length change (truncate)
3814        if data.stat.length != u64::MAX && data.stat.length != 0 {
3815            match &entry.state {
3816                FidState::Opened { file, .. } => {
3817                    file.lock().set_len(data.stat.length)?;
3818                }
3819                _ => anyhow::bail!("wstat truncate requires an opened fid"),
3820            }
3821        }
3822
3823        // Name changes (rename) would require path tracking — deferred
3824        if !data.stat.name.is_empty() {
3825            warn!("wstat rename not yet implemented (requires path tracking)");
3826        }
3827
3828        Ok(())
3829    }
3830
3831    /// Flush: cancel a pending operation (no-op for synchronous ops).
3832    async fn handle_flush(
3833        &self,
3834        _ctx: &EnvelopeContext,
3835        _request_id: u64,
3836        _repo_id: &str,
3837        _name: &str,
3838        _data: &NpFlush,
3839    ) -> Result<()> {
3840        // No-op for synchronous operations
3841        Ok(())
3842    }
3843
3844    // ========================================================================
3845    // Worktree-scoped git operations (moved from RepositoryRequest)
3846    // ========================================================================
3847
3848    /// Stage all tracked modified files in this worktree (git add -u).
3849    async fn handle_stage_all(
3850        &self,
3851        _ctx: &EnvelopeContext,
3852        _request_id: u64,
3853        repo_id: &str,
3854        name: &str,
3855    ) -> Result<()> {
3856        let id = Self::parse_repo_id(repo_id)?;
3857        self.with_worktree_blocking(&id, name, |repo| crate::git::ops::stage_all(&repo))
3858            .await
3859    }
3860
3861    /// Stage specific files in this worktree.
3862    async fn handle_stage_files(
3863        &self,
3864        _ctx: &EnvelopeContext,
3865        _request_id: u64,
3866        repo_id: &str,
3867        name: &str,
3868        data: &StageFilesRequest,
3869    ) -> Result<()> {
3870        let id = Self::parse_repo_id(repo_id)?;
3871        let files = data.files.clone();
3872        self.with_worktree_blocking(&id, name, move |repo| {
3873            let file_refs: Vec<&str> = files.iter().map(std::string::String::as_str).collect();
3874            crate::git::ops::stage_files(&repo, &file_refs)
3875        })
3876        .await
3877    }
3878
3879    /// Stage all files including untracked in this worktree (git add -A).
3880    async fn handle_stage_all_including_untracked(
3881        &self,
3882        _ctx: &EnvelopeContext,
3883        _request_id: u64,
3884        repo_id: &str,
3885        name: &str,
3886    ) -> Result<()> {
3887        let id = Self::parse_repo_id(repo_id)?;
3888        self.with_worktree_blocking(&id, name, |repo| {
3889            crate::git::ops::stage_all_with_untracked(&repo)
3890        })
3891        .await
3892    }
3893
3894    /// Commit staged changes in this worktree.
3895    async fn handle_commit(
3896        &self,
3897        _ctx: &EnvelopeContext,
3898        _request_id: u64,
3899        repo_id: &str,
3900        name: &str,
3901        data: &CommitRequest,
3902    ) -> Result<String> {
3903        let id = Self::parse_repo_id(repo_id)?;
3904        let message = data.message.clone();
3905        let author = data.author.clone();
3906        let email = data.email.clone();
3907        self.with_worktree_blocking(&id, name, move |repo| {
3908            let oid = if !author.is_empty() && !email.is_empty() {
3909                crate::git::ops::commit_with_author(&repo, &message, &author, &email)?
3910            } else {
3911                crate::git::ops::commit_index(&repo, &message)?
3912            };
3913            Ok(oid.to_string())
3914        })
3915        .await
3916    }
3917
3918    /// Commit staged changes with specified author.
3919    ///
3920    /// #910a: this is the RPC verb `git::promote::promote` drives (via
3921    /// `WorktreeClient::commit_with_author`) to snapshot the promoted upper
3922    /// layer, so publishing the PDS record here — rather than in the
3923    /// client-side `advance_pointer` stub — is what makes "promote" actually
3924    /// advance the atproto pointer for a local/single-node deployment.
3925    async fn handle_commit_with_author(
3926        &self,
3927        _ctx: &EnvelopeContext,
3928        _request_id: u64,
3929        repo_id: &str,
3930        name: &str,
3931        data: &CommitWithAuthorRequest,
3932    ) -> Result<String> {
3933        let id = Self::parse_repo_id(repo_id)?;
3934        let message = data.message.clone();
3935        let author_name = data.author_name.clone();
3936        let author_email = data.author_email.clone();
3937        let oid = self
3938            .with_worktree_blocking(&id, name, move |repo| {
3939                Ok(crate::git::ops::commit_with_author(
3940                    &repo,
3941                    &message,
3942                    &author_name,
3943                    &author_email,
3944                )?
3945                .to_string())
3946            })
3947            .await?;
3948        self.publish_pds_record(&id, &oid);
3949        Ok(oid)
3950    }
3951
3952    /// Amend the last commit in this worktree.
3953    async fn handle_amend_commit(
3954        &self,
3955        _ctx: &EnvelopeContext,
3956        _request_id: u64,
3957        repo_id: &str,
3958        name: &str,
3959        data: &AmendCommitRequest,
3960    ) -> Result<String> {
3961        let id = Self::parse_repo_id(repo_id)?;
3962        let message = data.message.clone();
3963        self.with_worktree_blocking(&id, name, move |repo| {
3964            Ok(crate::git::ops::amend_head(&repo, &message)?.to_string())
3965        })
3966        .await
3967    }
3968
3969    /// Checkout a ref in this worktree.
3970    async fn handle_checkout(
3971        &self,
3972        _ctx: &EnvelopeContext,
3973        _request_id: u64,
3974        repo_id: &str,
3975        name: &str,
3976        data: &CheckoutRequest,
3977    ) -> Result<()> {
3978        let id = Self::parse_repo_id(repo_id)?;
3979        let ref_name = data.ref_name.clone();
3980        self.with_worktree_blocking(&id, name, move |repo| {
3981            crate::git::ops::ensure_branch(&repo, &ref_name)
3982        })
3983        .await
3984    }
3985
3986    /// Merge a branch into this worktree.
3987    async fn handle_merge(
3988        &self,
3989        _ctx: &EnvelopeContext,
3990        _request_id: u64,
3991        repo_id: &str,
3992        name: &str,
3993        data: &MergeRequest,
3994    ) -> Result<()> {
3995        let id = Self::parse_repo_id(repo_id)?;
3996        let source = data.source.clone();
3997        let message = if data.message.is_empty() {
3998            None
3999        } else {
4000            Some(data.message.clone())
4001        };
4002        self.with_worktree_blocking(&id, name, move |repo| {
4003            crate::git::ops::merge(&repo, &source, message.as_deref())?;
4004            Ok(())
4005        })
4006        .await
4007    }
4008
4009    /// Abort an in-progress merge in this worktree.
4010    async fn handle_abort_merge(
4011        &self,
4012        _ctx: &EnvelopeContext,
4013        _request_id: u64,
4014        repo_id: &str,
4015        name: &str,
4016    ) -> Result<()> {
4017        let id = Self::parse_repo_id(repo_id)?;
4018        self.with_worktree_blocking(&id, name, |repo| crate::git::ops::abort_merge(&repo))
4019            .await
4020    }
4021
4022    /// Continue a merge after resolving conflicts.
4023    async fn handle_continue_merge(
4024        &self,
4025        _ctx: &EnvelopeContext,
4026        _request_id: u64,
4027        repo_id: &str,
4028        name: &str,
4029        data: &ContinueMergeRequest,
4030    ) -> Result<()> {
4031        let id = Self::parse_repo_id(repo_id)?;
4032        let message = if data.message.is_empty() {
4033            None
4034        } else {
4035            Some(data.message.clone())
4036        };
4037        self.with_worktree_blocking(&id, name, move |repo| {
4038            crate::git::ops::continue_merge(&repo, message.as_deref())?;
4039            Ok(())
4040        })
4041        .await
4042    }
4043
4044    /// Exit merge state without committing.
4045    async fn handle_quit_merge(
4046        &self,
4047        _ctx: &EnvelopeContext,
4048        _request_id: u64,
4049        repo_id: &str,
4050        name: &str,
4051    ) -> Result<()> {
4052        let id = Self::parse_repo_id(repo_id)?;
4053        self.with_worktree_blocking(&id, name, |repo| crate::git::ops::quit_merge(&repo))
4054            .await
4055    }
4056}
4057
4058#[cfg(feature = "postgres")]
4059pub(crate) const FEDERATE_REGISTRY_REQUEST_ROOT_TYPE_ID: u64 =
4060    <hyprstream_rpc_std::registry_capnp::registry_request::Reader<'static> as capnp::traits::HasTypeId>::TYPE_ID;
4061
4062#[cfg(feature = "postgres")]
4063fn federate_registry_operation(
4064    body: &hyprstream_rpc::service::DecodedRequestBody,
4065    pin: &crate::services::model::StagingModelPin,
4066) -> Result<(String, String)> {
4067    use hyprstream_rpc_std::registry_capnp::registry_request;
4068    anyhow::ensure!(
4069        pin == &crate::services::model::StagingModelPin::reviewed()?,
4070        "Federate Registry requires the reviewed staging model pin"
4071    );
4072    let request = body.root::<registry_request::Reader>()?;
4073    match request.which()? {
4074        registry_request::Which::List(()) => Ok(("registry:List".to_owned(), "query".to_owned())),
4075        registry_request::Which::GetByName(name) => {
4076            let name = name?.to_str()?;
4077            anyhow::ensure!(
4078                name == crate::services::model::StagingModelPin::reviewed_repo_name(),
4079                "Federate Registry lookup is not the reviewed model repository"
4080            );
4081            Ok((format!("registry:{name}"), "query".to_owned()))
4082        }
4083        _ => anyhow::bail!("unsupported Federate Registry method"),
4084    }
4085}
4086
4087#[async_trait(?Send)]
4088impl RequestService for RegistryService {
4089    fn accept_deferred_federate_credential(&self) -> bool {
4090        #[cfg(feature = "postgres")]
4091        {
4092            self.federate_dispatch.is_some()
4093        }
4094        #[cfg(not(feature = "postgres"))]
4095        {
4096            false
4097        }
4098    }
4099
4100    async fn admit_deferred_federate_request(
4101        &self,
4102        ctx: &EnvelopeContext,
4103        body: &hyprstream_rpc::service::DecodedRequestBody,
4104        proof: &hyprstream_rpc::proof::parser::ParsedProof,
4105    ) -> anyhow::Result<(
4106        hyprstream_rpc::proof::verify::VerifiedProof,
4107        [u8; 32],
4108        String,
4109        String,
4110        hyprstream_rpc::proof::admission::ProofReplayKey,
4111        u64,
4112    )> {
4113        #[cfg(feature = "postgres")]
4114        {
4115            let adapter = self
4116                .federate_dispatch
4117                .as_ref()
4118                .ok_or_else(|| anyhow::anyhow!("Federate dispatch is disabled"))?;
4119            let pin = crate::services::model::StagingModelPin::from_env()?
4120                .ok_or_else(|| anyhow::anyhow!("Federate Registry requires a staging model pin"))?;
4121            let (resource, operation) = federate_registry_operation(body, &pin)?;
4122            let (verified, holder, replay_key, replay_expiry) = adapter
4123                .admit(
4124                    ctx,
4125                    proof,
4126                    "registry",
4127                    FEDERATE_REGISTRY_REQUEST_ROOT_TYPE_ID,
4128                    body.bytes(),
4129                )
4130                .await?;
4131            Ok((
4132                verified,
4133                holder,
4134                resource,
4135                operation,
4136                replay_key,
4137                replay_expiry,
4138            ))
4139        }
4140        #[cfg(not(feature = "postgres"))]
4141        {
4142            let _ = (ctx, body, proof);
4143            anyhow::bail!("Federate dispatch is disabled")
4144        }
4145    }
4146
4147    async fn commit_deferred_federate_request(
4148        &self,
4149        ctx: &EnvelopeContext,
4150        resource: &str,
4151        operation: &str,
4152        replay_key: &hyprstream_rpc::proof::admission::ProofReplayKey,
4153        replay_expiry: u64,
4154    ) -> anyhow::Result<()> {
4155        #[cfg(feature = "postgres")]
4156        {
4157            let adapter = self
4158                .federate_dispatch
4159                .as_ref()
4160                .ok_or_else(|| anyhow::anyhow!("Federate dispatch is disabled"))?;
4161            adapter
4162                .commit_request_use(ctx, resource, operation, replay_key, replay_expiry)
4163                .await
4164                .map_err(anyhow::Error::new)
4165        }
4166        #[cfg(not(feature = "postgres"))]
4167        {
4168            let _ = (ctx, resource, operation, replay_key, replay_expiry);
4169            anyhow::bail!("Federate dispatch is disabled")
4170        }
4171    }
4172
4173    fn decode_request_body(
4174        &self,
4175        signed_body: &[u8],
4176    ) -> anyhow::Result<hyprstream_rpc::service::DecodedRequestBody> {
4177        // The ONE bounded decode (v16 §5.2): the generated decoder derives
4178        // the full method leaf and returns the decoded message that policy,
4179        // MAC, and dispatch below all consume.
4180        crate::services::generated::registry_client::decode_registry_request_body(signed_body)
4181    }
4182
4183    fn producer_reach_config_handle(
4184        &self,
4185    ) -> Option<hyprstream_rpc::moq_stream::ProducerReachConfigHandle> {
4186        Some(self.reach_config.clone())
4187    }
4188
4189    fn moq_origin_handle(&self) -> Option<hyprstream_rpc::moq_stream::MoqStreamOriginHandle> {
4190        Some(self.moq_origin.clone())
4191    }
4192
4193    async fn handle_request(
4194        &self,
4195        ctx: &EnvelopeContext,
4196        body: &hyprstream_rpc::service::DecodedRequestBody,
4197    ) -> Result<(Vec<u8>, Option<crate::services::Continuation>)> {
4198        // The mount ticket and Registry's ordinary direct resource currently
4199        // share the issuer audience. The generic delegated-resource hook only
4200        // runs when audiences differ, so fence this ticket class here as well.
4201        if ctx
4202            .claims()
4203            .is_some_and(crate::services::oauth::mount_ticket::is_mount_ticket_claims)
4204        {
4205            anyhow::ensure!(
4206                ctx.is_delegated_bearer() && self.accept_delegated_resource_leaf(ctx, body),
4207                "9P mount ticket cannot invoke this Registry leaf"
4208            );
4209        }
4210        dispatch_registry(self, ctx, body).await
4211    }
4212
4213    fn name(&self) -> &str {
4214        "registry"
4215    }
4216
4217    fn transport(&self) -> &TransportConfig {
4218        &self.transport
4219    }
4220
4221    fn signing_key(&self) -> SigningKey {
4222        self.signing_key.clone()
4223    }
4224
4225    fn expected_audience(&self) -> Option<&str> {
4226        self.expected_audience.as_deref()
4227    }
4228
4229    fn accept_delegated_bearer(&self, signer: &[u8; 32]) -> bool {
4230        if self.ninep_canonical_read.is_none() || self.delegated_ninep_audience.is_none() {
4231            return false;
4232        }
4233        let Ok(key) = hyprstream_rpc::prelude::VerifyingKey::from_bytes(signer) else {
4234            return false;
4235        };
4236        hyprstream_service::global_trust_store().is_authorized(&key, "mcp")
4237    }
4238
4239    fn delegated_user_audience(
4240        &self,
4241        signer: &[u8; 32],
4242        untrusted_aud: Option<&str>,
4243    ) -> Option<&str> {
4244        if self.accept_delegated_bearer(signer) {
4245            if let Some(audience) = self.delegated_ninep_audience.as_deref() {
4246                if untrusted_aud == Some(audience) {
4247                    return Some(audience);
4248                }
4249            }
4250        }
4251        self.expected_audience()
4252    }
4253
4254    fn accept_delegated_resource_leaf(
4255        &self,
4256        ctx: &EnvelopeContext,
4257        body: &hyprstream_rpc::service::DecodedRequestBody,
4258    ) -> bool {
4259        use hyprstream_rpc_std::registry_capnp::{
4260            registry_request, repository_request, worktree_request,
4261        };
4262        let Some(export) = self.ninep_canonical_read.as_ref() else {
4263            return false;
4264        };
4265        let Some(claims) = ctx.claims() else {
4266            return false;
4267        };
4268        if claims.aud.as_deref() != self.delegated_ninep_audience.as_deref()
4269            || !self.accept_delegated_bearer(&ctx.cnf)
4270            || !(crate::services::oauth::mount_ticket::is_mount_ticket_for(claims, "ws", "/")
4271                || crate::services::oauth::mount_ticket::is_mount_ticket_for(
4272                    claims,
4273                    "webtransport",
4274                    "/",
4275                ))
4276        {
4277            return false;
4278        }
4279        let Ok(request) = body.root::<registry_request::Reader>() else {
4280            return false;
4281        };
4282        match request.which() {
4283            Ok(registry_request::Which::Get(Ok(id))) => {
4284                id.to_str().is_ok_and(|id| id == export.repo_id)
4285            }
4286            Ok(registry_request::Which::Repo(Ok(repo))) => {
4287                if !repo
4288                    .get_repo_id()
4289                    .ok()
4290                    .and_then(|id| id.to_str().ok())
4291                    .is_some_and(|id| id == export.repo_id)
4292                {
4293                    return false;
4294                }
4295                let Ok(repository_request::Which::Worktree(Ok(worktree))) = repo.which() else {
4296                    return false;
4297                };
4298                if !worktree
4299                    .get_name()
4300                    .ok()
4301                    .and_then(|name| name.to_str().ok())
4302                    .is_some_and(|name| name == export.worktree)
4303                {
4304                    return false;
4305                }
4306                matches!(
4307                    worktree.which(),
4308                    Ok(worktree_request::Which::Walk(_)
4309                        | worktree_request::Which::OpenRead(_)
4310                        | worktree_request::Which::Read(_)
4311                        | worktree_request::Which::Clunk(_)
4312                        | worktree_request::Which::NpStat(_))
4313                )
4314            }
4315            _ => false,
4316        }
4317    }
4318
4319    fn jwt_key_source(&self) -> Option<std::sync::Arc<dyn hyprstream_rpc::auth::JwtKeySource>> {
4320        self.jwt_key_source.clone()
4321    }
4322
4323    fn build_error_payload(&self, request_id: u64, error: &str) -> Vec<u8> {
4324        let variant = RegistryResponseVariant::Error(ErrorInfo {
4325            message: error.to_owned(),
4326            code: "INTERNAL".to_owned(),
4327            details: String::new(),
4328        });
4329        serialize_response(request_id, &variant).unwrap_or_default()
4330    }
4331}
4332
4333// ============================================================================
4334// Metrics checkpoint adapter for the canonical generated RegistryClient
4335// ============================================================================
4336
4337#[cfg(feature = "metrics")]
4338use hyprstream_metrics::checkpoint::manager::{
4339    RegistryClient as MetricsRegistryClient, RegistryError as MetricsRegistryError,
4340};
4341
4342#[cfg(feature = "metrics")]
4343pub(crate) struct MetricsRegistryAdapter(pub(crate) RegistryClient);
4344
4345#[cfg(feature = "metrics")]
4346#[async_trait]
4347impl MetricsRegistryClient for MetricsRegistryAdapter {
4348    async fn get_by_name(
4349        &self,
4350        name: &str,
4351    ) -> Result<Option<TrackedRepository>, MetricsRegistryError> {
4352        let r = self
4353            .0
4354            .get_by_name(name)
4355            .await
4356            .map_err(|e| MetricsRegistryError::Operation(e.to_string()))?;
4357        Ok(Some(
4358            variant_to_tracked_repository(
4359                &r.id,
4360                &r.name,
4361                &r.url,
4362                "",
4363                &r.tracking_ref,
4364                &r.current_oid,
4365                r.registered_at,
4366            )
4367            .map_err(|e| MetricsRegistryError::Operation(e.to_string()))?,
4368        ))
4369    }
4370
4371    async fn register(
4372        &self,
4373        _id: &RepoId,
4374        name: Option<&str>,
4375        path: &std::path::Path,
4376    ) -> Result<(), MetricsRegistryError> {
4377        let path_str = path
4378            .to_str()
4379            .ok_or_else(|| MetricsRegistryError::Operation("Invalid path encoding".to_owned()))?;
4380        self.0
4381            .register(&RegisterRequest {
4382                path: path_str.to_owned(),
4383                name: name.unwrap_or("").to_owned(),
4384                tracking_ref: String::new(),
4385            })
4386            .await
4387            .map(|_| ())
4388            .map_err(|e| MetricsRegistryError::Operation(e.to_string()))
4389    }
4390}
4391
4392/// Parse a git-xet / git-lfs pointer file and report whether `merkle_hex` is the
4393/// pointer's **content-hash / OID field** — i.e. the address this tracked file
4394/// genuinely reconstructs *from*. This is the entitlement-by-reconstruction
4395/// primitive: a `true` result means "the requested merkle is the content-OID of
4396/// this file," not merely "the file's text mentions the hex somewhere."
4397///
4398/// The match is on the OID field only (exact, case-insensitive on the hex). An
4399/// arbitrary text blob that contains the hex in a comment or unrelated field does
4400/// NOT count — that was the planted-reference gap (#436): a writer could check in
4401/// a blob naming a merkle they aren't entitled to and (under a substring scan)
4402/// borrow read access to it over the global dedup store. Binding to the OID field
4403/// closes it, because the file only reconstructs from its own content-OID.
4404///
4405/// Recognized forms (one key=value / `key value` per line):
4406///   - git-lfs:  `oid sha256:<hex>`
4407///   - git-xet:  `xet://<hex>` or `merkle: <hex>` / `merklehash = <hex>`
4408///
4409/// Matching is case-insensitive on the hex.
4410fn xet_pointer_references_merkle(text: &str, merkle_hex: &str) -> bool {
4411    let want = merkle_hex.trim().to_ascii_lowercase();
4412    if want.is_empty() {
4413        return false;
4414    }
4415    // Only treat blobs that look like a pointer file (have a version/oid/xet
4416    // marker) as candidates — avoids matching arbitrary checked-in text.
4417    let looks_like_pointer = text.lines().any(|l| {
4418        let l = l.trim_start();
4419        l.starts_with("version https://git-lfs")
4420            || l.starts_with("version https://xet")
4421            || l.starts_with("# xet")
4422            || l.starts_with("xet://")
4423    });
4424    if !looks_like_pointer {
4425        return false;
4426    }
4427    for line in text.lines() {
4428        let line = line.trim();
4429        // Extract the candidate hash token from known field shapes.
4430        let candidate = if let Some(rest) = line.strip_prefix("oid sha256:") {
4431            Some(rest.trim())
4432        } else if let Some(rest) = line.strip_prefix("xet://") {
4433            Some(rest.trim())
4434        } else if let Some(rest) = line.strip_prefix("merkle:") {
4435            Some(rest.trim())
4436        } else {
4437            // `merklehash = <hex>` or `merklehash <hex>`
4438            line.strip_prefix("merklehash")
4439                .map(|rest| rest.trim_start_matches([' ', '=', '\t']).trim())
4440        };
4441        if let Some(c) = candidate {
4442            if c.to_ascii_lowercase() == want {
4443                return true;
4444            }
4445        }
4446    }
4447    false
4448}
4449
4450#[cfg(test)]
4451mod xet_pointer_tests {
4452    use super::xet_pointer_references_merkle;
4453
4454    const HEX: &str = "abc123def456abc123def456abc123def456abc123def456abc123def456abcd";
4455
4456    #[test]
4457    fn matches_lfs_pointer_exact_oid() {
4458        let ptr =
4459            format!("version https://git-lfs.github.com/spec/v1\noid sha256:{HEX}\nsize 1234\n");
4460        assert!(xet_pointer_references_merkle(&ptr, HEX));
4461    }
4462
4463    #[test]
4464    fn matches_xet_pointer_scheme() {
4465        let ptr = format!("version https://xet.example/v1\nxet://{HEX}\n");
4466        assert!(xet_pointer_references_merkle(&ptr, HEX));
4467    }
4468
4469    #[test]
4470    fn rejects_non_pointer_text_containing_hex() {
4471        // An arbitrary checked-in file that merely contains the hex string is
4472        // NOT a reference — this is the sub-gap the old substring scan allowed.
4473        let doc = format!("# notes\nsome unrelated text mentioning {HEX} in passing\n");
4474        assert!(!xet_pointer_references_merkle(&doc, HEX));
4475    }
4476
4477    #[test]
4478    fn rejects_pointer_with_different_oid() {
4479        let other = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
4480        let ptr = format!("version https://git-lfs.github.com/spec/v1\noid sha256:{other}\n");
4481        assert!(!xet_pointer_references_merkle(&ptr, HEX));
4482    }
4483
4484    #[test]
4485    fn rejects_empty_merkle() {
4486        let ptr = format!("version https://git-lfs.github.com/spec/v1\noid sha256:{HEX}\n");
4487        assert!(!xet_pointer_references_merkle(&ptr, ""));
4488    }
4489
4490    #[test]
4491    fn rejects_pointer_naming_merkle_in_non_oid_field() {
4492        // The #436 entitlement-by-reconstruction core: a real, pointer-SHAPED file
4493        // (it has the version marker) that names the requested merkle somewhere
4494        // OTHER than its content-OID field — here as a trailing comment and as the
4495        // `size` value — does NOT authorize the merkle. Its own OID is unrelated,
4496        // so this file does not reconstruct from the requested address. Under the
4497        // old reference/substring model this planted reference would have leaked
4498        // read access over the global dedup store.
4499        let other = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
4500        let planted = format!(
4501            "version https://git-lfs.github.com/spec/v1\n\
4502             oid sha256:{other}\n\
4503             size {HEX}\n\
4504             # see also {HEX}\n"
4505        );
4506        assert!(
4507            !xet_pointer_references_merkle(&planted, HEX),
4508            "merkle named outside the OID field must NOT count as a reconstruction target"
4509        );
4510        // Sanity: the same pointer DOES authorize its genuine content-OID.
4511        assert!(xet_pointer_references_merkle(&planted, other));
4512    }
4513
4514    #[test]
4515    fn xet_merkle_field_is_reconstruction_target() {
4516        // A git-xet pointer whose merkle field equals the requested hash is a
4517        // genuine reconstruction target → entitled.
4518        let ptr = format!("version https://xet.example/v1\nmerklehash = {HEX}\nsize 42\n");
4519        assert!(xet_pointer_references_merkle(&ptr, HEX));
4520    }
4521
4522    // KNOWN-OPEN (#436): a caller-committed pointer with a target private merkle
4523    // in its `oid sha256:` field must NOT authorize a read — the writer is a
4524    // planter, not the owner; only server-authoritative upload provenance (the
4525    // repo's mdb_shard manifest) distinguishes them. The pointer-only check
4526    // CANNOT yet make that distinction, so this asserts the CORRECT (deny)
4527    // behavior and is #[ignore]'d until provenance verification lands. It is a
4528    // failing tracking test for the fix, NOT a lock-in of current behavior.
4529    #[test]
4530    #[ignore = "#436: needs server-side upload-provenance; pointer-only check cannot deny a planted OID-field pointer yet"]
4531    fn oid_field_planted_pointer_must_be_denied() {
4532        let target_private = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";
4533        let planted_in_oid = format!(
4534            "version https://git-lfs.github.com/spec/v1\noid sha256:{target_private}\nsize 4096\n"
4535        );
4536        // Provenance-aware containment must reject a pointer the caller simply
4537        // committed naming someone else's content as its OID. (Fails today: the
4538        // pointer-only check returns true — that's the #436 gap.)
4539        assert!(
4540            !xet_pointer_references_merkle(&planted_in_oid, target_private),
4541            "a caller-committed OID-field pointer must not by itself prove entitlement"
4542        );
4543    }
4544}
4545
4546#[cfg(test)]
4547// Test-only: panics-on-error and ergonomic literals are acceptable in fixtures.
4548#[allow(
4549    clippy::unwrap_used,
4550    clippy::expect_used,
4551    clippy::str_to_string,
4552    clippy::needless_borrow,
4553    clippy::mem_forget
4554)]
4555mod tests {
4556    use super::*;
4557
4558    #[cfg(feature = "postgres")]
4559    #[test]
4560    fn federate_registry_route_admits_only_list_and_exact_pinned_get_by_name() -> Result<()> {
4561        let pin = crate::services::model::StagingModelPin::reviewed()?;
4562        let bytes = hyprstream_rpc::serialize_message(|message| {
4563            let mut request = message
4564                .init_root::<hyprstream_rpc_std::registry_capnp::registry_request::Builder>();
4565            request.set_id(1);
4566            request.set_list(());
4567        })?;
4568        let body =
4569            crate::services::generated::registry_client::decode_registry_request_body(&bytes)?;
4570        assert_eq!(
4571            federate_registry_operation(&body, &pin)?,
4572            ("registry:List".into(), "query".into())
4573        );
4574
4575        let bytes = hyprstream_rpc::serialize_message(|message| {
4576            let mut request = message
4577                .init_root::<hyprstream_rpc_std::registry_capnp::registry_request::Builder>();
4578            request.set_id(2);
4579            request.set_get_by_name(crate::services::model::StagingModelPin::reviewed_repo_name());
4580        })?;
4581        let body =
4582            crate::services::generated::registry_client::decode_registry_request_body(&bytes)?;
4583        assert_eq!(
4584            federate_registry_operation(&body, &pin)?,
4585            ("registry:qwen2.5-0.5b-instruct".into(), "query".into())
4586        );
4587
4588        for rejected in ["", "attacker", "qwen2.5-0.5b-instruct:main"] {
4589            let bytes = hyprstream_rpc::serialize_message(|message| {
4590                let mut request = message
4591                    .init_root::<hyprstream_rpc_std::registry_capnp::registry_request::Builder>(
4592                );
4593                request.set_id(3);
4594                request.set_get_by_name(rejected);
4595            })?;
4596            let body =
4597                crate::services::generated::registry_client::decode_registry_request_body(&bytes)?;
4598            assert!(
4599                federate_registry_operation(&body, &pin).is_err(),
4600                "accepted {rejected:?}"
4601            );
4602        }
4603
4604        let bytes = hyprstream_rpc::serialize_message(|message| {
4605            let mut request = message
4606                .init_root::<hyprstream_rpc_std::registry_capnp::registry_request::Builder>();
4607            request.set_id(4);
4608            request.set_get("repo-id");
4609        })?;
4610        let body =
4611            crate::services::generated::registry_client::decode_registry_request_body(&bytes)?;
4612        assert!(federate_registry_operation(&body, &pin).is_err());
4613        let other = crate::services::model::StagingModelPin::new("other:main", pin.commit)?;
4614        let bytes = hyprstream_rpc::serialize_message(|message| {
4615            let mut request = message
4616                .init_root::<hyprstream_rpc_std::registry_capnp::registry_request::Builder>();
4617            request.set_id(5);
4618            request.set_list(());
4619        })?;
4620        let body =
4621            crate::services::generated::registry_client::decode_registry_request_body(&bytes)?;
4622        assert!(federate_registry_operation(&body, &other).is_err());
4623        let wrong_oid = crate::services::model::StagingModelPin::new(
4624            pin.model_ref.clone(),
4625            git2::Oid::from_str("0000000000000000000000000000000000000001")?,
4626        )?;
4627        assert!(federate_registry_operation(&body, &wrong_oid).is_err());
4628        Ok(())
4629    }
4630    use crate::auth::PolicyManager;
4631    use crate::services::PolicyService;
4632    use hyprstream_rpc::crypto::generate_signing_keypair;
4633    use hyprstream_rpc_std::policy_client::PolicyClient;
4634    use hyprstream_service::ServiceManager;
4635    use tempfile::TempDir;
4636
4637    struct At9pTestSigner {
4638        ed: ed25519_dalek::SigningKey,
4639        pq: hyprstream_rpc::crypto::pq::MlDsaSigningKey,
4640        pair: hyprstream_pds::at9p::HybridKeyPair,
4641    }
4642    fn at9p_test_signer(tag: u8) -> At9pTestSigner {
4643        use hyprstream_rpc::crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes};
4644        let mut seed = [0u8; 32];
4645        seed[0] = tag;
4646        let ed = ed25519_dalek::SigningKey::from_bytes(&seed);
4647        let (pq, vk) = ml_dsa_generate_keypair();
4648        let pair = hyprstream_pds::at9p::HybridKeyPair::new(
4649            ed.verifying_key().to_bytes().to_vec(),
4650            ml_dsa_vk_bytes(&vk),
4651        )
4652        .unwrap();
4653        At9pTestSigner { ed, pq, pair }
4654    }
4655    fn at9p_test_body(
4656        current: &At9pTestSigner,
4657        next: &[&At9pTestSigner],
4658        tag: &str,
4659    ) -> hyprstream_pds::at9p::CapsuleBody {
4660        use hyprstream_pds::at9p::{
4661            CapsuleBody, ServiceEndpoint, ServiceEntry, ServiceType, Transport,
4662        };
4663        let service = ServiceEntry::new(
4664            "#ns",
4665            ServiceType::NinePExport,
4666            ServiceEndpoint::new(Transport::Iroh, format!("iroh://{tag}")).unwrap(),
4667        )
4668        .unwrap();
4669        let mut body = CapsuleBody::new(vec![current.pair.clone()], vec![service]).unwrap();
4670        body.next_key_commitments = next.iter().map(|s| s.pair.commitment_digest()).collect();
4671        body
4672    }
4673
4674    #[tokio::test]
4675    async fn test_registry_service_health_check() {
4676        crate::mac::install_explicit_test_dispatch_pep();
4677        use hyprstream_rpc::transport::TransportConfig;
4678        use hyprstream_service::InprocManager;
4679
4680        // Tests use Classical (EdDSA-only) keys — install Classical verify
4681        // policy on both the request and response arms so the global
4682        // fail-closed Hybrid defaults don't reject them.
4683        let _ = hyprstream_rpc::envelope::install_verify_config(
4684            hyprstream_rpc::envelope::EnvelopeVerifyConfig {
4685                policy: hyprstream_rpc::crypto::CryptoPolicy::Classical,
4686                pq_store: None,
4687            },
4688        );
4689        let _ = hyprstream_rpc::envelope::install_response_verify_config(
4690            hyprstream_rpc::envelope::ResponseVerifyConfig {
4691                policy: hyprstream_rpc::crypto::CryptoPolicy::Classical,
4692                pq_store: None,
4693            },
4694        );
4695
4696        let temp_dir = TempDir::new().expect("test: create temp dir");
4697
4698        // Generate keypair for signing/verification
4699        let (signing_key, _verifying_key) = generate_signing_keypair();
4700        hyprstream_service::global_trust_store().insert(
4701            signing_key.verifying_key(),
4702            hyprstream_service::Attestation {
4703                scopes: std::collections::HashSet::new(),
4704                subject: Some("service:registry".to_owned()),
4705                jwt: None,
4706                expires_at: 0,
4707                attested_by: None,
4708            },
4709        );
4710
4711        // Create a permissive policy manager and start PolicyService first
4712        let policy_manager = Arc::new(
4713            PolicyManager::permissive()
4714                .await
4715                .expect("test: create policy manager"),
4716        );
4717        let policy_transport = TransportConfig::inproc("test-policy-health");
4718        let git2db = Arc::new(tokio::sync::RwLock::new(
4719            git2db::Git2DB::open(temp_dir.path())
4720                .await
4721                .expect("test: open git2db"),
4722        ));
4723        let policy_service = PolicyService::new(
4724            policy_manager,
4725            Arc::new(signing_key.clone()),
4726            crate::config::TokenConfig::default(),
4727            git2db,
4728            policy_transport,
4729        );
4730        let manager = InprocManager::new();
4731        let _policy_handle = manager
4732            .spawn(Box::new(policy_service))
4733            .await
4734            .expect("test: start policy service");
4735
4736        // Create policy client for RegistryService
4737        let policy_client: PolicyClient = PolicyClient::for_local_endpoint_bootstrap(
4738            "inproc://test-policy-health",
4739            signing_key.clone(),
4740            signing_key.verifying_key(),
4741            None,
4742        )
4743        .expect("test: create policy client");
4744
4745        // Start the registry service with policy client
4746        let registry_transport = TransportConfig::inproc("test-registry-health");
4747        let registry_service = RegistryService::new(
4748            temp_dir.path(),
4749            policy_client,
4750            registry_transport,
4751            signing_key.clone(),
4752        )
4753        .await
4754        .expect("test: create registry service");
4755        let mut handle = manager
4756            .spawn(Box::new(registry_service))
4757            .await
4758            .expect("test: start registry service");
4759
4760        // Create signed client with matching key and local identity
4761        let client: RegistryClient = RegistryClient::for_local_endpoint_bootstrap(
4762            "inproc://test-registry-health",
4763            signing_key.clone(),
4764            signing_key.verifying_key(),
4765            None,
4766        )
4767        .expect("test: create registry client");
4768        // health_check returns () on success
4769        let result = client.health_check().await;
4770        assert!(
4771            result.is_ok(),
4772            "health_check should succeed: {:?}",
4773            result.err()
4774        );
4775
4776        // Stop the service
4777        let _ = handle.stop().await;
4778    }
4779
4780    #[cfg(feature = "rocksdb")]
4781    #[tokio::test]
4782    async fn registry_rpc_is_live_at9p_candidate_boundary() {
4783        crate::mac::install_explicit_test_dispatch_pep();
4784        use hyprstream_pds::at9p_sign::{sign_capsule, sign_update_record};
4785        use hyprstream_service::InprocManager;
4786        const NOW: &str = "2026-07-16T12:00:00Z";
4787        let _ = hyprstream_rpc::envelope::install_verify_config(
4788            hyprstream_rpc::envelope::EnvelopeVerifyConfig {
4789                policy: hyprstream_rpc::crypto::CryptoPolicy::Classical,
4790                pq_store: None,
4791            },
4792        );
4793        let _ = hyprstream_rpc::envelope::install_response_verify_config(
4794            hyprstream_rpc::envelope::ResponseVerifyConfig {
4795                policy: hyprstream_rpc::crypto::CryptoPolicy::Classical,
4796                pq_store: None,
4797            },
4798        );
4799        let root = TempDir::new().unwrap();
4800        let models = root.path().join("models");
4801        let pds = root.path().join("pds");
4802        let (key, _) = generate_signing_keypair();
4803        hyprstream_service::global_trust_store().insert(
4804            key.verifying_key(),
4805            hyprstream_service::Attestation {
4806                scopes: std::collections::HashSet::new(),
4807                subject: Some("service:registry".to_owned()),
4808                jwt: None,
4809                expires_at: 0,
4810                attested_by: None,
4811            },
4812        );
4813        let policy_manager = Arc::new(PolicyManager::permissive().await.unwrap());
4814        let policy_git = Arc::new(RwLock::new(Git2DB::open(&models).await.unwrap()));
4815        let policy = PolicyService::new(
4816            policy_manager,
4817            Arc::new(key.clone()),
4818            crate::config::TokenConfig::default(),
4819            policy_git,
4820            TransportConfig::inproc("at9p-policy"),
4821        );
4822        let manager = InprocManager::new();
4823        let mut policy_handle = manager.spawn(Box::new(policy)).await.unwrap();
4824        let policy_client = PolicyClient::for_local_endpoint_bootstrap(
4825            "inproc://at9p-policy",
4826            key.clone(),
4827            key.verifying_key(),
4828            None,
4829        )
4830        .unwrap();
4831        let store = Arc::new(
4832            crate::services::discovery::PdsRecordStore::open(&pds)
4833                .unwrap()
4834                .with_at9p_acceptance_identity(key.verifying_key()),
4835        );
4836        let ingest = crate::services::discovery::At9pStateIngest::open(
4837            Arc::clone(&store),
4838            &root.path().join("alarm"),
4839            key.clone(),
4840            ed25519_dalek::SigningKey::from_bytes(&[81u8; 32]),
4841            hyprstream_rpc::crypto::pq::ml_dsa_sk_from_seed(&[82u8; 32]),
4842        )
4843        .unwrap();
4844        let publisher = {
4845            use crate::auth::key_rotation::{Es256KeySlot, Es256KeySlots, Es256SigningKeyStore};
4846            let store_for_pub = Arc::new(Es256SigningKeyStore::new(Es256KeySlots {
4847                drain: None,
4848                active: Some(Es256KeySlot::new(
4849                    p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng),
4850                    0,
4851                    i64::MAX,
4852                )),
4853                lead: None,
4854            }));
4855            crate::services::discovery::PdsPublisher::new(
4856                Arc::clone(&store),
4857                "did:key:test".to_owned(),
4858                store_for_pub,
4859            )
4860            .with_at9p_state_ingest(ingest)
4861        };
4862        let registry = RegistryService::new(
4863            &models,
4864            policy_client,
4865            TransportConfig::inproc("at9p-registry"),
4866            key.clone(),
4867        )
4868        .await
4869        .unwrap()
4870        .with_pds_publisher(publisher);
4871        let mut handle = manager.spawn(Box::new(registry)).await.unwrap();
4872        let client = RegistryClient::for_local_endpoint_bootstrap(
4873            "inproc://at9p-registry",
4874            key.clone(),
4875            key.verifying_key(),
4876            None,
4877        )
4878        .unwrap();
4879        let (g, n1, n2, n3) = (
4880            at9p_test_signer(1),
4881            at9p_test_signer(2),
4882            at9p_test_signer(3),
4883            at9p_test_signer(4),
4884        );
4885        let genesis = sign_capsule(at9p_test_body(&g, &[&n1], "genesis"), &g.ed, &g.pq).unwrap();
4886        let genesis_bytes = genesis.to_dag_cbor().unwrap();
4887        let cid = genesis.cid512().unwrap();
4888        let did = format!("{}{}", hyprstream_pds::at9p_gate::DID_AT9P_PREFIX, cid);
4889        assert_eq!(
4890            client
4891                .ingest_at9p_candidate(&At9pCandidateRequest {
4892                    did: did.clone(),
4893                    kind: At9pCandidateKind::Genesis,
4894                    record_bytes: genesis_bytes.clone(),
4895                })
4896                .await
4897                .unwrap()
4898                .epoch,
4899            0
4900        );
4901        let update = sign_update_record(
4902            cid.clone(),
4903            1,
4904            hyprstream_pds::at9p::h512(&genesis_bytes),
4905            at9p_test_body(&n1, &[&n2], "rotated"),
4906            "2099-01-01T00:00:00Z".to_owned(),
4907            &n1.ed,
4908            &n1.pq,
4909        )
4910        .unwrap();
4911        let accepted = client
4912            .ingest_at9p_candidate(&At9pCandidateRequest {
4913                did: did.clone(),
4914                kind: At9pCandidateKind::Successor,
4915                record_bytes: update.to_dag_cbor().unwrap(),
4916            })
4917            .await
4918            .unwrap();
4919        assert_eq!(accepted.epoch, 1);
4920        let resolver = crate::services::discovery::PdsRecordResolver::new(Arc::clone(&store));
4921        let state = resolver.accepted_at9p_state(&did, NOW).unwrap().unwrap();
4922        assert_eq!(state.current.subject_keys[0], n1.pair);
4923        let fork = sign_update_record(
4924            cid.clone(),
4925            1,
4926            hyprstream_pds::at9p::h512(&genesis_bytes),
4927            at9p_test_body(&n1, &[&n2], "fork"),
4928            "2099-01-01T00:00:00Z".to_owned(),
4929            &n1.ed,
4930            &n1.pq,
4931        )
4932        .unwrap();
4933        assert!(client
4934            .ingest_at9p_candidate(&At9pCandidateRequest {
4935                did: did.clone(),
4936                kind: At9pCandidateKind::Successor,
4937                record_bytes: fork.to_dag_cbor().unwrap(),
4938            })
4939            .await
4940            .is_err());
4941        let expired = sign_update_record(
4942            cid.clone(),
4943            2,
4944            state.head_digest,
4945            at9p_test_body(&n2, &[], "expired"),
4946            "2026-01-01T00:00:00Z".to_owned(),
4947            &n2.ed,
4948            &n2.pq,
4949        )
4950        .unwrap();
4951        assert!(client
4952            .ingest_at9p_candidate(&At9pCandidateRequest {
4953                did: did.clone(),
4954                kind: At9pCandidateKind::Successor,
4955                record_bytes: expired.to_dag_cbor().unwrap(),
4956            })
4957            .await
4958            .is_err());
4959        let terminal = sign_update_record(
4960            cid.clone(),
4961            2,
4962            state.head_digest,
4963            at9p_test_body(&n2, &[], "terminal"),
4964            "2099-01-01T00:00:00Z".to_owned(),
4965            &n2.ed,
4966            &n2.pq,
4967        )
4968        .unwrap();
4969        let terminal_state = client
4970            .ingest_at9p_candidate(&At9pCandidateRequest {
4971                did: did.clone(),
4972                kind: At9pCandidateKind::Successor,
4973                record_bytes: terminal.to_dag_cbor().unwrap(),
4974            })
4975            .await
4976            .unwrap();
4977        assert!(terminal_state.terminal);
4978        let after_terminal = sign_update_record(
4979            cid,
4980            3,
4981            terminal_state.head_digest.try_into().unwrap(),
4982            at9p_test_body(&n3, &[&n3], "forbidden"),
4983            "2099-01-01T00:00:00Z".to_owned(),
4984            &n3.ed,
4985            &n3.pq,
4986        )
4987        .unwrap();
4988        assert!(client
4989            .ingest_at9p_candidate(&At9pCandidateRequest {
4990                did,
4991                kind: At9pCandidateKind::Successor,
4992                record_bytes: after_terminal.to_dag_cbor().unwrap(),
4993            })
4994            .await
4995            .is_err());
4996        handle.stop().await.unwrap();
4997        assert!(!handle.is_running());
4998        drop(resolver);
4999        // The client may retain the processor; stop must still destroy the
5000        // service's publisher/ingest and release its RocksDB ownership first.
5001        assert_eq!(
5002            Arc::strong_count(&store),
5003            1,
5004            "stopped Registry retained its DB"
5005        );
5006        drop(store);
5007        let reopened = crate::services::discovery::PdsRecordStore::open(&pds).unwrap();
5008        drop(reopened);
5009        policy_handle.stop().await.unwrap();
5010        assert!(!policy_handle.is_running());
5011    }
5012
5013    // ── #432 getBlob authz: the hash is NOT a capability ──────────────────────
5014    // These deny-path tests are the load-bearing security checks: a caller that
5015    // presents a valid-looking content address but no legitimate grant must be
5016    // refused, because XET global-dedup makes content hashes predictable for any
5017    // public-derived content. Both conditions (grantRepo access AND grantRepo
5018    // contains the address) gate the bytes; here we exercise the cheap denials
5019    // (empty / unknown grantRepo) that need no content setup.
5020    async fn spawn_registry_for_authz_test(
5021        temp_dir: &TempDir,
5022        suffix: &str,
5023    ) -> (
5024        RegistryClient,
5025        hyprstream_service::InprocManager,
5026        hyprstream_service::SpawnedService,
5027    ) {
5028        use hyprstream_rpc::transport::TransportConfig;
5029        use hyprstream_service::InprocManager;
5030
5031        let _ = hyprstream_rpc::envelope::install_verify_config(
5032            hyprstream_rpc::envelope::EnvelopeVerifyConfig {
5033                policy: hyprstream_rpc::crypto::CryptoPolicy::Classical,
5034                pq_store: None,
5035            },
5036        );
5037        let (signing_key, _vk) = generate_signing_keypair();
5038        let policy_manager = Arc::new(
5039            PolicyManager::permissive()
5040                .await
5041                .expect("test: policy manager"),
5042        );
5043        let policy_transport = TransportConfig::inproc(format!("test-policy-{suffix}"));
5044        let git2db = Arc::new(tokio::sync::RwLock::new(
5045            git2db::Git2DB::open(temp_dir.path())
5046                .await
5047                .expect("test: open git2db"),
5048        ));
5049        let policy_service = PolicyService::new(
5050            policy_manager,
5051            Arc::new(signing_key.clone()),
5052            crate::config::TokenConfig::default(),
5053            git2db,
5054            policy_transport,
5055        );
5056        let manager = InprocManager::new();
5057        let _policy_handle = manager
5058            .spawn(Box::new(policy_service))
5059            .await
5060            .expect("test: start policy");
5061        let policy_client: PolicyClient = PolicyClient::for_local_endpoint_bootstrap(
5062            &format!("inproc://test-policy-{suffix}"),
5063            signing_key.clone(),
5064            signing_key.verifying_key(),
5065            None,
5066        )
5067        .expect("test: policy client");
5068        let registry_transport = TransportConfig::inproc(format!("test-registry-{suffix}"));
5069        let registry_service = RegistryService::new(
5070            temp_dir.path(),
5071            policy_client,
5072            registry_transport,
5073            signing_key.clone(),
5074        )
5075        .await
5076        .expect("test: create registry service");
5077        let handle = manager
5078            .spawn(Box::new(registry_service))
5079            .await
5080            .expect("test: start registry");
5081        let client: RegistryClient = RegistryClient::for_local_endpoint_bootstrap(
5082            &format!("inproc://test-registry-{suffix}"),
5083            signing_key.clone(),
5084            signing_key.verifying_key(),
5085            None,
5086        )
5087        .expect("test: registry client");
5088        // Leak the policy handle for the test's lifetime (dropped at process exit).
5089        std::mem::forget(_policy_handle);
5090        (client, manager, handle)
5091    }
5092
5093    #[tokio::test]
5094    async fn test_get_blob_denied_empty_grant_repo() {
5095        // A predictable-looking git OID with NO grant context must be refused:
5096        // possessing the hash grants nothing.
5097        let temp_dir = TempDir::new().expect("test: temp dir");
5098        let (client, _manager, mut handle) =
5099            spawn_registry_for_authz_test(&temp_dir, "blob-empty").await;
5100        let req = GetBlobRequest {
5101            content: GetBlobRequestContent::GitOid("a".repeat(40)),
5102            grant_repo: String::new(),
5103        };
5104        let res = client.get_blob(&req, [0u8; 32]).await;
5105        assert!(
5106            res.is_err(),
5107            "getBlob with empty grantRepo must be denied (hash is not a capability), got: {res:?}"
5108        );
5109        let _ = handle.stop().await;
5110    }
5111
5112    // ── #436 entitlement-by-reconstruction (file-level) over global dedup ──────
5113    // These exercise condition (b) for XET against a REAL registered repo with a
5114    // committed git-lfs pointer. The fix: a merkle is authorized iff it is the
5115    // content-OID a tracked file reconstructs FROM (file-level entitlement), not
5116    // merely because some blob in the repo names the hex.
5117
5118    /// Build a RegistryService (not spawned over a transport) whose base_dir
5119    /// already tracks one non-bare repo. `commit_files` are written + committed
5120    /// into that repo's working tree at HEAD before the service opens base_dir.
5121    /// Returns the service and the registered RepoId.
5122    async fn registry_with_committed_repo(
5123        base_dir: &std::path::Path,
5124        repo_name: &str,
5125        commit_files: &[(&str, &str)],
5126    ) -> (RegistryService, RepoId) {
5127        use git2::{Repository, Signature};
5128        use hyprstream_rpc::transport::TransportConfig;
5129        use hyprstream_service::InprocManager;
5130
5131        let _ = hyprstream_rpc::envelope::install_verify_config(
5132            hyprstream_rpc::envelope::EnvelopeVerifyConfig {
5133                policy: hyprstream_rpc::crypto::CryptoPolicy::Classical,
5134                pq_store: None,
5135            },
5136        );
5137
5138        // 1. Create a non-bare git repo with a working tree + committed files.
5139        let repo_path = base_dir.join(repo_name);
5140        std::fs::create_dir_all(&repo_path).expect("test: mkdir repo");
5141        let repo = Repository::init(&repo_path).expect("test: git init");
5142        {
5143            let mut index = repo.index().expect("test: index");
5144            for (rel, contents) in commit_files {
5145                std::fs::write(repo_path.join(rel), contents).expect("test: write file");
5146                index
5147                    .add_path(std::path::Path::new(rel))
5148                    .expect("test: index add");
5149            }
5150            index.write().expect("test: index write");
5151            let tree_oid = index.write_tree().expect("test: write tree");
5152            let tree = repo.find_tree(tree_oid).expect("test: find tree");
5153            let sig = Signature::now("Test", "test@example.com").expect("test: sig");
5154            repo.commit(Some("HEAD"), &sig, &sig, "fixture", &tree, &[])
5155                .expect("test: commit");
5156        }
5157
5158        // 2. Register the repo with Git2DB via the builder API.
5159        let repo_id = RepoId::new();
5160        {
5161            let mut git2db = Git2DB::open(base_dir).await.expect("test: open git2db");
5162            git2db
5163                .register(repo_id.clone())
5164                .name(repo_name)
5165                .worktree_path(&repo_path)
5166                .url(String::new())
5167                .exec()
5168                .await
5169                .expect("test: register repo");
5170        }
5171
5172        // 3. Construct the service over the now-populated base_dir. A real (but
5173        // unused-by-these-tests) PolicyService backs the client so for_endpoint
5174        // resolves; repo_contains_xet_merkle never touches it.
5175        let (signing_key, _vk) = generate_signing_keypair();
5176        let policy_ep = format!("test-policy-436-{repo_name}");
5177        let policy_manager = Arc::new(
5178            PolicyManager::permissive()
5179                .await
5180                .expect("test: policy manager"),
5181        );
5182        let policy_git2db = Arc::new(tokio::sync::RwLock::new(
5183            Git2DB::open(base_dir)
5184                .await
5185                .expect("test: open git2db for policy"),
5186        ));
5187        let policy_service = PolicyService::new(
5188            policy_manager,
5189            Arc::new(signing_key.clone()),
5190            crate::config::TokenConfig::default(),
5191            policy_git2db,
5192            TransportConfig::inproc(&policy_ep),
5193        );
5194        let manager = InprocManager::new();
5195        let policy_handle = manager
5196            .spawn(Box::new(policy_service))
5197            .await
5198            .expect("test: start policy");
5199        std::mem::forget(policy_handle);
5200        let policy_client: PolicyClient = PolicyClient::for_local_endpoint_bootstrap(
5201            &format!("inproc://{policy_ep}"),
5202            signing_key.clone(),
5203            signing_key.verifying_key(),
5204            None,
5205        )
5206        .expect("test: policy client");
5207        let registry_transport = TransportConfig::inproc(format!("test-registry-436-{repo_name}"));
5208        let service =
5209            RegistryService::new(base_dir, policy_client, registry_transport, signing_key)
5210                .await
5211                .expect("test: create registry service");
5212        (service, repo_id)
5213    }
5214
5215    const MERKLE_A: &str = "1111111111111111111111111111111111111111111111111111111111111111";
5216    const MERKLE_B: &str = "2222222222222222222222222222222222222222222222222222222222222222";
5217
5218    #[tokio::test]
5219    async fn test_xet_merkle_permitted_when_file_reconstructs_from_it() {
5220        // (a) PERMIT: the repo tracks a git-lfs pointer whose content-OID equals
5221        // the requested merkle → the file genuinely reconstructs from this
5222        // address → entitled.
5223        let temp_dir = TempDir::new().expect("test: temp dir");
5224        let pointer = format!(
5225            "version https://git-lfs.github.com/spec/v1\noid sha256:{MERKLE_A}\nsize 4096\n"
5226        );
5227        let (service, repo_id) = registry_with_committed_repo(
5228            temp_dir.path(),
5229            "model-permit",
5230            &[("model.safetensors", &pointer)],
5231        )
5232        .await;
5233
5234        // Mirror the authenticated write path (putBlob calls xet_provenance.record):
5235        // the repo legitimately contributed MERKLE_A's bytes, so the authoritative
5236        // provenance gate is satisfied. Reconstruction/pointer match is the
5237        // second gate.
5238        service
5239            .xet_provenance
5240            .record(MERKLE_A, &repo_id.0.to_string())
5241            .await
5242            .expect("test: record provenance");
5243
5244        let permitted = service
5245            .repo_contains_xet_merkle(&repo_id, MERKLE_A)
5246            .await
5247            .expect("test: containment check");
5248        assert!(
5249            permitted,
5250            "merkle that equals a tracked file's content-OID must be a reconstruction target"
5251        );
5252    }
5253
5254    #[tokio::test]
5255    async fn test_xet_merkle_denied_for_planted_reference() {
5256        // (b) DENY — the core #436 fix: the repo tracks a real pointer (so it has
5257        // SOME xet content), and ALSO checks in a blob that merely NAMES MERKLE_B
5258        // (the private content the caller is not entitled to) outside any OID
5259        // field. MERKLE_B is not the content-OID of any file the caller can
5260        // reconstruct here → must be denied. Under the old reference/substring
5261        // model this planted reference would have leaked read access to MERKLE_B
5262        // over the global dedup store.
5263        let temp_dir = TempDir::new().expect("test: temp dir");
5264        let legit_pointer = format!(
5265            "version https://git-lfs.github.com/spec/v1\noid sha256:{MERKLE_A}\nsize 4096\n"
5266        );
5267        // A pointer-shaped file that names MERKLE_B only in non-OID positions.
5268        let planted = format!(
5269            "version https://git-lfs.github.com/spec/v1\n\
5270             oid sha256:{MERKLE_A}\n\
5271             size {MERKLE_B}\n\
5272             # borrowed: {MERKLE_B}\n"
5273        );
5274        let (service, repo_id) = registry_with_committed_repo(
5275            temp_dir.path(),
5276            "model-planted",
5277            &[
5278                ("model.safetensors", &legit_pointer),
5279                ("planted.txt", &planted),
5280            ],
5281        )
5282        .await;
5283
5284        // Bind only the legitimately-contributed content (MERKLE_A), as the
5285        // authenticated putBlob write path would. MERKLE_B was never authentically
5286        // written by this repo, so it stays unbound: the authoritative provenance
5287        // gate denies it regardless of the planted reference in the tree.
5288        service
5289            .xet_provenance
5290            .record(MERKLE_A, &repo_id.0.to_string())
5291            .await
5292            .expect("test: record provenance");
5293
5294        let denied = service
5295            .repo_contains_xet_merkle(&repo_id, MERKLE_B)
5296            .await
5297            .expect("test: containment check");
5298        assert!(
5299            !denied,
5300            "a planted reference that is not any file's content-OID must NOT authorize the merkle"
5301        );
5302
5303        // Sanity: the legitimately-tracked merkle (MERKLE_A) IS still permitted.
5304        let still_permitted = service
5305            .repo_contains_xet_merkle(&repo_id, MERKLE_A)
5306            .await
5307            .expect("test: containment check");
5308        assert!(
5309            still_permitted,
5310            "the genuine content-OID must remain entitled"
5311        );
5312    }
5313
5314    #[tokio::test]
5315    async fn test_get_blob_denied_unknown_grant_repo() {
5316        // A grant repo the registry doesn't track must be refused before any
5317        // content lookup — a caller can't name an arbitrary repo to fish bytes.
5318        let temp_dir = TempDir::new().expect("test: temp dir");
5319        let (client, _manager, mut handle) =
5320            spawn_registry_for_authz_test(&temp_dir, "blob-unknown").await;
5321        let req = GetBlobRequest {
5322            content: GetBlobRequestContent::XetMerkle("bafyunknownmerkleroot".to_string()),
5323            grant_repo: "at://did:web:nope.example/ai.hyprstream.model/missing".to_string(),
5324        };
5325        let res = client.get_blob(&req, [0u8; 32]).await;
5326        assert!(
5327            res.is_err(),
5328            "getBlob with unknown grantRepo must be denied, got: {res:?}"
5329        );
5330        let _ = handle.stop().await;
5331    }
5332
5333    // ── #427 finding 1: Tstat must return the real name, not "" ─────────────
5334    #[tokio::test]
5335    async fn test_tstat_returns_real_registry_repo_name() {
5336        // `metadata_to_np_stat("", ..)` meant the registry's Tstat handler
5337        // never returned a file name — identity was carried by qid/size only.
5338        // Walk to a real committed file in a registered repo and assert the
5339        // RStat now carries its actual name.
5340        let temp_dir = TempDir::new().expect("test: temp dir");
5341        let (service, repo_id) = registry_with_committed_repo(
5342            temp_dir.path(),
5343            "model-tstat-name",
5344            &[("config.json", "{}")],
5345        )
5346        .await;
5347
5348        let ctx = EnvelopeContext::from_callback_service(1, "test-caller");
5349        let repo_id_str = repo_id.to_string();
5350
5351        // Walk from the repo root to config.json with a deterministic fid.
5352        let walk = service
5353            .handle_walk(
5354                &ctx,
5355                1,
5356                &repo_id_str,
5357                ".",
5358                &NpWalk {
5359                    fid: 0,
5360                    newfid: 42,
5361                    wnames: vec!["config.json".to_string()],
5362                },
5363            )
5364            .await
5365            .expect("test: walk to config.json");
5366        assert_eq!(
5367            walk.qid.qtype & 0x80,
5368            0,
5369            "config.json must not be a directory"
5370        );
5371
5372        let stat = service
5373            .handle_np_stat(&ctx, 2, &repo_id_str, ".", &NpStatReq { fid: 42 })
5374            .await
5375            .expect("test: stat fid 42");
5376
5377        assert_eq!(
5378            stat.stat.name, "config.json",
5379            "Tstat on a real registry-repo record must return the actual file name, not empty"
5380        );
5381    }
5382
5383    #[tokio::test]
5384    async fn test_server_allocated_walk_fids_are_distinct_and_read_only_open_works() {
5385        let temp_dir = TempDir::new().expect("test: temp dir");
5386        let (service, repo_id) = registry_with_committed_repo(
5387            temp_dir.path(),
5388            "server-fid-read",
5389            &[("config.json", "canonical bytes")],
5390        )
5391        .await;
5392        let repo_id = repo_id.to_string();
5393        let caller = EnvelopeContext::from_callback_service(1, "same-holder");
5394
5395        let mut fids = Vec::new();
5396        for request_id in [1, 2] {
5397            let walk = service
5398                .handle_walk(
5399                    &caller,
5400                    request_id,
5401                    &repo_id,
5402                    ".",
5403                    &NpWalk {
5404                        fid: 0,
5405                        newfid: 0,
5406                        wnames: vec!["config.json".to_owned()],
5407                    },
5408                )
5409                .await
5410                .expect("server-allocated walk");
5411            assert_ne!(walk.fid, 0);
5412            assert!(!fids.contains(&walk.fid));
5413            service
5414                .handle_open_read(
5415                    &caller,
5416                    request_id + 2,
5417                    &repo_id,
5418                    ".",
5419                    &NpStatReq { fid: walk.fid },
5420                )
5421                .await
5422                .expect("read-only open");
5423            let read = service
5424                .handle_read(
5425                    &caller,
5426                    request_id + 4,
5427                    &repo_id,
5428                    ".",
5429                    &NpRead {
5430                        fid: walk.fid,
5431                        offset: 0,
5432                        count: 64,
5433                    },
5434                )
5435                .await
5436                .expect("read canonical bytes");
5437            assert_eq!(read.data, b"canonical bytes");
5438            fids.push(walk.fid);
5439        }
5440        for fid in fids {
5441            service
5442                .handle_clunk(&caller, 7, &repo_id, ".", &NpClunk { fid })
5443                .await
5444                .expect("clunk server fid");
5445        }
5446    }
5447
5448    // ── #427 finding 2: register RPC must honor the caller-supplied path ───
5449    #[tokio::test]
5450    async fn test_register_honors_caller_supplied_path() {
5451        // The deprecated `register_repository` ignored the supplied path and
5452        // hard-required the repo at `base_dir/<uuid>`. `handle_register` must
5453        // now route through the `Git2DB::register(repo_id)` builder and honor
5454        // the real, caller-chosen path.
5455        use git2::{Repository, Signature};
5456        use hyprstream_rpc::transport::TransportConfig;
5457        use hyprstream_service::InprocManager;
5458
5459        let _ = hyprstream_rpc::envelope::install_verify_config(
5460            hyprstream_rpc::envelope::EnvelopeVerifyConfig {
5461                policy: hyprstream_rpc::crypto::CryptoPolicy::Classical,
5462                pq_store: None,
5463            },
5464        );
5465
5466        let temp_dir = TempDir::new().expect("test: temp dir");
5467        let base_dir = temp_dir.path();
5468
5469        // Repo lives at a caller-chosen, non-UUID subdirectory of base_dir —
5470        // exactly the layout register_repository's base_dir/<uuid> assumption
5471        // could not honor.
5472        let repo_name = "my-custom-repo";
5473        let repo_path = base_dir.join(repo_name);
5474        std::fs::create_dir_all(&repo_path).expect("test: mkdir repo");
5475        let repo = Repository::init(&repo_path).expect("test: git init");
5476        {
5477            let mut index = repo.index().expect("test: index");
5478            std::fs::write(repo_path.join("README.md"), "hello").expect("test: write file");
5479            index
5480                .add_path(Path::new("README.md"))
5481                .expect("test: index add");
5482            index.write().expect("test: index write");
5483            let tree_oid = index.write_tree().expect("test: write tree");
5484            let tree = repo.find_tree(tree_oid).expect("test: find tree");
5485            let sig = Signature::now("Test", "test@example.com").expect("test: sig");
5486            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
5487                .expect("test: commit");
5488        }
5489
5490        let (signing_key, _vk) = generate_signing_keypair();
5491        let policy_manager = Arc::new(
5492            PolicyManager::permissive()
5493                .await
5494                .expect("test: policy manager"),
5495        );
5496        let policy_git2db = Arc::new(tokio::sync::RwLock::new(
5497            Git2DB::open(base_dir).await.expect("test: open git2db"),
5498        ));
5499        let policy_service = PolicyService::new(
5500            policy_manager,
5501            Arc::new(signing_key.clone()),
5502            crate::config::TokenConfig::default(),
5503            policy_git2db,
5504            TransportConfig::inproc("test-policy-register-path"),
5505        );
5506        let manager = InprocManager::new();
5507        let policy_handle = manager
5508            .spawn(Box::new(policy_service))
5509            .await
5510            .expect("test: start policy");
5511        std::mem::forget(policy_handle);
5512        let policy_client: PolicyClient = PolicyClient::for_local_endpoint_bootstrap(
5513            "inproc://test-policy-register-path",
5514            signing_key.clone(),
5515            signing_key.verifying_key(),
5516            None,
5517        )
5518        .expect("test: policy client");
5519
5520        let service = RegistryService::new(
5521            base_dir,
5522            policy_client,
5523            TransportConfig::inproc("test-registry-register-path"),
5524            signing_key,
5525        )
5526        .await
5527        .expect("test: create registry service");
5528
5529        let tracked = service
5530            .handle_register(&repo_path.to_string_lossy(), Some(repo_name), None)
5531            .await
5532            .expect("test: register");
5533
5534        assert_eq!(
5535            tracked.worktree_path, repo_path,
5536            "register RPC must honor the caller-supplied path, not force base_dir/<uuid>"
5537        );
5538        assert_eq!(tracked.name.as_deref(), Some(repo_name));
5539    }
5540
5541    #[tokio::test]
5542    async fn concurrent_register_rejects_duplicate_name_before_a_second_write() -> Result<()> {
5543        use git2::{Repository, Signature};
5544        use hyprstream_service::InprocManager;
5545
5546        let temp = TempDir::new()?;
5547        let mut candidates = Vec::new();
5548        for label in ["first", "second"] {
5549            let path = temp.path().join(label);
5550            let repo = Repository::init(&path)?;
5551            std::fs::write(path.join("README.md"), label)?;
5552            let mut index = repo.index()?;
5553            index.add_path(Path::new("README.md"))?;
5554            index.write()?;
5555            let tree_oid = index.write_tree()?;
5556            let tree = repo.find_tree(tree_oid)?;
5557            let author = Signature::now("Canary", "canary@example.invalid")?;
5558            let oid = repo.commit(Some("HEAD"), &author, &author, label, &tree, &[])?;
5559            candidates.push((path, oid.to_string()));
5560        }
5561
5562        let (signing_key, _) = generate_signing_keypair();
5563        let policy_manager = Arc::new(PolicyManager::permissive().await?);
5564        let policy_git = Arc::new(RwLock::new(Git2DB::open(temp.path()).await?));
5565        let policy_service = PolicyService::new(
5566            policy_manager,
5567            Arc::new(signing_key.clone()),
5568            crate::config::TokenConfig::default(),
5569            policy_git,
5570            TransportConfig::inproc("test-policy-register-duplicate"),
5571        );
5572        let manager = InprocManager::new();
5573        let _policy_handle = manager.spawn(Box::new(policy_service)).await?;
5574        let policy_client = PolicyClient::for_local_endpoint_bootstrap(
5575            "inproc://test-policy-register-duplicate",
5576            signing_key.clone(),
5577            signing_key.verifying_key(),
5578            None,
5579        )?;
5580        let service = RegistryService::new(
5581            temp.path(),
5582            policy_client,
5583            TransportConfig::inproc("test-registry-register-duplicate"),
5584            signing_key,
5585        )
5586        .await?;
5587        let first_path = candidates[0].0.to_string_lossy().into_owned();
5588        let second_path = candidates[1].0.to_string_lossy().into_owned();
5589        let (first, second) = tokio::join!(
5590            service.handle_register(&first_path, Some("canary"), None),
5591            service.handle_register(&second_path, Some("canary"), None),
5592        );
5593        assert_eq!(usize::from(first.is_ok()) + usize::from(second.is_ok()), 1);
5594        let winner = first.or(second)?;
5595        assert_eq!(winner.name.as_deref(), Some("canary"));
5596        assert!(candidates.iter().any(|(path, oid)| {
5597            winner.worktree_path == *path && winner.current_oid.as_deref() == Some(oid.as_str())
5598        }));
5599        let registry = service.registry.read().await;
5600        let matching = registry
5601            .list()
5602            .filter(|repo| repo.name.as_deref() == Some("canary"))
5603            .collect::<Vec<_>>();
5604        assert_eq!(matching.len(), 1);
5605        assert_eq!(matching[0].id, winner.id);
5606        assert_eq!(matching[0].current_oid, winner.current_oid);
5607        Ok(())
5608    }
5609}