agent-lock 3.1.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/.gitleaks.toml +23 -0
  3. data/AGENTS.md +11 -17
  4. data/CHANGELOG.md +124 -3
  5. data/README.md +496 -100
  6. data/Rakefile +13 -6
  7. data/docs/badges/coverage_badge.svg +21 -0
  8. data/docs/badges/yardoc.svg +1 -0
  9. data/docs/img/alock-sequence.avif +0 -0
  10. data/docs/img/alock-sequence.md +29 -0
  11. data/docs/img/alock-sequence.png +0 -0
  12. data/lefthook.yml +39 -0
  13. data/lib/agent/lock/cli/commands/acquire.rb +25 -19
  14. data/lib/agent/lock/cli/commands/base.rb +59 -23
  15. data/lib/agent/lock/cli/commands/break.rb +12 -7
  16. data/lib/agent/lock/cli/commands/check.rb +10 -9
  17. data/lib/agent/lock/cli/commands/completion.rb +15 -32
  18. data/lib/agent/lock/cli/commands/list.rb +46 -37
  19. data/lib/agent/lock/cli/commands/listing.rb +170 -0
  20. data/lib/agent/lock/cli/commands/mine.rb +7 -5
  21. data/lib/agent/lock/cli/commands/note.rb +13 -9
  22. data/lib/agent/lock/cli/commands/release.rb +10 -7
  23. data/lib/agent/lock/cli/commands/release_all.rb +7 -5
  24. data/lib/agent/lock/cli/commands/resume.rb +13 -7
  25. data/lib/agent/lock/cli/commands/show.rb +172 -0
  26. data/lib/agent/lock/cli/commands/skills.rb +28 -19
  27. data/lib/agent/lock/cli/commands/switch_backend.rb +205 -0
  28. data/lib/agent/lock/cli/commands/tree_command.rb +72 -0
  29. data/lib/agent/lock/cli/commands/version.rb +2 -1
  30. data/lib/agent/lock/cli/commands/whoami.rb +7 -3
  31. data/lib/agent/lock/cli.rb +63 -19
  32. data/lib/agent/lock/error.rb +52 -1
  33. data/lib/agent/lock/facade/async.rb +83 -0
  34. data/lib/agent/lock/facade/backend.rb +133 -0
  35. data/lib/agent/lock/facade/memo.rb +30 -0
  36. data/lib/agent/lock/facade/refusal.rb +78 -0
  37. data/lib/agent/lock/facade/session.rb +142 -0
  38. data/lib/agent/lock/facade/strategies.rb +36 -0
  39. data/lib/agent/lock/facade.rb +369 -0
  40. data/lib/agent/lock/freeze.rb +59 -5
  41. data/lib/agent/lock/identity.rb +63 -5
  42. data/lib/agent/lock/launcher.rb +17 -1
  43. data/lib/agent/lock/manager/enforcement.rb +98 -0
  44. data/lib/agent/lock/manager/switch.rb +91 -0
  45. data/lib/agent/lock/manager/thaw.rb +68 -0
  46. data/lib/agent/lock/manager.rb +176 -79
  47. data/lib/agent/lock/process_info/legacy_start.rb +60 -0
  48. data/lib/agent/lock/process_info.rb +42 -11
  49. data/lib/agent/lock/record.rb +124 -10
  50. data/lib/agent/lock/scope.rb +49 -4
  51. data/lib/agent/lock/skill.rb +14 -10
  52. data/lib/agent/lock/store/backend_name.rb +62 -0
  53. data/lib/agent/lock/store/file_system_store.rb +20 -1
  54. data/lib/agent/lock/store/redis_index.rb +179 -0
  55. data/lib/agent/lock/store/redis_store.rb +191 -33
  56. data/lib/agent/lock/store.rb +180 -19
  57. data/lib/agent/lock/text.rb +62 -0
  58. data/lib/agent/lock/tree.rb +143 -16
  59. data/lib/agent/lock/version.rb +2 -1
  60. data/lib/agent/lock.rb +3 -0
  61. data/skills/agent-lock/SKILL.md +75 -10
  62. metadata +41 -22
  63. data/justfile +0 -127
  64. data/sig/agent/lock.rbs +0 -6
data/README.md CHANGED
@@ -1,18 +1,40 @@
1
- # Agent Lock `agent-lock` CLI
2
1
 
