Distributed Resource Locking for Agents

Gem agent-lock: alock CLI and Ruby Interface


agent-lock is a versatile advisory locking utility which works like a reservation system: it marks certain files, directories, or "glob" patterns as being "owned" temporarily by a particular client or an agent, so that another client that checks the advisory lock on a given file realizes that the files are being modified by another agent and perhaps switch to work on something else.

The system is advisory, meaning that agents (or clients) are supposed to both acquire the locks and query for the locks using the same mechanism. Most of the time, setting a lock on the folder or a file won't actually prevent you from writing to one.


Ruby coverage Gem Version yardoc

This is a Ruby Gem that provides both a CLI utility alock that supports advisory locks on files and folders with pluggable backends (redis and file system provided out of the box, with redis being the default if it's available locally or if $REDIS_URL is set and points to a working Redis), and a Ruby API to the same commands. The two are one locker: a Ruby process and the alock calls of the agents it starts see, block and release each other's locks. See A Ruby dispatcher and its alock agents.

[!NOTE]

Only the Redis backend is distributed. If two or more nodes (virtual servers, laptops, etc.) can reach the same Redis, set REDIS_URL on each machine to the same value. A lock taken with alock acquire, or with acquire from Ruby, is then seen, and refused, on every machine that checks out the same repository and branch.

This locking tool is meant for coding agents that share a project, whether they run on one machine or on several: with every machine pointed at one Redis, it is a distributed lock.

[!NOTE] OpenLanes uses agent-lock to keep the agents it runs from overwriting each other: its dispatcher locks through the Ruby API, and the agents it launches lock with alock. The gem has no dependency on it. Any harness, or a person with three terminals open, can use alock on its own.

See it run

Two agents and a sub-agent sharing one checkout through alock

Every command in that recording is real: demo/play.sh types it and runs this checkout's alock in a throwaway repository, with the subtitles and pauses written into the script. just demo records it again through VHS from demo/alock.tape, and just demo-play plays it in your own terminal.

What it is

agent-lock is a gem with one executable, alock (also installed as agent-lock). An agent runs alock acquire <scope> before it writes, and learns in one reply whether anybody else is working there: who, since when, and doing what. It works for separate sessions in one checkout, for the sub-agents of a single session, the harder case, and for agents on different machines working on one branch of one repository.

Git does not help here. Two agents on one branch and one working tree never produce a conflict: the second writer simply wins, and the first one's work is gone without an error anywhere. A lock stops that, but only if every writer can be named reliably, even though an agent harness runs each command in a brand new shell. Making that name stable, and keeping claims correct when several agents ask at the same moment, is most of what this gem does.

Who it is for

  • People running several coding agents at once (Claude Code, Codex, Cursor, a terminal of your own) in the same checkout.

  • Orchestrators that fan out sub-agents into one worktree, each taking a different part of it.

  • Harnesses that launch agents over a repository and need them to stay out of each other's way. A harness written in Ruby locks in-process and hands its agents the same store: see A Ruby dispatcher and its alock agents.

  • Teams of agents spread over several machines, each with its own clone of the repository, at any path. Set REDIS_URL to the same shared Redis on every machine, and a claim on one is refused on the others. See One repository, many machines.

Not for work that can have a checkout of its own. A git worktree per agent removes the sharing altogether, which is better than coordinating it. The locks are advisory: they protect a file only from agents that check. --enforce exists for the few files that must not move at all.

How to use it

Install

gem install agent-lock
hash -r
alock version  # alock must be on PATH

Or add gem "agent-lock" to a Gemfile.

Claim before you write

alock acquire "lib/billing/**" "rewriting the invoices"   # claim a corner of the tree
alock check   "lib/billing/tax.rb"                        # exits 1 if somebody else holds it
alock note    "lib/billing/**" "totals done, specs red"   # where you are, for whoever comes next
alock list                                                # everything held in this repository
alock release-all                                         # when you are done

A refusal tells you who and what, not just that you lost:

$ alock acquire lib/billing/tax.rb
REFUSED, do not write here
HELD  lib/billing/**  by luke-backend  since 2026-09-09T21:04:11Z
      intent: rewriting the invoices

Exit 1 means do not write there. Exit 2 means the command could not run at all.

Fan out to sub-agents in one worktree

The orchestrator claims the area it hands out, running alock bare. Each sub-agent then claims its own part of it, naming itself on every call:

alock acquire "src/**" "fanning out the billing work"            # orchestrator

AGENT_ID=billing-a alock acquire "src/billing/**" "tax rounding"  # sub-agent A
AGENT_ID=billing-b alock acquire "src/billing/tax.rb" "..."       # sub-agent B: REFUSED, held by billing-a
AGENT_ID=billing-a alock release-all                              # A's own locks, never the orchestrator's

diagram

Three things matter, and each one fails silently if skipped:

  1. The name goes on every call. Sub-agents run inside the parent's process and would sign every lock as the parent. Each call is also a fresh shell, so an export AGENT_ID from an earlier call is gone. AGENT_ID=<name> alock whoami shows the name a lock would be signed with.

  2. Run alock in the checkout being written, with cd or --dir. A lock in another repository protects nothing.

  3. Sub-agents claim even inside the orchestrator's lock. The orchestrator's lock keeps other sessions out; only a sub-agent's own claim keeps its siblings out.

Teach your agents

The gem ships a skill that teaches an agent all of the above, so the rules reach the agents rather than living only in this README. Install it into the skills directory your agent reads:

alock skills install                   # into ~/.agents/skills, read by most agents
alock skills install --for claude      # into ~/.claude/skills
alock skills install --into some/path  # anywhere else; wins over --for
alock skills path                      # where the bundled copy is

install refuses to replace a copy that differs (--overwrite replaces it) and never touches a symlink, since a symlink belongs to some other installer.

If a manifest-driven installer manages your skills, point it at this repository instead, so the skill is recorded with where it came from:

- name: agent-lock
  type: skills
  repo: git@github.com:kigster/agent-lock.git
  path: skills

Then put the rule where every agent reads it, such as CLAUDE.md or AGENTS.md:

Several agents may work in this checkout at once. Before creating or editing
files, load the agent-lock skill and claim the narrowest scope that covers your
writes:

    alock acquire <scope> "<what you are doing>"

If it refuses, work somewhere else. A sub-agent prefixes every call with its
own name: AGENT_ID=<sub-agent-name> alock acquire ... 

Release with `alock release-all` when you are done.

Advisory locks work because everybody checks. That is why the rule belongs in the instructions your agents load, and not only here.

Ruby API

The utility was built CLI-first, so that any language and any agent framework can use it. A Ruby project pays less by calling its Ruby API instead: Agent::Lock::Facade runs every command in-process, which saves a fork()/exec() per call.

A Ruby process can also hold more than one locker, for example one per checkout, or a Redis locker and a file-store locker kept deliberately apart. Within one checkout, though, the backend marker binds every locker to the backend that checkout chose first: a file-store facade raises Agent::Lock::Store::Mismatch in a checkout claimed for Redis, and two facades on two Redis URLs never see each other's locks. Use separate lockers for separate checkouts or namespaces, never to split one checkout.

Mapping alock Commands to Ruby API

The same commands that are available when you run alock -h become methods on an instance of the class Agent::Lock::Facade, and run within your process, so no Ruby process is started per call. Each returns the Manager::Result (status, records, record). Where the command would print a refusal, the method raises Agent::Lock::Refused: the message says who holds the scope, and result is the Manager::Result behind it. Releasing, breaking or resuming a free scope is not a refusal: it returns :not_found, although the command exits 1.

Types of Locks

There are four ways to get a locker, and each is an instance of the class Agent::Lock::Facade:

  1. A default version of a local file-system based lock that works great for a single repository work on multiple agents on a single machine. It can be lazy loaded by calling Agent::Lock.local
  2. A default version of a distributed lock can be obtained by calling Agent::Lock.distributed. It lazily builds a Redis-backed locker, one per URL, from redis_url: when given (Agent::Lock.distributed(redis_url: url)), else $AGENT_LOCK_REDIS_URL, else $REDIS_URL, else redis://127.0.0.1:6379/0, and raises Agent::Lock::RedisUnavailableError when that Redis does not answer.
  3. Agent::Lock.facade(**opts) builds a fresh locker that prefers Redis and falls back to the file store, as alock does by default.
  4. And of course you can create any number of Agent::Lock::Facade instances by calling its constructor: @locker = Agent::Lock::Facade.new(**opts).

Facade.new and Agent::Lock.facade take the same options:

Option Default Does
strategies: %w[redis file] Stores to try, in order. filesystem is another name for file
redis_url: see below The Redis to use: this, else $AGENT_LOCK_REDIS_URL, else $REDIS_URL, else redis://127.0.0.1:6379/0
async: false Adds #async, see Async
holder: :process What a lock's liveness is tied to: this Ruby process, or :session for alock's rule
session_name: none Names the session; its locks are tied to no process and survive restarts
agent_id: the session's id The holder a call signs as, when the call names none
parent_id: inferred That holder's parent. false means it has none
dir: Dir.pwd The checkout whose locks a call reads, when the call names none
stale_minutes: 120 When a quiet lock counts as stale

A list that is only redis raises Agent::Lock::RedisUnavailableError (a RuntimeError) at construction when that URL does not answer.

A facade and alock do not look for Redis the same way:

  • A facade uses one URL. With $REDIS_URL unset or blank that is redis://127.0.0.1:6379/0 (Facade::DEFAULT_REDIS_URL, the same local Redis alock tries). When the URL does not answer, the facade goes on to its next strategy, never to another Redis.
  • alock tries $REDIS_URL when it is set, then redis://127.0.0.1:6379/0 (RedisStore::LOCAL_URL).
  • Both defaults are database 0 of the local Redis, so the two meet there wherever localhost resolves to 127.0.0.1. To be sure, name one URL on both sides: redis_url: and -u, or AGENT_LOCK_REDIS_URL for both.

Examples

The first example is the shared local file-system based lock.

require "agent/lock"

# First we'll use a File-System local lock which is cheap and fast
# NOTE: the current directory is expected to be a git project.
locker = Agent::Lock.local # file store, built once per process. 

# Now we acquire an advisory lock on all files under lib/billing, presumably
# because we want to work on a billing feature.

locker.acquire "lib/billing/**", "rewriting the invoices", agent_id: "backend-agent"
locker.note    "lib/billing/**", "totals done, specs red", agent_id: "backend-agent"
locker.check   "lib/billing/tax.rb", agent_id: "backend-agent" # :mine

# And release all locks held by this agent
locker.release_all(agent_id: "backend-agent")

Acquire with a block

Given a block, acquire yields the result, returns the block's value, and releases the lock afterwards, even when the block raises, breaks or throws. It releases only a lock this call took: inside a scope you already hold, the result is :already_mine, and the outer lock survives the inner block. A refusal raises before the block runs. If somebody broke your lock and took the scope while the block ran, the block's own exception still propagates; a block that finished gets the refused release as Agent::Lock::Refused.

locker.acquire("lib/billing/**", "rewriting the invoices", agent_id: "backend-agent") do |lock|
  lock.status # => :acquired
  rewrite_invoices
end # released here

Async

Facade.new(async: true) adds #async, which runs any lock method on concurrent-ruby's I/O pool and returns a Concurrent::Promises::Future. Arguments, keywords and blocks pass through exactly as on a direct call. value! returns the result or raises what the call raised; value returns nil on failure, with the error in reason. Direct calls on the same facade stay synchronous.

One facade's async calls run one at a time, in the order they were made, so async.acquire, async.note and async.release issued back to back take effect in that order, and fifty async.note calls leave fifty notes. Calls on different facades run in parallel. A block given to async.acquire runs on that queue: inside it call the facade directly, or call #async, which runs inline there.

concurrent-ruby is not a direct dependency of this gem, though dry-cli-ui currently installs it. Add gem "concurrent-ruby" to your Gemfile so async: true does not rest on that; if the gem is missing, async: true raises LoadError naming it.

locker = Agent::Lock::Facade.new(strategies: %w[redis], async: true)

future = locker.async.acquire("lib/billing/**", "rewriting the invoices", agent_id: "backend-agent")
future.value!.status # => :acquired, or raises Agent::Lock::Refused

locker.async.release("lib/billing/**", agent_id: "backend-agent").wait

Wait on every future whose outcome matters, a release above all: a future still running when the process exits can be dropped, and the lock then lives until it is reaped.

Threads, lifetime and session names

A facade is frozen and builds a fresh Manager per call, so one instance can be shared by any number of threads. Agent::Lock.local and Agent::Lock.distributed are memoized separately, built once even when several threads ask at the same time, and a distributed that failed to connect is retried on the next call. Facade.new and Agent::Lock.facade each build a fresh facade and leave those two in place. Two facades pointed at two Redis URLs keep separate locks. The checkout's backend marker binds a facade as it binds alock: a facade claims a new checkout for its backend, and raises Agent::Lock::Store::Mismatch in one already claimed for the other, so a facade and the CLI never split one checkout across the file store and Redis. The marker names the backend, not the Redis URL: a facade given another redis_url than the CLI's REDIS_URL is still a separate locker.

A facade ties each lock's liveness to its own Ruby process (holder: :process, the default), so the locks of a host that crashes are reaped like those of a dead alock session. alock ties a lock to the first ancestor that is not a shell, because its own process exits after every command; pass holder: :session for that behaviour, for example from a short script whose lock should outlive it. Either way the lock is signed with the session's holder id, so a script and the alock of the session that runs it are one holder.

A host that restarts while its work goes on names its session instead. session_name: (a plan id, a job id: letters, digits and . _ : @ / + -) is used as given in place of CLAUDE_SESSION_ID and the fingerprint. It signs the facade's locks unless the call passes agent_id: or AGENT_ID is set, and then it is that holder's inferred parent. A lock taken under a session name is tied to no process, the named agents' locks included:

  • It survives any number of restarts, and a restarted host that gives the same name finds it its own.
  • It lapses when untouched for the stale window of whoever looks at it: a plain alock list clears one that has been quiet for 120 minutes, whatever stale_minutes: its holder passed. note is the only heartbeat, so a long silent job should write one now and then.
  • A lapsed lock with notes becomes interrupted work, for its own holder too: resume takes it back. One without notes is simply free again.
  • On Redis, AGENT_LOCK_TTL_SECONDS still expires it outright, notes and all.
  • Release it when the work is done; nothing else will until the window passes.

holder: is for a facade that names no session: Facade.new raises ArgumentError given both, and a session_name: passed to one call overrides the facade's holder: for that call.

locks = Agent::Lock::Facade.new(strategies: %w[redis], session_name: "plan-003.00")
locks.acquire("lib/billing/**", "building")                   # held by plan-003.00, across restarts
locks.acquire("lib/billing/a.rb", agent_id: "luke-backend")  # its parent is plan-003.00

Method reference

Every lock method takes dir:, agent_id:, parent_id:, stale_minutes: and session_name:, overriding the facade's defaults for that call; any other keyword raises ArgumentError, through #async too. check, list, mine, release, release_all, resume, whoami, skills_path, skills_install and version take the same arguments as the command. show_repos and show_repo read Redis only (redis_url: names which one) and return the rows the CLI prints. break is break_lock (it returns the result; the command succeeded). acquire takes enforce: and allow_wide:. skills_install takes into:, agent: (the --for flag) and overwrite:. whoami returns the Identity the lock would be signed with.

A Ruby dispatcher and its alock agents

A dispatcher is a long-lived Ruby process that starts coding agents over a checkout: OpenLanes is one. The dispatcher can call Ruby, so it locks through the Ruby API, in-process. The agents it starts are claude or codex processes that can only run commands, so they lock with alock. Both write the same lock documents to the same store, so the two halves are one locker.

flowchart TB
    subgraph DISP["Dispatcher: one Ruby process"]
        FACADE["Agent::Lock.distributed(redis_url: url)<br/>agent_id: dispatcher, parent_id: false"]
    end

    DISP -->|"starts each agent with"| ENV["AGENT_LOCK_REDIS_URL = url<br/>AGENT_PARENT_ID = dispatcher<br/>AGENT_ID = the agent's own name"]

    ENV --> A1["Agent luke-backend<br/>alock acquire lib/billing/tax.rb"]
    ENV --> A2["Agent rey-frontend<br/>alock acquire app/views/**"]

    FACADE -->|"claims the plan's area"| STORE[("Redis<br/>alock-v4-&lt;owner&gt;/&lt;repo&gt;")]
    A1 -->|"claims its files inside it"| STORE
    A2 -->|"claims its files inside it"| STORE

What has to match

A lock taken by one side blocks the other only when all three of these agree. Each one fails silently when it does not: both sides are told they hold the scope.

Must match The dispatcher, in Ruby An agent, with alock When it does not
The store Agent::Lock.distributed(redis_url: url) AGENT_LOCK_REDIS_URL=url in its environment, or -u url on every call Two stores that never see each other's locks. Naming the file store in a tree marked for Redis exits 2
The tree dir: on every call: the checkout or worktree the agent writes in The agent's working directory, or --dir Locks collide only within one repository and branch, so a claim made from another worktree guards nothing here
The family agent_id: "dispatcher", parent_id: false AGENT_PARENT_ID=dispatcher, and its own AGENT_ID The agent is a stranger to the dispatcher, and is refused everywhere inside the dispatcher's claim

AGENT_LOCK_REDIS_URL is the form made for this. Exported once to the agent, it reaches every fresh shell the agent runs a command in and every sub-agent it starts, it keeps a URL with a password out of prompts and transcripts, and it leaves REDIS_URL to the project being worked on. It has no fallback: if that Redis does not answer, alock exits 2 and never drops to the file store, where the dispatcher would not be looking.

The dispatcher's side

require "agent/lock"

url   = "redis://locks.internal:6379/0"
locks = Agent::Lock.distributed(redis_url: url)   # one facade per URL, built once, thread-safe
me    = { agent_id: "dispatcher", parent_id: false }

# Claim the area a plan may touch, in the checkout its agent will write in.
locks.acquire("lib/billing/**", "plan 003.00: build", dir: worktree, **me)

# Start the agent in that checkout, with the store and the family in its environment.
pid = Process.spawn(
  { "AGENT_LOCK_REDIS_URL" => url, "AGENT_PARENT_ID" => "dispatcher", "AGENT_ID" => "luke-backend" },
  "claude", "-p", prompt, chdir: worktree
)
Process.wait(pid)

locks.release_all(dir: worktree, **me)             # the dispatcher's locks, and what its agents left behind
  • parent_id: false is not optional. A holder that names itself is otherwise taken for a child of whatever terminal or agent started the process, and a lock that session holds would not block the dispatcher. false makes it nobody's child, however it was launched.
  • Pass dir: on every call. A dispatcher's own working directory is rarely the checkout its agents write in.
  • A refusal is Agent::Lock::Refused, and a Redis that does not answer is Agent::Lock::RedisUnavailableError. A facade that failed to connect is not kept, so the next call asks Redis again.
  • The lock is tied to the dispatcher's process (holder: :process, the default). To keep a claim across a dispatcher restart, name the session instead: see session names.

An agent's side

The agent needs nothing but the skill (see Teach your agents): the store and its parent are already in its environment. This is what it sees while the dispatcher holds lib/billing/**:

$ alock whoami
id:     luke-backend  (from AGENT_ID)
parent: dispatcher  (from AGENT_PARENT_ID)

$ alock acquire lib/billing/tax.rb "tax rounding"       # inside its parent's claim
ACQUIRED lib/billing/tax.rb  (holder: luke-backend)

$ alock acquire "lib/billing/**"                        # exactly its parent's claim
REFUSED: lib/billing/** is your parent's (dispatcher) whole claim; claim a narrower scope inside it

$ AGENT_ID=rey-frontend alock acquire lib/billing/tax.rb   # another agent of the same dispatcher
REFUSED, do not write here
HELD  lib/billing/tax.rb  by luke-backend  since 2026-11-27T19:14:05Z
      intent: tax rounding

An agent that was not started by this dispatcher, or a person in a terminal, is refused by both locks and shown both holders.

A family is two levels deep: a holder may claim inside its parent's lock, and nobody may claim inside a grandparent's. So an agent that fans out to sub-agents of its own does not make itself their parent, since they would then be strangers to the dispatcher and refused everywhere in its claim. They keep the inherited AGENT_PARENT_ID and each takes a name of its own, which makes them the dispatcher's children too:

AGENT_ID=luke-tax alock acquire lib/billing/tax.rb "rounding"   # parent: dispatcher, inherited

They are then siblings of the agent that started them, so that agent releases, or never claims, what it hands to a sub-agent, and its release-all does not release their locks. The dispatcher's release_all does.

How one claim is decided

Both sides run the same check, under the store's mutex, against every live lock that overlaps the scope asked for:

flowchart TB
    ASK["Holder H asks for scope S"] --> OVER{"Does a live lock<br/>overlap S?"}
    OVER -->|no| GRANT["ACQUIRED"]
    OVER -->|yes| WHO{"Who holds it?"}
    WHO -->|"H itself"| MINE["ALREADY YOURS"]
    WHO -->|"H's parent"| SAME{"Is it exactly S?"}
    SAME -->|"no, S is inside it"| GRANT
    SAME -->|yes| NARROW["REFUSED<br/>claim a narrower scope"]
    WHO -->|"a child of H, a sibling,<br/>or a stranger"| HELD["REFUSED<br/>HELD by that holder"]

One refusing lock is enough. An interrupted lock at exactly S is neither granted nor refused: it is INTERRUPTED WORK, to resume or break.

One plan, start to finish

sequenceDiagram
    participant D as Dispatcher (Ruby API)
    participant S as Redis
    participant A as luke-backend (alock)
    participant B as rey-frontend (alock)

    D->>S: acquire lib/billing/** (parent_id: false)
    S-->>D: :acquired
    D->>A: start, with the store and AGENT_PARENT_ID
    D->>B: start, with the store and AGENT_PARENT_ID
    A->>S: alock acquire lib/billing/tax.rb
    S-->>A: ACQUIRED (inside its parent's claim)
    B->>S: alock acquire lib/billing/tax.rb
    S-->>B: REFUSED, HELD by luke-backend
    A->>S: alock note lib/billing/tax.rb "rounding done"
    A->>S: alock release-all
    S-->>A: its own locks, never the dispatcher's
    A-->>D: exits
    D->>S: release_all
    S-->>D: its locks, and any its agents left

Who ends which lock

Event The dispatcher's lock An agent's lock
The agent runs alock release-all Stays Released
The dispatcher calls release(scope) That one is released Stays, even inside the released scope
The dispatcher calls release_all Released Released too: they are its children
The agent's process exits without releasing Stays Reaped by the next command on that machine; with notes it becomes interrupted work
The dispatcher's process exits or crashes Reaped the same way; resume takes back one that had notes Stays until the agent releases it or exits
Either holder is on another machine and goes quiet Trusted until untouched for AGENT_LOCK_STALE_MINUTES The same
Redis stops answering RedisUnavailableError; nothing is claimed alock exits 2; nothing is claimed, and nothing falls back to disk

A lock taken with alock is tied to the first ancestor of the command that is not a shell, which for a launched agent is its own claude or codex process. That is why an agent's locks end with the agent and not with each command.

How it works

Identity comes from the session

In order of preference:

Source When it applies
AGENT_ID A human or a harness named this session on purpose
session_name: Ruby API only: the host named its session, see Ruby API
CLAUDE_SESSION_ID A harness that exports it, since it survives --resume
Fingerprint None of the above is set

The fingerprint walks up from the current process until it finds an ancestor that is not a shell. That is the claude or codex process driving the session, or the terminal a person is typing in. Its pid, start time (read in UTC, so TZ and the locale do not change it), uid and hostname are hashed into a name like claude-1f4c8a02, which stays the same for as long as the session lives and differs from anybody else's.

[!NOTE] The start time is in the hash on purpose. PIDs get recycled, and a new session that lands on a dead one's number should not inherit its locks.

alock whoami prints the name this session would sign a lock with, its parent, and where each came from. Run it before the first claim if in doubt.

The file store lives inside .git

With the file backend, the store is $(git rev-parse --git-common-dir)/agent-locks. The Redis backend keeps the same documents in Redis instead; see Backends.

Property Why it matters
Git cannot track anything in .git No repository needs a .gitignore entry
git clean -xdf cannot reach it A cleanup does not silently drop every lock
Every worktree resolves to the same directory One store serves the whole repository
It is deleted with the checkout Nothing outlives the repo in your home directory

Outside a git repository the store falls back to ~/.agent-locks, keyed by a digest of the tree.

A lock is a document, not a flag

---
agent_id: luke-backend
scope: workflow/**
status: active
pid: 69232
created_at: 2026-09-09T21:04:11Z
---
Rewriting the installer

## Progress
- 2026-09-09T21:14:02Z installer rewritten, specs still red

A line of the intent that is exactly ## Progress is stored as \## Progress, so only alock note can start the notes section.

An agent that runs into this learns who owns the scope and what they are doing, so it can decide whether to wait or work elsewhere. A human can read the same file in an editor.

Scopes are globs

Scope Means
** The whole tree
workflow/** Everything under workflow
workflow The same thing. A directory means everything in it
lib/cli.rb One file

Two scopes conflict when one fixed part contains the other. So workflow/** conflicts with workflow/lib/cli.rb, and docs/** does not conflict with workflow/**. Case is ignored when two scopes are compared, on every filesystem, so README.md and readme.md conflict.

Case is ignored when two scopes are compared, on every filesystem: README.md and readme.md are one scope, on a case-sensitive filesystem too. A lock keeps the spelling it was taken under.

[!TIP] The rule deliberately refuses more often than it strictly must. Whether two globs can ever match the same path is unpredictable, and guessing wrong costs somebody lost work.

A scope is read from where you stand, globs included, and an absolute path inside the tree is made relative. So $PWD/lib/** and lib/** are the same claim, and *.rb typed in lib/ is lib/*.rb. Only ., * and ** mean the whole tree from anywhere. Two things are refused with exit 2 rather than guessed at:

Scope Why it is refused
"" Usually an unset variable. Claiming the whole tree by accident blocks everybody; write ** if you mean it
/etc/passwd, ../other/** Outside the tree, so no lock in this store can protect it

Sub-agents are a family, not one holder

Ownership and blocking are separate questions, and conflating them is what lets sibling sub-agents overwrite each other.

Relationship May claim an overlapping scope Appears in mine, can be released
Yourself Yes, it is already yours Yes
Your parent session Yes, inside its claim, and the claim is recorded as yours No
A sub-agent you spawned No, you handed that scope out Yes, so cleanup takes them with it
A sibling sub-agent No No

A sub-agent claiming inside its parent's lock gets its own lock, and that lock keeps its siblings out. Asking for exactly the parent's scope is refused, since that would leave nothing for a sibling to be kept out of; claim something narrower. A sub-agent's release-all gives back its own locks and its children's, never its parent's.

Sub-agents that share their parent's process

Claude Code runs sub-agents inside the parent's own claude process, and sets nothing in the environment that tells them apart. They therefore share the parent's fingerprint, and without help every one of them would sign locks as the parent and none would ever block another.

So a sub-agent names itself, on every call, since each command runs in a fresh shell and an export does not survive to the next one:

AGENT_ID=luke-backend alock whoami                        # id luke-backend, parent claude-1f4c8a02 (inferred)
AGENT_ID=luke-backend alock acquire lib/billing/** "invoices"
AGENT_ID=luke-backend alock release-all

When AGENT_ID is set and AGENT_PARENT_ID is not, the parent is taken to be the session's own name, CLAUDE_SESSION_ID if the harness exports it and the fingerprint otherwise, which is the orchestrator running bare alock. Set AGENT_PARENT_ID explicitly when the parent named itself too.

A holder that is nobody's child says so with AGENT_PARENT_ID set and empty (AGENT_ID=svc AGENT_PARENT_ID= alock acquire ...), or parent_id: false in Ruby, per call or as a facade default. A top-level service that names itself needs this: left to inference it is the child of whatever terminal or agent started it, and a lock that session holds does not block it. Unset still infers. Three things follow from it being an environment variable:

  • alock whoami prints parent: none (AGENT_PARENT_ID is set and empty), so a variable exported empty by accident can be told from having no parent to infer. Such a sub-agent is refused inside its orchestrator's lock, and its orchestrator's release-all does not release its locks.
  • A service that exports it empty passes that to the agents it starts. Give each of them AGENT_PARENT_ID=<the service's id>.
  • In Ruby, parent_id: nil means "not said": the facade's default applies, then the process's own AGENT_PARENT_ID, then inference. A blank String raises ArgumentError.

[!NOTE] The same rule applies in a terminal. Setting AGENT_ID there makes the terminal's own session your parent, so a bare alock typed in that terminal can release what you claimed under the name.

A crash does not strand the tree

A lock is cleared when its holder is provably gone: the process that signed it has exited on this machine. A holder on another machine cannot be checked, so its lock is trusted until nobody has touched it for AGENT_LOCK_STALE_MINUTES (120 by default). Every note counts as a touch. What happens next depends on whether anything was written down:

The lock has What happens to it
No notes Deleted. There is nothing to come back to
Notes Orphaned. The claim is void, the record survives
$ alock acquire workflow/**
INTERRUPTED WORK on workflow/**, left by luke-backend
  alock resume 'workflow/**'   # take it back, notes and all
  alock break 'workflow/**'    # throw it away and start over

[!WARNING] An orphan blocks nobody, but acquire will not silently overwrite one, because the notes inside it may be the only record of half-finished work. Choose resume or break.

A lock whose holder is alive on this machine is never cleared, no matter how old it is. (Two kinds of lock have no process here to ask, and lapse once untouched for the stale window instead: one held on another machine, and one that names no process, such as a lock taken under a session_name:. See the Ruby API section.) An agent may legitimately work on one scope for hours, and deleting its lock underneath it would hand its files to the next agent while it is still writing them. Past the stale window list marks the row stale, and check and mine tag it STALE. Taking it is a break that somebody announces first.

alock list prints this repository only. The columns are the namespace, the holder, the scope, the status (active, stale, interrupted), and how long the lock has been held. Progress notes stay out of that table unless you pass --notes, which prints them on the row underneath. The namespace is the Redis label either way. When the locks are in the file store, the line above the table says so: show repos and show repo read Redis and will not list them.

$ alock list
┌────────────────────────────┬──────────────┬─────────┬─────────────┬────────┐
│ Namespace                  │ Holder       │ Scope   │ Status      │ Held   │
├────────────────────────────┼──────────────┼─────────┼─────────────┼────────┤
│ alock-v4-kigster/shop      │ orchestrator │ app/**  │ active      │ 2m 10s │
│ alock-v4-kigster/shop      │ slow-agent   │ docs/** │ stale       │ 3h 01m │
│ alock-v4-kigster/shop      │ crashed      │ db/**   │ interrupted │ 12m    │
└────────────────────────────┴──────────────┴─────────┴─────────────┴────────┘

--json gives every record its status and a stale flag.

Commands

alock --help lists them; alock <command> --help shows each one's arguments, flags and examples.

Command Does Exits 1 when
acquire <scope> [intent] Claim a path, directory or glob before writing there held, interrupted, or exactly your parent's scope
release <scope> Give a lock back, thawing any files it froze somebody else holds it
check <scope> Say who holds a path another agent holds it
note <scope> <text> Append a timestamped progress note to your lock you do not hold it
resume <scope> Take back work a crash or reboot interrupted there is nothing to resume, or it was re-claimed
break <scope> Take a lock from its holder, even a live one nothing is locked there
list (ls) Every lock in this repository, live and interrupted never
show repos Redis: repositories, lock counts, and the memory used never (exit 2 when Redis does not answer)
show repo [owner/name] Redis: that repository's locks, and how to break one (host/owner/name off GitHub), with the name in any case. Without a name, the origin remote of the checkout you are in never (exit 2 when Redis does not answer)
mine Locks held by this session and its sub-agents never
release-all Release all of those never
switch-backend <store> Bind this checkout to redis or filesystem the old store still holds this checkout's locks
whoami The id your locks would carry, its parent, their source never
skills install Copy the bundled skill into a skills directory a different copy, or a symlink, is there
skills path Print where the bundled skill lives never
`completion bash\ zsh` Print a shell completion script
version Print the installed version never

check answers HELD when another agent's lock overlaps the scope, YOURS when one of your own locks contains all of it, and FREE otherwise. FREE means the scope is yours to acquire, not that no lock touches it: your parent's lock over it, or a narrower lock of your own inside it, still answers FREE. Two refusals come only from acquire itself: a scope that is exactly your parent's, and interrupted work on exactly that scope.

Flags:

Flag Where Does
--dir PATH every command that reads locks (not whoami, skills, version) Act on the checkout that contains PATH
-s, `--locking-strategy redis\ filesystem` the same commands
-u, --redis-url URL the same commands Use that one Redis, with no fallback. Implies --locking-strategy redis
--json check, list, mine, whoami Machine-readable output
--enforce acquire Also freeze the matched files (macOS)
--allow-wide acquire Let --enforce freeze more than 500 files
--discard-locks switch-backend Delete the old store's locks instead of refusing
--into DIR skills install Install into DIR
--for AGENT skills install claude means ~/.claude/skills, else ~/.agents/skills
--overwrite skills install Replace an installed copy that differs

Any command exits 2 when it cannot run at all: an empty or out-of-tree scope, a backend mismatch, a freeze that is refused, or a store it cannot reach.

Shell completion

alock completion bash > "$(brew --prefix)/etc/bash_completion.d/alock"
alock completion zsh  > "${fpath[1]}/_alock"

Names every command and flag alock currently knows, since the script is generated from the same registry the CLI runs on, rather than hand-maintained separately.

Configuration

Variable Default Does
AGENT_ID fingerprint Name this session yourself
AGENT_PARENT_ID the fingerprint, when AGENT_ID is set The session that spawned this one. Set and empty: no parent
AGENT_LOCK_DIR .git/agent-locks Keep locks somewhere else: an absolute path or ~ is used as given, a relative path is read from the root of the checkout, and an empty value counts as unset
AGENT_LOCK_STALE_MINUTES 120 When a lock is tagged STALE, and when one from another machine, or with no process, expires
AGENT_LOCK_MUTEX_TIMEOUT 15 Seconds a claim waits for the store's mutex before giving up with exit 2
AGENT_LOCK_BACKEND redis if one answers, else file file (or filesystem) or redis; any other name exits 2 and claims nothing, and an empty value is unset
AGENT_LOCK_TTL_SECONDS 0 Redis expiry. 0 means no TTL
REDIS_URL unset A shared Redis, tried before redis://127.0.0.1:6379/0
AGENT_LOCK_REDIS_URL unset The one Redis to use, with no fallback: --redis-url for every call

alock ignores GIT_DIR, GIT_INDEX_FILE, GIT_WORK_TREE and the other variables git rev-parse --local-env-vars lists. The checkout is always the one around the working directory, or around --dir, so a git hook that runs alock against another checkout cannot put its locks into the hook's own repository.

Backends

Redis stores the same documents as the file store, and buys two things a filesystem cannot: its mutex holds across machines, and a TTL (AGENT_LOCK_TTL_SECONDS, off by default) expires an abandoned lock without anybody having to reason about liveness. A tree defaults to Redis when one answers, and falls back to the file store, which needs nothing installed, when none does.

Anything that can write to a shared Redis can write a lock record, so alock treats every field it prints as untrusted. Control characters, C1 characters and bidi overrides in a scope, agent ID, intent or note print as visible escapes (\x1b[2J, \u{202e}) rather than reaching the terminal, and a scope inside a suggested alock break or alock resume line is shell-quoted, so it pastes as one argument. The Ruby facade's Refused messages are escaped the same way, through Agent::Lock::Text.printable. The record itself is left as it was written.

The search for a Redis runs in a fixed order: REDIS_URL first, when it is set, then redis://127.0.0.1:6379/0. A REDIS_URL nobody answers on is not the end of it, since the usual reason to set one is a shared instance that is occasionally down, and a local Redis is still a better lock store than the filesystem. Only when neither answers does the tree land on the file store. alock list names the store in use on STDERR (store: redis redis://10.0.0.5:6379/0 (...), or the file store's directory), with --json too, so it is never a guess which one you are on.

AGENT_LOCK_BACKEND=redis alock acquire workflow/**   # force it, rather than autodetect
AGENT_LOCK_BACKEND=file  alock acquire workflow/**   # or force the file store instead

For alock, the store is settled in this order. A Ruby facade tries its strategies: in order instead, and is bound by the same marker:

flowchart TB
    CMD["alock command"] --> NAMED{"Is a store named?<br/>-s, -u, AGENT_LOCK_REDIS_URL<br/>or AGENT_LOCK_BACKEND"}
    NAMED -->|yes| AGREE{"Does the tree's marker<br/>name another store?"}
    AGREE -->|yes| MISMATCH["exit 2: mismatch<br/>HINT: alock switch-backend"]
    AGREE -->|"no, or no marker yet"| USE["Use the named store.<br/>A named Redis must answer, or exit 2"]
    NAMED -->|no| MARK{"Does the tree<br/>have a marker?"}
    MARK -->|yes| BOUND["Use the marker's store"]
    MARK -->|no| PROBE{"Does a Redis answer?<br/>REDIS_URL, then 127.0.0.1:6379"}
    PROBE -->|yes| REDIS["Redis, and the marker says so"]
    PROBE -->|no| FILE["File store, and the marker says so"]

The same choice can be made per call, which is how an agent started by a dispatcher lands in the dispatcher's store whatever its own shell exports:

alock acquire workflow/** --locking-strategy filesystem            # -s for short; file is another name for it
alock acquire workflow/** --locking-strategy redis                 # Redis or fail: REDIS_URL, then the local default
alock acquire workflow/** --redis-url redis://locks.internal:6379  # -u for short: this Redis and no other
alock release workflow/** --redis-url redis://locks.internal:6379  # every later call names it too
  • A flag wins over AGENT_LOCK_BACKEND. Neither wins over the tree's marker: naming the store the tree does not use exits 2.
  • --redis-url has no fallback. If nothing answers there, or it is empty or not a Redis URL, the command exits 2 and a virgin tree is left unclaimed. A password in it is never printed back. The flag itself is still visible in ps on that host, so a URL with a password belongs in AGENT_LOCK_REDIS_URL, not in -u.
  • AGENT_LOCK_REDIS_URL means the same as --redis-url on every call, and the flag wins over it. It is the form for a dispatcher: exported to the agents it starts, it reaches their sub-agents and every fresh shell, keeps a URL with a password out of prompts and transcripts, and leaves REDIS_URL to the project being worked on. The Ruby facade reads it before REDIS_URL too.
  • The marker records redis, not which Redis. Every agent in the tree has to be given the same URL, by the flag or by REDIS_URL; two URLs are two stores that cannot see each other's locks.
  • A Redis URL, from the flag or the variable, beside the file store (--locking-strategy filesystem or AGENT_LOCK_BACKEND=file) exits 2.
  • --locking-strategy redis with no URL is Redis or fail as well: if neither REDIS_URL nor the local default answers, it exits 2 without claiming the tree.

Switching a checkout to the other store

Releasing every lock does not move the marker. switch-backend does, and a mismatch error names it on its second line:

ERROR: alock: this tree's locks live in file, not redis
HINT: run 'alock switch-backend redis'
alock switch-backend redis                            # exits 1 while the file store holds this checkout's locks
alock switch-backend redis -u redis://locks.internal  # this Redis, which must answer before anything changes
alock switch-backend filesystem --discard-locks       # delete the old store's locks, thawing what they froze, then switch
  • A lock left in the old store would block nobody and still tell its holder it held something, so switch-backend refuses while any is there and lists them. Release them, break them, or pass --discard-locks. Interrupted locks count, since their notes would be lost with them.
  • The marker sits in the git common dir, so the switch applies to every worktree of the checkout. From the file store, every lock in it counts. From Redis, only the locks taken on this host in one of those worktrees: other clones and other machines keep their own markers.
  • The new store is connected to first. A Redis that does not answer exits 2 with nothing deleted and the marker unchanged.
  • When the old store is a Redis that no longer answers, --discard-locks switches anyway and says on STDERR which Redis was not read: its locks are not deleted, and files they froze stay frozen. Clear those by hand with chflags -R nouchg <dir>.
  • switch-backend filesystem runs with AGENT_LOCK_REDIS_URL exported, but the variable still asks for Redis afterwards: every later command exits 2 with the mismatch error until it is unset.
  • A command that was waiting on the old store while the switch ran exits 2 and asks to be run again, so it never claims in a store nobody reads.
  • From Redis, a lock taken in a worktree that has since been removed is not counted and not discarded: its path is no longer one of this checkout's. alock show repo lists it, with the break command that drops it.

One repository, many machines

A lock is about a repository and the files in it, not about where a checkout sits on disk. Point every machine at one Redis with REDIS_URL, and each checkout of the repository reads the same locks, wherever it is cloned:

Two checkouts of one repository Do their locks collide?
Same branch, any machine, any path Yes, on overlapping scopes; different files are fine
Different branches, such as two worktrees No: separate branches are what a worktree is for
One checkout that switched branch after claiming Yes: the files on disk did not change hands
A detached HEAD Only within that checkout, since it has no branch to share

The repository is named by its origin URL, normalized so that git@github.com:a/b.git and https://github.com/a/b agree. In the scp form (git@host:path) everything after the colon is the path, so an all-digit owner such as git@github.com:123/app.git is kept; only a URL that opens with a scheme (ssh://, https://) can carry a port. The whole name is lower-cased, owner and repository included, so git@github.com:Acme/App.git and https://github.com/acme/app share their locks. A remote that names a directory (/srv/git/App.git, file://...) keeps its case. A repository with no origin is named by its root commit, and a directory outside git by its path.

Why this makes it a distributed lock

Before 3.1.0 a lock was named after the checkout's absolute path. A shared Redis did not help: /Users/a/repo on one laptop and /home/b/repo on a build box hashed to two unrelated namespaces, so each machine saw only its own locks, and two agents on two hosts could both claim lib/billing/** on main and both be told they won. Since 3.1.0, with every machine on one REDIS_URL, the gem has everything a distributed lock needs:

A distributed lock needs How agent-lock provides it
One name for the resource on every host A lock's id comes from the repository, branch and scope, which every clone computes the same way. Nothing local, such as a path or a username, goes into it
One store that every host reads Every checkout of a repository reads and writes [alock-v<major>-<owner>/<repo>]-<sha256>:<id>. For github.com/kigster/laser-cutter on gem 4.x the label is [alock-v4-kigster/laser-cutter]. The SHA-256 is of repository@branch, so every worktree on that branch, on any machine, computes the same key. A detached HEAD has no branch, and its hash is of host:worktree-path. alock list scans every branch under the label.
Mutual exclusion across hosts The conflict check and the write run under [alock-v<major>-<owner>/<repo>]-mutex, one mutex for the repository, taken with SET NX PX and a random token and released by compare-and-delete. The lock itself is written with SET NX, so two hosts after the same id cannot both create it
Recovery from a holder that disappears A crashed holder's mutex lease runs out within 10 seconds. A pid on another host cannot be checked, so that host's lock expires once nobody has touched it for AGENT_LOCK_STALE_MINUTES, and every note counts as a touch. AGENT_LOCK_TTL_SECONDS adds a hard Redis TTL
A boundary on what counts as a collision Locks collide only on the same branch. Worktrees on their own branches stay independent, which is what a worktree is for

Where the guarantees stop:

  • It is advisory. A lock protects a file only from agents that check. --enforce freezes files on the local machine only.
  • Every host has to reach the same Redis. If the shared REDIS_URL does not answer, a command falls back to redis://127.0.0.1:6379/0, and that host is then working in a different store from the others without being told. When agents on several machines depend on the lock, name the Redis with AGENT_LOCK_REDIS_URL or --redis-url instead, which has no fallback and exits 2 when that Redis does not answer, or keep the shared Redis up and check that alock list names it on each one.
  • It is one Redis, not a quorum. Lock state lives on a single instance. A failover to a replica that has not received the latest writes can lose recent claims, so this is not Redlock, and it is not meant to guard anything stronger than agents editing files.
  • The mutex lease is not renewed. A critical section that outlives its 10-second lease fails with an error rather than continuing unprotected, so a slow claim costs a retry, not a double grant.

[!IMPORTANT] The Redis key is [alock-v<major>-<owner>/<repo>]-<sha256 of the branch>. Locks written under the older agent-lock:<digest> prefix are not read and not reaped. Release them before upgrading. With AGENT_LOCK_TTL_SECONDS left at 0 they stay in Redis until deleted by hand. They block nobody. The file store is not affected. Its records stay in .git/agent-locks. Every release of a major shares the prefix, so hosts on 4.0 and 4.1 still exclude each other. A new major (v5 after v4) starts another one, and leaves the previous major's keys the same way.

Either way, every claim checks for conflicts and writes its lock while holding one mutex for the whole repository. Refusing an atomic write of an identical scope is not enough on its own: lib/** and lib/cli.rb are different keys, and two agents claiming them at the same moment would both find the store empty and both win. The file store takes an exclusive flock on .mutex beside the locks. Redis takes [alock-v<major>-<owner>/<repo>]-mutex with SET NX PX and a random token, and gives it back with a compare-and-delete script, so a process whose lease ran out cannot release somebody else's.

[!CAUTION] Picking a default from whether Redis happens to answer is still never a runtime auto-switch. If one agent found a running Redis and switched to it while the agent beside it did not, the two would take locks in different stores, see nothing of each other, and both report success — worse than no lock at all. The first store created in a tree records its backend in a marker file, and every later process in that tree is bound to it regardless of what Redis does next; a mismatch stops the run rather than silently picking the other one.

That default is decided at the one moment two processes could otherwise race: both find a virgin tree, both probe Redis, and a flaky answer could hand them different defaults before either writes the marker. The marker is claimed atomically — written to a temp file and hard-linked into place, so the first link wins and the marker never exists empty — and every process builds from whatever ends up on disk, never from its own guess, so a race can land on either backend but never on a split.

The redis gem ships as a dependency of this one now, since deciding the default means probing for it. If you never want that probe, or never install a local Redis, set AGENT_LOCK_BACKEND=file yourself.

Freezing files, on macOS

acquire --enforce also runs chflags uchg on every matched file, which makes them unwritable by anything, whether it checks for locks or not. Dotfiles and the contents of dot-directories (conf/.env) are frozen like any other file. Anything named .git, at any depth, and the lock store never are.

alock acquire "config/credentials/**" "keys must not move during the migration" --enforce

[!WARNING] This is opt-in for three reasons. It's macOS-only, since the Linux equivalent (chattr +i) requires root. It denies the holder too, so it suits a freeze rather than a file you are editing. And a session that dies leaves the files frozen, at which point git checkout and rm -rf start failing with "Operation not permitted".

Every frozen path is written into the lock, so release and break thaw them without needing the process that froze them to still exist.

The thaw happens in the checkout that froze the files, whichever worktree the command runs in. A lock taken on another machine can only be thawed there, and a resumed lock does not bring its freeze back.

Upgrading to 4.0.0

What changes for a caller coming from 3.1.0:

Before In 4.0.0
alock acquire --enforce --force --allow-wide
alock skills install --force or -f --overwrite
alock skills install -o DIR --into DIR; -o is gone
AGENT_PARENT_ID set and empty was ignored It means "no parent". alock whoami says so when that is why
Manager#acquire(force:), Skill#install(force:) wide:, overwrite:
alock printed nothing and exited 0 on an unexpected error ERROR: alock: ... and exit 2

New in 4.0.0: the Ruby API, --locking-strategy and --redis-url, AGENT_LOCK_REDIS_URL, session names, and a holder that declares it has no parent. CHANGELOG.md has the full list.

Development

bin/setup
bundle exec rspec                               # against the file backend
AGENT_LOCK_TEST_BACKEND=redis bundle exec rspec # the same suite, against Redis
bundle exec rubocop                             # or: just lint
bundle exec rake doc                            # YARD site in doc/ (git-ignored), opened in a browser

The suite runs against one backend at a time, picked by AGENT_LOCK_TEST_BACKEND rather than the machine's own default, so it is deterministic whether or not Redis is running. A Redis run uses database 15, so it never touches a developer's own data. CI runs both backends, plus rubocop as a third job.

The justfile covers the rest: just lint, just test, just test-coverage, just ci (lint, then coverage), just format (autocorrect, then regenerate .rubocop_todo.yml), just doc, and just publish / just release for cutting a version.

The library decides and the CLI prints. Every verb is a method on Agent::Lock::Manager that returns a Result and prints nothing, so the lifecycle is tested without capturing output. Launcher takes argv, stdin, stdout, stderr and kernel as arguments, and nothing below it calls puts or a bare exit, which lets Aruba run the CLI end to end inside the test process. Every public class, method and constant carries YARD documentation; yard stats --list-undoc stays at 100%.

License

MIT

Authors

  • Konstantin Gredeskoul @kigster
  • Claude Code, @claude