///|
/// A call that the app does not do. The text is for people, and a client shows
/// it as it is.
#derive(Eq, Debug)
pub(all) suberror Refusal {
  Refusal(String)
}

///|
/// A call that is not correct. The client has an error, and not the user.
priv suberror CallError {
  /// The app has no command with this name.
  UnknownCommand(String)
  /// The request does not have the shape that the command needs.
  BadRequest(String)
}

///|
/// The state of an instance, and the commands that read and change it. It knows
/// nothing about HTTP or the hub.
priv struct App {
  folder : @core.InstanceFolder
  version : @contracts.Version
  /// Sends an event to each view. The name is the name in the contract.
  publish : (String, Json) -> Unit
  /// Whether a view of this kind is connected.
  has_view : (@app.Surface) -> Bool
  /// Asks for the stop of the server. It returns before the server stops.
  stop : () -> Unit
  now : () -> @app.UnixMillis
  /// A call holds the lock only while it changes the list, writes the file and
  /// sends the event. It never waits for the state of a folder with the lock.
  lock : @async.Mutex
  /// Per-workspace locks serializing local dictionary read-modify-write calls.
  dictionary_locks : Map[@app.WorkspaceId, @async.Mutex]
  /// The list that is in the file. Only `App::save` changes it.
  mut projects : @core.ProjectList
  /// The states of the folders. Each folder in `projects` has a known state when
  /// `App::save` sends an event: a call reads the folders that are not known
  /// before it takes the lock, and `add_project` records the new folder.
  states : FolderStates
  /// Single async I/O boundary answering backend and deriver `Inquiry` trees.
  machine : &Machine
  /// Registered VCS backends (`GitBackend` by default).
  backends : @core.Backends
  /// Registered metadata derivers (`GitMetadataDeriver`, `FolderPathDeriver`).
  derivers : @core.MetadataDerivers
  /// Registered in-tree workspace source adapters.
  source_adapters : @core.SourceAdapters
  /// Registered configured mount providers.
  mount_providers : @core.MountProviders
  /// Explicit host environment snapshot captured at server startup.
  host_env : @core.HostEnv
  /// Last observed wire workspace state per project ID so branch, revision,
  /// folder-availability, and unavailable-state transitions publish
  /// `workspaces_changed` even when the persisted `Entry` did not change.
  observed_workspaces : Map[@app.ProjectId, @app.ProjectWorkspaces]
  /// The project that the next window must show. `show_project` sets it, and
  /// `App::greeting` takes it.
  mut waiting : @core.WaitingProject
  /// True after the first `stop_app`.
  mut stopping : Bool
}

///|
/// An app with a project list that was read from the file of the instance. The
/// folder of the instance must exist, and the task group of `states` must live
/// longer than the last call.
fn App::App(
  folder : @core.InstanceFolder,
  version : @contracts.Version,
  projects : @core.ProjectList,
  states~ : FolderStates,
  machine~ : &Machine,
  backends~ : @core.Backends = default_backends(),
  derivers~ : @core.MetadataDerivers = default_derivers(),
  source_adapters~ : @core.SourceAdapters = @core.default_source_adapters(),
  mount_providers~ : @core.MountProviders = @core.default_mount_providers(),
  host_env~ : @core.HostEnv = @core.HostEnv::empty(machine_platform()),
  publish~ : (String, Json) -> Unit,
  has_view~ : (@app.Surface) -> Bool,
  stop~ : () -> Unit,
  now~ : () -> @app.UnixMillis,
) -> App {
  {
    folder,
    version,
    publish,
    has_view,
    stop,
    now,
    lock: @async.Mutex(),
    dictionary_locks: Map([]),
    projects,
    states,
    machine,
    backends,
    derivers,
    source_adapters,
    mount_providers,
    host_env,
    observed_workspaces: Map([]),
    waiting: @core.WaitingProject::none(),
    stopping: false,
  }
}

///|
/// A command in the table: JSON in, JSON out.
priv struct Operation {
  name : String
  /// Raises `Refusal` or `BadRequest`.
  run : async (App, Json) -> Json
}

