///|
/// Explicit host environment values passed into server startup and pure source
/// resolution (never read from hidden global state inside core code).
#derive(Eq, Debug)
pub(all) struct HostEnv {
  platform : Platform
  system_config_dir : FolderPath?
  user_config_dir : FolderPath?
  env_vars : ReadOnlyArray[(String, String)]
}

///|
/// Creates an empty `HostEnv` for a platform with no config dirs or env vars.
pub fn HostEnv::empty(platform : Platform) -> HostEnv {
  { platform, system_config_dir: None, user_config_dir: None, env_vars: [], }
}

///|
/// Workspace root availability resolved once via `Inquiry::RealPath` before
/// running in-tree adapters and mount providers.
#derive(Eq, Debug)
pub(all) enum WorkspaceRoot {
  /// Folder exists and resolved to canonical `real`.
  Present(root~ : FolderPath, real~ : FolderPath)
  /// Folder does not exist on disk.
  Missing(root~ : FolderPath)
  /// Canonical resolution timed out or failed.
  Unavailable(root~ : FolderPath, reason~ : String)
}

///|
/// Validated target of a configured mount inside the pure core.
#derive(Eq, Debug)
pub(all) enum MountTarget {
  /// Workspace-confined relative path (required for `ProjectMount` and `LocalMount`).
  Relative(@app.TreePath)
  /// External host path (allowed only for `UserMount` and `SystemMount`).
  HostPath(FolderPath)
}

///|
/// The display target string projected to wire DTOs.
pub fn MountTarget::display(self : MountTarget) -> String {
  match self {
    Relative(tp) => tp.to_string()
    HostPath(fp) => fp.to_string()
  }
}

///|
/// Untrusted workspace-level mount trust tier (`ProjectMount` or `LocalMount`).
#derive(Eq, Debug)
pub(all) enum ConfinedTier {
  Project
  Local
}

///|
/// Converts a `ConfinedTier` to its wire `TrustTier`.
pub fn ConfinedTier::to_trust_tier(self : ConfinedTier) -> @app.TrustTier {
  match self {
    Project => ProjectMount
    Local => LocalMount
  }
}

///|
/// Trusted host-level mount trust tier (`UserMount` or `SystemMount`).
#derive(Eq, Debug)
pub(all) enum TrustedTier {
  User
  System
}

///|
/// Converts a `TrustedTier` to its wire `TrustTier`.
pub fn TrustedTier::to_trust_tier(self : TrustedTier) -> @app.TrustTier {
  match self {
    User => UserMount
    System => SystemMount
  }
}

///|
/// Validated trust, target, and access grant of a mount specification.
/// Illegal combinations (such as a `ProjectMount` or `LocalMount` with an
/// external `HostPath` or `ReadWrite` access) are unrepresentable by construction.
#derive(Eq, Debug)
pub(all) enum MountGrant {
  /// Workspace-confined mount: always relative (`TreePath`) and `ReadOnly`.
  Confined(tier~ : ConfinedTier, target~ : @app.TreePath)
  /// Trusted host mount: may use a relative or host path and either access mode.
  Trusted(
    tier~ : TrustedTier,
    target~ : MountTarget,
    access~ : @app.SourceAccess,
  )
}

///|
/// Returns the wire `TrustTier` of this mount grant.
pub fn MountGrant::trust(self : MountGrant) -> @app.TrustTier {
  match self {
    Confined(tier~, ..) => tier.to_trust_tier()
    Trusted(tier~, ..) => tier.to_trust_tier()
  }
}

///|
/// Returns the `MountTarget` of this mount grant.
pub fn MountGrant::target(self : MountGrant) -> MountTarget {
  match self {
    Confined(target~, ..) => Relative(target)
    Trusted(target~, ..) => target
  }
}

///|
/// Returns the effective `SourceAccess` of this mount grant.
pub fn MountGrant::access(self : MountGrant) -> @app.SourceAccess {
  match self {
    Confined(..) => ReadOnly
    Trusted(access~, ..) => access
  }
}

///|
/// Validated mount specification ready to be resolved by a `MountProvider`.
#derive(Eq, Debug)
pub(all) struct MountSpec {
  name : @app.SourceName
  kind : @app.MountKind
  role : @app.SourceRole
  grant : MountGrant
  origin : @app.ConfigOrigin
}

