README.md

EzAgent Ruby companion

The companion is part of the EzAgent repository.

ez-agent-ruby is a self-extracting, pure-Go Linux/amd64 launcher containing a curated static CRuby runtime. The payload is built from the exact, unpatched official CRuby 3.4.11 archive and the checksum-pinned cross-tools/musl-cross 20260515 x86_64 toolchain in runtime/sources.lock. Launcher installation, extraction, verification, and notice display perform no network access. The executed Ruby interpreter is not a network sandbox; Ruby programs can use available operating-system networking facilities.

Build and test

sh
1just test # lock/cache validation and lightweight Go tests; no payload required
2just test-ruby-source # fast EzAgent::API and Workflow source tests through an existing bundled interpreter
3just build # downloads verified inputs and assembles the runtime/payload/wrapper
4just build --force # rebuilds generated runtime state from verified archives
5just clean # removes generated wrapper/payload but preserves .build
6just clean-cache # explicitly removes downloaded, compiled, and staged cache state

The full build requires Linux x86_64 plus Go, curl, make, tar, gzip, xz, bzip2, awk, readelf, and standard POSIX utilities. It requires no sudo and uses no package manager. Downloaded archives, extracted toolchains, staged trees, generated payloads, and binaries remain under ignored .build/, cmd/ez-agent-ruby/payload.zip, and build/ paths. Extracted toolchain caches are keyed by release, target, and locked archive SHA-256 and become reusable only after identity validation and atomic publication of a success stamp. Ruby library sources live under lib/ and are copied separately into lib/ruby/vendor_ruby/3.4.0; editing them rebuilds the payload/wrapper but not CRuby. The test-ruby-source recipe uses a test-only load path so normal library iterations do not rebuild either artifact.

The installed standard-library-only libraries are require "ez_agent/api" for typed reusable service access, require "ez_agent/webfetch" for process-based HTTP(S) and WebSocket access through the standalone Go executable, and require "ez_agent/workflow" for the prepared append-only API. WebFetch does not load API or Workflow and does not implement HTTP, TLS, or RFC 6455. EzAgent::Workflow < EzAgent::WorkflowAgent; construction declares the initial graph without service interaction and eval freezes that shape while allowing only scheduler-owned on_done callbacks to append finite atomic tails. The former procedural open/session/run/command and reconciliation façade has no compatibility shim.

EzAgent::API::Connection.open(reader:, writer:, close: nil, name: "ruby-api", cwd: Dir.pwd, leaf_id: nil, ...) is the canonical initiating-client constructor. Caller-provided streams stay caller-owned unless close: supplies their once-only cleanup callback. The writer is protocol JSONL only and flushes every complete frame; reserve stdin/stdout for protocol traffic and write logs to stderr. API.connect is the local AF_UNIX adapter. Ruby supplies no listener, acceptor, server-side protocol implementation, or raw-frame public API. Shared daemon shutdown remains only under api.daemon.shutdown!.

CWD activity summaries

api.roots.cwds(timeout: ...) still returns a frozen array of CWD strings. api.roots.cwd_infos(timeout: ...) sends the same list_cwd request and returns a frozen array of EzAgent::API::CwdInfo values. Each value exposes cwd, leaf_count, active_leaf_count, and optional last_activity_at. Unknown fields remain accessible through [] and to_h; values and nested data are immutable. Missing or null cwd_infos from older peers yields an empty array, without inventing counts. Malformed collections or known field types raise DecodeError.

The daemon aligns summaries one-for-one with cwds in the same order. Only non-temporary leaves with a canonical turn contribute, including forks with inherited history. Active counts include running, aborting, and background leaves, but not idle or unloaded leaves. Unlike sessions.list(is_active: true), these summaries include background work. CWDs without qualifying leaves are excluded, even if a root or connection default still names them. Missing paths remain listed when they have qualifying leaves.

last_activity_at is an RFC3339 string, or nil when unavailable. Active CWDs use the current UTC time; otherwise the daemon uses the latest qualifying leaf update, without a root-timestamp fallback. Separate calls to cwds and cwd_infos are separate snapshots.