///|
/// Connects a command of the contract to its handler. A handler raises only
/// `Refusal`, so each failure of it has a text for people.
fn[Req : @json.FromJson, Res : ToJson] on(
  command : @proton_contract.Command[Req, Res],
  handler : async (App, Req) -> Res raise Refusal,
) -> Operation {
  {
    name: command.name(),
    run: async fn(app, json) {
      let request : Req = @json.from_json(json) catch {
        JsonDecodeError((path, message)) =>
          match path.to_string() {
            "" => raise BadRequest(message)
            place => raise BadRequest("\{place}: \{message}")
          }
      }
      handler(app, request).to_json()
    },
  }
}

///|
/// Each command of the server, in the order of `@app.server_commands`.
let operations : ReadOnlyArray[Operation] = [
  on(@app.app_info, (app, _) => app.info()),
  on(@app.list_projects, (app, _) => app.list_projects()),
  on(@app.add_project, App::add_project),
  on(@app.open_project, App::open_project),
  on(@app.remove_project, App::remove_project),
  on(@app.show_project, App::show_project),
  on(@app.list_workspaces, App::list_workspaces),
  on(@app.open_workspace, App::open_workspace),
  on(@app.list_workspace_sources, App::list_workspace_sources),
  on(@app.list_workspace_intent, App::list_workspace_intent),
  on(@app.list_workspace_dictionary, App::list_workspace_dictionary),
  on(@app.add_dictionary_concept, App::add_dictionary_concept),
  on(@app.evaluate_workspace_sdlc, App::evaluate_workspace_sdlc),
  on(@app.save_workspace_workflow, App::save_workspace_workflow),
  on(@app.create_workspace, App::create_workspace),
  on(@app.rename_workspace, App::rename_workspace),
  on(@app.reset_workspace, App::reset_workspace),
  on(@app.delete_workspace, App::delete_workspace),
  on(@app.stop_app, (app, _) => app.stop_app()),
]

///|
/// The names of the commands, in the order of `@app.server_commands`.
fn App::operation_names(_ : App) -> Array[String] {
  operations.iter().map(operation => operation.name).collect()
}

///|
/// Does a command. Raises `Refusal` when the app does not do it, and
/// `CallError` when the name or the request is not correct.
async fn App::call(self : App, name : String, request : Json) -> Json {
  match operations.iter().find_first(operation => operation.name == name) {
    Some(operation) => (operation.run)(self, request)
    None => raise UnknownCommand(name)
  }
}

///|
fn App::info(self : App) -> @app.AppInfo {
  { instance: self.folder.name(), version: self.version, }
}

///|
/// Gives the list as it is after the wait for the states, so the reply is not
/// older than an event that was sent before it.
async fn App::list_projects(self : App) -> Array[@app.Project] noraise {
  self.states.refresh(self.folders())
  self.describe(self.projects)
}

///|
async fn App::add_project(
  self : App,
  request : @app.AddProject,
) -> @app.AddedProject raise Refusal {
  let folder = self.states.find_folder(request.path)
  let validated = @core.ValidatedFolder::of_path(folder)
  let located = answer(self.backends.locate(validated), self.machine)
  let explicit : @core.DerivedMetadata = {
    title: request.title,
    caption: request.caption,
  }
  let (title, caption) = answer(
    self.derivers.resolve(located, explicit~),
    self.machine,
  )
  self.states.refresh(self.folders())
  let (project, addition, target, notify_workspaces) = self.admit_locked(
    located,
    title~,
    caption~,
  )
  if notify_workspaces is Some(entry) {
    let obs = answer(self.backends.observe(entry.anchor), self.machine)
    self.lock.acquire()
    defer self.lock.release()
    match (Some(self.projects.entry(entry.id)) catch { _ => None }) {
      Some(current) => {
        let (updated, domain_ws, _) = current.reconcile(obs)
        let wire_ws = domain_ws.to_wire()
        if updated != current {
          self.save(self.projects.replace_entry(updated)) |> ignore
        }
        self.publish_workspaces(current.id, wire_ws, force=true)
      }
      None => ()
    }
  }
  { project, addition, target, }
}

