Class: Agent::Lock::Facade

Inherits:
Object
  • Object
show all
Defined in:
lib/agent/lock/facade.rb,
lib/agent/lock/facade/memo.rb,
lib/agent/lock/facade/async.rb,
lib/agent/lock/facade/backend.rb,
lib/agent/lock/facade/refusal.rb,
lib/agent/lock/facade/session.rb,
lib/agent/lock/facade/strategies.rb

Overview

Every alock command as a method, run in this process, so a caller pays for no new Ruby process per call. (git and ps still run, as they do under the CLI, to find the checkout and check holders.)

One facade is one locker. It picks its backend when it is built and keeps it, so every thread calling it takes locks in the same store. A second facade with another redis_url is a separate locker. Building one never touches local or distributed.

Thread-safe: a facade is frozen, and each call builds its own Manager, so threads share nothing but the store, whose mutex serializes the writes.

A lock method returns the Manager::Result on success. Where the CLI would print a refusal on stderr, it raises Refused, whose result is the same Manager::Result. :not_found from #release, #break_lock and #resume is returned, although the CLI exits 1 on it: nothing was there, so nothing was refused.

Every lock method also takes these keywords, which override the facade's defaults for that one call:

  • dir: [String] a directory inside the checkout (default: the current one)
  • agent_id: [String] who holds the lock
  • parent_id: [String, false] that holder's parent session; false for none
  • stale_minutes: [Integer] when an unverifiable lock counts as stale
  • session_name: [String] the session's name, tied to no process

The checkout's backend marker binds a facade just as it binds alock: a facade claims a virgin checkout for its backend, and raises Store::Mismatch in one already claimed for the other, so a facade and the CLI can never take the same scope in two stores.

async: true adds #async, which runs any lock method on concurrent-ruby's I/O pool and returns a Concurrent::Promises::Future: value! is the result or re-raises, value is nil when the call raised and reason holds why. Arguments, keywords and blocks pass through as on a direct call, and direct calls stay synchronous. concurrent-ruby is not a dependency of this gem; add it to the Gemfile to use this.

Examples:

File store, signed by a sub-agent

locks = Agent::Lock.local
locks.acquire("lib/**", "rewriting billing", agent_id: "luke-backend")

Redis, falling back to the file store when it does not answer

locks = Agent::Lock::Facade.new(
  strategies: %w[redis file],
  redis_url: ENV.fetch("REDIS_URL", "redis://127.0.0.1:6379/0")
)

Defined Under Namespace

Modules: Refusal, Strategies Classes: Async, Backend, Memo, Session

Constant Summary collapse

DEFAULT_STRATEGIES =

Tried in this order when the caller does not pass strategies.

%w[redis file].freeze
DEFAULT_REDIS_URL =

Used when redis_url is omitted and neither AGENT_LOCK_REDIS_URL nor REDIS_URL is set. It is the local Redis alock itself tries, by the same constant, so the two cannot drift apart again: this was redis://localhost:6379, a second spelling of the same server.

Store::RedisStore::LOCAL_URL

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(strategies: DEFAULT_STRATEGIES, redis_url: nil, async: false, **defaults) ⇒ Facade

Returns a new instance of Facade.

Parameters:

  • strategies (Array<String, Symbol>) (defaults to: DEFAULT_STRATEGIES) —

    backends to try, in order: redis, and file (or filesystem)

  • redis_url (String, nil) (defaults to: nil) —

    defaults as redis_url says: AGENT_LOCK_REDIS_URL, then REDIS_URL, then DEFAULT_REDIS_URL

  • async (Boolean) (defaults to: false) —

    offer #async; needs the concurrent-ruby gem

  • defaults (Hash) —

    what a call uses when it does not say:

Options Hash (**defaults):

  • :agent_id (String) —

    signs locks when a call does not name its own

  • :parent_id (String, false) —

    that holder's parent, likewise. false says it has none: a top-level service that names itself is otherwise the child of whatever started it, and is not blocked by that session's locks

  • :stale_minutes (Integer) —

    nil reads AGENT_LOCK_STALE_MINUTES

  • :holder (Symbol) —

    :process (default) ties a lock's liveness to this Ruby process, so locks left by a crashed host are reaped; :session ties it to the first non-shell ancestor, as alock does

  • :session_name (String) —

    the session's name, such as a plan id, in place of CLAUDE_SESSION_ID and the fingerprint, and in place of holder:. Its locks are tied to no process: they survive a restart and lapse when untouched for stale_minutes

Raises:

  • (RedisUnavailableError) —

    when no strategy but redis is left and it does not answer

  • (ArgumentError) —

    when strategies is empty or names an unknown backend, holder is not :process or :session or is given beside session_name, or a default is not one of those five

  • (LoadError) —

    when async is true and concurrent-ruby is not installed



111
112
113
114
115
116
# File 'lib/agent/lock/facade.rb', line 111

def initialize(strategies: DEFAULT_STRATEGIES, redis_url: nil, async: false, **defaults)
  @backend = Backend.new(strategies:, redis_url: Facade.redis_url(redis_url))
  @session = Session.new(@backend, **defaults)
  @async = async ? Async.tap(&:load!).new(self) : nil
  freeze