///|
/// The wire `TrustTier` of this mount specification.
pub fn MountSpec::trust(self : MountSpec) -> @app.TrustTier {
  self.grant.trust()
}

///|
/// The validated target of this mount specification.
pub fn MountSpec::target(self : MountSpec) -> MountTarget {
  self.grant.target()
}

///|
/// The effective access mode of this mount specification.
pub fn MountSpec::access(self : MountSpec) -> @app.SourceAccess {
  self.grant.access()
}

///|
/// Pure core in-tree source discovered inside a workspace root (no wire traits).
#derive(Eq, Debug)
pub(all) struct DomainInTreeSource {
  id : @app.SourceId
  name : @app.SourceName
  adapter : @app.AdapterId
  role : @app.SourceRole
  location : @app.InTreeLocation
  /// Lexical folder path inside the workspace root (never an escaped target).
  path : FolderPath
  access : @app.SourceAccess
  status : @app.InTreeStatus
}

///|
/// Projects a pure core in-tree source into its wire DTO.
pub fn DomainInTreeSource::to_wire(
  self : DomainInTreeSource,
) -> @app.InTreeSource {
  {
    id: self.id,
    name: self.name,
    adapter: self.adapter,
    role: self.role,
    location: self.location,
    path: self.path.to_string(),
    access: self.access,
    status: self.status,
  }
}

///|
/// Pure core resolved mount guaranteed to carry a resolved `FolderPath`.
#derive(Eq, Debug)
pub(all) struct DomainResolvedMount {
  id : @app.SourceId
  name : @app.SourceName
  kind : @app.MountKind
  role : @app.SourceRole
  target : MountTarget
  resolved_root : FolderPath
  access : @app.SourceAccess
  trust : @app.TrustTier
  origin : @app.ConfigOrigin
  status : @app.ResolvedMountStatus
}

///|
/// Projects a pure core resolved mount into its wire DTO.
pub fn DomainResolvedMount::to_wire(
  self : DomainResolvedMount,
) -> @app.ResolvedMount {
  {
    id: self.id,
    name: self.name,
    kind: self.kind,
    role: self.role,
    target: self.target.display(),
    resolved_path: self.resolved_root.to_string(),
    access: self.access,
    trust: self.trust,
    origin: self.origin,
    status: self.status,
  }
}

///|
/// Pure core refused mount carrying no resolved root path.
#derive(Eq, Debug)
pub(all) struct DomainRefusedMount {
  id : @app.SourceId
  name : @app.SourceName
  kind : @app.MountKind?
  role : @app.SourceRole?
  target : String?
  trust : @app.TrustTier
  origin : @app.ConfigOrigin
  reason : @app.MountRefusalReason
}

///|
/// Projects a pure core refused mount into its wire DTO.
pub fn DomainRefusedMount::to_wire(
  self : DomainRefusedMount,
) -> @app.RefusedMount {
  {
    id: self.id,
    name: self.name,
    kind: self.kind,
    role: self.role,
    target: self.target,
    trust: self.trust,
    origin: self.origin,
    reason: self.reason,
  }
}

///|
/// Pure core mounted source: either resolved to a `FolderPath` or refused.
#derive(Eq, Debug)
pub(all) enum DomainMountedSource {
  Resolved(DomainResolvedMount)
  Refused(DomainRefusedMount)
}

///|
/// Projects a pure core mounted source into its wire DTO.
pub fn DomainMountedSource::to_wire(
  self : DomainMountedSource,
) -> @app.MountedSource {
  match self {
    Resolved(mount) => Resolved(mount.to_wire())
    Refused(mount) => Refused(mount.to_wire())
  }
}

///|
/// Pure core composed workspace source.
#derive(Eq, Debug)
pub(all) enum DomainWorkspaceSource {
  InTree(DomainInTreeSource)
  Mounted(DomainMountedSource)
}

///|
/// Projects a pure core workspace source into its wire DTO.
pub fn DomainWorkspaceSource::to_wire(
  self : DomainWorkspaceSource,
) -> @app.WorkspaceSource {
  match self {
    InTree(source) => InTree(source.to_wire())
    Mounted(source) => Mounted(source.to_wire())
  }
}

