///|
/// Maps a `moon-lander-config` file role to a workspace mount `TrustTier`.
/// Every file discovered from a workspace root (including `UserOverride`, which
/// a cloned repository can commit) maps to an untrusted tier.
pub fn trust_tier_of_file_role(role : @config.FileRole) -> @app.TrustTier {
  match role {
    System => SystemMount
    Global | Explicit => UserMount
    Workspace | Member | Legacy | EnvironmentFile | ProfileFile(_) =>
      ProjectMount
    LocalOverride | UserOverride => LocalMount
  }
}

///|
/// Reports whether a dotted configuration key path belongs to `workspace.mounts`.
pub fn is_workspace_mount_key(key : String) -> Bool {
  key == "workspace.mounts" || key.has_prefix("workspace.mounts.")
}

///|
/// Human-readable summary of a `MountRefusalReason` for CLI and `config show`.
pub fn mount_refusal_summary(reason : @app.MountRefusalReason) -> String {
  reason.summary()
}

///|
/// A warning or validation error attached to a `workspace.mounts` key and file.
#derive(Eq, Debug)
pub(all) struct MountConfigDiagnostic {
  key : String
  origin : @app.ConfigOrigin
  message : String
}

///|
/// Result of loading `workspace.mounts` across isolated trust layers.
#derive(Eq, Debug)
pub(all) struct MountConfigResult {
  mounts : ReadOnlyArray[EvaluatedMount]
  problems : ReadOnlyArray[@app.SourceProblem]
  warnings : ReadOnlyArray[MountConfigDiagnostic]
  errors : ReadOnlyArray[MountConfigDiagnostic]
}

///|
let mount_app_name : String = "mission-control"

///|
let mount_format_layers : @conventions.FormatLayers = try {
  let yaml = @conventions.Extension::parse("yaml")
  let yml = @conventions.Extension::parse("yml")
  let toml = @conventions.Extension::parse("toml")
  @conventions.FormatLayers::new([
    @conventions.FormatGroup::new([yaml, yml]),
    @conventions.FormatGroup::new([toml]),
  ])
} catch {
  _ => abort("invalid built-in mount config format layers")
}

///|
fn config_platform_of(platform : Platform) -> @config.Platform {
  match platform {
    Linux => Linux
    MacOs => MacOs
    Windows => Windows
  }
}

///|
fn mount_formats() -> Array[@config.Format] {
  [@config_toml.format(), @config_yaml.format()]
}

///|
fn host_env_map(host_env : HostEnv) -> Map[String, String] {
  let map : Map[String, String] = Map([])
  for pair in host_env.env_vars {
    let key = match host_env.platform {
      Windows => pair.0.to_upper()
      Linux | MacOs => pair.0
    }
    map[key] = pair.1
  }
  map
}

///|
fn base_mount_builder(
  host_env : HostEnv,
  working_dir : FolderPath?,
) -> @config.ConfigBuilder {
  // Never call `@config.env(...)`: workspace.mounts is file-only so
  // `MISSION_CONTROL__WORKSPACE__MOUNTS__*` environment variables are ignored.
  let builder = @config.builder()
    |> @config.format(@config_toml.format())
    |> @config.format(@config_yaml.format())
    |> @config.env_vars(host_env_map(host_env))
    |> @config.platform(config_platform_of(host_env.platform))
  match working_dir {
    Some(dir) => builder |> @config.working_dir(dir.to_string())
    None => builder
  }
}

///|
fn explicit_dir_builder(
  host_env : HostEnv,
  dir : FolderPath,
  role : @config.FileRole,
  display : String,
) -> @config.ConfigBuilder {
  let yaml = dir.join(["\{mount_app_name}.yaml"]).to_string()
  let yml = dir.join(["\{mount_app_name}.yml"]).to_string()
  let toml = dir.join(["\{mount_app_name}.toml"]).to_string()
  base_mount_builder(host_env, None)
  |> @config.add(
    @config.ConfigSource::candidates(
      [yaml, yml],
      display~,
      role~,
      name="\{display}-yaml",
      priority=100,
    ),
  )
  |> @config.add(
    @config.ConfigSource::candidates(
      [toml],
      display~,
      role~,
      name="\{display}-toml",
      priority=110,
    ),
  )
}