end

Class Method Details

.redis_url(redis_url = nil) ⇒ String

The Redis a facade uses, by the rule alock follows: what the caller named, then AGENT_LOCK_REDIS_URL, then REDIS_URL.

A blank REDIS_URL counts as unset, as it does for alock (Store::RedisStore.candidate_urls). Taken for a URL, REDIS_URL="" sent a facade to the file store beside a local Redis that alock went on to use, so the two could claim one new checkout for different backends.

Parameters:

  • redis_url (String, nil) (defaults to: nil) —

    the caller's

Returns:

  • (String)


82
83
84
85
# File 'lib/agent/lock/facade.rb', line 82

def self.redis_url(redis_url = nil)
  ambient = ENV.fetch("REDIS_URL", "").strip
  redis_url || Store.named_redis_url || (ambient.empty? ? DEFAULT_REDIS_URL : ambient)
end

Instance Method Details

#acquire(scope, intent = nil, enforce: false, allow_wide: false, **session) {|result| ... } ⇒ Manager::Result, Object

alock acquire: claim a scope before writing in it.

With a block, yields the Manager::Result and returns the block's value. The lock is released afterwards only when this call took it (:acquired). :already_mine yields and leaves the lock you already held, so a nested block does not drop the outer one. A refusal raises before the block runs. An exception from the block releases, then propagates. When that release is itself refused (somebody broke the lock and took the scope while the block ran), the block's exception still wins: replacing it with the release's Refused hid the bug the caller actually had.

