#!/usr/bin/env ruby
# frozen_string_literal: true
# ag-store — the backlog store client. Every skill that touches the Inbox, a spec,
# an Outcome, a checkpoint or a run goes through here instead of talking to a
# store itself, so a skill's instructions name one command and one output shape.
# The contract every store meets is docs/store-protocol.md (the Agentile Store
# Protocol, version 1); this client speaks both of its transports.
#
# Usage: ag-store <op> [args...] [--dir <agentile-dir>]
#
# Config — .agentile/store.md frontmatter, written by /ag-init:
#   url:     where the store is (AGENTILE_STORE_URL, else AGENTILE_PROJECTS_URL, overrides):
#              https://host                 HTTP binding, e.g. Agentile Projects
#              http://localhost:3300, http://*.localhost
#                                           HTTP binding, a store on this machine
#              local | local:<dir>          the bundled local store (bin/ag-store-local)
#              exec:<command line>          any program speaking the process binding
#   project: <slug>
#   (any other key is passed to a process store as config, e.g. wip_limit)
# Auth (HTTP only) — AGENTILE_STORE_TOKEN, else AGENTILE_PROJECTS_TOKEN, in the
# environment only, never a tracked file. The url in .agentile/store.md is a tracked
# file, so the client refuses to send the token to it unless it is https, or a loopback
# host (localhost, 127.0.0.1, ::1, *.localhost), or AGENTILE_STORE_ALLOW_HTTP=1 (or
# AGENTILE_PROJECTS_ALLOW_HTTP=1) is set (exit 2, names the offending host, never the
# token). `doctor` prints the resolved host (or the store command) so a redirected url
# is visible. A process store needs no token: it is told the git user, and holds any
# credentials of its own.
# --dir (default docs/agentile) is used by promote and brief_sync, which touch
# the repo; every other op ignores it. `promote` never reaches the store, so unlike every
# other op it needs neither a url nor a token.
#
# Ops (all output one JSON value on stdout; errors to stderr, exit 1 for an API
# or usage error, exit 2 for a configuration/connectivity error):
#   inbox_list [--status open|shaped|dropped]
#   inbox_add <text> [--title "<label>"] [--type feature|bug|chore|spike] [--serves <outcome-slug>]
#     [--suggested-kind k] [--duplicate-of id-or-slug] [--duplicate-of-type inbox|spec]
#     [--duplicate-probability p]   (sent as suggested_kind/duplicate_of/duplicate_of_type/
#     duplicate_probability, omitted when absent; the type defaults to inbox for an
#     all-digit value, else spec)
#                                                  -> the new item's id (integer, unwrapped from {ok, id})
#   inbox_drop <id>
#   inbox_assist <text>                          tidy + classify; returns
#     {title, text, kind, serves_outcome_slug, duplicate_of, duplicate_of_type,
#      duplicate_probability, judgment_id} — saves nothing
#   inbox_shape <id>            (markdown on stdin)  create the spec, mark the stub shaped
#                                                  -> slug string (the app's full spec object, unwrapped)
#   spec_list [--status s] [--pool active|done|abandoned]
#   spec_read <slug>                              canonical markdown
#   spec_create <slug>          (markdown on stdin)          -> slug string (unwrapped, as above)
#   spec_write <slug> --set k=v [--set k=v ...]   list fields accept "[a, b]"
#     (the app rejects status/rank here — 422 — they are set via their own endpoints)
#   rank <slug> [<slug>...]                       ready specs only, dense ranks in this order
#   claim <identity> [label] [wip] [--spec <slug>] [--model <id>]   slug, or WIP_FULL|BLOCKED|UNPRIORITISED|NONE|NOT_FOUND|TAKEN
#     (wip omitted -> the project's own wip_limit applies; wip 0 -> unlimited, sent explicitly)
#   release <slug> | ship <slug> | abandon <slug> --reason "<text>" [--cascade "[a, b]"]
#   promote <slug> --dir <dir>                    ensures <dir>/specs/<slug>/ exists; prints it
#   deps <slug> | dependents <slug>
#   map | flow [<slug>]
#   outcome_list [--status s] | outcome_read <slug> | outcome_write <slug> --set k=v
#   outcome_create <slug>       (markdown on stdin)          -> slug string (unwrapped, as above)
#   outcome_rank <slug>... | outcome_achieve <slug> | outcome_abandon <slug> --reason "<text>"
#   checkpoint_open <slug> <reason> --session <id> --by <who> [--model <id>]   (ask on stdin) -> checkpoint id
#     (warns on stderr if the ask does not follow the Checkpoint ask format; still posts it, exit 0)
#   checkpoint_list <slug> | checkpoint_open_count <slug>
#   checkpoint_answer <id> --by <who>             (answer on stdin)
#   run_event <event> --spec <slug> --runner <id> [--detail "<text>"] [--model <id>]
#                                                  -> ISO8601 stamp (the run's last_event_at, unwrapped)
#   run_list [--spec <slug>] [--status active|closed]
#   run_close --spec <slug> --runner <id> [--detail "<text>"]
#   brief_sync --dir <dir>                        writes <dir>/brief.md from the store; prints the path
#   brief_write                 (markdown on stdin)  replaces the project's brief in the store
#   whoami | doctor
#
# --model (else AGENTILE_MODEL; omitted when both are blank) is sent as `model`
# when claim or ensure_run opens a run; never sent for an existing run; sent
# verbatim, no alias normalisation.
#
# The app's create/event endpoints return the full resource (spec/outcome/run)
# object, not the bare string the CLI prints; ag-store unwraps `slug` (create
# ops) or `last_event_at` (run_event) client-side so every skill's documented
# "-> slug string" / "-> ISO8601 stamp" contract holds regardless of how much
# detail the app's JSON response carries.
#
# Runs belong to a spec. checkpoint_open, run_event and run_close resolve the
# run themselves: the active run for <spec> whose runner_id is the identity
# (--runner, else AGENTILE_RUNNER_ID, else CLAUDE_SESSION_ID), else the newest
# active run; run_event creates one when none exists. `claim` opens the run
# server-side, so no skill ever handles a run id. The model (--model, else
# AGENTILE_MODEL) is sent only when a run is opened, never for an existing run.