///|
/// Outcome of static config validation for one mount entry prior to provider resolution.
#derive(Eq, Debug)
pub(all) enum EvaluatedMount {
  Accepted(MountSpec)
  Refused(DomainRefusedMount)
}

///|
/// Pure core composed source list and configuration problems for one workspace.
#derive(Eq, Debug)
pub(all) struct DomainWorkspaceSources {
  workspace : @app.WorkspaceId
  sources : ReadOnlyArray[DomainWorkspaceSource]
  problems : ReadOnlyArray[@app.SourceProblem]
}

///|
/// Projects pure core composed workspace sources into the wire DTO reply.
pub fn DomainWorkspaceSources::to_wire(
  self : DomainWorkspaceSources,
) -> @app.WorkspaceSources {
  {
    workspace: self.workspace,
    sources: ReadOnlyArray::from_array(
      self.sources.iter().map(s => s.to_wire()).collect(),
    ),
    problems: self.problems,
  }
}

///|
/// Open-closed extension point for discovering in-tree workspace sources.
pub(open) trait SourceAdapter {
  /// Stable open adapter identifier (`openspec`, `okf`, `dictionary`, etc.).
  fn id(Self) -> @app.AdapterId
  /// Discovers in-tree sources inside `workspace_root` whose canonical path is `real_root`.
  fn discover(Self, @app.WorkspaceId, FolderPath, FolderPath) -> Inquiry[
    ReadOnlyArray[DomainInTreeSource],
  ]
}

///|
/// Raised when constructing `SourceAdapters` with duplicate adapter IDs.
#derive(Eq, Debug)
pub(all) suberror DuplicateAdapter {
  DuplicateAdapter(@app.AdapterId)
}

///|
/// Ordered registry of in-tree source adapters with unique identifiers.
struct SourceAdapters {
  list : ReadOnlyArray[&SourceAdapter]
}

///|
/// Constructs a validated `SourceAdapters` registry rejecting duplicate IDs.
pub fn SourceAdapters::SourceAdapters(
  adapters : ArrayView[&SourceAdapter],
) -> SourceAdapters raise DuplicateAdapter {
  let seen : Array[@app.AdapterId] = []
  let items : Array[&SourceAdapter] = []
  for adapter in adapters {
    let adapter_id = adapter.id()
    if seen.contains(adapter_id) {
      raise DuplicateAdapter(adapter_id)
    }
    seen.push(adapter_id)
    items.push(adapter)
  }
  { list: ReadOnlyArray::from_array(items), }
}

///|
/// Returns the registered adapters in priority order.
pub fn SourceAdapters::all(
  self : SourceAdapters,
) -> ReadOnlyArray[&SourceAdapter] {
  self.list
}

///|
/// Open-closed extension point for resolving configured mounts.
pub(open) trait MountProvider {
  /// Stable open mount kind identifier (`folder`, etc.).
  fn kind(Self) -> @app.MountKind
  /// Resolves one validated `MountSpec` against `workspace_root`.
  fn resolve(Self, @app.WorkspaceId, WorkspaceRoot, MountSpec) -> Inquiry[
    DomainMountedSource,
  ]
}

///|
/// Raised when constructing `MountProviders` with duplicate mount kinds.
#derive(Eq, Debug)
pub(all) suberror DuplicateMountProvider {
  DuplicateMountProvider(@app.MountKind)
}

///|
/// Registry of mount providers with unique mount kinds.
struct MountProviders {
  list : ReadOnlyArray[&MountProvider]
}

///|
/// Constructs a validated `MountProviders` registry rejecting duplicate kinds.
pub fn MountProviders::MountProviders(
  providers : ArrayView[&MountProvider],
) -> MountProviders raise DuplicateMountProvider {
  let seen : Array[@app.MountKind] = []
  let items : Array[&MountProvider] = []
  for provider in providers {
    let kind = provider.kind()
    if seen.contains(kind) {
      raise DuplicateMountProvider(kind)
    }
    seen.push(kind)
    items.push(provider)
  }
  { list: ReadOnlyArray::from_array(items), }
}