Parameters:

  • scope (String) —

    a path, a directory, or a glob such as lib/**

  • intent (String, nil) (defaults to: nil) —

    what the holder is about to do

  • enforce (Boolean) (defaults to: false) —

    also freeze the matched files (macOS only)

  • allow_wide (Boolean) (defaults to: false) —

    let enforce freeze more than Agent::Lock::Freeze::LIMIT files

  • session (Hash) —

    dir:, agent_id:, parent_id:, stale_minutes:, session_name:

Yield Parameters:

Returns:

  • (Manager::Result) —

    without a block: :acquired, or :already_mine

  • (Object) —

    with a block: the block's value

Raises:

  • (Refused) —

    held by another agent, interrupted work, or exactly your parent's scope

  • (Scope::Invalid) —

    when the scope is empty or outside the checkout

  • (Freeze::TooBroad) —

    when enforce exceeds the limit without allow_wide



159
160
161
162
163
164
165
166
167
168
# File 'lib/agent/lock/facade.rb', line 159

def acquire(scope, intent = nil, enforce: false, allow_wide: false, **session)
  result = Refusal.check!(
    @session.manager(**session).acquire(scope, intent: intent || "unspecified", enforce:, wide: allow_wide),
    scope:
  )
  return result unless block_given?
  return yield(result) unless result.status == :acquired

  within(scope, session) { yield result }
end

#async ⇒ Async

The lock methods again, each returning a future instead of waiting.

Examples:

locks = Agent::Lock::Facade.new(strategies: %w[file], async: true)
future = locks.async.acquire("lib/**", "rewriting billing", agent_id: "luke-backend")
future.value!.status # => :acquired

Returns:

Raises:

  • (ArgumentError) —

    when the facade was built without async: true



133
# File 'lib/agent/lock/facade.rb', line 133

def async = @async || raise(ArgumentError, "build the facade with async: true to call #async")

#backend_name ⇒ String

Returns "redis" or "file", chosen once at construction.

Returns:

  • (String) —

    "redis" or "file", chosen once at construction



119
# File 'lib/agent/lock/facade.rb', line 119

def backend_name = @backend.name

#break_lock(scope, **session) ⇒ Manager::Result

alock break: drop somebody else's lock. Announce it first. Never raises a refusal: breaking a free scope returns :not_found.

Parameters:

  • scope (String)
  • session (Hash) —

    dir:, agent_id:, parent_id:, stale_minutes:, session_name:

Returns:



216
# File 'lib/agent/lock/facade.rb', line 216

def break_lock(scope, **session) = @session.manager(**session).break_lock(scope)

#check(scope, **session) ⇒ Manager::Result

alock check: may I write here?

Parameters:

  • scope (String)
  • session (Hash) —

    dir:, agent_id:, parent_id:, stale_minutes:, session_name:

Returns:

Raises:

  • (Refused) —

    when another agent holds an overlapping scope



186
# File 'lib/agent/lock/facade.rb', line 186

def check(scope, **session) = Refusal.check!(@session.manager(**session).check(scope), scope:)

#list(**session) ⇒ Manager::Result

alock list.

Parameters:

  • session (Hash) —

    dir:, agent_id:, parent_id:, stale_minutes:, session_name:

Returns:



193
# File 'lib/agent/lock/facade.rb', line 193

def list(**session) = @session.manager(**session).list

#mine(**session) ⇒ Manager::Result

alock mine.

Parameters:

  • session (Hash) —

    dir:, agent_id:, parent_id:, stale_minutes:, session_name:

Returns:



200
# File 'lib/agent/lock/facade.rb', line 200

def mine(**session) = @session.manager(**session).mine

#note(scope, text, **session) ⇒ Manager::Result

alock note: leave a note on a lock you hold.

Parameters:

  • scope (String)
  • text (String)
  • session (Hash) —

    dir:, agent_id:, parent_id:, stale_minutes:, session_name:

Returns:

Raises:

  • (Refused) —

    when nothing is locked there, or another agent holds it



226
227
228
# File 'lib/agent/lock/facade.rb', line 226

def note(scope, text, **session)
  Refusal.check!(@session.manager(**session).note(scope, text), scope:, also: %i[not_found])
end

#redis_url ⇒ String

Returns the Redis URL this facade was given, used or not.

Returns:

  • (String) —

    the Redis URL this facade was given, used or not



122
# File 'lib/agent/lock/facade.rb', line 122

def redis_url = @backend.redis_url

#release(scope, **session) ⇒ Manager::Result

alock release.

Parameters:

  • scope (String)
  • session (Hash) —

    dir:, agent_id:, parent_id:, stale_minutes:, session_name:

Returns:

  • (Manager::Result) —

    :released, or :not_found when nothing is locked there

Raises:

  • (Refused) —

    when another agent holds it



177
# File 'lib/agent/lock/facade.rb', line 177

def release(scope, **session) = Refusal.check!(@session.manager(**session).release(scope), scope:)

#release_all(**session) ⇒ Manager::Result

alock release-all.

Parameters:

  • session (Hash) —

    dir:, agent_id:, parent_id:, stale_minutes:, session_name:

Returns:



207
# File 'lib/agent/lock/facade.rb', line 207

def release_all(**session) = @session.manager(**session).release_all

#resume(scope, **session) ⇒ Manager::Result

alock resume: take back interrupted work, notes and all.

Parameters:

  • scope (String)
  • session (Hash) —

    dir:, agent_id:, parent_id:, stale_minutes:, session_name:

Returns:

  • (Manager::Result) —

    :resumed, or :not_found when there is nothing to resume

Raises:

  • (Refused) —

    when another agent holds an overlapping scope, or the interrupted work could not be moved onto this scope



238
# File 'lib/agent/lock/facade.rb', line 238

def resume(scope, **session) = Refusal.check!(@session.manager(**session).resume(scope), scope:)

#show_repo(repo = nil, dir: Dir.pwd, redis_url: nil) ⇒ Array<Store::RedisIndex::Lock>

alock show repo [owner/name]. Redis only, same as #show_repos.

Parameters:

  • repo (String, nil) (defaults to: nil) —

    owner/name, github.com/owner/name, or host/owner/name on another forge; nil for the checkout dir is in

  • dir (String) (defaults to: Dir.pwd) —

    the checkout whose origin remote names the repository when repo is nil

  • redis_url (String, nil) (defaults to: nil)

Returns:

Raises:

  • (Error) —

    when repo is a bare name, or is nil and dir is in no checkout with an origin remote

  • (Store::Unreachable) —

    when Redis does not answer



287
288
289
# File 'lib/agent/lock/facade.rb', line 287

def show_repo(repo = nil, dir: Dir.pwd, redis_url: nil)
  Store::RedisIndex.open(redis_url).locks(repo || Store::RedisIndex.slug_for(dir))
end

#show_repos(redis_url: nil) ⇒ Array<Store::RedisIndex::Repo>

alock show repos. Redis only: the file store keeps one checkout's locks and has no list of repositories.

Parameters:

  • redis_url (String, nil) (defaults to: nil) —

    that one Redis, with no fallback when given

Returns:

Raises:



274
# File 'lib/agent/lock/facade.rb', line 274

def show_repos(redis_url: nil) = Store::RedisIndex.open(redis_url).repos

#skills_install(into: nil, agent: nil, overwrite: false) ⇒ Skill::Result

alock skills install.

Parameters:

  • into (String, nil) (defaults to: nil) —

    skills directory; wins over agent when both are given

  • agent (String, nil) (defaults to: nil) —

    the CLI's --for: claude installs into ~/.claude/skills, anything else into ~/.agents/skills

  • overwrite (Boolean) (defaults to: false) —

    replace an installed copy that differs

Returns:

Raises:

  • (Refused) —

    when the installed copy differs, or is a symlink



259
260
261
# File 'lib/agent/lock/facade.rb', line 259

def skills_install(into: nil, agent: nil, overwrite: false)
  Refusal.check!(Skill.new(into: into || Skill.default_into(agent)).install(overwrite:))
end

#skills_path ⇒ String

alock skills path.

Returns:

  • (String) —

    the directory of the bundled skill



249
# File 'lib/agent/lock/facade.rb', line 249

def skills_path = Skill.source

#version ⇒ String

alock version.

Returns:



266
# File 'lib/agent/lock/facade.rb', line 266

def version = VERSION

#whoami(**session) ⇒ Identity

alock whoami: who a lock taken through this facade would name.

Parameters:

  • session (Hash) —

    agent_id:, parent_id:, session_name:

Returns:



244
# File 'lib/agent/lock/facade.rb', line 244

def whoami(**session) = @session.identity(**session)