require "json"
require "yaml"
require "net/http"
require "uri"
require "erb"
require "fileutils"
require "open3"
require "shellwords"
require "rbconfig"

module AgStore
  class Error < StandardError; end        # exit 1
  class ConfigError < StandardError; end  # exit 2

  CHECKPOINT_REASONS = %w[plan_review build_blocked build_checkpoint gate_failure
                          verify_checkpoint ship_approval question].freeze
  # Replies for these are fixed (approve, or send back with a note), so an ask
  # without an Options: line is normal and never warned about.
  OPTIONS_EXEMPT_REASONS = %w[plan_review ship_approval].freeze
  RUN_EVENTS = %w[started claimed shipped paused failed idle deployed closed].freeze
  LIST_FIELDS = %w[depends_on tags shaped_by cascade].freeze
  STORE_MD = ".agentile/store.md"

  def self.parse_flags(argv)
    positional = []
    flags = {}
    i = 0
    while i < argv.length
      arg = argv[i]
      if arg.start_with?("--")
        key = arg[2..]
        if i + 1 < argv.length && !argv[i + 1].start_with?("--")
          flags[key] = argv[i + 1]
          i += 2
        else
          flags[key] = true
          i += 1
        end
      else
        positional << arg
        i += 1
      end
    end
    [positional, flags]
  end

  # --set key=value may repeat; pull every occurrence out before the generic parser runs.
  def self.extract_sets(argv)
    sets = {}
    rest = []
    i = 0
    while i < argv.length
      if argv[i] == "--set" && argv[i + 1]
        k, v = argv[i + 1].split("=", 2)
        sets[k] = v
        i += 2
      else
        rest << argv[i]
        i += 1
      end
    end
    [rest, sets]
  end

  # Percent-encode one path segment (a slug, an id, the project). Never call
  # this on a whole path — only on the interpolated piece — so literal
  # separators ("/", and a trailing ".md") stay untouched.
  # Advisory format check for a checkpoint ask (see "Checkpoint ask format" in
  # skills/ag-build/SKILL.md). Returns warning messages, [] when fine; never raises.
  def self.ask_warnings(reason, ask)
    ask = ask.to_s
    warnings = []
    if ask.length > 200 && !ask.match?(/\n[ \t]*\n/)
      warnings << "checkpoint ask is #{ask.length} characters with no blank line — split headline from details (see Checkpoint ask format in /ag-build)"
    end
    if !OPTIONS_EXEMPT_REASONS.include?(reason.to_s) && !ask.match?(/^[ \t]*Options:/)
      warnings << "#{reason} ask has no Options: line — list the replies (see Checkpoint ask format in /ag-build)"
    end
    warnings
  rescue StandardError
    []
  end

  def self.enc(segment) = ERB::Util.url_encode(segment.to_s)

  PROTOCOL = 1
  PROCESS_TIMEOUT = 60

  # The first non-blank of several environment variables: the protocol's name, then
  # the older Agentile Projects one.
  def self.env(*names)
    names.each do |n|
      v = ENV[n].to_s
      return v unless v.empty?
    end
    ""
  end

  # Who is at the keyboard, for a process store's attribution (§9). Not authentication.
  def self.git_user
    %w[email name].to_h do |k|
      out, _e, st = Open3.capture3("git", "config", "user.#{k}")
      [ k, st.success? ? out.strip : "" ]
    end
  rescue StandardError
    { "email" => "", "name" => "" }
  end

  # Smooth over the older field names an Agentile Projects response may carry, so
  # skills see protocol-1 shapes whichever store answered (§12, G9): a spec's
  # `prefix` is also `rank`, and its `kind` is also `type`.
  def self.normalise(value)
    case value
    when Array then value.map { |v| normalise(v) }
    when Hash
      if value.key?("slug") && value.key?("status")
        value = value.merge("rank" => value["prefix"]) if value.key?("prefix") && !value.key?("rank")
        value = value.merge("prefix" => value["rank"]) if value.key?("rank") && !value.key?("prefix") && value.key?("path")
        value = value.merge("type" => value["kind"]) if value.key?("kind") && !value.key?("type")
      end
      value
    else value
    end
  end

  # "[a, b]" -> ["a", "b"]; "[]" -> []; anything else unchanged.
  def self.coerce_list(key, val)
    return val unless LIST_FIELDS.include?(key) && val.is_a?(String)

    s = val.strip
    return val unless s.start_with?("[") && s.end_with?("]")

    s[1..-2].split(",").map(&:strip).reject(&:empty?)
  end

  class Config
    LOCAL_HOSTS = %w[localhost 127.0.0.1 ::1 [::1]].freeze

    attr_reader :url, :project, :token, :dir, :store_md

    def initialize(flags)
      @store_md = self.class.read_store_md
      env_url = AgStore.env("AGENTILE_STORE_URL", "AGENTILE_PROJECTS_URL")
      @url = (env_url.empty? ? @store_md["url"] : env_url).to_s.sub(%r{/+\z}, "")
      @project = (flags["project"] || @store_md["project"]).to_s
      @token = AgStore.env("AGENTILE_STORE_TOKEN", "AGENTILE_PROJECTS_TOKEN")
      @dir = (flags["dir"] || "docs/agentile").to_s.sub(%r{/+\z}, "")
    end

    # A relative `local:<dir>` is relative to the main checkout, never the cwd, so
    # every worktree of the repo reaches the same backlog (§2).
    def self.main_checkout
      out, _e, st = Open3.capture3("git", "rev-parse", "--path-format=absolute", "--git-common-dir")
      st.success? ? File.dirname(out.strip) : Dir.pwd
    rescue StandardError
      Dir.pwd
    end

    def self.read_store_md
      return {} unless File.exist?(STORE_MD)

      fm = File.read(STORE_MD)[/\A---\n(.*?)\n---/m, 1]
      fm ? (YAML.safe_load(fm) || {}) : {}
    rescue StandardError
      {}
    end

    # :http for http(s) urls; :process for `local`, `local:<dir>` and `exec:<command>`
    # (docs/store-protocol.md §2).
    def transport
      url == "local" || url.start_with?("local:", "exec:") ? :process : :http
    end

    # The argv a process store is started with.
    def command
      if url.start_with?("exec:")
        Shellwords.split(url.delete_prefix("exec:"))
      else
        dir = url.delete_prefix("local").delete_prefix(":")
        cmd = [ RbConfig.ruby, File.expand_path("ag-store-local", __dir__) ]
        dir.empty? ? cmd : cmd + [ "--root", File.expand_path(dir, self.class.main_checkout) ]
      end
    end

    # The host the url resolves to, for doctor/logging — never the token.
    def host
      URI.parse(url).host.to_s
    rescue URI::InvalidURIError
      ""
    end

    # needs_network: false is for ops that never reach the store (promote) — they need
    # neither a url, a token, nor the https/loopback check below.
    def validate!(needs_project: true, needs_network: true)
      if needs_network
        if url.empty?
          raise ConfigError, "no store url — #{STORE_MD} has no `url:` (run /ag-init to link this project) and AGENTILE_STORE_URL is unset"
        end
        if transport == :http
          validate_scheme!
          raise ConfigError, "AGENTILE_STORE_TOKEN (or AGENTILE_PROJECTS_TOKEN) is not set — create a token in your store (Agentile Projects: Settings → API tokens) and export it" if token.empty?
        elsif command.empty?
          raise ConfigError, "store url #{url.inspect} names no command"
        end
      end
      raise ConfigError, "no project — #{STORE_MD} has no `project:` (run /ag-init to link this project)" if needs_project && project.empty?
    end

    private

    # A tracked file (.agentile/store.md) names the url every skill sends the bearer token
    # to — refuse anything that could send it somewhere other than a host we control by
    # default: https, or a loopback host over plain http (dev) — localhost/127.0.0.1/::1,
    # or a *.localhost name (RFC 6761: the .localhost TLD always resolves to loopback, and
    # Keith's dev apps are served through a local Caddy proxy on stable *.localhost
    # hostnames) — or an explicit opt-out.
    def validate_scheme!
      uri = URI.parse(url)
      return if uri.scheme == "https"
      return if loopback_host?(uri.host)
      return if AgStore.env("AGENTILE_STORE_ALLOW_HTTP", "AGENTILE_PROJECTS_ALLOW_HTTP") == "1"

      raise ConfigError, "refusing to send AGENTILE_STORE_TOKEN/AGENTILE_PROJECTS_TOKEN to '#{uri.host}' over #{uri.scheme || 'a non-https scheme'} — " \
                          "the store url must be https, or a loopback host (localhost, 127.0.0.1, ::1, *.localhost), or set AGENTILE_STORE_ALLOW_HTTP=1 to override"
    rescue URI::InvalidURIError
      raise ConfigError, "no store url — #{url.inspect} is not a valid url"
    end

    def loopback_host?(host)
      return false if host.nil?

      h = host.downcase
      LOCAL_HOSTS.include?(h) || h.end_with?(".localhost")
    end
  end

  # One response, whichever transport carried it.
  Response = Struct.new(:status, :content_type, :body)

  class Client
    def initialize(config)
      @config = config
    end

    def get(path, params = {})   = request(:get, path, params: params)
    def post(path, body = nil)   = request(:post, path, body: body)
    def patch(path, body)        = request(:patch, path, body: body)
    def put(path, body)          = request(:put, path, body: body)
    def post_markdown(path, md)  = request(:post, path, body: md, content_type: "text/markdown")
    def put_markdown(path, md)   = request(:put, path, body: md, content_type: "text/markdown")

    def project_path(rest) = "/projects/#{AgStore.enc(@config.project)}#{rest}"

    private

    def request(method, path, body: nil, params: {}, content_type: "application/json")
      clean = params.reject { |_, v| v.nil? || v.to_s.empty? }.transform_keys(&:to_s).transform_values(&:to_s)
      res = if @config.transport == :process
              process_request(method, path, body, clean, content_type)
            else
              http_request(method, path, body, clean, content_type)
            end
      AgStore.normalise(parse(res))
    end

    def http_request(method, path, body, params, content_type)
      uri = URI.parse("#{@config.url}/api/v1#{path}")
      uri.query = URI.encode_www_form(params) unless params.empty?
      req = { get: Net::HTTP::Get, post: Net::HTTP::Post, patch: Net::HTTP::Patch, put: Net::HTTP::Put }.fetch(method).new(uri)
      req["Authorization"] = "Bearer #{@config.token}"
      req["Accept"] = "application/json, text/markdown"
      unless body.nil?
        req["Content-Type"] = content_type
        req.body = content_type == "application/json" ? JSON.generate(body) : body
      end
      res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 60) do |http|
        http.request(req)
      end
      Response.new(res.code.to_i, res["content-type"].to_s, res.body.to_s)
    rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, SocketError, Net::OpenTimeout => e
      raise ConfigError, "cannot reach #{@config.url} (#{e.class}) — is the store running, and is the url in #{STORE_MD} (or AGENTILE_STORE_URL) right?"
    end

    # The process binding (docs/store-protocol.md §9): one JSON request on stdin,
    # one JSON response on stdout.
    # A process store never sees the HTTP token: its command comes from a tracked
    # file, and that file must not be able to redirect the token (§9).
    SCRUBBED_ENV = { "AGENTILE_STORE_TOKEN" => nil, "AGENTILE_PROJECTS_TOKEN" => nil }.freeze

    def process_request(method, path, body, params, content_type)
      request = { "protocol" => PROTOCOL, "method" => method.to_s.upcase, "path" => path, "query" => params,
                  "content_type" => body.nil? ? nil : content_type, "body" => body,
                  "user" => AgStore.git_user, "config" => @config.store_md.except("url").merge("project" => @config.project) }
      out, err, status = run_with_deadline(JSON.generate(request))
      unless status&.success?
        raise ConfigError, "store command #{@config.command.first(2).join(' ')} failed (exit #{status&.exitstatus}): #{err.lines.first(3).join.strip}"
      end

      res = begin
        JSON.parse(out)
      rescue JSON::ParserError
        nil
      end
      unless res.is_a?(Hash) && res["status"].is_a?(Integer)
        raise ConfigError, "store command printed something that is not a protocol response: #{out.to_s[0, 160].inspect}" \
                           "#{err.strip.empty? ? '' : " — stderr: #{err.lines.first(3).join.strip}"}"
      end

      text = res["body"].is_a?(String) ? res["body"] : JSON.generate(res["body"])
      Response.new(res["status"], res["content_type"].to_s, text)
    rescue Errno::ENOENT, Errno::EACCES => e
      raise ConfigError, "cannot start store command #{@config.command.first.inspect} (#{e.class})"
    end

    # §9: a process store has PROCESS_TIMEOUT seconds (AGENTILE_STORE_TIMEOUT
    # overrides); past that it is killed and the operation fails with exit 2.
    def run_with_deadline(input)
      limit = Float(ENV.fetch("AGENTILE_STORE_TIMEOUT", PROCESS_TIMEOUT.to_s), exception: false) || PROCESS_TIMEOUT
      Open3.popen3(SCRUBBED_ENV, *@config.command, pgroup: true) do |stdin, stdout, stderr, wait|
        out_reader = Thread.new { stdout.read }
        err_reader = Thread.new { stderr.read }
        begin
          stdin.write(input)
        rescue Errno::EPIPE
          nil
        end
        stdin.close
        unless wait.join(limit)
          begin
            Process.kill("KILL", -wait.pid)
          rescue Errno::ESRCH
            nil
          end
          wait.join
          raise ConfigError, "store command #{@config.command.first(2).join(' ')} did not answer within #{limit.to_i}s"
        end
        [ out_reader.value.to_s, err_reader.value.to_s, wait.value ]
      end
    end

    def parse(res)
      text = res.body.to_s
      json = res.content_type.include?("json") || text.start_with?("{", "[", "\"") ? (JSON.parse(text) rescue text) : text
      json = json.strip if json.is_a?(String) && !res.content_type.include?("markdown")
      return json if (200..299).cover?(res.status)

      detail = truncate(json.is_a?(Hash) ? (json["detail"] || json["error"] || text) : text)
      raise ConfigError, "#{res.status} #{detail} — check AGENTILE_STORE_TOKEN/AGENTILE_PROJECTS_TOKEN" if res.status == 401
      raise Error, "#{res.status} #{detail}"
    end

    # A non-JSON error body (an HTML 500 page, a proxy's plaintext error, …)
    # can be arbitrarily large; keep stderr readable instead of dumping it whole.
    def truncate(text, max = 300)
      text = text.to_s
      text.length > max ? "#{text[0, max]}…" : text
    end
  end

  class Ops
    def initialize(config, client)
      @c = config
      @api = client
    end

    def identity(flag = nil)
      return flag.to_s unless flag.to_s.empty?
      return ENV["AGENTILE_RUNNER_ID"].to_s unless ENV["AGENTILE_RUNNER_ID"].to_s.empty?

      ENV["CLAUDE_SESSION_ID"].to_s
    end

    def model(flag = nil)
      [flag, ENV["AGENTILE_MODEL"]].each do |v|
        return v if v.is_a?(String) && !v.strip.empty?
      end
      nil
    end

    def active_run_for(slug, runner)
      runs = Array(@api.get(@api.project_path("/runs"), spec: slug, status: "active"))
      runs.find { |r| r["runner_id"] == runner } || runs.max_by { |r| r["started_at"].to_s }
    end

    def ensure_run(slug, runner, session, model = nil)
      active_run_for(slug, runner) ||
        @api.post(@api.project_path("/runs"), { spec: slug, runner_id: runner, session_id: session, model: model }.compact)
    end

    def require_spec!(flags, op)
      raise Error, "#{op} needs --spec <slug> — since 0.20.0 a run belongs to a spec" if flags["spec"].to_s.empty?

      flags["spec"].to_s
    end

    def run(op, positional, flags, sets)
      p = ->(rest) { @api.project_path(rest) }
      case op
      when "inbox_list" then @api.get(p["/inbox"], status: flags["status"])
      when "inbox_add"
        dup = flags["duplicate-of"]
        dup_type = flags["duplicate-of-type"] || (dup.nil? ? nil : (dup.to_s.match?(/\A\d+\z/) ? "inbox" : "spec"))
        body = { text: positional[0].to_s, title: flags["title"], kind: flags["type"], serves: flags["serves"],
                 suggested_kind: flags["suggested-kind"], duplicate_of: dup, duplicate_of_type: dup_type,
                 duplicate_probability: flags["duplicate-probability"] }.compact
        res = begin
          @api.post(p["/inbox"], body)
        rescue Error => e
          # Store Protocol §12 G15: Agentile Projects takes only an inbox id as
          # duplicate_of, so a spec slug 404s. The duplicate note is advisory; the
          # stub is not — save it without the note rather than lose it.
          raise unless dup_type == "spec" && e.message.start_with?("404")

          warn "ag-store: the store would not record duplicate_of #{dup} (a spec); saved the stub without it"
          @api.post(p["/inbox"], body.except(:duplicate_of, :duplicate_of_type))
        end
        res.is_a?(Hash) ? res["id"] : res
      when "inbox_drop" then @api.post(p["/inbox/#{AgStore.enc(positional[0])}/drop"]); true
      when "inbox_assist" then @api.post(p["/inbox/assist"], { text: positional[0].to_s })
      when "inbox_shape"
        res = @api.post_markdown(p["/inbox/#{AgStore.enc(positional[0])}/shape"], $stdin.read)
        res.is_a?(Hash) ? res["slug"] : res
      when "spec_list" then @api.get(p["/specs"], status: flags["status"], pool: flags["pool"] || "active")
      when "spec_read" then @api.get(p["/specs/#{AgStore.enc(positional[0])}.md"])
      when "spec_create"
        res = @api.post_markdown(p["/specs"], $stdin.read)
        res.is_a?(Hash) ? res["slug"] : res
      when "spec_write" then @api.patch(p["/specs/#{AgStore.enc(positional[0])}"], sets.to_h { |k, v| [k, AgStore.coerce_list(k, v)] })
      when "rank" then @api.put(p["/specs/rank"], { slugs: positional })
      when "claim"
        body = { identity: positional[0].to_s, label: positional[1].to_s }
        unless positional[2].nil?
          begin
            body[:wip] = Integer(positional[2])
          rescue ArgumentError, TypeError
            raise Error, "claim: invalid wip #{positional[2].inspect} (must be an integer)"
          end
        end
        body[:slug] = flags["spec"] if flags["spec"]
        m = model(flags["model"])
        body[:model] = m if m
        res = @api.post(p["/specs/claim"], body)
        res.is_a?(Hash) ? res["result"] : res
      when "release" then @api.post(p["/specs/#{AgStore.enc(positional[0])}/release"])
      when "ship" then @api.post(p["/specs/#{AgStore.enc(positional[0])}/ship"])
      when "abandon"
        body = { reason: flags["reason"].to_s }
        body[:cascade] = AgStore.coerce_list("cascade", flags["cascade"]) if flags["cascade"]
        @api.post(p["/specs/#{AgStore.enc(positional[0])}/abandon"], body)
      when "promote"
        path = File.join(@c.dir, "specs", positional[0].to_s)
        FileUtils.mkdir_p(path)
        path
      when "deps" then @api.get(p["/specs/#{AgStore.enc(positional[0])}/deps"])
      when "dependents" then @api.get(p["/specs/#{AgStore.enc(positional[0])}/dependents"])
      when "map" then @api.get(p["/map"])
      when "flow" then positional[0].to_s.empty? ? @api.get(p["/flow"]) : @api.get(p["/flow/#{AgStore.enc(positional[0])}"])
      when "outcome_list" then @api.get(p["/outcomes"], status: flags["status"])
      when "outcome_read" then @api.get(p["/outcomes/#{AgStore.enc(positional[0])}.md"])
      when "outcome_create"
        res = @api.post_markdown(p["/outcomes"], $stdin.read)
        res.is_a?(Hash) ? res["slug"] : res
      when "outcome_write" then @api.patch(p["/outcomes/#{AgStore.enc(positional[0])}"], sets.to_h { |k, v| [k, AgStore.coerce_list(k, v)] })
      when "outcome_rank" then @api.put(p["/outcomes/rank"], { slugs: positional })
      when "outcome_achieve" then @api.post(p["/outcomes/#{AgStore.enc(positional[0])}/achieve"])
      when "outcome_abandon" then @api.post(p["/outcomes/#{AgStore.enc(positional[0])}/abandon"], { reason: flags["reason"].to_s })
      when "checkpoint_open"
        slug, reason = positional
        raise Error, "unknown checkpoint reason #{reason.inspect} (#{CHECKPOINT_REASONS.join('|')})" unless CHECKPOINT_REASONS.include?(reason.to_s)

        session = flags["session"].to_s.empty? ? ENV["CLAUDE_SESSION_ID"].to_s : flags["session"].to_s
        ask = $stdin.read.to_s.strip
        AgStore.ask_warnings(reason, ask).each { |m| warn "ag-store: warning: #{m}" }
        run = ensure_run(slug, identity, session, model(flags["model"]))
        res = @api.post(p["/runs/#{AgStore.enc(run['id'])}/checkpoints"],
                        { reason: reason, asked_by: flags["by"].to_s, session_id: session, ask: ask })
        res.is_a?(Hash) ? res["id"] : res
      when "checkpoint_list" then @api.get(p["/specs/#{AgStore.enc(positional[0])}/checkpoints"])
      when "checkpoint_open_count"
        Array(@api.get(p["/specs/#{AgStore.enc(positional[0])}/checkpoints"])).count { |c| c["status"].to_s != "answered" }
      when "checkpoint_answer"
        @api.post(p["/checkpoints/#{AgStore.enc(positional[0])}/answer"], { answer: $stdin.read.to_s.strip, by: flags["by"].to_s })
      when "run_event"
        event = positional[0].to_s
        raise Error, "unknown run event #{event.inspect} (#{RUN_EVENTS.join('|')})" unless RUN_EVENTS.include?(event)

        slug = require_spec!(flags, "run_event")
        run = ensure_run(slug, identity(flags["runner"]), ENV["CLAUDE_SESSION_ID"].to_s, model(flags["model"]))
        res = @api.post(p["/runs/#{AgStore.enc(run['id'])}/events"], { event: event, detail: flags["detail"].to_s })
        res.is_a?(Hash) ? res["last_event_at"] : res
      when "run_list" then @api.get(p["/runs"], spec: flags["spec"], status: flags["status"])
      when "run_close"
        slug = require_spec!(flags, "run_close")
        run = active_run_for(slug, identity(flags["runner"]))
        raise Error, "no active run for #{slug} — nothing to close" unless run

        @api.post(p["/runs/#{AgStore.enc(run['id'])}/close"], { detail: (flags["detail"].to_s.empty? ? "run closed" : flags["detail"].to_s) })
      when "brief_sync"
        md = @api.get(p["/brief"])
        path = File.join(@c.dir, "brief.md")
        FileUtils.mkdir_p(File.dirname(path))
        File.write(path, md.to_s)
        path
      when "brief_write"
        @api.put_markdown(p["/brief"], $stdin.read)
      when "whoami" then @api.get("/me")
      when "doctor"
        res = @api.get(p["/doctor"])
        if res.is_a?(Hash)
          # A store that predates the protocol's doctor fields is Agentile Projects at protocol 1 (§12, G10).
          res = { "protocol" => PROTOCOL, "store" => "agentile-projects", "capabilities" => [] }.merge(res)
          if res["protocol"].to_i > PROTOCOL
            raise ConfigError, "the store speaks Store Protocol #{res['protocol']}; this ag-store speaks #{PROTOCOL} — update the Agentile plugin"
          end

          res = res.merge(@c.transport == :http ? { "host" => @c.host } : { "command" => @c.command.join(" ") })
        end
        res
      else raise Error, "unknown op '#{op}'"
      end
    end
  end
end

op = ARGV[0]
abort "usage: ag-store <op> [args...] [--dir <agentile-dir>]" if op.nil?

rest, sets = AgStore.extract_sets(ARGV[1..])
positional, flags = AgStore.parse_flags(rest)
warn "ag-store: --store is obsolete since 0.20.0 (the store is chosen by `url` in .agentile/store.md) — ignoring it" if flags.key?("store")
warn "ag-store: --airtable-base is obsolete since 0.20.0 — ignoring it" if flags.key?("airtable-base")

begin
  config = AgStore::Config.new(flags)
  config.validate!(needs_project: !%w[whoami promote].include?(op), needs_network: op != "promote")
  result = AgStore::Ops.new(config, AgStore::Client.new(config)).run(op, positional, flags, sets)
  puts JSON.generate(result)
rescue AgStore::ConfigError => e
  warn "ag-store: #{e.message}"
  exit 2
rescue AgStore::Error => e
  warn "ag-store: #{e.message}"
  exit 1
end