///|
fn system_mount_builder(host_env : HostEnv) -> @config.ConfigBuilder {
  match host_env.system_config_dir {
    Some(dir) => explicit_dir_builder(host_env, dir, System, "system")
    None =>
      base_mount_builder(host_env, None)
      |> @conventions.add(
        @conventions.base(mount_app_name)
        |> @conventions.system_dir
        |> @conventions.format_layers(mount_format_layers),
      )
  }
}

///|
fn user_mount_builder(host_env : HostEnv) -> @config.ConfigBuilder {
  match host_env.user_config_dir {
    Some(dir) => explicit_dir_builder(host_env, dir, Global, "user")
    None =>
      base_mount_builder(host_env, None)
      |> @conventions.add(
        @conventions.base(mount_app_name)
        |> @conventions.user_config_dir
        |> @conventions.app_home
        |> @conventions.format_layers(mount_format_layers),
      )
  }
}

///|
fn workspace_mount_builder(
  host_env : HostEnv,
  workspace_root : FolderPath,
) -> @config.ConfigBuilder {
  base_mount_builder(host_env, Some(workspace_root))
  |> @conventions.add(
    @conventions.app_dirs(mount_app_name)
    |> @conventions.without(SystemDir)
    |> @conventions.without(UserConfigDir)
    |> @conventions.without(AppHome)
    |> @conventions.format_layers(mount_format_layers),
  )
}

///|
fn display_origin_of(
  raw_path : String,
  platform : Platform,
) -> @app.ConfigOrigin {
  let cfg_platform = config_platform_of(platform)
  let shown = match platform {
    Windows =>
      @config.FileTreePath::parse(raw_path).to_native(cfg_platform) catch {
        _ => raw_path
      }
    Linux | MacOs => raw_path
  }
  @app.ConfigOrigin::ConfigOrigin(shown) catch {
    _ =>
      @app.ConfigOrigin::ConfigOrigin("config") catch {
        _ => abort("config is a valid ConfigOrigin")
      }
  }
}

///|
fn folder_path_of_tree_path(
  ftp : @config.FileTreePath,
  platform : Platform,
) -> FolderPath? {
  let native = ftp.to_native(config_platform_of(platform))
  Some(FolderPath::FolderPath(native, platform)) catch {
    _ => None
  }
}

///|
fn strip_bom(text : String) -> String {
  match text {
    ['\u{feff}', .. rest] => rest.to_owned()
    _ => text
  }
}

///|
fn parse_error_origin(err : @config.ConfigError, fallback : String) -> String {
  match err {
    Parse(origin~, ..)
    | UnsupportedYaml(origin~, ..)
    | InvalidRoot(origin~, ..)
    | DuplicateKey(origin~, ..) => origin
    Ambiguous(location~, ..) => location
    FileNotFound(path~) | UnsupportedFormat(path~, ..) => path
    _ => fallback
  }
}

///|
priv struct PassLoadOutput {
  reports : Array[@config.SourceReport]
  raw_files : Map[String, String]
}