///|
/// Looks up a registered provider by mount kind.
pub fn MountProviders::find(
  self : MountProviders,
  kind : @app.MountKind,
) -> &MountProvider? {
  self.list.iter().find_first(p => p.kind() == kind)
}

///|
fn source_name_of_slug(raw : String, fallback : String) -> @app.SourceName {
  let slug = slug_of(raw, fallback)
  @app.SourceName::SourceName(slug) catch {
    _ =>
      @app.SourceName::SourceName(fallback) catch {
        _ => abort("fallback source name is invalid: \{fallback}")
      }
  }
}

///|
fn check_in_tree_containment(
  target : FolderPath,
  real_root : FolderPath,
) -> Inquiry[@app.InTreeStatus] {
  RealPath(target, answer => {
    match answer {
      Resolved(real_target) =>
        if real_root.contains(real_target) {
          Done(Available)
        } else {
          Done(EscapesWorkspace)
        }
      Missing =>
        Done(Unavailable("source folder disappeared during inspection"))
      TimedOut => Done(Unavailable("resolving real path timed out"))
      Failed(reason) => Done(Unavailable(reason))
    }
  })
}

///|
/// Built-in source adapter discovering `openspec/` inside a workspace root.
pub struct OpenSpecSourceAdapter {}

///|
/// Constructs an `OpenSpecSourceAdapter`.
pub fn OpenSpecSourceAdapter::OpenSpecSourceAdapter() -> OpenSpecSourceAdapter {
  OpenSpecSourceAdapter::{ }
}

///|
pub impl SourceAdapter for OpenSpecSourceAdapter with fn id(_self) {
  @app.AdapterId::openspec()
}

///|
pub impl SourceAdapter for OpenSpecSourceAdapter with fn discover(
  self,
  workspace_id,
  workspace_root,
  real_root,
) {
  let tree_path = @app.TreePath::TreePath("openspec") catch {
    _ => abort("openspec is a valid TreePath")
  }
  let target = workspace_root.join_tree(tree_path)
  Look(target, looked => {
    match looked {
      Folder =>
        check_in_tree_containment(target, real_root).map(status => {
          let name = source_name_of_slug("openspec", "openspec")
          let location = @app.InTreeLocation::Subpath(tree_path)
          let id = source_id_in_tree(workspace_id, self.id(), name, location)
          [
            {
              id,
              name,
              adapter: self.id(),
              role: Intent,
              location,
              path: target,
              access: ReadWrite,
              status,
            },
          ]
        })
      File | Missing | TimedOut | Failed(_) => Done([])
    }
  })
}

///|
let max_okf_subdir_scan : Int32 = 64

///|
/// Built-in source adapter discovering OKF bundles (`index.md` at the workspace
/// root or inside up to 64 non-hidden top-level subdirectories).
pub struct OkfSourceAdapter {}

///|
/// Constructs an `OkfSourceAdapter`.
pub fn OkfSourceAdapter::OkfSourceAdapter() -> OkfSourceAdapter {
  OkfSourceAdapter::{ }
}

///|
pub impl SourceAdapter for OkfSourceAdapter with fn id(_self) {
  @app.AdapterId::okf()
}