Workflow

Workflow composes typed API services. The root is a WorkflowAgent, and every explicit child, nested child, and fanout member uses the same recursive interface: agent, queue, fanout, queue_command, select, assert, and on_done. Only the root provides eval, root-level buffers, and lifecycle control. Agent declarations are lazy. Once admitted, an Agent has a stable leaf_id; its head_leaf_id advances as later declaration-ordered queues and retries settle. Structural children always attach to the owner's stable leaf. Generation zero runs on the stable leaf, while later generations and retries are sibling leaves grouped beneath it. Conversation forks still follow the selected prior head or captured source tip.

Version-3 replay identity contains the Workflow ID/nonce, typed structural Agent path, receiver-local operation key, generation, and try. It excludes titles, fanout tags, prompts, dependencies, profiles, tools, plugins, callbacks, repairs, and buffers. Exact stable and staged identity checks fail closed; duplicate or ambiguous candidates are errors. Change an edited key and affected downstream keys, or change the Workflow nonce for a fresh root. Commands rerun whenever reached, but inline, external, result-derived, merged, and command-output buffers do not force model work fresh. Prompt and result-derived buffer blocks remain lazy until fresh issue. Workflow stores no durable ledger or evaluator checkpoint, and replayed model records do not recreate filesystem side effects. Serialize shared-worktree writers, use command dispositions plus assertions for intended artifacts and tests, and version keys or nonce when mutations must be reproduced.

Fresh model completion follows correlated terminal events and protected trigger signals. There is no Workflow model-duration timeout; a 30-second stats sweep is only missed-signal recovery. retries: is a hard extra-occurrence bound; on_error: may authorize eligible live model errors, historical model errors, or exhausted structured-output errors without parsing provider prose. Optional on_success: observes the final record before operation on_done. The retry stays inside one logical query and preserves completed branches and successful fanout siblings. Abort/cancellation and setup, identity, preparation, dependency, and transport-integrity failures remain ineligible. Structured repairs correct one response format in the same conversation/occurrence and are not business retries. Each Agent's queues form one automatic conversation lineage. A later queue waits for the prior generation and forks its validated terminal tip, including an eligible failed model or exhausted structured-output tip and the final post-compaction tip. A separate fallback query stays on that Agent but has its own key and profile. The original disposition remains failed. Sources without trustworthy terminal model tips are rejected before forking.

max_parallel bounds active model queries; commands use a separate sequential lane. A fanout aggregate is a no-leaf dependency handle over exactly its ordered initial member queries. fanout.members is a frozen Array of real Agents with initial_query and the full recursive interface. The fanout itself is an ordered Enumerable; use fanout[index], each, size, or length to access members. Fanout name: supplies the base title; optional item tag: values, or one-based index fallbacks, produce names such as Reviewer - security and Reviewer - 2. Titles and tags are presentation-only and are not inserted into prompts.

Results are immutable per-operation dispositions; WorkflowResult#[] accepts operation handles and rejects Agent handles. Use a queue's query handle, the fanout aggregate, or fanout[index].initial_query for member lookup. WorkflowResult#success?, #recovered?, and #clean? distinguish unresolved failure, recovered query attempts, and first-attempt success. Fanout aggregate dispositions retain ordered member dispositions and cannot silently succeed with an unresolved member. WorkflowResult#print_summary prints a deterministic one-line state count. Post-create setup/config/profile/verification service failures are fatal to later admissions; ordinary provider/query failures settle their branch while independent work drains. Closing requests cancellation of evaluator-owned work. A borrowed API remains caller-owned and supports one Workflow.

Generated scripts are ordinary previewable files. An advertised cache_dir is an expiring artifact location, not durable workflow state, and its absence must never be replaced by a guessed path. See docs/ez-agent-ruby/lib/ez_agent/workflow.md and the bundled Workflow skill for the complete public contract.