///|
fn fulfill_file_requests(
  requests : Array[@config.FileRequest],
  idx : Int32,
  platform : Platform,
  tree : @config.FileTree,
  raw_files : Map[String, String],
  problems : Array[@app.SourceProblem],
  reported_io : Map[String, Bool],
) -> Inquiry[@config.FileTree] {
  if idx >= requests.length() {
    return Done(tree)
  }
  match requests[idx] {
    ReadFile(ftp) => {
      let key = ftp.to_string()
      match folder_path_of_tree_path(ftp, platform) {
        None =>
          fulfill_file_requests(
            requests,
            idx + 1,
            platform,
            tree.with_missing(ftp),
            raw_files,
            problems,
            reported_io,
          )
        Some(fp) =>
          ReadFile(fp, answer => {
            let next_tree = match answer {
              Found(text) => {
                let clean = strip_bom(text)
                raw_files[key] = clean
                tree.with_file(ftp, clean)
              }
              Missing => tree.with_missing(ftp)
              TooLarge => {
                if !reported_io.contains(key) {
                  reported_io[key] = true
                  problems.push(
                    @app.SourceProblem::ConfigTooLarge(
                      origin=display_origin_of(key, platform),
                    ),
                  )
                }
                tree.with_missing(ftp)
              }
              TimedOut => {
                if !reported_io.contains(key) {
                  reported_io[key] = true
                  problems.push(
                    @app.SourceProblem::ConfigReadFailed(
                      origin=display_origin_of(key, platform),
                      reason="reading configuration file timed out",
                    ),
                  )
                }
                tree.with_missing(ftp)
              }
              Failed(reason) => {
                if !reported_io.contains(key) {
                  reported_io[key] = true
                  problems.push(
                    @app.SourceProblem::ConfigReadFailed(
                      origin=display_origin_of(key, platform),
                      reason~,
                    ),
                  )
                }
                tree.with_missing(ftp)
              }
            }
            fulfill_file_requests(
              requests,
              idx + 1,
              platform,
              next_tree,
              raw_files,
              problems,
              reported_io,
            )
          })
      }
    }
    ListDir(ftp) =>
      match folder_path_of_tree_path(ftp, platform) {
        None =>
          fulfill_file_requests(
            requests,
            idx + 1,
            platform,
            tree.with_missing(ftp),
            raw_files,
            problems,
            reported_io,
          )
        Some(fp) =>
          Names(fp, listing => {
            let next_tree = match listing {
              Entries(names) => {
                let entries : Array[@config.DirEntry] = []
                for name in names {
                  entries.push({ name, kind: File, })
                }
                tree.with_listing(ftp, entries)
              }
              Missing | Failed(_) => tree.with_missing(ftp)
            }
            fulfill_file_requests(
              requests,
              idx + 1,
              platform,
              next_tree,
              raw_files,
              problems,
              reported_io,
            )
          })
      }
  }
}

///|
fn drive_config_pass(
  builder : @config.ConfigBuilder,
  pass_label : String,
  platform : Platform,
  tree : @config.FileTree,
  raw_files : Map[String, String],
  problems : Array[@app.SourceProblem],
  reported_io : Map[String, Bool],
  retries_left : Int32,
) -> Inquiry[PassLoadOutput] {
  let step : Result[@config.LoadStep[@config.Config], @config.ConfigError] = Ok(
    @config.load(builder, tree),
  ) catch {
    err => Err(err)
  }
  match step {
    Ok(Done(cfg)) => Done({ reports: cfg.reports(), raw_files, })
    Ok(Need(requests)) =>
      fulfill_file_requests(
        requests, 0, platform, tree, raw_files, problems, reported_io,
      ).then(next_tree => {
        drive_config_pass(
          builder, pass_label, platform, next_tree, raw_files, problems, reported_io,
          retries_left,
        )
      })
    Err(err) => {
      let origin_raw = parse_error_origin(err, pass_label)
      problems.push(
        @app.SourceProblem::ConfigParseFailed(
          origin=display_origin_of(origin_raw, platform),
          reason=err.message(),
        ),
      )
      // If a specific file failed to parse, mark it missing and retry so
      // sibling files in the same pass can still load cleanly.
      if retries_left > 0 && raw_files.contains(origin_raw) {
        let parsed_ftp : @config.FileTreePath? = Some(
          @config.FileTreePath::parse(origin_raw),
        ) catch {
          _ => None
        }
        match parsed_ftp {
          Some(ftp) =>
            drive_config_pass(
              builder,
              pass_label,
              platform,
              tree.with_missing(ftp),
              raw_files,
              problems,
              reported_io,
              retries_left - 1,
            )
          None => Done({ reports: [], raw_files, })
        }
      } else {
        Done({ reports: [], raw_files, })
      }
    }
  }
}