3
- [![Ruby](https://github.com/kigster/agent-lock/actions/workflows/main.yml/badge.svg)](https://github.com/kigster/agent-lock/actions/workflows/main.yml)
2
+ # Distributed Resource Locking for Agents
4
3
 
5
- 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). This locking tool is meant for coding agents that share a project.
4
+ ## Gem **agent-lock**: `alock` CLI and Ruby Interface
6
5
 
7
- > [!NOTE]
6
+ > ------
7
+ >
8
+ > **`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.**
9
+ >
10
+ > **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.**
11
+ >
12
+ > ------
13
+ >
14
+ > [![Ruby](https://github.com/kigster/agent-lock/actions/workflows/main.yml/badge.svg)](https://github.com/kigster/agent-lock/actions/workflows/main.yml) ![coverage](docs/badges/coverage_badge.svg) [![Gem Version](https://badge.fury.io/rb/agent-lock.svg)](https://badge.fury.io/rb/agent-lock) [![yardoc](docs/badges/yardoc.svg)](https://kigster.github.io/agent-lock/)
8
15
  >
9
- > Please note that `agent-lock` is part of a three-part system: [`OpenLanes`](https://github.com/kigster/openlanes) is an AI harness workflow that works by creating specs, plans, and executing the plan until one or more PRs passing CI are created, and [`agentilda-ai-setup`](https://kigster/agentilda-ai-setup) — the GitHub repo that's a mixture of BASH and Ruby installers. It comes with the [`configuration.yml`](https://github.com/kigster/agentilda-ai-setup/blob/main/configuration.example.yml) file, which determines what skills, commands, plugins, and AI coding agents are locally installed.
16
+ >
17
+
18
+ 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](#a-ruby-dispatcher-and-its-alock-agents).
19
+
20
+ > [!NOTE]
10
21
  >
11
- > That said, you can absolutely use the `agent-lock` gem in your own environment.
22
+ > 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.
23
+
24
+ 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.
25
+
26
+ > [!NOTE]
27
+ > [OpenLanes](https://github.com/kigster/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.
28
+
29
+ ## See it run
30
+
31
+ ![Two agents and a sub-agent sharing one checkout through alock](demo/alock.gif)
32
+
33
+ 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](https://github.com/charmbracelet/vhs) from `demo/alock.tape`, and `just demo-play` plays it in your own terminal.
12
34
 
13
35
  ## What it is
14
36
 
15
- `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 and for the sub-agents of a single session, the harder case.
37
+ `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.
16
38
 
17
39
  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.
18
40
 
@@ -22,9 +44,9 @@ Git does not help here. Two agents on one branch and one working tree never prod
22
44
 
23
45
  - **Orchestrators that fan out sub-agents** into one worktree, each taking a different part of it.
24
46
 
25
- - **Harnesses** that launch agents over a repository and need them to stay out of each other's way.
47
+ - **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](#a-ruby-dispatcher-and-its-alock-agents).
26
48
 
27
- - **Supports multiple local nodes** with the same project directories, if `$REDIS_URL` is set to a non-local Redis instance (it needs to be set to the same value on all participating nodes)
49
+ - **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](#one-repository-many-machines).
28
50
 
29
51
  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.
30
52
 
@@ -73,26 +95,7 @@ AGENT_ID=billing-b alock acquire "src/billing/tax.rb" "..." # sub-agent B:
73
95
  AGENT_ID=billing-a alock release-all # A's own locks, never the orchestrator's
74
96
  ```
75
97
 
76
- ```mermaid
77
- sequenceDiagram
78
- participant O as Orchestrator (alo)
79
- participant A as Sub-agent billing-a
80
- participant B as Sub-agent billing-b
81
- participant S as Lock store (.git/agent-locks)
82
- O->>S: acquire src/**
83
- S-->>O: ACQUIRED
84
- par fan out
85
- A->>S: AGENT_ID=billing-a acquire src/billing/**
86
- S-->>A: ACQUIRED, parent inferred as the orchestrator
87
- and
88
- B->>S: AGENT_ID=billing-b acquire src/billing/tax.rb
89
- S-->>B: REFUSED, held by billing-a
90
- end
91
- B->>S: AGENT_ID=billing-b acquire src/shipping/**
92
- S-->>B: ACQUIRED
93
- A->>S: AGENT_ID=billing-a release-all
94
- Note over O,S: the orchestrator's src/** survives its children's release-all
95
- ```
98
+ ![diagram](docs/img/alock-sequence.png)
96
99
 
97
100
  Three things matter, and each one fails silently if skipped:
98
101
 
@@ -107,15 +110,15 @@ Three things matter, and each one fails silently if skipped:
107
110
  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:
108
111
 
109
112
  ```bash
110
- alock skills install # default: into ~/.agents/skills, for most agents
111
- alock skills install --for claude # into ~/.claude/skills instead
112
- alock skills install --into some/path # anywhere else, --for is ignored if both are given
113
+ alock skills install # into ~/.agents/skills, read by most agents
114
+ alock skills install --for claude # into ~/.claude/skills
115
+ alock skills install --into some/path # anywhere else; wins over --for
113
116
  alock skills path # where the bundled copy is
114
117
  ```
115
118
 
116
- `install` refuses to overwrite a copy that differs (`--force` replaces it) and never touches a symlink, since a symlink is some other installer's.
119
+ `install` refuses to replace a copy that differs (`--overwrite` replaces it) and never touches a symlink, since a symlink belongs to some other installer.
117
120
 
118
- If you installed skills on your machine from repositories via a manifest, name this one as a source instead so the skill is recorded along with where it came from. For example:
121
+ If a manifest-driven installer manages your skills, point it at this repository instead, so the skill is recorded with where it came from:
119
122
 
120
123
  ```yaml
121
124
  - name: agent-lock
@@ -134,12 +137,280 @@ writes:
134
137
  alock acquire <scope> "<what you are doing>"
135
138
 
136
139
  If it refuses, work somewhere else. A sub-agent prefixes every call with its
137
- own name: AGENT_ID=<sub-agent-name> alock acquire ... Release with
138
- `alock release-all` when you are done.
140
+ own name: AGENT_ID=<sub-agent-name> alock acquire ...
141
+
142
+ Release with `alock release-all` when you are done.
139
143
  ```
140
144
 
141
145
  Advisory locks work because everybody checks. That is why the rule belongs in the instructions your agents load, and not only here.
142
146
 
147
+ ### Ruby API
148
+
149
+ 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.
150
+
151
+ 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.
152
+
153
+ #### Mapping `alock` Commands to Ruby API
154
+
155
+ 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.
156
+
157
+ #### Types of Locks
158
+
159
+ There are four ways to get a locker, and each is an instance of the class `Agent::Lock::Facade`:
160
+
161
+ 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`
162
+ 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.
163
+ 3. `Agent::Lock.facade(**opts)` builds a fresh locker that prefers Redis and falls back to the file store, as `alock` does by default.
164
+ 4. And of course you can create any number of `Agent::Lock::Facade` instances by calling its constructor: `@locker = Agent::Lock::Facade.new(**opts)`.
165
+
166
+ `Facade.new` and `Agent::Lock.facade` take the same options:
167
+
168
+ | Option | Default | Does |
169
+ | :--------------- | :---------------- | :----------------------------------------------------------------------------------------------------- |
170
+ | `strategies:` | `%w[redis file]` | Stores to try, in order. `filesystem` is another name for `file` |
171
+ | `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` |
172
+ | `async:` | `false` | Adds `#async`, see [Async](#async) |
173
+ | `holder:` | `:process` | What a lock's liveness is tied to: this Ruby process, or `:session` for `alock`'s rule |
174
+ | `session_name:` | none | Names the session; its locks are tied to no process and survive restarts |
175
+ | `agent_id:` | the session's id | The holder a call signs as, when the call names none |
176
+ | `parent_id:` | inferred | That holder's parent. `false` means it has none |
177
+ | `dir:` | `Dir.pwd` | The checkout whose locks a call reads, when the call names none |
178
+ | `stale_minutes:` | `120` | When a quiet lock counts as stale |
179
+
180
+ A list that is only `redis` raises `Agent::Lock::RedisUnavailableError` (a `RuntimeError`) at construction when that URL does not answer.
181
+
182
+ A facade and `alock` do not look for Redis the same way:
183
+
184
+ - 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.
185
+ - `alock` tries `$REDIS_URL` when it is set, then `redis://127.0.0.1:6379/0` (`RedisStore::LOCAL_URL`).
186
+ - 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.
187
+
188
+ #### Examples
189
+
190
+ The first example is the shared local file-system based lock.
191
+
192
+ ```ruby
193
+ require "agent/lock"
194
+
195
+ # First we'll use a File-System local lock which is cheap and fast
196
+ # NOTE: the current directory is expected to be a git project.
197
+ locker = Agent::Lock.local # file store, built once per process.
198
+
199
+ # Now we acquire an advisory lock on all files under lib/billing, presumably
200
+ # because we want to work on a billing feature.
201
+
202
+ locker.acquire "lib/billing/**", "rewriting the invoices", agent_id: "backend-agent"
203
+ locker.note "lib/billing/**", "totals done, specs red", agent_id: "backend-agent"
204
+ locker.check "lib/billing/tax.rb", agent_id: "backend-agent" # :mine
205
+
206
+ # And release all locks held by this agent
207
+ locker.release_all(agent_id: "backend-agent")
208
+ ```
209
+
210
+ #### Acquire with a block
211
+
212
+ Given a block, `acquire` yields the result, returns the block's value, and releases the lock afterwards, even when the block raises, `break`s or `throw`s. 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`.
213
+
214
+ ```ruby
215
+ locker.acquire("lib/billing/**", "rewriting the invoices", agent_id: "backend-agent") do |lock|
216
+ lock.status # => :acquired
217
+ rewrite_invoices
218
+ end # released here
219
+ ```
220
+
221
+ #### Async
222
+
223
+ `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.
224
+
225
+ 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.
226
+
227
+ 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.
228
+
229
+ ```ruby
230
+ locker = Agent::Lock::Facade.new(strategies: %w[redis], async: true)
231
+
232
+ future = locker.async.acquire("lib/billing/**", "rewriting the invoices", agent_id: "backend-agent")
233
+ future.value!.status # => :acquired, or raises Agent::Lock::Refused
234
+
235
+ locker.async.release("lib/billing/**", agent_id: "backend-agent").wait
236
+ ```
237
+
238
+ 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.
239
+
240
+
241
+ #### Threads, lifetime and session names
242
+
243
+ 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.
244
+
245
+ 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.
246
+
247
+ 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:
248
+
249
+ - It survives any number of restarts, and a restarted host that gives the same name finds it its own.
250
+ - 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.
251
+ - A lapsed lock with notes becomes interrupted work, for its own holder too: `resume` takes it back. One without notes is simply free again.
252
+ - On Redis, `AGENT_LOCK_TTL_SECONDS` still expires it outright, notes and all.
253
+ - Release it when the work is done; nothing else will until the window passes.
254
+
255
+ `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.
256
+
257
+ ```ruby
258
+ locks = Agent::Lock::Facade.new(strategies: %w[redis], session_name: "plan-003.00")
259
+ locks.acquire("lib/billing/**", "building") # held by plan-003.00, across restarts
260
+ locks.acquire("lib/billing/a.rb", agent_id: "luke-backend") # its parent is plan-003.00
261
+ ```
262
+
263
+ #### Method reference
264
+
265
+ 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.
266
+
267
+ ## A Ruby dispatcher and its `alock` agents
268
+
269
+ A dispatcher is a long-lived Ruby process that starts coding agents over a checkout: [OpenLanes](https://github.com/kigster/openlanes) is one. The dispatcher can call Ruby, so it locks through the [Ruby API](#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.
270
+
271
+ ```mermaid
272
+ flowchart TB
273
+ subgraph DISP["Dispatcher: one Ruby process"]
274
+ FACADE["Agent::Lock.distributed(redis_url: url)<br/>agent_id: dispatcher, parent_id: false"]
275
+ end
276
+
277
+ DISP -->|"starts each agent with"| ENV["AGENT_LOCK_REDIS_URL = url<br/>AGENT_PARENT_ID = dispatcher<br/>AGENT_ID = the agent's own name"]
278
+
279
+ ENV --> A1["Agent luke-backend<br/>alock acquire lib/billing/tax.rb"]
280
+ ENV --> A2["Agent rey-frontend<br/>alock acquire app/views/**"]
281
+
282
+ FACADE -->|"claims the plan's area"| STORE[("Redis<br/>alock-v4-&lt;owner&gt;/&lt;repo&gt;")]
283
+ A1 -->|"claims its files inside it"| STORE
284
+ A2 -->|"claims its files inside it"| STORE
285
+ ```
286
+
287
+ ### What has to match
288
+
289
+ 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.
290
+
291
+ | Must match | The dispatcher, in Ruby | An agent, with `alock` | When it does not |
292
+ | :--------- | :---------------------- | :--------------------- | :--------------- |
293
+ | 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 |
294
+ | 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 |
295
+ | 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 |
296
+
297
+ `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.
298
+
299
+ ### The dispatcher's side
300
+
301
+ ```ruby
302
+ require "agent/lock"
303
+
304
+ url = "redis://locks.internal:6379/0"
305
+ locks = Agent::Lock.distributed(redis_url: url) # one facade per URL, built once, thread-safe
306
+ me = { agent_id: "dispatcher", parent_id: false }
307
+
308
+ # Claim the area a plan may touch, in the checkout its agent will write in.
309
+ locks.acquire("lib/billing/**", "plan 003.00: build", dir: worktree, **me)
310
+
311
+ # Start the agent in that checkout, with the store and the family in its environment.
312
+ pid = Process.spawn(
313
+ { "AGENT_LOCK_REDIS_URL" => url, "AGENT_PARENT_ID" => "dispatcher", "AGENT_ID" => "luke-backend" },
314
+ "claude", "-p", prompt, chdir: worktree
315
+ )
316
+ Process.wait(pid)
317
+
318
+ locks.release_all(dir: worktree, **me) # the dispatcher's locks, and what its agents left behind
319
+ ```
320
+
321
+ - **`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.
322
+ - **Pass `dir:` on every call.** A dispatcher's own working directory is rarely the checkout its agents write in.
323
+ - **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.
324
+ - **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](#threads-lifetime-and-session-names).
325
+
326
+ ### An agent's side
327
+
328
+ The agent needs nothing but the skill (see [Teach your agents](#teach-your-agents)): the store and its parent are already in its environment. This is what it sees while the dispatcher holds `lib/billing/**`:
329
+
330
+ ```bash
331
+ $ alock whoami
332
+ id: luke-backend (from AGENT_ID)
333
+ parent: dispatcher (from AGENT_PARENT_ID)
334
+
335
+ $ alock acquire lib/billing/tax.rb "tax rounding" # inside its parent's claim
336
+ ACQUIRED lib/billing/tax.rb (holder: luke-backend)
337
+
338
+ $ alock acquire "lib/billing/**" # exactly its parent's claim
339
+ REFUSED: lib/billing/** is your parent's (dispatcher) whole claim; claim a narrower scope inside it
340
+
341
+ $ AGENT_ID=rey-frontend alock acquire lib/billing/tax.rb # another agent of the same dispatcher
342
+ REFUSED, do not write here
343
+ HELD lib/billing/tax.rb by luke-backend since 2026-11-27T19:14:05Z
344
+ intent: tax rounding
345
+ ```
346
+
347
+ An agent that was not started by this dispatcher, or a person in a terminal, is refused by both locks and shown both holders.
348
+
349
+ 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:
350
+
351
+ ```bash
352
+ AGENT_ID=luke-tax alock acquire lib/billing/tax.rb "rounding" # parent: dispatcher, inherited
353
+ ```
354
+
355
+ 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.
356
+
357
+ ### How one claim is decided
358
+
359
+ Both sides run the same check, under the store's mutex, against every live lock that overlaps the scope asked for:
360
+
361
+ ```mermaid
362
+ flowchart TB
363
+ ASK["Holder H asks for scope S"] --> OVER{"Does a live lock<br/>overlap S?"}
364
+ OVER -->|no| GRANT["ACQUIRED"]
365
+ OVER -->|yes| WHO{"Who holds it?"}
366
+ WHO -->|"H itself"| MINE["ALREADY YOURS"]
367
+ WHO -->|"H's parent"| SAME{"Is it exactly S?"}
368
+ SAME -->|"no, S is inside it"| GRANT
369
+ SAME -->|yes| NARROW["REFUSED<br/>claim a narrower scope"]
370
+ WHO -->|"a child of H, a sibling,<br/>or a stranger"| HELD["REFUSED<br/>HELD by that holder"]
371
+ ```
372
+
373
+ One refusing lock is enough. An interrupted lock at exactly `S` is neither granted nor refused: it is `INTERRUPTED WORK`, to `resume` or `break`.
374
+
375
+ ### One plan, start to finish
376
+
377
+ ```mermaid
378
+ sequenceDiagram
379
+ participant D as Dispatcher (Ruby API)
380
+ participant S as Redis
381
+ participant A as luke-backend (alock)
382
+ participant B as rey-frontend (alock)
383
+
384
+ D->>S: acquire lib/billing/** (parent_id: false)
385
+ S-->>D: :acquired
386
+ D->>A: start, with the store and AGENT_PARENT_ID
387
+ D->>B: start, with the store and AGENT_PARENT_ID
388
+ A->>S: alock acquire lib/billing/tax.rb
389
+ S-->>A: ACQUIRED (inside its parent's claim)
390
+ B->>S: alock acquire lib/billing/tax.rb
391
+ S-->>B: REFUSED, HELD by luke-backend
392
+ A->>S: alock note lib/billing/tax.rb "rounding done"
393
+ A->>S: alock release-all
394
+ S-->>A: its own locks, never the dispatcher's
395
+ A-->>D: exits
396
+ D->>S: release_all
397
+ S-->>D: its locks, and any its agents left
398
+ ```
399
+
400
+ ### Who ends which lock
401
+
402
+ | Event | The dispatcher's lock | An agent's lock |
403
+ | :---- | :-------------------- | :-------------- |
404
+ | The agent runs `alock release-all` | Stays | Released |
405
+ | The dispatcher calls `release(scope)` | That one is released | Stays, even inside the released scope |
406
+ | The dispatcher calls `release_all` | Released | Released too: they are its children |
407
+ | The agent's process exits without releasing | Stays | Reaped by the next command on that machine; with notes it becomes interrupted work |
408
+ | 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 |
409
+ | Either holder is on another machine and goes quiet | Trusted until untouched for `AGENT_LOCK_STALE_MINUTES` | The same |
410
+ | Redis stops answering | `RedisUnavailableError`; nothing is claimed | `alock` exits 2; nothing is claimed, and nothing falls back to disk |
411
+
412
+ 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.
413
+
143
414
  ## How it works
144
415
 
145
416
  ### Identity comes from the session
@@ -149,19 +420,20 @@ In order of preference:
149
420
  | Source | When it applies |
150
421
  | :------------------ | :------------------------------------------------------ |
151
422
  | `AGENT_ID` | A human or a harness named this session on purpose |
423
+ | `session_name:` | Ruby API only: the host named its session, see [Ruby API](#threads-lifetime-and-session-names) |
152
424
  | `CLAUDE_SESSION_ID` | A harness that exports it, since it survives `--resume` |
153
- | Fingerprint | Neither of the above is set |
425
+ | Fingerprint | None of the above is set |
154
426
 
155
- 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, 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.
427
+ 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.
156
428
 
157
429
  > [!NOTE]
158
430
  > 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.
159
431
 
160
432
  `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.
161
433
 
162
- ### Locks live inside `.git.`
434
+ ### The file store lives inside `.git`
163
435
 
164
- The store is `$(git rev-parse --git-common-dir)/agent-locks`.
436
+ 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](#backends).
165
437
 
166
438
  | Property | Why it matters |
167
439
  | :-------------------------------------------- | :----------------------------------------------- |
@@ -188,6 +460,8 @@ Rewriting the installer
188
460
  - 2026-09-09T21:14:02Z installer rewritten, specs still red
189
461
  ```
190
462
 
463
+ A line of the intent that is exactly `## Progress` is stored as `\## Progress`, so only `alock note` can start the notes section.
464
+
191
465
  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.
192
466
 
193
467
  ### Scopes are globs
@@ -199,7 +473,9 @@ An agent that runs into this learns who owns the scope and what they are doing,
199
473
  | `workflow` | The same thing. A directory means everything in it |
200
474
  | `lib/cli.rb` | One file |
201
475
 
202
- 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/**`.
476
+ 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.
477
+
478
+ 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.
203
479
 
204
480
  > [!TIP]
205
481
  > 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.
@@ -238,6 +514,12 @@ AGENT_ID=luke-backend alock release-all
238
514
 
239
515
  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.
240
516
 
517
+ 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:
518
+
519
+ - `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.
520
+ - A service that exports it empty passes that to the agents it starts. Give each of them `AGENT_PARENT_ID=<the service's id>`.
521
+ - 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`.
522
+
241
523
  > [!NOTE]
242
524
  > 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.
243
525
 
@@ -253,63 +535,78 @@ A lock is cleared when its holder is provably gone: the process that signed it h
253
535
  ```
254
536
  $ alock acquire workflow/**
255
537
  INTERRUPTED WORK on workflow/**, left by luke-backend
256
- alock resume workflow/** # take it back, notes and all
257
- alock break workflow/** # throw it away and start over
538
+ alock resume 'workflow/**' # take it back, notes and all
539
+ alock break 'workflow/**' # throw it away and start over
258
540
  ```
259
541
 
260
542
  > [!WARNING]
261
543
  > 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`.
262
544
 
263
- A live holder's lock is never cleared, no matter how old it is. 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`, `check` and `mine` tag it `STALE` instead, and taking it is a `break` that somebody announces first.
545
+ 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.
546
+
547
+ `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.
264
548
 
265
549
  ```
266
550
  $ alock list
267
- Locks held (2):
268
- app/** orchestrator 2026-09-11T16:04:56Z
269
- fanning out
270
- docs/** slow-agent 2026-09-11T13:04:55Z STALE
271
- rewriting the guides
272
- Interrupted (1):
273
- db/** crashed-agent 2026-09-11T15:54:55Z INTERRUPTED
274
- splitting the migrations
551
+ ┌────────────────────────────┬──────────────┬─────────┬─────────────┬────────┐
552
+ │ Namespace │ Holder │ Scope │ Status │ Held │
553
+ ├────────────────────────────┼──────────────┼─────────┼─────────────┼────────┤
554
+ │ alock-v4-kigster/shop │ orchestrator │ app/** │ active │ 2m 10s │
555
+ │ alock-v4-kigster/shop │ slow-agent │ docs/** │ stale │ 3h 01m │
556
+ │ alock-v4-kigster/shop │ crashed │ db/** │ interrupted │ 12m │
557
+ └────────────────────────────┴──────────────┴─────────┴─────────────┴────────┘
275
558
  ```
276
559
 
277
- Only live claims are counted as held. `--json` gives every record its `status` and a `stale` flag.
560
+ `--json` gives every record its `status` and a `stale` flag.
278
561
 
279
562
  ## Commands
280
563
 
281
- | Command | Does | Exit code |
282
- | :------------------------- | :----------------------------------------------------- | :----------------------------------------------------- |
283
- | `acquire <scope> [intent]` | Claim a scope | 1 if held, interrupted, or exactly your parent's scope |
284
- | `release <scope>` | Give it back | 1 if it belongs to somebody else |
285
- | `check <scope>` | Report who holds it | 1 if held by another session |
286
- | `note <scope> <text>` | Record progress inside a lock you hold | 1 if you do not hold it |
287
- | `resume <scope>` | Take back work a crash interrupted | 1 if there is nothing to resume |
288
- | `list` | Every lock in the store | 0 |
289
- | `mine` | What this session and its sub-agents hold | 0 |
290
- | `release-all` | Everything this session and its sub-agents hold | 0 |
291
- | `break <scope>` | Take a live lock away from its holder | 0 |
292
- | `whoami` | The name this session signs locks with, and its parent | 0 |
293
- | `skills install` | Copy the bundled skill into a skills directory | 1 if a different copy or a symlink is there |
294
- | `skills path` | Where the bundled skill is | 0 |
295
- | `completion bash\|zsh` | Print a shell completion script | 1 for any other shell |
564
+ `alock --help` lists them; `alock <command> --help` shows each one's arguments, flags and examples.
565
+
566
+ | Command | Does | Exits 1 when |
567
+ | :------------------------- | :------------------------------------------------------ | :------------------------------------------------ |
568
+ | `acquire <scope> [intent]` | Claim a path, directory or glob before writing there | held, interrupted, or exactly your parent's scope |
569
+ | `release <scope>` | Give a lock back, thawing any files it froze | somebody else holds it |
570
+ | `check <scope>` | Say who holds a path | another agent holds it |
571
+ | `note <scope> <text>` | Append a timestamped progress note to your lock | you do not hold it |
572
+ | `resume <scope>` | Take back work a crash or reboot interrupted | there is nothing to resume, or it was re-claimed |
573
+ | `break <scope>` | Take a lock from its holder, even a live one | nothing is locked there |
574
+ | `list` (`ls`) | Every lock in this repository, live and interrupted | never |
575
+ | `show repos` | Redis: repositories, lock counts, and the memory used | never (exit 2 when Redis does not answer) |
576
+ | `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) |
577
+ | `mine` | Locks held by this session and its sub-agents | never |
578
+ | `release-all` | Release all of those | never |
579
+ | `switch-backend <store>` | Bind this checkout to `redis` or `filesystem` | the old store still holds this checkout's locks |
580
+ | `whoami` | The id your locks would carry, its parent, their source | never |
581
+ | `skills install` | Copy the bundled skill into a skills directory | a different copy, or a symlink, is there |
582
+ | `skills path` | Print where the bundled skill lives | never |
583
+ | `completion bash\|zsh` | Print a shell completion script | any other shell |
584
+ | `version` | Print the installed version | never |
585
+
586
+ `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.
296
587
 
297
588
  Flags:
298
589
 
299
- | Flag | Where | Does |
300
- | :----------- | :-------------------------------- | :-------------------------------------- |
301
- | `--json` | `check`, `list`, `mine`, `whoami` | Machine-readable output |
302
- | `--dir PATH` | Everywhere | Work as if run from `PATH` |
303
- | `--enforce` | `acquire` | Also make the matched files unwritable |
304
- | `--force` | `acquire` | Permit `--enforce` on a very wide scope |
305
-
306
- Any command exits 2 when it cannot run at all: an empty or out-of-tree scope, a backend mismatch, or a store it cannot reach.
590
+ | Flag | Where | Does |
591
+ | :------------- | :----------------------------------------------------------------- | :--------------------------------------------------------- |
592
+ | `--dir PATH` | every command that reads locks (not `whoami`, `skills`, `version`) | Act on the checkout that contains `PATH` |
593
+ | `-s`, `--locking-strategy redis\|filesystem` | the same commands | Use that store, instead of `AGENT_LOCK_BACKEND` or whichever answers first |
594
+ | `-u`, `--redis-url URL` | the same commands | Use that one Redis, with no fallback. Implies `--locking-strategy redis` |
595
+ | `--json` | `check`, `list`, `mine`, `whoami` | Machine-readable output |
596
+ | `--enforce` | `acquire` | Also freeze the matched files (macOS) |
597
+ | `--allow-wide` | `acquire` | Let `--enforce` freeze more than 500 files |
598
+ | `--discard-locks` | `switch-backend` | Delete the old store's locks instead of refusing |
599
+ | `--into DIR` | `skills install` | Install into `DIR` |
600
+ | `--for AGENT` | `skills install` | `claude` means `~/.claude/skills`, else `~/.agents/skills` |
601
+ | `--overwrite` | `skills install` | Replace an installed copy that differs |
602
+
603
+ 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.
307
604
 
308
605
  ## Shell completion
309
606
 
310
607
  ```bash
311
- alock completion bash > "$(brew --prefix)/etc/bash_completion.d/alo"
312
- alock completion zsh > "${fpath[1]}/_alo"
608
+ alock completion bash > "$(brew --prefix)/etc/bash_completion.d/alock"
609
+ alock completion zsh > "${fpath[1]}/_alock"
313
610
  ```
314
611
 
315
612
  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.
@@ -319,50 +616,131 @@ Names every command and flag `alock` currently knows, since the script is genera
319
616
  | Variable | Default | Does |
320
617
  | :------------------------- | :-------------------------------------- | :----------------------------------------------------------------------- |
321
618
  | `AGENT_ID` | fingerprint | Name this session yourself |
322
- | `AGENT_PARENT_ID` | the fingerprint, when `AGENT_ID` is set | The session that spawned this one |
323
- | `AGENT_LOCK_DIR` | `.git/agent-locks` | Keep locks somewhere else |
324
- | `AGENT_LOCK_STALE_MINUTES` | `120` | When a lock is tagged `STALE`, and when one from another machine expires |
619
+ | `AGENT_PARENT_ID` | the fingerprint, when `AGENT_ID` is set | The session that spawned this one. Set and empty: no parent |
620
+ | `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 |
621
+ | `AGENT_LOCK_STALE_MINUTES` | `120` | When a lock is tagged `STALE`, and when one from another machine, or with no process, expires |
325
622
  | `AGENT_LOCK_MUTEX_TIMEOUT` | `15` | Seconds a claim waits for the store's mutex before giving up with exit 2 |
326
- | `AGENT_LOCK_BACKEND` | `redis` if one answers, else `file` | `file` or `redis` |
623
+ | `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 |
327
624
  | `AGENT_LOCK_TTL_SECONDS` | `0` | Redis expiry. `0` means no TTL |
328
625
  | `REDIS_URL` | unset | A shared Redis, tried before `redis://127.0.0.1:6379/0` |
626
+ | `AGENT_LOCK_REDIS_URL` | unset | The one Redis to use, with no fallback: `--redis-url` for every call |
627
+
628
+ `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.
329
629
 
330
630
  ## Backends
331
631
 
332
- Redis stores the same documents as the file store, and buys two things a filesystem cannot: its mutex holds across machines, and a TTL 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.
632
+ 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.
333
633
 
334
- 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, so it is never a guess which one you are on.
634
+ 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.
635
+
636
+ 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.
335
637
 
336
638
  ```bash
337
639
  AGENT_LOCK_BACKEND=redis alock acquire workflow/** # force it, rather than autodetect
338
640
  AGENT_LOCK_BACKEND=file alock acquire workflow/** # or force the file store instead
339
641
  ```
340
642
 
643
+ 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:
644
+
645
+ ```mermaid
646
+ flowchart TB
647
+ CMD["alock command"] --> NAMED{"Is a store named?<br/>-s, -u, AGENT_LOCK_REDIS_URL<br/>or AGENT_LOCK_BACKEND"}
648
+ NAMED -->|yes| AGREE{"Does the tree's marker<br/>name another store?"}
649
+ AGREE -->|yes| MISMATCH["exit 2: mismatch<br/>HINT: alock switch-backend"]
650
+ AGREE -->|"no, or no marker yet"| USE["Use the named store.<br/>A named Redis must answer, or exit 2"]
651
+ NAMED -->|no| MARK{"Does the tree<br/>have a marker?"}
652
+ MARK -->|yes| BOUND["Use the marker's store"]
653
+ MARK -->|no| PROBE{"Does a Redis answer?<br/>REDIS_URL, then 127.0.0.1:6379"}
654
+ PROBE -->|yes| REDIS["Redis, and the marker says so"]
655
+ PROBE -->|no| FILE["File store, and the marker says so"]
656
+ ```
657
+
658
+ 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:
659
+
660
+ ```bash
661
+ alock acquire workflow/** --locking-strategy filesystem # -s for short; file is another name for it
662
+ alock acquire workflow/** --locking-strategy redis # Redis or fail: REDIS_URL, then the local default
663
+ alock acquire workflow/** --redis-url redis://locks.internal:6379 # -u for short: this Redis and no other
664
+ alock release workflow/** --redis-url redis://locks.internal:6379 # every later call names it too
665
+ ```
666
+
667
+ - A flag wins over `AGENT_LOCK_BACKEND`. Neither wins over the tree's marker: naming the store the tree does not use exits 2.
668
+ - `--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`.
669
+ - `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.
670
+ - 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.
671
+ - A Redis URL, from the flag or the variable, beside the file store (`--locking-strategy filesystem` or `AGENT_LOCK_BACKEND=file`) exits 2.
672
+ - `--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.
673
+
674
+ ### Switching a checkout to the other store
675
+
676
+ Releasing every lock does not move the marker. `switch-backend` does, and a mismatch error names it on its second line:
677
+
678
+ ```text
679
+ ERROR: alock: this tree's locks live in file, not redis
680
+ HINT: run 'alock switch-backend redis'
681
+ ```
682
+
683
+ ```bash
684
+ alock switch-backend redis # exits 1 while the file store holds this checkout's locks
685
+ alock switch-backend redis -u redis://locks.internal # this Redis, which must answer before anything changes
686
+ alock switch-backend filesystem --discard-locks # delete the old store's locks, thawing what they froze, then switch
687
+ ```
688
+
689
+ - 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.
690
+ - 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.
691
+ - The new store is connected to first. A Redis that does not answer exits 2 with nothing deleted and the marker unchanged.
692
+ - 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>`.
693
+ - `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.
694
+ - 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.
695
+ - 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.
696
+
341
697
  ### One repository, many machines
342
698
 
343
699
  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:
344
700
 
345
- | Two checkouts of one repository | Do their locks collide? |
346
- | ------------------------------------------------- | ---------------------------------------------------------- |
347
- | Same branch, any machine, any path | Yes, on overlapping scopes; different files are fine |
348
- | Different branches, such as two worktrees | No: separate branches are what a worktree is for |
349
- | One checkout that switched branch after claiming | Yes: the files on disk did not change hands |
350
- | A detached HEAD | Only within that checkout, since it has no branch to share |
701
+ | Two checkouts of one repository | Do their locks collide? |
702
+ | ------------------------------------------------ | ---------------------------------------------------------- |
703
+ | Same branch, any machine, any path | Yes, on overlapping scopes; different files are fine |
704
+ | Different branches, such as two worktrees | No: separate branches are what a worktree is for |
705
+ | One checkout that switched branch after claiming | Yes: the files on disk did not change hands |
706
+ | A detached HEAD | Only within that checkout, since it has no branch to share |
707
+
708
+ 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.
709
+
710
+ #### Why this makes it a distributed lock
351
711
 
352
- The repository is named by its `origin` URL, normalized so that `git@github.com:a/b.git` and `https://github.com/a/b` agree. A repository with no `origin` is named by its root commit, and a directory outside git by its path.
712
+ 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:
353
713
 
354
- Either way, every claim checks for conflicts and writes its lock while holding one mutex for the whole store. 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 `agent-lock-mutex:<repository digest>` 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.
714
+ | A distributed lock needs | How `agent-lock` provides it |
715
+ | :--------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
716
+ | 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 |
717
+ | 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. |
718
+ | 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 |
719
+ | 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 |
720
+ | 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 |
721
+
722
+ Where the guarantees stop:
723
+
724
+ - **It is advisory.** A lock protects a file only from agents that check. `--enforce` freezes files on the local machine only.
725
+ - **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.
726
+ - **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.
727
+ - **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.
728
+
729
+ > [!IMPORTANT]
730
+ > 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.
731
+
732
+ 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.
355
733
 
356
734
  > [!CAUTION]
357
735
  > 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.
358
736
  >
359
- > 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 — the first `O_CREAT|O_EXCL` wins — 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.
737
+ > 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.
360
738
 
361
739
  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.
362
740
 
363
741
  ## Freezing files, on macOS
364
742
 
365
- `acquire --enforce` also runs `chflags uchg` on every matched file, which makes them unwritable by anything, whether it checks for locks or not.
743
+ `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.
366
744
 
367
745
  ```bash
368
746
  alock acquire "config/credentials/**" "keys must not move during the migration" --enforce
@@ -372,21 +750,39 @@ alock acquire "config/credentials/**" "keys must not move during the migration"
372
750
  > 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".
373
751
  >
374
752
  > Every frozen path is written into the lock, so `release` and `break` thaw them without needing the process that froze them to still exist.
753
+ >
754
+ > 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.
755
+
756
+ ## Upgrading to 4.0.0
757
+
758
+ What changes for a caller coming from 3.1.0:
759
+
760
+ | Before | In 4.0.0 |
761
+ | :----- | :------- |
762
+ | `alock acquire --enforce --force` | `--allow-wide` |
763
+ | `alock skills install --force` or `-f` | `--overwrite` |
764
+ | `alock skills install -o DIR` | `--into DIR`; `-o` is gone |
765
+ | `AGENT_PARENT_ID` set and empty was ignored | It means "no parent". `alock whoami` says so when that is why |
766
+ | `Manager#acquire(force:)`, `Skill#install(force:)` | `wide:`, `overwrite:` |
767
+ | `alock` printed nothing and exited 0 on an unexpected error | `ERROR: alock: ...` and exit 2 |
768
+
769
+ New in 4.0.0: the [Ruby API](#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.
375
770
 
376
771
  ## Development
377
772
 
378
773
  ```bash
379
774
  bin/setup
380
- bundle exec rspec # 228 examples, against the file backend
381
- AGENT_LOCK_TEST_BACKEND=redis bundle exec rspec # the same suite, against Redis instead
382
- bundle exec rubocop
775
+ bundle exec rspec # against the file backend
776
+ AGENT_LOCK_TEST_BACKEND=redis bundle exec rspec # the same suite, against Redis
777
+ bundle exec rubocop # or: just lint
778
+ bundle exec rake doc # YARD site in doc/ (git-ignored), opened in a browser
383
779
  ```
384
780
 
385
- The suite runs against one backend at a time, picked by `AGENT_LOCK_TEST_BACKEND` rather than the machine's own default, so it stays deterministic whether or not Redis happens to be running: only the examples that test one backend's own on-disk or on-Redis shape care which one that is, and a Redis run defaults to database 15 so it never touches whatever database a developer's own Redis work lives in. CI runs both, plus rubocop as a third, independent job.
781
+ 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.
386
782
 
387
- A `justfile` covers the rest: `just test`, `just test-coverage`, `just ci` (rubocop then coverage), `just format` (autocorrect, then regenerate `.rubocop_todo.yml`), and `just publish`/`just release` for cutting a version. `just lint` currently names `standardrb`, which is not one of this gem's dependencies; use `bundle exec rubocop` until that recipe is reconciled with the rest of the project's tooling.
783
+ 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.
388
784
 
389
- The library decides and the CLI prints. Every verb is a method on `Manager` that returns a result and prints nothing, so the whole lifecycle can be tested without capturing output. `Launcher` takes `argv`, `stdin`, `stdout`, `stderr` and `kernel` as arguments, and nothing below it calls `puts` or a receiverless `exit`, which is what lets Aruba run the CLI end to end inside the test process instead of forking a Ruby per example.
785
+ 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%.
390
786
 
391
787
  ## License
392
788