///|
async fn App::admit_locked(
  self : App,
  located : @core.Located,
  title~ : @app.ProjectTitle,
  caption~ : @app.ProjectCaption?,
) -> (@app.Project, @app.Addition, @app.AddedTarget, @core.Entry?) raise Refusal {
  self.lock.acquire()
  defer self.lock.release()
  let before = self.projects
  let (next, admission, _) = self.projects.admit(
    located,
    title~,
    caption~,
    (self.now)(),
  )
  let (entry, addition, target) : (@core.Entry, @app.Addition, @app.AddedTarget) = match
    admission {
    Added(entry, target) => (entry, New, target)
    Existing(entry, target) => (entry, AlreadyListed, target)
  }
  let mut notify_workspaces : @core.Entry? = None
  let projects = if next != before {
    if addition is AlreadyListed {
      notify_workspaces = Some(entry)
    }
    self.save(next, found=entry.check_folder())
  } else {
    self.states.record_present(entry.check_folder())
    self.describe(next)
  }
  (project_of(projects, entry.id), addition, target, notify_workspaces)
}

///|
/// Sets the time of the last open. The time is in the list, so this is a change
/// of the list.
async fn App::open_project(
  self : App,
  id : @app.ProjectId,
) -> @app.Project raise Refusal {
  let folder = self.folder_of(id)
  let unknown = self
    .folders()
    .filter(other => other != folder && !self.states.is_known(other))
  self.states.refresh([folder, ..unknown])
  self.lock.acquire()
  defer self.lock.release()
  let (next, _) = self.projects.open(id, (self.now)()) catch {
    UnknownProject(id) => raise no_project(id)
  }
  project_of(self.save(next), id)
}

///|
/// Gives the project as it was in the list.
async fn App::remove_project(
  self : App,
  id : @app.ProjectId,
) -> @app.Project raise Refusal {
  self.folder_of(id) |> ignore
  self.states.refresh(self.folders())
  self.lock.acquire()
  defer self.lock.release()
  let (next, _) = self.projects.remove(id) catch {
    UnknownProject(id) => raise no_project(id)
  }
  let removed = project_of(self.describe(self.projects), id)
  self.observed_workspaces.remove(id)
  self.save(next) |> ignore
  removed
}

///|
/// Tells the views of one kind to show a project.
async fn App::show_project(
  self : App,
  shown : @app.ShownProject,
) -> @app.Project raise Refusal {
  self.states.refresh([self.folder_of(shown.project)])
  let project = project_of(self.describe(self.projects), shown.project)
  if shown.surface is Desktop && !(self.has_view)(Desktop) {
    self.waiting = WaitingProject(shown.project, (self.now)())
  }
  (self.publish)(@app.project_shown.name(), shown.to_json())
  project
}

///|
/// Records the latest observed workspace state for `id` and publishes
/// `workspaces_changed` whenever it changed (or when `force` is true).
fn App::publish_workspaces(
  self : App,
  id : @app.ProjectId,
  wire_ws : @app.ProjectWorkspaces,
  force~ : Bool = false,
) -> Unit {
  let changed = self.observed_workspaces.get(id) != Some(wire_ws)
  self.observed_workspaces[id] = wire_ws
  if force || changed {
    let payload : @app.WorkspacesChanged = { project: id, workspaces: wire_ws, }
    (self.publish)(@app.workspaces_changed.name(), payload.to_json())
  }
}

///|
/// Observes and returns the live peer workspaces of one project. Updates
/// `projects.toml` when remembered roots change, and publishes
/// `workspaces_changed` whenever the observed workspace state changes.
async fn App::list_workspaces(
  self : App,
  id : @app.ProjectId,
) -> @app.ProjectWorkspaces raise Refusal {
  let entry = self.entry_of(id)
  let unknown = self.folders().filter(other => !self.states.is_known(other))
  if !unknown.is_empty() {
    self.states.refresh(unknown)
  }
  let obs = answer(self.backends.observe(entry.anchor), self.machine)
  self.lock.acquire()
  defer self.lock.release()
  let current = self.projects.entry(id) catch {
    UnknownProject(missing) => raise no_project(missing)
  }
  let (updated, domain_ws, _) = current.reconcile(obs)
  let wire_ws = domain_ws.to_wire()
  let persisted_changed = updated != current
  if persisted_changed {
    self.save(self.projects.replace_entry(updated)) |> ignore
  }
  self.publish_workspaces(id, wire_ws, force=persisted_changed)
  wire_ws
}