///|
fn source_name_rule_message(rule : @app.SourceNameRule) -> String {
  match rule {
    Empty => "must not be empty"
    TooLong => "must have at most 64 characters"
    InvalidStart => "must start with a lower-case letter or digit"
    InvalidChar => "must use only lower-case letters, digits, '.', '_' or '-'"
  }
}

///|
fn open_id_rule_message(rule : @app.OpenIdRule) -> String {
  match rule {
    Length => "must have 1 to 64 characters"
    FirstCharacter => "must start with a lower-case letter or digit"
    Characters => "must use only lower-case letters, digits or '-'"
  }
}

///|
fn upsert_mount(
  entries : Array[(@app.SourceName, EvaluatedMount)],
  name : @app.SourceName,
  mount : EvaluatedMount,
) -> Unit {
  for i in 0.. Bool {
  for pair in entries {
    if pair.0 == name {
      return true
    }
  }
  false
}

///|
fn single_file_mounts_json(
  raw_path : String,
  text : String,
  role : @config.FileRole,
) -> Json? raise @config.ConfigError {
  let value = @config.parse_file(mount_formats(), raw_path, text)
  let cfg = @config.build([
    @config.ConfigSource::parsed_file(raw_path, value, role~),
  ])
  let wrapped : Json? = Some(@config.get_json(cfg, "workspace.mounts")) catch {
    KeyNotFound(..) => None
    err => raise err
  }
  match wrapped {
    Some(Object(fields)) => fields.get("value")
    other => other
  }
}

///|
fn refused_mount(
  workspace_id : @app.WorkspaceId,
  name~ : @app.SourceName,
  kind~ : @app.MountKind?,
  role~ : @app.SourceRole?,
  target~ : String?,
  trust~ : @app.TrustTier,
  origin~ : @app.ConfigOrigin,
  reason~ : @app.MountRefusalReason,
) -> EvaluatedMount {
  Refused({
    id: source_id_mounted(workspace_id, trust, kind, name),
    name,
    kind,
    role,
    target,
    trust,
    origin,
    reason,
  })
}

///|
fn extract_file_mounts(
  workspace_id : @app.WorkspaceId,
  raw_path : String,
  text : String,
  role : @config.FileRole,
  platform : Platform,
  dest : Array[(@app.SourceName, EvaluatedMount)],
  problems : Array[@app.SourceProblem],
  warnings : Array[MountConfigDiagnostic],
  errors : Array[MountConfigDiagnostic],
) -> Unit {
  let origin = display_origin_of(raw_path, platform)
  let tier = trust_tier_of_file_role(role)
  let maybe_json : Result[Json?, @config.ConfigError] = Ok(
    single_file_mounts_json(raw_path, text, role),
  ) catch {
    err => Err(err)
  }
  let mounts_json = match maybe_json {
    Ok(None) => return
    Ok(Some(json)) => json
    Err(err) => {
      problems.push(
        @app.SourceProblem::ConfigParseFailed(origin~, reason=err.message()),
      )
      return
    }
  }
  guard mounts_json is Object(mount_entries) else {
    let msg = "`workspace.mounts` must be a table of named mounts."
    problems.push(@app.SourceProblem::ConfigParseFailed(origin~, reason=msg))
    errors.push({ key: "workspace.mounts", origin, message: msg, })
    return
  }
  let keys : Array[String] = mount_entries.keys().collect()
  keys.sort()
  for raw_name in keys {
    guard mount_entries.get(raw_name) is Some(entry_json) else { continue }
    let validated_name : Result[@app.SourceName, @app.SourceNameError] = Ok(
      @app.SourceName::SourceName(raw_name),
    ) catch {
      err => Err(err)
    }
    let name = match validated_name {
      Ok(n) => n
      Err(InvalidSourceName(rule~, ..)) => {
        problems.push(
          @app.SourceProblem::InvalidMountName(origin~, name=raw_name, rule~),
        )
        errors.push({
          key: "workspace.mounts.\{raw_name}",
          origin,
          message: "`workspace.mounts.\{raw_name}` is not a valid mount name: \{source_name_rule_message(rule)}.",
        })
        continue
      }
    }
    let prefix = "workspace.mounts.\{name}"
    guard entry_json is Object(fields) else {
      let msg = "`\{prefix}` must be a table with `kind`, `role`, and `path`."
      errors.push({ key: prefix, origin, message: msg, })
      upsert_mount(
        dest,
        name,
        refused_mount(
          workspace_id,
          name~,
          kind=None,
          role=None,
          target=None,
          trust=tier,
          origin~,
          reason=InvalidEntry(msg),
        ),
      )
      continue
    }
    // Check unknown keys first (warn and continue per spec).
    let field_keys : Array[String] = fields.keys().collect()
    field_keys.sort()
    for fk in field_keys {
      if fk != "kind" && fk != "role" && fk != "path" && fk != "access" {
        let key = "\{prefix}.\{fk}"
        warnings.push({
          key,
          origin,
          message: "`\{key}` is not a mount setting.",
        })
      }
    }
    let entry_errors : Array[(String, String)] = []
    // Parse `kind` (required)
    let parsed_kind : @app.MountKind? = match fields.get("kind") {
      None => {
        entry_errors.push(("\{prefix}.kind", "`\{prefix}.kind` is required."))
        None
      }
      Some(String(s)) => {
        let res : Result[@app.MountKind, @app.MountKindError] = Ok(
          @app.MountKind::MountKind(s),
        ) catch {
          err => Err(err)
        }
        match res {
          Ok(k) => Some(k)
          Err(InvalidMountKind(rule~, ..)) => {
            entry_errors.push(
              (
                "\{prefix}.kind",
                "`\{prefix}.kind` has an invalid mount kind '\{s}': \{open_id_rule_message(rule)}.",
              ),
            )
            None
          }
        }
      }
      Some(_) => {
        entry_errors.push(
          ("\{prefix}.kind", "`\{prefix}.kind` must be a string."),
        )
        None
      }
    }
    // Parse `role` (required)
    let parsed_role : @app.SourceRole? = match fields.get("role") {
      None => {
        entry_errors.push(("\{prefix}.role", "`\{prefix}.role` is required."))
        None
      }
      Some(String(s)) =>
        match @app.SourceRole::of_wire_name(s) {
          Some(r) => Some(r)
          None => {
            entry_errors.push(
              (
                "\{prefix}.role",
                "`\{prefix}.role` must be intent, knowledge-base, dictionary or policy.",
              ),
            )
            None
          }
        }
      Some(_) => {
        entry_errors.push(
          (
            "\{prefix}.role",
            "`\{prefix}.role` must be intent, knowledge-base, dictionary or policy.",
          ),
        )
        None
      }
    }
    // Parse `path` (required)
    let parsed_path : String? = match fields.get("path") {
      None => {
        entry_errors.push(("\{prefix}.path", "`\{prefix}.path` is required."))
        None
      }
      Some(String(s)) => Some(s)
      Some(_) => {
        entry_errors.push(
          ("\{prefix}.path", "`\{prefix}.path` must be a string."),
        )
        None
      }
    }
    // Parse `access` (optional, default read-only)
    let parsed_access : @app.SourceAccess? = match fields.get("access") {
      None => Some(ReadOnly)
      Some(String(s)) =>
        match @app.SourceAccess::of_wire_name(s) {
          Some(a) => Some(a)
          None => {
            entry_errors.push(
              (
                "\{prefix}.access",
                "`\{prefix}.access` must be read-only or read-write.",
              ),
            )
            None
          }
        }
      Some(_) => {
        entry_errors.push(
          (
            "\{prefix}.access",
            "`\{prefix}.access` must be read-only or read-write.",
          ),
        )
        None
      }
    }
    if !entry_errors.is_empty() {
      for pair in entry_errors {
        errors.push({ key: pair.0, origin, message: pair.1, })
      }
      upsert_mount(
        dest,
        name,
        refused_mount(
          workspace_id,
          name~,
          kind=parsed_kind,
          role=parsed_role,
          target=parsed_path,
          trust=tier,
          origin~,
          reason=InvalidEntry(entry_errors[0].1),
        ),
      )
      continue
    }
    guard (parsed_kind, parsed_role, parsed_path, parsed_access)
      is (Some(kind), Some(mount_role), Some(raw_path), Some(access)) else {
      continue
    }
    // Enforce trust-tier rules on valid entry fields.
    let evaluated : EvaluatedMount = match tier {
      ProjectMount | LocalMount => {
        let confined_tier : ConfinedTier = match tier {
          ProjectMount => Project
          LocalMount | UserMount | SystemMount => Local
        }
        let tp_res : Result[@app.TreePath, @app.TreePathError] = Ok(
          @app.TreePath::TreePath(raw_path),
        ) catch {
          err => Err(err)
        }
        match tp_res {
          Err(err) =>
            refused_mount(
              workspace_id,
              name~,
              kind=Some(kind),
              role=Some(mount_role),
              target=Some(raw_path),
              trust=tier,
              origin~,
              reason=InvalidPath(err),
            )
          Ok(tp) =>
            if access == ReadWrite {
              refused_mount(
                workspace_id,
                name~,
                kind=Some(kind),
                role=Some(mount_role),
                target=Some(raw_path),
                trust=tier,
                origin~,
                reason=WriteAccessNotAllowed,
              )
            } else {
              Accepted({
                name,
                kind,
                role: mount_role,
                grant: Confined(tier=confined_tier, target=tp),
                origin,
              })
            }
        }
      }
      UserMount | SystemMount => {
        let trusted_tier : TrustedTier = match tier {
          SystemMount => System
          UserMount | ProjectMount | LocalMount => User
        }
        let host_fp : FolderPath? = Some(
          FolderPath::FolderPath(raw_path, platform),
        ) catch {
          _ => None
        }
        match host_fp {
          Some(fp) =>
            Accepted({
              name,
              kind,
              role: mount_role,
              grant: Trusted(tier=trusted_tier, target=HostPath(fp), access~),
              origin,
            })
          None => {
            let tp_res : Result[@app.TreePath, @app.TreePathError] = Ok(
              @app.TreePath::TreePath(raw_path),
            ) catch {
              err => Err(err)
            }
            match tp_res {
              Ok(tp) =>
                Accepted({
                  name,
                  kind,
                  role: mount_role,
                  grant: Trusted(
                    tier=trusted_tier,
                    target=Relative(tp),
                    access~,
                  ),
                  origin,
                })
              Err(err) =>
                refused_mount(
                  workspace_id,
                  name~,
                  kind=Some(kind),
                  role=Some(mount_role),
                  target=Some(raw_path),
                  trust=tier,
                  origin~,
                  reason=InvalidPath(err),
                )
            }
          }
        }
      }
    }
    upsert_mount(dest, name, evaluated)
  }
}

///|
fn extract_pass_reports(
  workspace_id : @app.WorkspaceId,
  output : PassLoadOutput,
  platform : Platform,
  skip_paths : Map[String, Bool]?,
  record_paths : Map[String, Bool]?,
  dest : Array[(@app.SourceName, EvaluatedMount)],
  problems : Array[@app.SourceProblem],
  warnings : Array[MountConfigDiagnostic],
  errors : Array[MountConfigDiagnostic],
) -> Unit {
  for report in output.reports {
    guard report.status == Loaded &&
      report.kind is File(role) &&
      report.path is Some(raw_path) else {
      continue
    }
    if skip_paths is Some(skipped) && skipped.contains(raw_path) {
      continue
    }
    if record_paths is Some(recorded) {
      recorded[raw_path] = true
    }
    guard output.raw_files.get(raw_path) is Some(text) else { continue }
    extract_file_mounts(
      workspace_id, raw_path, text, role, platform, dest, problems, warnings, errors,
    )
  }
}

///|
fn refuse_as_shadowing(
  workspace_id : @app.WorkspaceId,
  entry : EvaluatedMount,
) -> EvaluatedMount {
  match entry {
    Accepted(spec) =>
      refused_mount(
        workspace_id,
        name=spec.name,
        kind=Some(spec.kind),
        role=Some(spec.role),
        target=Some(spec.target().display()),
        trust=spec.trust(),
        origin=spec.origin,
        reason=ShadowsTrustedMount,
      )
    Refused(r) => Refused({ ..r, reason: ShadowsTrustedMount, })
  }
}

///|
fn effective_workspace_id(
  workspace_id : @app.WorkspaceId?,
  workspace_root : FolderPath?,
) -> @app.WorkspaceId {
  match workspace_id {
    Some(id) => id
    None =>
      match workspace_root {
        Some(root) => workspace_id_of(root)
        None =>
          @app.WorkspaceId::WorkspaceId("urn:mc:ws:config-00000000") catch {
            _ => abort("urn:mc:ws:config-00000000 is a valid WorkspaceId")
          }
      }
  }
}

///|
/// Pure 4-target inquiry that loads `workspace.mounts` across isolated system,
/// user, and workspace configuration layers without merging mounts across trust
/// boundaries or reading `MISSION_CONTROL__WORKSPACE__MOUNTS__*` environment
/// variables.
pub fn load_workspace_mounts(
  workspace_id : @app.WorkspaceId?,
  workspace_root : FolderPath?,
  host_env : HostEnv,
) -> Inquiry[MountConfigResult] {
  let ws_id = effective_workspace_id(workspace_id, workspace_root)
  let problems : Array[@app.SourceProblem] = []
  let warnings : Array[MountConfigDiagnostic] = []
  let errors : Array[MountConfigDiagnostic] = []
  let trusted_paths : Map[String, Bool] = Map([])
  let trusted_mounts : Array[(@app.SourceName, EvaluatedMount)] = []
  let workspace_mounts : Array[(@app.SourceName, EvaluatedMount)] = []
  let reported_io : Map[String, Bool] = Map([])
  // Pass 1: System config (`SystemMount`)
  drive_config_pass(
    system_mount_builder(host_env),
    "system-config",
    host_env.platform,
    @config.FileTree::new(),
    Map([]),
    problems,
    reported_io,
    8,
  ).then(sys_out => {
    extract_pass_reports(
      ws_id,
      sys_out,
      host_env.platform,
      None,
      Some(trusted_paths),
      trusted_mounts,
      problems,
      warnings,
      errors,
    )
    // Pass 2: User config (`UserMount`)
    drive_config_pass(
      user_mount_builder(host_env),
      "user-config",
      host_env.platform,
      @config.FileTree::new(),
      Map([]),
      problems,
      reported_io,
      8,
    ).then(user_out => {
      extract_pass_reports(
        ws_id,
        user_out,
        host_env.platform,
        None,
        Some(trusted_paths),
        trusted_mounts,
        problems,
        warnings,
        errors,
      )
      // Pass 3: Workspace config (`ProjectMount` and `LocalMount`), isolated from trusted files.
      let ws_step : Inquiry[Unit] = match workspace_root {
        None => Done(())
        Some(root) =>
          drive_config_pass(
            workspace_mount_builder(host_env, root),
            root.to_string(),
            host_env.platform,
            @config.FileTree::new(),
            Map([]),
            problems,
            reported_io,
            8,
          ).map(ws_out => {
            extract_pass_reports(
              ws_id,
              ws_out,
              host_env.platform,
              Some(trusted_paths),
              None,
              workspace_mounts,
              problems,
              warnings,
              errors,
            )
          })
      }
      ws_step.map(_ => {
        let combined : Array[EvaluatedMount] = []
        for pair in trusted_mounts {
          combined.push(pair.1)
        }
        for pair in workspace_mounts {
          if has_mount_name(trusted_mounts, pair.0) {
            combined.push(refuse_as_shadowing(ws_id, pair.1))
          } else {
            combined.push(pair.1)
          }
        }
        {
          mounts: ReadOnlyArray::from_array(combined),
          problems: ReadOnlyArray::from_array(problems),
          warnings: ReadOnlyArray::from_array(warnings),
          errors: ReadOnlyArray::from_array(errors),
        }
      })
    })
  })
}

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

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

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

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