///|
fn probe_okf_subdirs(
  adapter_id : @app.AdapterId,
  workspace_id : @app.WorkspaceId,
  workspace_root : FolderPath,
  real_root : FolderPath,
  names : Array[String],
  idx : Int32,
  acc : Array[DomainInTreeSource],
) -> Inquiry[ReadOnlyArray[DomainInTreeSource]] {
  if idx >= names.length() {
    return Done(ReadOnlyArray::from_array(acc))
  }
  let entry = names[idx]
  let maybe_tp : @app.TreePath? = Some(@app.TreePath::TreePath(entry)) catch {
    _ => None
  }
  match maybe_tp {
    None =>
      probe_okf_subdirs(
        adapter_id,
        workspace_id,
        workspace_root,
        real_root,
        names,
        idx + 1,
        acc,
      )
    Some(tp) => {
      let dir_path = workspace_root.join_tree(tp)
      let index_path = dir_path.join(["index.md"])
      Look(index_path, looked => {
        match looked {
          File =>
            check_in_tree_containment(dir_path, real_root).then(dir_status => {
              let final_status_step : Inquiry[@app.InTreeStatus] = match
                dir_status {
                Available => check_in_tree_containment(index_path, real_root)
                other => Done(other)
              }
              final_status_step.then(status => {
                let name = source_name_of_slug(entry, "kb")
                let location = @app.InTreeLocation::Subpath(tp)
                let id = source_id_in_tree(
                  workspace_id, adapter_id, name, location,
                )
                acc.push({
                  id,
                  name,
                  adapter: adapter_id,
                  role: KnowledgeBase,
                  location,
                  path: dir_path,
                  access: ReadWrite,
                  status,
                })
                probe_okf_subdirs(
                  adapter_id,
                  workspace_id,
                  workspace_root,
                  real_root,
                  names,
                  idx + 1,
                  acc,
                )
              })
            })
          Folder | Missing | TimedOut | Failed(_) =>
            probe_okf_subdirs(
              adapter_id,
              workspace_id,
              workspace_root,
              real_root,
              names,
              idx + 1,
              acc,
            )
        }
      })
    }
  }
}

///|
pub impl SourceAdapter for OkfSourceAdapter with fn discover(
  self,
  workspace_id,
  workspace_root,
  real_root,
) {
  let adapter_id = self.id()
  let root_index = workspace_root.join(["index.md"])
  Look(root_index, root_looked => {
    let initial : Inquiry[Array[DomainInTreeSource]] = match root_looked {
      File =>
        check_in_tree_containment(root_index, real_root).map(status => {
          let name = source_name_of_slug("kb-root", "kb")
          let location = @app.InTreeLocation::WorkspaceRoot
          let id = source_id_in_tree(workspace_id, adapter_id, name, location)
          [
            {
              id,
              name,
              adapter: adapter_id,
              role: KnowledgeBase,
              location,
              path: workspace_root,
              access: ReadWrite,
              status,
            },
          ]
        })
      Folder | Missing | TimedOut | Failed(_) => Done([])
    }
    initial.then(found => {
      Names(workspace_root, listing => {
        match listing {
          Entries(raw_entries) => {
            let filtered : Array[String] = []
            for entry in raw_entries {
              if !entry.has_prefix(".") && entry != "openspec" {
                filtered.push(entry)
              }
            }
            filtered.sort()
            let candidates : Array[String] = []
            for entry in filtered {
              if candidates.length() < max_okf_subdir_scan {
                candidates.push(entry)
              }
            }
            probe_okf_subdirs(
              adapter_id, workspace_id, workspace_root, real_root, candidates, 0,
              found,
            )
          }
          Missing | Failed(_) => Done(ReadOnlyArray::from_array(found))
        }
      })
    })
  })
}

///|
/// Built-in source adapter discovering `.mission-control/dictionary` inside a
/// workspace root.
pub struct DictionarySourceAdapter {}

///|
/// Constructs a `DictionarySourceAdapter`.
pub fn DictionarySourceAdapter::DictionarySourceAdapter() -> DictionarySourceAdapter {
  DictionarySourceAdapter::{ }
}

///|
pub impl SourceAdapter for DictionarySourceAdapter with fn id(_self) {
  @app.AdapterId::dictionary()
}

///|
pub impl SourceAdapter for DictionarySourceAdapter with fn discover(
  self,
  workspace_id,
  workspace_root,
  real_root,
) {
  let tree_path = @app.TreePath::TreePath(".mission-control/dictionary") catch {
    _ => abort(".mission-control/dictionary is a valid TreePath")
  }
  let target = workspace_root.join_tree(tree_path)
  Look(target, looked => {
    match looked {
      Folder =>
        check_in_tree_containment(target, real_root).map(status => {
          let name = source_name_of_slug("dictionary", "dictionary")
          let location = @app.InTreeLocation::Subpath(tree_path)
          let id = source_id_in_tree(workspace_id, self.id(), name, location)
          [
            {
              id,
              name,
              adapter: self.id(),
              role: Dictionary,
              location,
              path: target,
              access: ReadWrite,
              status,
            },
          ]
        })
      File | Missing | TimedOut | Failed(_) => Done([])
    }
  })
}