///|
/// Atomically records the last-opened timestamp on both the workspace and its
/// owning project, saves `projects.toml`, and publishes `projects_changed` and
/// `workspaces_changed`.
async fn App::open_workspace(
  self : App,
  target : @app.WorkspaceRef,
) -> @app.Workspace raise Refusal {
  let entry = self.entry_of(target.project)
  let unknown = self.folders().filter(other => !self.states.is_known(other))
  if !unknown.is_empty() {
    self.states.refresh(unknown)
  }
  let obs = answer(self.backends.observe(entry.anchor), self.machine)
  self.lock.acquire()
  defer self.lock.release()
  let (next_list, updated_entry, updated_ws, _) = self.projects.open_workspace(
    target.project,
    target.workspace,
    obs,
    (self.now)(),
  ) catch {
    UnknownProject(id) => raise no_project(id)
    UnknownWorkspace(proj_id, ws_id) =>
      raise Refusal(
        "No workspace has the ID \{ws_id.to_string()} in project \{proj_id.to_string()}.",
      )
  }
  let (_, domain_ws, _) = updated_entry.reconcile(obs)
  self.save(next_list) |> ignore
  self.publish_workspaces(target.project, domain_ws.to_wire(), force=true)
  updated_ws.to_wire()
}

///|
/// Resolves the root folder of a peer workspace (live or remembered), refusing
/// unknown project or workspace IDs.
async fn App::resolve_workspace_root(
  self : App,
  target : @app.WorkspaceRef,
) -> @core.FolderPath raise Refusal {
  let entry = self.entry_of(target.project)
  let obs = answer(self.backends.observe(entry.anchor), self.machine)
  let (_, domain_ws, _) = entry.reconcile(obs)
  match domain_ws {
    Populated(set) =>
      match set.get(target.workspace) {
        Some(ws) => ws.root
        None =>
          raise Refusal(
            "No workspace has the ID \{target.workspace.to_string()} in project \{target.project.to_string()}.",
          )
      }
    Unavailable(remembered~, ..) =>
      match
        remembered
        .iter()
        .find_first(r => @core.workspace_id_of(r.root) == target.workspace) {
        Some(seen) => seen.root
        None =>
          raise Refusal(
            "No workspace has the ID \{target.workspace.to_string()} in project \{target.project.to_string()}.",
          )
      }
    Empty =>
      raise Refusal(
        "No workspace has the ID \{target.workspace.to_string()} in project \{target.project.to_string()}.",
      )
  }
}

///|
/// Composes and returns the live in-tree and configured mounted sources of one
/// peer workspace, together with any configuration problems encountered.
async fn App::list_workspace_sources(
  self : App,
  target : @app.WorkspaceRef,
) -> @app.WorkspaceSources raise Refusal {
  let ws_root = self.resolve_workspace_root(target)
  let cfg = answer(
    @core.load_workspace_mounts(
      Some(target.workspace),
      Some(ws_root),
      self.host_env,
    ),
    self.machine,
  )
  let composed = answer(
    @core.compose_workspace_sources(
      target.workspace,
      ws_root,
      self.source_adapters,
      self.mount_providers,
      cfg.mounts,
      cfg.problems,
    ),
    self.machine,
  )
  composed.to_wire()
}

///|
/// Inspects the live OpenSpec intent items, main specifications, and
/// diagnostics of one peer workspace.
async fn App::list_workspace_intent(
  self : App,
  target : @app.WorkspaceRef,
) -> @app.WorkspaceIntent raise Refusal {
  let ws_root = self.resolve_workspace_root(target)
  answer(
    @core.inspect_workspace_intent(target.workspace, ws_root),
    self.machine,
  )
}

///|
/// Composes and returns the live RDF/SKOS Data Dictionary (named graphs,
/// concepts, and Prose Term Audit findings) for one peer workspace.
async fn App::list_workspace_dictionary(
  self : App,
  target : @app.WorkspaceRef,
) -> @app.WorkspaceDictionary raise Refusal {
  let ws_root = self.resolve_workspace_root(target)
  let cfg = answer(
    @core.load_workspace_mounts(
      Some(target.workspace),
      Some(ws_root),
      self.host_env,
    ),
    self.machine,
  )
  let composed = answer(
    @core.compose_workspace_sources(
      target.workspace,
      ws_root,
      self.source_adapters,
      self.mount_providers,
      cfg.mounts,
      cfg.problems,
    ),
    self.machine,
  )
  let intent = answer(
    @core.inspect_workspace_intent(target.workspace, ws_root),
    self.machine,
  )
  answer(
    @core.inspect_workspace_dictionary(
      target.workspace,
      ws_root,
      composed,
      intent,
    ),
    self.machine,
  )
}

