tests/suites/test_ruby_api.py

"""No-LLM acceptance for the installed Ruby API foundation."""

from __future__ import annotations

import json
import os
import subprocess
import time
from pathlib import Path

import pytest

pytestmark = pytest.mark.quick

from client import SocketClient, find_frame
from conftest import _write_offline_config, patch_config, start_daemon


REPO_ROOT = Path(__file__).resolve().parents[2]
RUBY = REPO_ROOT / "build" / "ez-agent-ruby"


@pytest.fixture
def exact_name_service_daemon(tmp_path, model_override):
    config_dir = tmp_path / "config"
    ez_config_dir = config_dir / "ez-agent"
    _write_offline_config(ez_config_dir)
    patch_config(
        ez_config_dir / "config.yaml",
        {
            "services": {
                "ruby-api": {
                    "path": "/must/not/execute",
                    "direct": True,
                    "tools": ["forbidden.ruby-policy"],
                }
            }
        },
    )
    yield from start_daemon(config_dir=config_dir, tmp_path=tmp_path)


@pytest.mark.no_llm
def test_installed_ruby_api_connects_without_rubylib_or_rubygems(daemon, tmp_path):
    script = tmp_path / "ruby_api_acceptance.rb"
    script.write_text(
        """
require "json"
require "ez_agent/api"

EzAgent::API.connect(cwd: Dir.pwd) do |api|
  feature = $LOADED_FEATURES.find { |path| path.end_with?("/ez_agent/api.rb") }
  puts JSON.generate(
    protocol: EzAgent::API::PROTOCOL_VERSION,
    version: EzAgent::API::VERSION,
    connection_name: EzAgent::API::DEFAULT_CONNECTION_NAME,
    server_id: api.hello_ack.server_id,
    state_dir: api.hello_ack.state_dir,
    feature: feature,
    rubygems: defined?(Gem)
  )
end
""".strip()
    )
    home = tmp_path / "home"
    home.mkdir()
    env = os.environ.copy()
    env.pop("RUBYLIB", None)
    env.pop("RUBYOPT", None)
    env.pop("GEM_HOME", None)
    env.pop("GEM_PATH", None)
    env["HOME"] = str(home)
    env["XDG_DATA_HOME"] = str(tmp_path / "ruby-data")

    result = subprocess.run(
        [str(RUBY), "--disable-gems", str(script)],
        cwd=tmp_path,
        env=env,
        capture_output=True,
        text=True,
        timeout=20,
    )
    assert result.returncode == 0, result.stderr
    payload = json.loads(result.stdout)
    assert payload["protocol"] == 1
    assert payload["version"] == "0.4.0"
    assert payload["connection_name"] == "ruby-api"
    assert payload["server_id"] == "ez1"
    assert payload["state_dir"] == str(daemon["state_dir"] / "ez-agent")
    assert "/lib/ruby/vendor_ruby/3.4.0/ez_agent/api.rb" in payload["feature"]
    assert payload["rubygems"] is None

    # Ruby block cleanup closes only its own connection; it never stops the daemon.
    with SocketClient(daemon["socket_path"]) as client:
        ack = client.hello(name="ruby-api-post-close")
        assert ack is not None and ack["type"] == "hello_ack"


@pytest.mark.no_llm
def test_ruby_client_name_is_allowed_and_does_not_claim_direct_service_placeholder(
    exact_name_service_daemon, tmp_path
):
    script = tmp_path / "exact_name_service.rb"
    script.write_text(
        """
require "json"
require "ez_agent/api"
EzAgent::API.connect do |api|
  current = api.connections.list.find { |connection| connection.id == api.hello_ack.connection_id }
  puts JSON.generate(
    config_error: api.hello_ack.config_error,
    connection_id: api.hello_ack.connection_id,
    current_connection: current && {
      id: current.id, name: current.name, tools: current.tools
    }
  )
end
""".strip()
    )
    result = subprocess.run(
        [str(RUBY), "--disable-gems", str(script)],
        cwd=tmp_path,
        env=os.environ.copy(),
        capture_output=True,
        text=True,
        timeout=20,
    )
    assert result.returncode == 0, result.stderr
    payload = json.loads(result.stdout)
    assert payload["config_error"] in (None, "")
    assert payload["connection_id"]
    assert payload["current_connection"] == {
        "id": payload["connection_id"],
        "name": "ruby-api",
        "tools": [],
    }

    # The direct-service recipe remains a lazy-spawn placeholder. Ruby's
    # display name cannot make its connection own the configured capability.
    with SocketClient(exact_name_service_daemon["socket_path"]) as client:
        ack = client.hello(name="exact-name-audit")
        assert ack is not None and ack["type"] == "hello_ack"
        frames = client.send_and_recv(
            {"type": "list_tools", "request_id": "exact-name-tools"},
            done_types={"tool_list"},
            timeout=5,
        )
        tools = find_frame(frames, "tool_list")
        assert tools is not None
        assert "forbidden.ruby-policy" in tools.get("tools", [])