///|
/// Built-in mount provider for `kind = "folder"` local directory mounts.
pub struct LocalFolderMountProvider {}

///|
/// Constructs a `LocalFolderMountProvider`.
pub fn LocalFolderMountProvider::LocalFolderMountProvider() -> LocalFolderMountProvider {
  LocalFolderMountProvider::{ }
}

///|
pub impl MountProvider for LocalFolderMountProvider with fn kind(_self) {
  @app.MountKind::folder()
}

///|
fn probe_folder_mount(
  id : @app.SourceId,
  spec : MountSpec,
  target_path : FolderPath,
) -> Inquiry[DomainMountedSource] {
  Look(target_path, looked => {
    let status : @app.ResolvedMountStatus = match looked {
      Folder => Available
      Missing => Missing
      File => Unavailable("mount target is a file, not a folder")
      TimedOut => Unavailable("probing mount target timed out")
      Failed(reason) => Unavailable(reason)
    }
    Done(
      Resolved({
        id,
        name: spec.name,
        kind: spec.kind,
        role: spec.role,
        target: spec.target(),
        resolved_root: target_path,
        access: spec.access(),
        trust: spec.trust(),
        origin: spec.origin,
        status,
      }),
    )
  })
}

///|
pub impl MountProvider for LocalFolderMountProvider with fn resolve(
  _self,
  workspace_id,
  workspace_root,
  spec,
) {
  let trust = spec.trust()
  let id = source_id_mounted(workspace_id, trust, Some(spec.kind), spec.name)
  match spec.grant {
    Trusted(target=HostPath(host_path), ..) =>
      probe_folder_mount(id, spec, host_path)
    Trusted(target=Relative(tree_path), ..) =>
      match workspace_root {
        Missing(root~) =>
          Done(
            Resolved({
              id,
              name: spec.name,
              kind: spec.kind,
              role: spec.role,
              target: spec.target(),
              resolved_root: root.join_tree(tree_path),
              access: spec.access(),
              trust,
              origin: spec.origin,
              status: Missing,
            }),
          )
        Unavailable(root~, reason~) =>
          Done(
            Resolved({
              id,
              name: spec.name,
              kind: spec.kind,
              role: spec.role,
              target: spec.target(),
              resolved_root: root.join_tree(tree_path),
              access: spec.access(),
              trust,
              origin: spec.origin,
              status: Unavailable(reason),
            }),
          )
        Present(root~, ..) =>
          probe_folder_mount(id, spec, root.join_tree(tree_path))
      }
    Confined(target=tree_path, ..) =>
      match workspace_root {
        Missing(root~) =>
          Done(
            Resolved({
              id,
              name: spec.name,
              kind: spec.kind,
              role: spec.role,
              target: Relative(tree_path),
              resolved_root: root.join_tree(tree_path),
              access: ReadOnly,
              trust,
              origin: spec.origin,
              status: Missing,
            }),
          )
        Unavailable(root~, reason~) =>
          Done(
            Resolved({
              id,
              name: spec.name,
              kind: spec.kind,
              role: spec.role,
              target: Relative(tree_path),
              resolved_root: root.join_tree(tree_path),
              access: ReadOnly,
              trust,
              origin: spec.origin,
              status: Unavailable(reason),
            }),
          )
        Present(root~, real~) => {
          let lexical = root.join_tree(tree_path)
          // Resolve RealPath BEFORE Look so symlinks to external files (e.g.
          // `/etc/passwd`) are refused as EscapesWorkspace without leaking a
          // file-vs-folder oracle on host paths.
          RealPath(lexical, rp => {
            match rp {
              Missing =>
                Done(
                  Resolved({
                    id,
                    name: spec.name,
                    kind: spec.kind,
                    role: spec.role,
                    target: Relative(tree_path),
                    resolved_root: lexical,
                    access: ReadOnly,
                    trust,
                    origin: spec.origin,
                    status: Missing,
                  }),
                )
              TimedOut =>
                Done(
                  Resolved({
                    id,
                    name: spec.name,
                    kind: spec.kind,
                    role: spec.role,
                    target: Relative(tree_path),
                    resolved_root: lexical,
                    access: ReadOnly,
                    trust,
                    origin: spec.origin,
                    status: Unavailable("resolving mount real path timed out"),
                  }),
                )
              Failed(reason) =>
                Done(
                  Resolved({
                    id,
                    name: spec.name,
                    kind: spec.kind,
                    role: spec.role,
                    target: Relative(tree_path),
                    resolved_root: lexical,
                    access: ReadOnly,
                    trust,
                    origin: spec.origin,
                    status: Unavailable(reason),
                  }),
                )
              Resolved(real_target) =>
                if !real.contains(real_target) {
                  Done(
                    Refused({
                      id,
                      name: spec.name,
                      kind: Some(spec.kind),
                      role: Some(spec.role),
                      target: Some(tree_path.to_string()),
                      trust,
                      origin: spec.origin,
                      reason: EscapesWorkspace,
                    }),
                  )
                } else {
                  probe_folder_mount(id, spec, real_target)
                }
            }
          })
        }
      }
  }
}