///|
async fn ensure_folder(path : String) -> Unit {
  @fs.mkdir(path, permission=0o755) catch {
    @os_error.OSError(_) as err if err.is_EEXIST() => ()
    err => raise err
  }
}

///|
/// Returns the workspace-scoped mutex serializing dictionary file mutations.
fn App::dictionary_lock_for(
  self : App,
  workspace : @app.WorkspaceId,
) -> @async.Mutex {
  match self.dictionary_locks.get(workspace) {
    Some(mutex) => mutex
    None => {
      let mutex = @async.Mutex()
      self.dictionary_locks[workspace] = mutex
      mutex
    }
  }
}

///|
/// Validates and appends a new local SKOS concept into
/// `/.mission-control/dictionary/local.ttl`, enforcing workspace
/// symlink containment, and returns the refreshed `WorkspaceDictionary`.
async fn App::add_dictionary_concept(
  self : App,
  request : @app.AddDictionaryConcept,
) -> @app.WorkspaceDictionary raise Refusal {
  let ws_root = self.resolve_workspace_root(request.workspace)
  let dict_lock = self.dictionary_lock_for(request.workspace.workspace)
  dict_lock.acquire()
  defer dict_lock.release()
  let real_root = match self.machine.real_path(ws_root) {
    Resolved(r) => r
    Missing =>
      raise Refusal("Workspace folder is missing: \{ws_root.to_string()}.")
    TimedOut =>
      raise Refusal(
        "Timed out resolving workspace folder: \{ws_root.to_string()}.",
      )
    Failed(reason) =>
      raise Refusal("Cannot access workspace folder: \{reason}.")
  }
  let mc_tp = @app.TreePath(".mission-control") catch {
    _ => abort(".mission-control is a valid TreePath")
  }
  let dict_tp = @app.TreePath(".mission-control/dictionary") catch {
    _ => abort(".mission-control/dictionary is a valid TreePath")
  }
  let ttl_tp = @app.TreePath(".mission-control/dictionary/local.ttl") catch {
    _ => abort(".mission-control/dictionary/local.ttl is a valid TreePath")
  }
  let mc_dir = ws_root.join_tree(mc_tp)
  let dict_dir = ws_root.join_tree(dict_tp)
  let local_ttl = ws_root.join_tree(ttl_tp)
  // Verify symlink confinement for existing ancestors and target file BEFORE any read or mkdir.
  match self.machine.real_path(mc_dir) {
    Resolved(real_mc) =>
      if !real_root.contains(real_mc) {
        raise Refusal(
          "Refused to access outside workspace root: .mission-control escapes workspace.",
        )
      }
    Missing => ()
    TimedOut =>
      raise Refusal("Timed out verifying canonical path of .mission-control.")
    Failed(reason) =>
      raise Refusal(
        "Could not verify canonical path of .mission-control: \{reason}.",
      )
  }
  match self.machine.real_path(dict_dir) {
    Resolved(real_dict) =>
      if !real_root.contains(real_dict) {
        raise Refusal(
          "Refused to access outside workspace root: .mission-control/dictionary escapes workspace.",
        )
      }
    Missing => ()
    TimedOut =>
      raise Refusal(
        "Timed out verifying canonical path of .mission-control/dictionary.",
      )
    Failed(reason) =>
      raise Refusal(
        "Could not verify canonical path of .mission-control/dictionary: \{reason}.",
      )
  }
  match self.machine.real_path(local_ttl) {
    Resolved(real_ttl) =>
      if !real_root.contains(real_ttl) {
        raise Refusal(
          "Refused to access outside workspace root: local.ttl escapes workspace.",
        )
      }
    Missing => ()
    TimedOut =>
      raise Refusal(
        "Timed out verifying canonical path of .mission-control/dictionary/local.ttl.",
      )
    Failed(reason) =>
      raise Refusal(
        "Could not verify canonical path of .mission-control/dictionary/local.ttl: \{reason}.",
      )
  }
  let existing_ttl : String = match self.machine.read_file(local_ttl) {
    Found(content) => content
    Missing => ""
    TooLarge =>
      raise Refusal("Local dictionary file exceeds 1 MiB and cannot be edited.")
    TimedOut => raise Refusal("Timed out reading local dictionary file.")
    Failed(reason) =>
      raise Refusal("Failed reading local dictionary file: \{reason}.")
  }
  let updated_ttl = @core.merge_local_concept_turtle(
    existing_ttl,
    pref_label=request.pref_label,
    definition=request.definition,
    alt_labels=request.alt_labels,
  ) catch {
    err => raise Refusal(err.message())
  }
  ensure_folder(mc_dir.to_string()) catch {
    err =>
      raise Refusal(
        "Could not create .mission-control folder: \{reason_of(err)}",
      )
  }
  match self.machine.real_path(mc_dir) {
    Resolved(real_mc) =>
      if !real_root.contains(real_mc) {
        raise Refusal(
          "Refused to write outside workspace root: .mission-control escapes workspace.",
        )
      }
    Missing | TimedOut | Failed(_) =>
      raise Refusal("Could not verify canonical path of .mission-control.")
  }
  ensure_folder(dict_dir.to_string()) catch {
    err =>
      raise Refusal(
        "Could not create .mission-control/dictionary folder: \{reason_of(err)}",
      )
  }
  match self.machine.real_path(dict_dir) {
    Resolved(real_dict) =>
      if !real_root.contains(real_dict) {
        raise Refusal(
          "Refused to write outside workspace root: .mission-control/dictionary escapes workspace.",
        )
      }
    Missing | TimedOut | Failed(_) =>
      raise Refusal(
        "Could not verify canonical path of .mission-control/dictionary.",
      )
  }
  write_private(local_ttl.to_string(), updated_ttl) catch {
    err =>
      raise Refusal("Failed writing local dictionary Turtle: \{reason_of(err)}")
  }
  self.list_workspace_dictionary(request.workspace)
}