@pytest.mark.no_llm
def test_plain_ruby_api_persistence_and_typed_release_surface(daemon, tmp_path):
    script = tmp_path / "plain_ruby_operations.rb"
    script.write_text(
        """
require "json"
require "ez_agent/api"

EzAgent::API.connect(cwd: Dir.pwd) do |api|
  created = api.sessions.create(name: "plain-ruby-api", cwd: Dir.pwd)
  api.metadata.update(
    created.leaf_id,
    set: {"session_origin" => "plain_ruby_api", "e2e_marker" => "ruby2"}
  )
  api.config.set(created.leaf_id, "active_tools", JSON.generate([]))
  api.turns.create_virtual_root(
    created.leaf_id,
    reason: "plain Ruby API no-LLM fixture",
    pending_turns: [
      EzAgent::API::PendingTurn.text("question", kind: "user"),
      EzAgent::API::PendingTurn.text(
        "canonical answer", kind: "assistant", content_type: "markdown"
      )
    ]
  )

  stats = api.sessions.stats(created.leaf_id)
  history = api.turns.canonical_history(created.leaf_id)
  forked = api.sessions.fork(history.last.id)
  renamed = api.sessions.rename(created.leaf_id, "plain-ruby-api-renamed")
  queued = api.sessions.queued(created.leaf_id)
  tools = api.tools.list(leaf_id: created.leaf_id)
  tool_info = api.tools.info(names: tools.first(1), leaf_id: created.leaf_id)
  plugins = api.plugins.list(leaf_id: created.leaf_id)
  providers = api.providers.list(leaf_id: created.leaf_id)
  connections = api.connections.list(leaf_id: created.leaf_id)
  filetypes = api.filetypes.supported
  disposable = api.sessions.create(name: "ruby-api-delete-contract", cwd: Dir.pwd)
  deleted = api.sessions.delete(disposable.leaf_id)
  listed = api.sessions.list(
    cwd: Dir.pwd,
    metadata_keys: ["session_origin", "e2e_marker"]
  ).find { |leaf| leaf.id == created.leaf_id }

  puts JSON.generate(
    leaf_id: created.leaf_id,
    root_id: created.root_id,
    fork_leaf_id: forked.leaf_id,
    stats_state: stats.state,
    runtime_present: !stats.runtime.nil?,
    outcome_reason: stats.runtime&.outcome&.reason,
    history: history.map { |turn| [turn.kind, turn.content, turn.state] },
    metadata: listed.metadata,
    renamed: renamed.name,
    queued_count: queued.length,
    tools: tools,
    tool_info_names: tool_info.map(&:name),
    plugins: plugins,
    provider_names: providers.map(&:name),
    current_connection: connections.any? { |connection| connection.name == "ruby-api" },
    filetypes: filetypes,
    deleted_leaf_id: deleted.leaf_id,
    workflow_loaded: $LOADED_FEATURES.any? { |path| path.include?("ez_agent/workflow") }
  )
end
""".strip()
    )
    env = os.environ.copy()
    env.pop("RUBYLIB", None)
    env.pop("RUBYOPT", None)
    env.pop("GEM_HOME", None)
    env.pop("GEM_PATH", None)

    result = subprocess.run(
        [str(RUBY), "--disable-gems", str(script)],
        cwd=tmp_path,
        env=env,
        capture_output=True,
        text=True,
        timeout=30,
    )
    assert result.returncode == 0, result.stderr
    payload = json.loads(result.stdout)
    assert payload["leaf_id"].startswith("l_")
    assert payload["root_id"].startswith("r_")
    assert payload["fork_leaf_id"].startswith("l_")
    assert payload["fork_leaf_id"] != payload["leaf_id"]
    assert payload["stats_state"] == "idle"
    assert payload["runtime_present"] is False
    assert payload["outcome_reason"] is None
    assert payload["history"] == [
        ["virtual_root", "plain Ruby API no-LLM fixture", "sent"],
        ["user", "question", "sent"],
        ["assistant", "canonical answer", "sent"],
    ]
    assert payload["metadata"] == {
        "e2e_marker": "ruby2",
        "session_origin": "plain_ruby_api",
    }
    assert payload["renamed"] == "plain-ruby-api-renamed"
    assert payload["queued_count"] == 0
    assert payload["tools"]
    assert payload["tool_info_names"] == payload["tools"][:1]
    assert isinstance(payload["plugins"], list)
    assert payload["provider_names"]
    assert payload["current_connection"] is True
    assert payload["filetypes"] == ["image/*", "application/pdf"]
    assert payload["deleted_leaf_id"].startswith("l_")
    assert payload["workflow_loaded"] is False

    # Both leaves remain service-visible after the Ruby socket has closed.
    with SocketClient(daemon["socket_path"]) as client:
        client.hello(name="ruby2-persistence-audit")
        frames = client.send_and_recv(
            {
                "type": "list_leaves",
                "cwd": str(tmp_path),
                "metadata_keys": ["e2e_marker"],
                "request_id": "ruby2-persisted",
            },
            done_types={"leaf_list", "error"},
            timeout=5,
        )
        leaf_list = find_frame(frames, "leaf_list")
        assert leaf_list is not None
        ids = {leaf["id"] for leaf in leaf_list["leaves"]}
        assert payload["leaf_id"] in ids
        assert payload["fork_leaf_id"] in ids
        assert payload["deleted_leaf_id"] not in ids