///|
/// Default built-in in-tree source adapters (`openspec`, `okf`, `dictionary`).
pub fn default_source_adapters() -> SourceAdapters {
  SourceAdapters::SourceAdapters([
    OpenSpecSourceAdapter::OpenSpecSourceAdapter() as &SourceAdapter,
    OkfSourceAdapter::OkfSourceAdapter() as &SourceAdapter,
    DictionarySourceAdapter::DictionarySourceAdapter() as &SourceAdapter,
  ]) catch {
    _ => abort("built-in source adapter IDs are unique")
  }
}

///|
/// Default built-in mount providers (`folder`).
pub fn default_mount_providers() -> MountProviders {
  MountProviders::MountProviders([
    LocalFolderMountProvider::LocalFolderMountProvider() as &MountProvider,
  ]) catch {
    _ => abort("built-in mount provider kinds are unique")
  }
}

///|
fn run_adapters(
  adapters : ReadOnlyArray[&SourceAdapter],
  idx : Int32,
  workspace_id : @app.WorkspaceId,
  root : FolderPath,
  real : FolderPath,
  acc : Array[DomainWorkspaceSource],
) -> Inquiry[Array[DomainWorkspaceSource]] {
  if idx >= adapters.length() {
    return Done(acc)
  }
  adapters[idx]
  .discover(workspace_id, root, real)
  .then(found => {
    for item in found {
      acc.push(InTree(item))
    }
    run_adapters(adapters, idx + 1, workspace_id, root, real, acc)
  })
}

///|
fn run_mounts(
  mounts : ReadOnlyArray[EvaluatedMount],
  idx : Int32,
  workspace_id : @app.WorkspaceId,
  workspace_root : WorkspaceRoot,
  providers : MountProviders,
  acc : Array[DomainWorkspaceSource],
) -> Inquiry[Array[DomainWorkspaceSource]] {
  if idx >= mounts.length() {
    return Done(acc)
  }
  match mounts[idx] {
    Refused(refused) => {
      acc.push(Mounted(Refused(refused)))
      run_mounts(mounts, idx + 1, workspace_id, workspace_root, providers, acc)
    }
    Accepted(spec) =>
      match providers.find(spec.kind) {
        None => {
          let trust = spec.trust()
          let id = source_id_mounted(
            workspace_id,
            trust,
            Some(spec.kind),
            spec.name,
          )
          acc.push(
            Mounted(
              Refused({
                id,
                name: spec.name,
                kind: Some(spec.kind),
                role: Some(spec.role),
                target: Some(spec.target().display()),
                trust,
                origin: spec.origin,
                reason: UnknownMountKind(spec.kind),
              }),
            ),
          )
          run_mounts(
            mounts,
            idx + 1,
            workspace_id,
            workspace_root,
            providers,
            acc,
          )
        }
        Some(provider) =>
          provider
          .resolve(workspace_id, workspace_root, spec)
          .then(resolved => {
            acc.push(Mounted(resolved))
            run_mounts(
              mounts,
              idx + 1,
              workspace_id,
              workspace_root,
              providers,
              acc,
            )
          })
      }
  }
}