///|
/// Evaluates live document scorecards and Rego v1 transition gates for one peer
/// workspace using its live OpenSpec intent, Data Dictionary, and workflow config.
async fn App::evaluate_workspace_sdlc(
  self : App,
  target : @app.WorkspaceRef,
) -> @app.WorkspaceSdlc raise Refusal {
  let ws_root = self.resolve_workspace_root(target)
  let intent = answer(
    @core.inspect_workspace_intent(target.workspace, ws_root),
    self.machine,
  )
  let dict = self.list_workspace_dictionary(target)
  answer(
    @core.inspect_workspace_sdlc(target.workspace, ws_root, intent, dict),
    self.machine,
  )
}

///|
/// Validates and persists `.mission-control/workflow.toml` inside the workspace
/// root under symlink containment, then returns the freshly evaluated `WorkspaceSdlc`.
async fn App::save_workspace_workflow(
  self : App,
  request : @app.SaveWorkspaceWorkflow,
) -> @app.WorkspaceSdlc raise Refusal {
  let ws_root = self.resolve_workspace_root(request.workspace)
  let real_root = match self.machine.real_path(ws_root) {
    Resolved(r) => r
    Missing =>
      raise Refusal("Workspace folder is missing: \{ws_root.to_string()}.")
    TimedOut =>
      raise Refusal(
        "Timed out resolving workspace folder: \{ws_root.to_string()}.",
      )
    Failed(reason) =>
      raise Refusal("Cannot access workspace folder: \{reason}.")
  }
  let toml = @core.serialize_workflow_toml(
    preset=request.preset,
    min_scorecard=request.min_scorecard,
    require_security_gate=request.require_security_gate,
  ) catch {
    err => raise Refusal(err.message())
  }
  let mc_tp = @app.TreePath(".mission-control") catch {
    _ => abort(".mission-control is a valid TreePath")
  }
  let wf_tp = @app.TreePath(".mission-control/workflow.toml") catch {
    _ => abort(".mission-control/workflow.toml is a valid TreePath")
  }
  let mc_dir = ws_root.join_tree(mc_tp)
  let wf_file = ws_root.join_tree(wf_tp)
  ensure_folder(mc_dir.to_string()) catch {
    err =>
      raise Refusal(
        "Could not create .mission-control folder: \{reason_of(err)}",
      )
  }
  match self.machine.real_path(mc_dir) {
    Resolved(real_mc) =>
      if !real_root.contains(real_mc) {
        raise Refusal(
          "Refused to write outside workspace root: .mission-control escapes workspace.",
        )
      }
    Missing | TimedOut | Failed(_) =>
      raise Refusal("Could not verify canonical path of .mission-control.")
  }
  write_private(wf_file.to_string(), toml) catch {
    err =>
      raise Refusal(
        "Failed writing .mission-control/workflow.toml: \{reason_of(err)}",
      )
  }
  self.evaluate_workspace_sdlc(request.workspace)
}