The Ruby archive is extracted without ownership or permission restoration and configured out of tree; the build does not patch or edit its source. CRuby is configured with --disable-shared, --enable-load-relative, and --with-static-linked-ext. Because static musl provides dladdr as a weak failing stub while unmodified CRuby uses it to locate its executable, the build externally links the companion-owned runtime/static-dladdr.c implementation that resolves the image through /proc/self/exe; no CRuby source file is changed. The runtime includes date, time, pathname, zlib, and yaml through Psych. The native zlib and libyaml dependencies are statically linked from checksum-pinned sources in runtime/sources.lock; host installations are not required. zlib uses the permissive zlib license, and Psych and libyaml use MIT licenses. Their notices ship alongside CRuby's notices, with native dependency versions and source hashes recorded in the payload provenance. OpenSSL and readline extensions are excluded. The profile rejects an ELF interpreter, DT_NEEDED entries, and runtime .so modules, then exercises date/time parsing, path normalization, zlib/gzip round trips, YAML safe loading and dumping, JSON, digest/SHA-256, AF_UNIX sockets, Open3, threads, pipes, Process.spawn, require_relative, and relocated RbConfig/load paths in an empty Ruby environment. The same scrubbed relocation profile loads an installed vendor-path helper, require "ez_agent/api", require "ez_agent/webfetch", and require "ez_agent/workflow" without RUBYLIB or RubyGems.

Launcher lifecycle

State is a launcher-owned strict JSON document at ${XDG_DATA_HOME:-$HOME/.local/share}/ez-agent/ez-agent-ruby.json. New state is written as 0600; existing state may be read-only or readable by others, but not writable by others. Duplicate keys, unknown fields or sections, missing sections, and trailing values are rejected. Valid Linux paths are JSON-escaped and round-trip safely.

Each runtime is content-addressed by the embedded payload digest and installed atomically below the selected data home. The schema-1 completion manifest contains the release identity and sorted path/mode/size/SHA-256 file set. Embedded payloads must match the current release. Pruning also accepts historical schema-1 versions and revisions while retaining strict JSON, path, size, hash, target and tree checks.

Extraction respects the process umask. Reuse and verification allow tighter permissions and read-only files, provided the owner can read all files and execute the required binaries. They reject symlinks, foreign-owned or group/other-writable content, privilege-changing executable bits, missing or extra files, and changed contents. Valid reuse neither widens permissions nor requires a writer lock or an unchanged state rewrite.

The launcher strips Ruby and Bundler/RubyGems injection variables from both its execution probe and the final Ruby environment. It does not synthesize RUBYLIB or search for socket.so: CRuby's load-relative support and complete upstream-generated RbConfig relocate the tree from canonical bin/ruby.

--ez-runtime-prune removes only complete, checksum-valid sibling trees whose names have the launcher's 24-hex runtime-ID form, excluding the selected ID. It cannot determine whether another process is still using an old tree, so prune only after old processes are quiescent. Malformed, unrelated, symlink, foreign-owned, writable, and changed-during-quarantine entries are preserved.

Auto mode probes the preferred runtime and falls back on EACCES only to a secure $HOME/.local/bin, creating it if missing without changing existing permissions. Explicit homes never fall back. Verification checks the recorded selected runtime, including a fallback, unless an explicit home is supplied. Saving a different home clears the cached runtime selection. Existing base-path symlinks are resolved only when their resolved prefixes have safe ownership and permissions; symlinks remain forbidden inside managed state and runtime trees. Safe sticky ancestors are allowed beyond the system temporary directory.

Commands

  • --ez-help: launcher help
  • --ez-runtime-home PATH [--save] --ez-runtime-install: install the embedded runtime or reuse a valid existing installation
  • --ez-runtime-path / --ez-runtime-info: selected path and identity
  • --ez-runtime-verify: exact verification without repair
  • --ez-runtime-notices: install if needed and print all bundled notices, entirely offline
  • --ez-runtime-prune: remove valid old content-addressed runtimes

A leading Ruby --help or -h prints a short launcher preamble and then executes private CRuby's own help. Other arguments pass unchanged to Ruby.