@pytest.mark.no_llm
def test_plain_ruby_api_provides_capabilities_over_real_daemon(daemon, tmp_path):
    script = tmp_path / "ruby_capability_provider.rb"
    script.write_text(
        """
require "json"
require "ez_agent/api"

STDOUT.sync = true
EzAgent::API.connect(provider_workers: 2, provider_heartbeat_interval: 0.1) do |api|
  # One startup batch, so the whole capability set arrives in one announce.
  macro, tool, plugin, versionless = api.capabilities.batch do
    [
      api.macros.provide(
        "ruby.e2e.echo",
        description: "Ordinary non-workflow Ruby provider fixture",
        version: "ruby-e2e-v1",
        triggers: ["custom.e2e.trigger"]
      ) { |call| call.success("ruby-provider:#{call.param_string}:#{call.class.name}") },
      api.tools.provide("ruby.e2e.tool", description: "Ruby tool") { |call| call.error("unused") },
      api.plugins.provide("ruby.e2e.plugin", description: "Ruby plugin") { |call| call.error },
      api.macros.provide(
        "ruby.e2e.versionless",
        description: "Ruby versionless macro fixture",
        triggers: ["custom.e2e.versionless"]
      ) { |call| call.success("versionless:#{call.param_string}") }
    ]
  end
  duplicate = begin
    api.macros.provide("ruby.e2e.echo") { "never" }
    nil
  rescue EzAgent::API::RegistrationCollisionError => error
    {kind: error.kind, name: error.name}
  end
  puts JSON.generate(
    ready: true,
    tool: tool.to_h,
    plugin: plugin.to_h,
    macro: macro.to_h,
    versionless: versionless.to_h,
    duplicate: duplicate,
    closed: api.closed?
  )
  # Released only once the daemon has already answered metadata for the batch,
  # so this later announce arrives with its category already satisfied.
  STDIN.gets
  late = api.macros.provide(
    "ruby.e2e.late",
    description: "Ruby late macro fixture",
    triggers: ["custom.e2e.late"]
  ) do |call|
    call.success("late:#{call.param_string}")
  end
  puts JSON.generate(late: late.to_h)
  STDIN.gets
end
""".strip()
    )
    env = os.environ.copy()
    env.pop("RUBYLIB", None)
    env.pop("RUBYOPT", None)
    env.pop("GEM_HOME", None)
    env.pop("GEM_PATH", None)
    provider = subprocess.Popen(
        [str(RUBY), "--disable-gems", str(script)],
        cwd=tmp_path,
        env=env,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    try:
        import select

        readable, _, _ = select.select([provider.stdout], [], [], 10)
        assert readable, "Ruby provider did not return from provide_*"
        ready = json.loads(provider.stdout.readline())
        assert ready["ready"] is True
        assert ready["tool"] == {"name": "ruby.e2e.tool", "description": "Ruby tool"}
        assert ready["plugin"] == {
            "name": "ruby.e2e.plugin",
            "description": "Ruby plugin",
        }
        assert ready["macro"] == {
            "name": "ruby.e2e.echo",
            "description": "Ordinary non-workflow Ruby provider fixture",
            "version": "ruby-e2e-v1",
            "triggers": ["custom.e2e.trigger"],
        }
        assert ready["versionless"] == {
            "name": "ruby.e2e.versionless",
            "description": "Ruby versionless macro fixture",
            "triggers": ["custom.e2e.versionless"],
        }
        assert "version" not in ready["versionless"]
        assert ready["duplicate"] == {
            "kind": "macro",
            "name": "ruby.e2e.echo",
        }
        assert ready["closed"] is False

        with SocketClient(daemon["socket_path"]) as client:
            client.hello(name="ruby-provider-e2e-caller")
            capabilities_visible = False
            for attempt in range(100):
                tool_frames = client.send_and_recv(
                    {"type": "list_tools", "request_id": f"ruby-tools-{attempt}"},
                    done_types={"tool_list", "error"},
                    timeout=5,
                )
                plugin_frames = client.send_and_recv(
                    {"type": "list_plugins", "request_id": f"ruby-plugins-{attempt}"},
                    done_types={"plugin_list", "error"},
                    timeout=5,
                )
                tools = find_frame(tool_frames, "tool_list")["tools"]
                plugins = find_frame(plugin_frames, "plugin_list")["plugins"]
                capabilities_visible = (
                    "ruby.e2e.tool" in tools and "ruby.e2e.plugin" in plugins
                )
                if capabilities_visible:
                    break
                time.sleep(0.01)
            assert capabilities_visible, (tools, plugins)

            metadata = {}
            for attempt in range(100):
                frames = client.send_and_recv(
                    {"type": "list_macros", "request_id": f"ruby-metadata-{attempt}"},
                    done_types={"macro_list", "error"},
                    timeout=5,
                )
                listed = find_frame(frames, "macro_list")
                metadata = {
                    macro["name"]: macro
                    for macro in listed["macros"]
                    if macro["name"] in {"ruby.e2e.echo", "ruby.e2e.versionless"}
                }
                if (
                    metadata.get("ruby.e2e.echo", {}).get("triggers")
                    == ["custom.e2e.trigger"]
                    and metadata.get("ruby.e2e.versionless", {}).get("triggers")
                    == ["custom.e2e.versionless"]
                ):
                    break
                time.sleep(0.01)
            explicit = metadata["ruby.e2e.echo"]
            assert explicit["triggers"] == ["custom.e2e.trigger"]
            assert explicit["version"] == "ruby-e2e-v1"
            versionless = metadata["ruby.e2e.versionless"]
            assert versionless["triggers"] == ["custom.e2e.versionless"]
            assert "version" not in versionless
            # Only now, with metadata for the batch already delivered, release
            # the later registration. A capability introduced by an announce
            # that arrives after its category was satisfied must still have its
            # metadata fetched rather than staying permanently unresolved.
            provider.stdin.write("late\n")
            provider.stdin.flush()
            late_ready = json.loads(provider.stdout.readline())
            assert late_ready["late"] == {
                "name": "ruby.e2e.late",
                "description": "Ruby late macro fixture",
                "triggers": ["custom.e2e.late"],
            }
            late = {}
            for attempt in range(200):
                frames = client.send_and_recv(
                    {"type": "list_macros", "request_id": f"ruby-late-{attempt}"},
                    done_types={"macro_list", "error"},
                    timeout=5,
                )
                late = next(
                    (
                        macro
                        for macro in find_frame(frames, "macro_list")["macros"]
                        if macro["name"] == "ruby.e2e.late"
                    ),
                    {},
                )
                if late.get("triggers") == ["custom.e2e.late"]:
                    break
                time.sleep(0.01)
            assert late.get("triggers") == ["custom.e2e.late"], late
            assert late["description"] == "Ruby late macro fixture"

            frames = client.send_and_recv(
                {
                    "type": "macro_call",
                    "macro_name": "ruby.e2e.echo",
                    "param_string": "hello",
                    "request_id": "ruby-provider-call",
                },
                done_types={"macro_result", "error"},
                timeout=5,
            )
            result = find_frame(frames, "macro_result")
            assert result is not None, frames
            assert result["is_error"] is False
            assert result["result"] == (
                "ruby-provider:hello:EzAgent::API::MacroProviderCall"
            )
            assert result["macro_call_id"].startswith("mc_")
    finally:
        if provider.stdin and not provider.stdin.closed:
            provider.stdin.write("stop\n")
            provider.stdin.flush()
        stdout, stderr = provider.communicate(timeout=10)
        assert provider.returncode == 0, stderr + stdout

    # Closing the provider releases all runtime capabilities from the daemon.
    with SocketClient(daemon["socket_path"]) as client:
        client.hello(name="ruby-provider-e2e-audit")
        tool_frames = client.send_and_recv(
            {"type": "list_tools", "request_id": "ruby-tools-after-close"},
            done_types={"tool_list", "error"},
            timeout=5,
        )
        plugin_frames = client.send_and_recv(
            {"type": "list_plugins", "request_id": "ruby-plugins-after-close"},
            done_types={"plugin_list", "error"},
            timeout=5,
        )
        macro_frames = client.send_and_recv(
            {"type": "list_macros", "request_id": "ruby-macros-after-close"},
            done_types={"macro_list", "error"},
            timeout=5,
        )
        assert "ruby.e2e.tool" not in find_frame(tool_frames, "tool_list")["tools"]
        assert "ruby.e2e.plugin" not in find_frame(plugin_frames, "plugin_list")["plugins"]
        macros = {macro["name"] for macro in find_frame(macro_frames, "macro_list")["macros"]}
        assert "ruby.e2e.echo" not in macros
        assert "ruby.e2e.versionless" not in macros
        assert "ruby.e2e.late" not in macros