///|
/// Re-observes a project after a workspace lifecycle mutation, saves updated
/// `projects.toml` if needed, publishes `workspaces_changed`, and returns the
/// fresh wire `ProjectWorkspaces`.
async fn App::refresh_after_mutation(
  self : App,
  project_id : @app.ProjectId,
) -> @app.ProjectWorkspaces raise Refusal {
  let entry = self.entry_of(project_id)
  let obs = answer(self.backends.observe(entry.anchor), self.machine)
  self.lock.acquire()
  defer self.lock.release()
  let current = self.projects.entry(project_id) catch {
    UnknownProject(missing) => raise no_project(missing)
  }
  let (updated, domain_ws, _) = current.reconcile(obs)
  let wire_ws = domain_ws.to_wire()
  if updated != current {
    self.save(self.projects.replace_entry(updated)) |> ignore
  }
  self.publish_workspaces(project_id, wire_ws, force=true)
  wire_ws
}

///|
/// Requires that `entry` is anchored at a Git repository store, returning that
/// store path or raising a clear `Refusal`.
fn require_git_store(entry : @core.Entry) -> @core.FolderPath raise Refusal {
  match entry.anchor {
    Repository(backend~, store~, ..) if backend == @app.BackendId::git() =>
      store
    _ =>
      raise Refusal(
        "Workspace lifecycle operations require a Git repository project.",
      )
  }
}

///|
/// Creates a new linked Git worktree for a Git project and publishes
/// `workspaces_changed`.
async fn App::create_workspace(
  self : App,
  request : @app.CreateWorkspace,
) -> @app.WorkspaceMutation raise Refusal {
  let entry = self.entry_of(request.project)
  let store = require_git_store(entry)
  let outcome = answer(
    @core.git_create_worktree(
      store,
      request.path,
      request.branch,
      start_point=request.start_point,
    ),
    self.machine,
  )
  let detail = match outcome {
    Succeeded(msg) => msg
    Refused(msg) => raise Refusal(msg)
  }
  let workspaces = self.refresh_after_mutation(request.project)
  let created_id : @app.WorkspaceId? = match workspaces {
    Populated(set) =>
      set
      .workspaces()
      .iter()
      .find_first(ws => {
        ws.path == request.path ||
        (ws.position is OnLine(line~, ..) && line.to_string() == request.branch)
      })
      .map(ws => ws.id)
    _ => None
  }
  {
    project: request.project,
    workspace: created_id,
    action: "create",
    detail,
    workspaces,
  }
}

///|
/// Renames the active Git branch of a workspace and publishes `workspaces_changed`.
async fn App::rename_workspace(
  self : App,
  request : @app.RenameWorkspace,
) -> @app.WorkspaceMutation raise Refusal {
  let entry = self.entry_of(request.workspace.project)
  let _ = require_git_store(entry)
  let ws_root = self.resolve_workspace_root(request.workspace)
  let outcome = answer(
    @core.git_rename_worktree(ws_root, request.new_branch),
    self.machine,
  )
  let detail = match outcome {
    Succeeded(msg) => msg
    Refused(msg) => raise Refusal(msg)
  }
  let workspaces = self.refresh_after_mutation(request.workspace.project)
  {
    project: request.workspace.project,
    workspace: Some(request.workspace.workspace),
    action: "rename",
    detail,
    workspaces,
  }
}

///|
/// Resets a Git workspace to a target commit or `HEAD`, refusing dirty trees
/// unless `hard = true`, and publishes `workspaces_changed`.
async fn App::reset_workspace(
  self : App,
  request : @app.ResetWorkspace,
) -> @app.WorkspaceMutation raise Refusal {
  let entry = self.entry_of(request.workspace.project)
  let _ = require_git_store(entry)
  let ws_root = self.resolve_workspace_root(request.workspace)
  let outcome = answer(
    @core.git_reset_worktree(ws_root, target=request.target, hard=request.hard),
    self.machine,
  )
  let detail = match outcome {
    Succeeded(msg) => msg
    Refused(msg) => raise Refusal(msg)
  }
  let workspaces = self.refresh_after_mutation(request.workspace.project)
  {
    project: request.workspace.project,
    workspace: Some(request.workspace.workspace),
    action: "reset",
    detail,
    workspaces,
  }
}