///|
/// Probes `workspace_root` once via `Inquiry::RealPath` and composes all
/// in-tree sources and evaluated mounts into one `DomainWorkspaceSources`.
pub fn compose_workspace_sources(
  workspace_id : @app.WorkspaceId,
  workspace_root : FolderPath,
  adapters : SourceAdapters,
  providers : MountProviders,
  mounts : ReadOnlyArray[EvaluatedMount],
  problems : ReadOnlyArray[@app.SourceProblem],
) -> Inquiry[DomainWorkspaceSources] {
  RealPath(workspace_root, rp => {
    let root_state : WorkspaceRoot = match rp {
      Resolved(real) => Present(root=workspace_root, real~)
      Missing => Missing(root=workspace_root)
      TimedOut =>
        Unavailable(
          root=workspace_root,
          reason="resolving workspace real path timed out",
        )
      Failed(reason) => Unavailable(root=workspace_root, reason~)
    }
    let in_tree : Inquiry[Array[DomainWorkspaceSource]] = match root_state {
      Present(root~, real~) =>
        run_adapters(adapters.all(), 0, workspace_id, root, real, [])
      Missing(_) | Unavailable(_) => Done([])
    }
    in_tree.then(acc => {
      run_mounts(mounts, 0, workspace_id, root_state, providers, acc).map(all => {
        workspace: workspace_id,
        sources: ReadOnlyArray::from_array(all),
        problems,
      })
    })
  })
}

///|
pub extend HostEnv with Eq::{not_equal, equal}

///|
pub extend HostEnv with @debug.Debug::{to_repr}

///|
pub extend WorkspaceRoot with Eq::{not_equal, equal}

///|
pub extend WorkspaceRoot with @debug.Debug::{to_repr}

///|
pub extend MountTarget with Eq::{not_equal, equal}

///|
pub extend MountTarget with @debug.Debug::{to_repr}

///|
pub extend ConfinedTier with Eq::{not_equal, equal}

///|
pub extend ConfinedTier with @debug.Debug::{to_repr}

///|
pub extend TrustedTier with Eq::{not_equal, equal}

///|
pub extend TrustedTier with @debug.Debug::{to_repr}

///|
pub extend MountGrant with Eq::{not_equal, equal}

///|
pub extend MountGrant with @debug.Debug::{to_repr}

///|
pub extend MountSpec with Eq::{not_equal, equal}

///|
pub extend MountSpec with @debug.Debug::{to_repr}

///|
pub extend DomainInTreeSource with Eq::{not_equal, equal}

///|
pub extend DomainInTreeSource with @debug.Debug::{to_repr}

///|
pub extend DomainResolvedMount with Eq::{not_equal, equal}

///|
pub extend DomainResolvedMount with @debug.Debug::{to_repr}

///|
pub extend DomainRefusedMount with Eq::{not_equal, equal}

///|
pub extend DomainRefusedMount with @debug.Debug::{to_repr}

///|
pub extend DomainMountedSource with Eq::{not_equal, equal}

///|
pub extend DomainMountedSource with @debug.Debug::{to_repr}

///|
pub extend DomainWorkspaceSource with Eq::{not_equal, equal}

///|
pub extend DomainWorkspaceSource with @debug.Debug::{to_repr}

///|
pub extend EvaluatedMount with Eq::{not_equal, equal}

///|
pub extend EvaluatedMount with @debug.Debug::{to_repr}

///|
pub extend DomainWorkspaceSources with Eq::{not_equal, equal}

///|
pub extend DomainWorkspaceSources with @debug.Debug::{to_repr}

///|
pub extend DuplicateAdapter with Eq::{not_equal, equal}

///|
pub extend DuplicateAdapter with @debug.Debug::{to_repr}

///|
pub extend DuplicateMountProvider with Eq::{not_equal, equal}

///|
pub extend DuplicateMountProvider with @debug.Debug::{to_repr}

///|
pub extend OpenSpecSourceAdapter with SourceAdapter::{id, discover}

///|
pub extend OkfSourceAdapter with SourceAdapter::{id, discover}

///|
pub extend DictionarySourceAdapter with SourceAdapter::{id, discover}

///|
pub extend LocalFolderMountProvider with MountProvider::{kind, resolve}