///|
/// Removes a non-default linked Git worktree and publishes `workspaces_changed`.
/// Refuses deleting the default/main workspace.
async fn App::delete_workspace(
  self : App,
  request : @app.DeleteWorkspace,
) -> @app.WorkspaceMutation raise Refusal {
  let entry = self.entry_of(request.workspace.project)
  let store = require_git_store(entry)
  let obs = answer(self.backends.observe(entry.anchor), self.machine)
  let (_, domain_ws, _) = entry.reconcile(obs)
  let ws_root : @core.FolderPath = match domain_ws {
    Populated(set) => {
      if set.default_id() == request.workspace.workspace {
        raise Refusal(
          "Refused to delete the default workspace of this repository.",
        )
      }
      match set.get(request.workspace.workspace) {
        Some(ws) => ws.root
        None =>
          raise Refusal(
            "No workspace has the ID \{request.workspace.workspace.to_string()} in project \{request.workspace.project.to_string()}.",
          )
      }
    }
    _ =>
      raise Refusal(
        "No workspace has the ID \{request.workspace.workspace.to_string()} in project \{request.workspace.project.to_string()}.",
      )
  }
  let outcome = answer(
    @core.git_delete_worktree(store, ws_root, force=request.force),
    self.machine,
  )
  let detail = match outcome {
    Succeeded(msg) => msg
    Refused(msg) => raise Refusal(msg)
  }
  let workspaces = self.refresh_after_mutation(request.workspace.project)
  {
    project: request.workspace.project,
    workspace: None,
    action: "delete",
    detail,
    workspaces,
  }
}

///|
/// The event `project_shown` for a view that connects now, if a project waits for it.
/// Only the first window gets it.
fn App::greeting(self : App, surface : @app.Surface) -> @app.ShownProject? {
  guard surface is Desktop else { return None }
  let (project, waiting) = self.waiting.take((self.now)())
  self.waiting = waiting
  project.map(project => { project, surface, })
}

///|
/// Tells the views that the server stops, and asks for the stop. Two views can
/// do this at the same time, and the second call then only gets the reply.
fn App::stop_app(self : App) -> @app.Stopping {
  if !self.stopping {
    self.stopping = true
    (self.publish)(@app.app_stopping.name(), @app.Stopping::{ }.to_json())
    (self.stop)()
  }
  @app.Stopping::{ }
}

///|
/// Writes a new list to the file, makes it the list of the app, and publishes
/// it. The caller holds the lock. `found` is a folder that the call checked.
/// Gives the details of the projects.
async fn App::save(
  self : App,
  next : @core.ProjectList,
  found? : @core.FolderPath,
) -> Array[@app.Project] raise Refusal {
  let path = self.folder.projects()
  write_private(path, next.to_file_text()) catch {
    error =>
      raise Refusal(
        "The project list is not saved in \{path}: \{reason_of(error)}",
      )
  }
  self.projects = next
  if found is Some(folder) {
    self.states.record_present(folder)
  }
  let projects = self.describe(next)
  (self.publish)(@app.projects_changed.name(), ToJson::to_json(projects))
  projects
}

///|
/// The details of each project, with the last known state of its folder. It does
/// not wait.
fn App::describe(self : App, list : @core.ProjectList) -> Array[@app.Project] {
  list.describe(entry => self.states.state_of(entry.check_folder()))
}

///|
/// The folders of the list checked for presence.
fn App::folders(self : App) -> Array[@core.FolderPath] {
  self.projects.entries().iter().map(entry => entry.check_folder()).collect()
}

///|
fn App::entry_of(self : App, id : @app.ProjectId) -> @core.Entry raise Refusal {
  self.projects.entry(id) catch {
    UnknownProject(missing) => raise no_project(missing)
  }
}

///|
/// The folder of a project in the list.
fn App::folder_of(
  self : App,
  id : @app.ProjectId,
) -> @core.FolderPath raise Refusal {
  self.entry_of(id).check_folder()
}

///|
fn project_of(
  projects : ArrayView[@app.Project],
  id : @app.ProjectId,
) -> @app.Project raise Refusal {
  match projects.iter().find_first(project => project.id == id) {
    Some(project) => project
    None => raise no_project(id)
  }
}

///|
fn no_project(id : @app.ProjectId) -> Refusal {
  Refusal("No project has the ID \{id.to_string()}.")
}

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

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