agent-lock 2.1.0 → 3.1.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d1f106a6394f81598c390390a2d83aeb051b9e22d799c23129eeed6aba0f0822
4
- data.tar.gz: d31b63c4c1469eee913e33ca102dcb35f108d7b1aabb24408ec8bdd8b92958d4
3
+ metadata.gz: 45e7c0e68bb173ac3a8ff2f05626a18c0f84c932f61bebe55162206362f25214
4
+ data.tar.gz: 9a5abc2c815b315a46b9dd72002b3f790c588d486bf1f8f5be9294bf17d6e404
5
5
  SHA512:
6
- metadata.gz: 8a947455256070a8bc2eb2211f63fdcc970b64e25d479ed57724ac17dbd39a28c4317fcf28465fa91b58942f4a24231af72190c34519640c905c4e04a254b38a
7
- data.tar.gz: ce09be390c7cbbd93315e7b359fd30efbb53fb064d8b98b849fcb8e3fa59756fb85eec0c46b0c23d837aa87aa5d815d726c152bf4be56f44d48163eaa402310d
6
+ metadata.gz: 0d560c2b7ec0b568744fae8918486e0fb8fa621f6123d7ad6880319f5eb6822f5ab651a5ffc2fdc6722e43e16a110259cfb11b55d86a9733af318c2da9493b7f
7
+ data.tar.gz: 0d3b0c50a64864e64f467a58d373e59b552f0e1b08704c1dd2723adcc532f3bf6f50fc85e401b13b2c1614b4f569c314b7b93b2aff49428943a564a8513b6994
data/.openlanes.yml ADDED
@@ -0,0 +1,3 @@
1
+ project: agent-lock
2
+ lane: plan
3
+ frontend: false
data/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ### Changed
6
+
7
+ - **Breaking for Redis users:** locks are keyed by the repository and branch, not the checkout's absolute path. The Redis namespace and mutex are now `agent-lock:<repository digest>`, where the repository is the normalized `origin` URL, else the root commit, else the path outside git. Two machines on one Redis, or two clones on one machine, now block each other on overlapping scopes of the same branch, and checkouts on different branches (worktrees, typically) still do not. Locks taken by an earlier version under the old path-keyed namespace are not seen; release them before upgrading.
8
+ - `release`, `note`, `break` and `resume` find a lock this checkout took on another branch, so switching branches after claiming no longer strands it. That checkout still blocks itself on those files, since they are the same files on disk. `release` and `note` take the lock this session owns when another checkout holds the same scope on the new branch.
9
+ - A detached HEAD is keyed by its path on its own host, so two machines with a checkout at the same path do not collide.
10
+ - `resume` refuses (exit 1, `HELD`) when somebody claimed an overlapping scope while the work sat interrupted, and the resumed claim covers the branch the checkout is on now rather than the one the orphan was taken on.
11
+ - Reaping a lock from another checkout or another machine no longer clears this checkout's freeze flags on files of the same relative name.
12
+
13
+ - Development moves to Ruby 4.1.0-preview1 (`.ruby-version`). CI runs the suite on both 4.0.6 and 4.1.0-preview1, and rubocop on whatever `.ruby-version` names. `required_ruby_version` is unchanged.
14
+ - `alock skill install` and `alock skill path` are now `alock skills install` and `alock skills path`. The old `skill` spelling is gone.
15
+ - `alock skills install --help` names every skill it installs, and renders at all: an empty example string used to crash dry-cli-help, and the launcher exited 0 with no output.
16
+
5
17
  ## [2.1.0]
6
18
 
7
19
  ### Added
data/README.md CHANGED
@@ -1,21 +1,18 @@
1
- # Agent::Lock (v2.0.1)
1
+ # Agent Lock `agent-lock` CLI
2
2
 
3
3
  [![Ruby](https://github.com/kigster/agent-lock/actions/workflows/main.yml/badge.svg)](https://github.com/kigster/agent-lock/actions/workflows/main.yml)
4
4
 
5
- Advisory locks on files and folders with pluggable backends (redis and file-system provided out the box, with redis being the default if it's available locally). This locking tool is meant to be used by the coding agents that share a checkout.
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.
6
6
 
7
7
  > [!NOTE]
8
8
  >
9
- > Please note that `agent-lock` is part of a three-part system:
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.
10
10
  >
11
- > 1. `agentilda` is the Ruby Gem, which is a CLI tool that creates and manages the `.plans` folder, and comes with eight or so specialized agents that take a spec.md file and work through it until it's a set of PRs open, reviewed, and passing on your CI. It does not automatically merge anything.
12
- > 2. [`agentilda-ai-setup`](https://kigster/agentilda-ai-setup) is the GitHub repo that's a mixture of BASH and Ruby installers. It's comes with the [`configuration.yml`](https://github.com/kigster/agentilda-ai-setup/blob/main/configuration.example.yml) file, which lists the installation commands for the coding agents you'd like to install locally, any other executables you might want (for instance, it installs `bt` — braintrust's CLI utility), and then you can list any number of Github Repos and use them to install skills, plugins, commands from them, specifying exactly which you want to install and which you want to exclude. Moreover you can specify a sub-directory of a github repo to install from.
13
- >
14
- > Together, the three repos, after installation provide you with the consistent way to replicate your `~/.agents` and `~/.claude` folders on multiple computers, and to also replicate a consistent agentic software team workflow across many projects.
11
+ > That said, you can absolutely use the `agent-lock` gem in your own environment.
15
12
 
16
13
  ## What it is
17
14
 
18
- `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, which is the harder case.
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.
19
16
 
20
17
  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.
21
18
 
@@ -27,6 +24,8 @@ Git does not help here. Two agents on one branch and one working tree never prod
27
24
 
28
25
  - **Harnesses** that launch agents over a repository and need them to stay out of each other's way.
29
26
 
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)
28
+
30
29
  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.
31
30
 
32
31
  ## How to use it
@@ -35,7 +34,8 @@ Not for work that can have a checkout of its own. A git worktree per agent remov
35
34
 
36
35
  ```bash
37
36
  gem install agent-lock
38
- alock version # alock must be on PATH
37
+ hash -r
38
+ alock version # alock must be on PATH
39
39
  ```
40
40
 
41
41
  Or add `gem "agent-lock"` to a Gemfile.
@@ -107,15 +107,15 @@ Three things matter, and each one fails silently if skipped:
107
107
  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
108
 
109
109
  ```bash
110
- alock skill install # default: into ~/.agents/skills, for most agents
111
- alock skill install --for claude # into ~/.claude/skills instead
112
- alock skill install --into some/path # anywhere else, --for is ignored if both are given
113
- alock skill path # where the bundled copy is
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 path # where the bundled copy is
114
114
  ```
115
115
 
116
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.
117
117
 
118
- If skills on your machine are installed from repositories by a manifest, name this one as a source instead, so the skill is recorded along with where it came from. For example:
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:
119
119
 
120
120
  ```yaml
121
121
  - name: agent-lock
@@ -155,11 +155,11 @@ In order of preference:
155
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.
156
156
 
157
157
  > [!NOTE]
158
- > 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.
158
+ > 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
159
 
160
160
  `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
161
 
162
- ### Locks live inside `.git`
162
+ ### Locks live inside `.git.`
163
163
 
164
164
  The store is `$(git rev-parse --git-common-dir)/agent-locks`.
165
165
 
@@ -182,13 +182,13 @@ status: active
182
182
  pid: 69232
183
183
  created_at: 2026-09-09T21:04:11Z
184
184
  ---
185
- rewriting the installer
185
+ Rewriting the installer
186
186
 
187
187
  ## Progress
188
188
  - 2026-09-09T21:14:02Z installer rewritten, specs still red
189
189
  ```
190
190
 
191
- An agent that runs into this learns who holds the scope and what they are doing, so it can decide whether to wait or to work somewhere else. A human can read the same file in an editor.
191
+ 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
192
 
193
193
  ### Scopes are globs
194
194
 
@@ -199,10 +199,10 @@ An agent that runs into this learns who holds the scope and what they are doing,
199
199
  | `workflow` | The same thing. A directory means everything in it |
200
200
  | `lib/cli.rb` | One file |
201
201
 
202
- Two scopes conflict when either one's fixed part contains the other's. So `workflow/**` conflicts with `workflow/lib/cli.rb`, and `docs/**` does not conflict with `workflow/**`.
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/**`.
203
203
 
204
204
  > [!TIP]
205
- > The rule deliberately refuses more often than it strictly must. Working out whether two globs can ever match the same path has answers nobody can predict, and the price of guessing wrong is somebody's lost work.
205
+ > 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.
206
206
 
207
207
  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:
208
208
 
@@ -222,7 +222,7 @@ Ownership and blocking are separate questions, and conflating them is what lets
222
222
  | A sub-agent you spawned | No, you handed that scope out | Yes, so cleanup takes them with it |
223
223
  | A sibling sub-agent | No | No |
224
224
 
225
- A sub-agent claiming inside its parent's lock gets a lock of its own, and that lock is what 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.
225
+ 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.
226
226
 
227
227
  #### Sub-agents that share their parent's process
228
228
 
@@ -243,7 +243,7 @@ When `AGENT_ID` is set and `AGENT_PARENT_ID` is not, the parent is taken to be t
243
243
 
244
244
  ### A crash does not strand the tree
245
245
 
246
- A lock is cleared out of the way 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:
246
+ 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:
247
247
 
248
248
  | The lock has | What happens to it |
249
249
  | :----------- | :----------------------------------------------- |
@@ -260,7 +260,7 @@ INTERRUPTED WORK on workflow/**, left by luke-backend
260
260
  > [!WARNING]
261
261
  > 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
262
 
263
- A live holder's lock is never cleared, however 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.
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.
264
264
 
265
265
  ```
266
266
  $ alock list
@@ -290,8 +290,8 @@ Only live claims are counted as held. `--json` gives every record its `status` a
290
290
  | `release-all` | Everything this session and its sub-agents hold | 0 |
291
291
  | `break <scope>` | Take a live lock away from its holder | 0 |
292
292
  | `whoami` | The name this session signs locks with, and its parent | 0 |
293
- | `skill install` | Copy the bundled skill into a skills directory | 1 if a different copy or a symlink is there |
294
- | `skill path` | Where the bundled skill is | 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
295
  | `completion bash\|zsh` | Print a shell completion script | 1 for any other shell |
296
296
 
297
297
  Flags:
@@ -303,7 +303,7 @@ Flags:
303
303
  | `--enforce` | `acquire` | Also make the matched files unwritable |
304
304
  | `--force` | `acquire` | Permit `--enforce` on a very wide scope |
305
305
 
306
- Any command exits 2 when it cannot run at all: a scope that is empty or outside the tree, a backend mismatch, or a store it cannot reach.
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.
307
307
 
308
308
  ## Shell completion
309
309
 
@@ -312,7 +312,7 @@ alock completion bash > "$(brew --prefix)/etc/bash_completion.d/alo"
312
312
  alock completion zsh > "${fpath[1]}/_alo"
313
313
  ```
314
314
 
315
- Names every command and flag `alock` currently knows, since the script is generated from the same registry the CLI runs, rather than hand-maintained separately from it.
315
+ 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.
316
316
 
317
317
  ## Configuration
318
318
 
@@ -338,10 +338,23 @@ AGENT_LOCK_BACKEND=redis alock acquire workflow/** # force it, rather than aut
338
338
  AGENT_LOCK_BACKEND=file alock acquire workflow/** # or force the file store instead
339
339
  ```
340
340
 
341
- 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:<tree 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.
341
+ ### One repository, many machines
342
+
343
+ 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
+
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 |
351
+
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.
353
+
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.
342
355
 
343
356
  > [!CAUTION]
344
- > 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 which backend it is, in a marker file, and every later process in that tree is bound to it regardless of what Redis is doing next; a mismatch stops the run rather than silently picking the other one.
357
+ > 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.
345
358
  >
346
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.
347
360
 
@@ -356,7 +369,7 @@ alock acquire "config/credentials/**" "keys must not move during the migration"
356
369
  ```
357
370
 
358
371
  > [!WARNING]
359
- > This is opt-in for three reasons. It is 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".
372
+ > 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".
360
373
  >
361
374
  > Every frozen path is written into the lock, so `release` and `break` thaw them without needing the process that froze them to still exist.
362
375
 
data/Rakefile CHANGED
@@ -2,11 +2,43 @@
2
2
 
3
3
  require "bundler/gem_tasks"
4
4
  require "rspec/core/rake_task"
5
+ require "timeout"
6
+ require "yard"
5
7
 
6
- RSpec::Core::RakeTask.new(:spec)
8
+ def shell(*args)
9
+ puts "running: #{args.join(" ")}"
10
+ system(args.join(" "))
11
+ end
12
+
13
+ desc "Clean all temporary files"
14
+ task :clean do
15
+ shell("rm -rf pkg/ tmp/ coverage/ doc/ ")
16
+ end
17
+
18
+ desc "Build the gem locally into pkg/"
19
+ task gem: [:build] do
20
+ shell("gem install pkg/*")
21
+ end
7
22
 
8
- require "rubocop/rake_task"
23
+ desc "Set permissions on all files so that users can read them"
24
+ task permissions: [:clean] do
25
+ # One traversal replaces a six-level glob chain that printed "No such file
26
+ # or directory" for every level this project does not have, skipped dotfiles
27
+ # entirely, and silently stopped at depth six. .git is pruned — its objects
28
+ # have no business being group-readable.
29
+ shell("find . -path ./.git -prune -o -type d -exec chmod o+rx,g+rx {} + -o -type f -exec chmod o+r,g+r {} +")
30
+ end
9
31
 
10
- RuboCop::RakeTask.new
32
+ desc "Build the gem and set the permissions"
33
+ task build: :permissions
34
+
35
+ desc "Generate yard documentation"
36
+ YARD::Rake::YardocTask.new(:doc) do |t|
37
+ t.files = %w[lib/**/*.rb exe/*.rb - README.md CHANGELOG.md AGENTS.md LICENSE.txt]
38
+ t.options.unshift("--title", '"FlowEngine — DSL + AST for buildiong complex flows in Ruby."')
39
+ t.after = -> { exec("open doc/index.html") } if RUBY_PLATFORM.match?(/darwin/)
40
+ end
41
+
42
+ RSpec::Core::RakeTask.new(:spec)
11
43
 
12
- task default: %i[spec rubocop]
44
+ task default: :spec
@@ -17,17 +17,33 @@ module Agent
17
17
  argument :scope, required: true, desc: "The path or glob to pick up"
18
18
 
19
19
  def call(scope:, **options)
20
- result = manager(options[:dir]).resume(scope)
20
+ manager = manager(options[:dir])
21
+ result = manager.resume(scope)
22
+ report(result, scope, manager.stale_minutes)
23
+ finish(result)
24
+ end
25
+
26
+ private
21
27
 
22
- if result.status == :not_found
23
- say("NOTHING TO RESUME #{scope}")
28
+ # @param result [Manager::Result]
29
+ # @param scope [String] as typed
30
+ # @param stale_minutes [Integer]
31
+ def report(result, scope, stale_minutes)
32
+ case result.status
33
+ when :not_found then say("NOTHING TO RESUME #{scope}")
34
+ when :held
35
+ # Somebody claimed an overlapping scope while the work sat
36
+ # orphaned; their claim is live and this one is not.
37
+ warn_("REFUSED, somebody claimed it while it was interrupted; the notes are still there")
38
+ report_held(result.records, stale_minutes: stale_minutes)
39
+ when :interrupted
40
+ warn_("REFUSED, #{result.record&.agent_id || "another session"} left interrupted work " \
41
+ "on #{scope} on this branch; resume or break that first")
24
42
  else
25
43
  say("RESUMED #{result.record.scope} (holder: #{result.record.agent_id})")
26
44
  say("")
27
45
  say(result.record.intent)
28
46
  end
29
-
30
- finish(result)
31
47
  end
32
48
  end
33
49
  end
@@ -9,7 +9,7 @@ module Agent
9
9
  module Commands
10
10
  # Where the bundled skill is, for a harness that would rather link it
11
11
  # than copy it, or a configuration that names it by path.
12
- class SkillPath < Base
12
+ class SkillsPath < Base
13
13
  desc "Print the directory of the skill this gem ships"
14
14
 
15
15
  def call(**)
@@ -19,8 +19,8 @@ module Agent
19
19
 
20
20
  # Copy the bundled skill into a skills directory, so an agent learns
21
21
  # how to claim files before it first needs to.
22
- class SkillInstall < Base
23
- desc "Copy the skill this gem ships into a skills directory"
22
+ class SkillsInstall < Base
23
+ desc "Copy the skills this gem ships into a skills directory: #{Skill.bundled.join(", ")}"
24
24
 
25
25
  option :into, type: :string, default: nil, aliases: ["-o"],
26
26
  desc: "The skills directory, default ~/.agents/skills"
@@ -29,8 +29,13 @@ module Agent
29
29
  option :force, type: :boolean, default: false, aliases: ["-f"],
30
30
  desc: "Replace a copy that differs from this one"
31
31
 
32
- example ["", "--into ~/.claude/skills", "--force"]
33
- example ["", "--for claude"]
32
+ # An empty example crashes dry-cli-help's renderer, so the default
33
+ # install is spelled out as an option-free line with a comment.
34
+ example [
35
+ " # into ~/.agents/skills",
36
+ "--for claude # into ~/.claude/skills",
37
+ "--into ~/some/skills --force # replace a copy that differs"
38
+ ]
34
39
 
35
40
  # @param options [Hash]
36
41
  def call(**options)
@@ -63,7 +68,7 @@ module Agent
63
68
  when :current then say("UP TO DATE #{result.path}")
64
69
  when :differs
65
70
  warn_("REFUSED: #{result.path} differs from the copy this gem ships")
66
- warn_(" #{program} skill install --force # replace it")
71
+ warn_(" #{program} skills install --force # replace it")
67
72
  when :linked
68
73
  warn_("REFUSED: #{result.path} is a symlink, so something else installs it; left alone")
69
74
  end
@@ -81,7 +81,7 @@ require_relative "cli/commands/break"
81
81
  require_relative "cli/commands/note"
82
82
  require_relative "cli/commands/resume"
83
83
  require_relative "cli/commands/whoami"
84
- require_relative "cli/commands/skill"
84
+ require_relative "cli/commands/skills"
85
85
  require_relative "cli/commands/version"
86
86
  require_relative "cli/commands/completion"
87
87
 
@@ -99,8 +99,8 @@ module Agent
99
99
  "note" => [Commands::Note, []],
100
100
  "resume" => [Commands::Resume, []],
101
101
  "whoami" => [Commands::Whoami, []],
102
- "skill path" => [Commands::SkillPath, []],
103
- "skill install" => [Commands::SkillInstall, []],
102
+ "skills path" => [Commands::SkillsPath, []],
103
+ "skills install" => [Commands::SkillsInstall, []],
104
104
  "version" => [Commands::Version, %w[-v --version]]
105
105
  }.freeze
106
106
  end
@@ -69,7 +69,7 @@ module Agent
69
69
  # @return [Result]
70
70
  def release(path)
71
71
  scope = Scope.parse(path, tree: tree)
72
- record = store.find(scope)
72
+ record = locate(scope, prefer: ->(found) { found.held_by?(identity) })
73
73
  return result(:not_found, []) if record.nil?
74
74
  return result(:refused, [record]) unless record.held_by?(identity)
75
75
 
@@ -117,7 +117,7 @@ module Agent
117
117
  # @return [Result]
118
118
  def break_lock(path)
119
119
  scope = Scope.parse(path, tree: tree)
120
- record = store.find(scope)
120
+ record = locate(scope)
121
121
  return result(:not_found, []) if record.nil?
122
122
 
123
123
  drop(record)
@@ -152,7 +152,7 @@ module Agent
152
152
  # @return [Result]
153
153
  def note(path, text)
154
154
  scope = Scope.parse(path, tree: tree)
155
- record = store.find(scope)
155
+ record = locate(scope, prefer: ->(found) { found.held_by?(identity) })
156
156
  return result(:not_found, []) if record.nil?
157
157
  return result(:refused, [record]) unless record.held_by?(identity)
158
158
 
@@ -167,17 +167,25 @@ module Agent
167
167
  # steps: two sessions resuming one orphan would otherwise both find it
168
168
  # interrupted, both write themselves in, and both report :resumed.
169
169
  #
170
+ # An orphan blocks nobody, so while it sat there somebody may have
171
+ # claimed an overlapping scope; that claim is checked for exactly as
172
+ # `acquire` would check it. And the resumed claim covers the branch this
173
+ # checkout is on now, not the one the orphan was taken on: it is rebound
174
+ # to the current tree, so that other checkouts of this branch see it.
175
+ #
170
176
  # @param path [String]
171
- # @return [Result]
177
+ # @return [Result] :resumed, :not_found, or :held with what overlaps
172
178
  def resume(path)
173
179
  scope = Scope.parse(path, tree: tree)
174
180
  store.synchronize do
175
- record = store.find(scope)
181
+ reap
182
+ record = locate(scope, prefer: :orphaned?.to_proc)
176
183
  next result(:not_found, []) if record.nil? || record.active?
177
184
 
178
- adopted = record.with(status: Record::ACTIVE, updated_at: Time.now.utc.iso8601, **claim)
179
- store.update(adopted)
180
- result(:resumed, [adopted])
185
+ blocking = conflicts(scope).select { |other| other.blocks?(identity) }
186
+ next result(:held, blocking) if blocking.any?
187
+
188
+ rebind(record, scope)
181
189
  end
182
190
  end
183
191
 
@@ -247,15 +255,6 @@ module Agent
247
255
  result(:interrupted, [record]) if record&.orphaned?
248
256
  end
249
257
 
250
- # Who this session is, as a lock records it.
251
- #
252
- # @return [Hash]
253
- def claim
254
- evidence = identity.evidence
255
- { agent_id: identity.id, parent_agent_id: identity.parent_id,
256
- pid: evidence[:pid], started: evidence[:started], host: evidence[:host] }
257
- end
258
-
259
258
  # Freezing happens after the claim is won, never before. Flagging files
260
259
  # first and then losing the race would leave a tree full of unwritable
261
260
  # files that no lock admits to having frozen, which is the one failure
@@ -292,21 +291,67 @@ module Agent
292
291
  # @return [Array<Record>]
293
292
  def conflicts(scope)
294
293
  store.all.select do |record|
295
- record.active? && record.tree == tree.root && record.scope_object.conflicts_with?(scope)
294
+ record.active? && record.about?(tree) && record.scope_object.conflicts_with?(scope)
296
295
  end
297
296
  end
298
297
 
298
+ # The frozen paths of a lock taken in another checkout, or on another
299
+ # machine, name files that are not here. Clearing them would unfreeze
300
+ # this checkout's files of the same name, which may be frozen under a
301
+ # lock of its own, so they are left alone. An orphan keeps the list, so
302
+ # the checkout that froze them can still see what to thaw.
303
+ #
299
304
  # @param record [Record]
300
305
  def orphan(record)
301
- Freeze.clear(record.frozen_paths, tree: tree)
302
- store.update(record.with(status: Record::ORPHANED, frozen_paths: [], updated_at: Time.now.utc.iso8601))
306
+ local = record.local_to?(tree)
307
+ Freeze.clear(record.frozen_paths, tree: tree) if local
308
+ store.update(record.with(status: Record::ORPHANED, frozen_paths: local ? [] : record.frozen_paths,
309
+ updated_at: Time.now.utc.iso8601))
303
310
  end
304
311
 
312
+ # @param record [Record]
305
313
  def drop(record)
306
- Freeze.clear(record.frozen_paths, tree: tree)
314
+ Freeze.clear(record.frozen_paths, tree: tree) if record.local_to?(tree)
307
315
  store.delete(record)
308
316
  end
309
317
 
318
+ # The lock this tree holds on a scope. Looked up by id first, which is
319
+ # the whole point of the id, and then by scope among this checkout's own,
320
+ # because the id carries the branch: a session that switched branches
321
+ # after claiming would otherwise be told its own lock was not there, and
322
+ # could neither release nor resume it.
323
+ #
324
+ # Both can exist at once: this checkout's lock from `main`, and another
325
+ # checkout's lock on the same scope on the branch this one has since
326
+ # switched to. `prefer` picks which one a command is after, so `release`
327
+ # finds the lock it owns rather than refusing on somebody else's.
328
+ #
329
+ # @param scope [Scope]
330
+ # @param prefer [Proc, nil] the record wanted when there is a choice
331
+ # @return [Record, nil]
332
+ def locate(scope, prefer: nil)
333
+ found = [store.find(scope), *store.all.select { |record| record.scope == scope.to_s && record.local_to?(tree) }]
334
+ .compact.uniq(&:id)
335
+ (prefer && found.find(&prefer)) || found.first
336
+ end
337
+
338
+ # An orphan made a live claim again, by this session, on this tree's
339
+ # current branch. When the branch moved, the id moves with it: the new
340
+ # record is created first, so a lost race leaves the orphan where it
341
+ # was, and the old one is deleted only once the new one stands.
342
+ #
343
+ # @param record [Record] the orphan
344
+ # @param scope [Scope]
345
+ # @return [Result]
346
+ def rebind(record, scope)
347
+ adopted = record.resumed(tree: tree, scope: scope, identity: identity)
348
+ moved = adopted.id != record.id
349
+ return result(:interrupted, [store.find(scope)].compact) if moved && !store.create(adopted)
350
+
351
+ moved ? store.delete(record) : store.update(adopted)
352
+ result(:resumed, [adopted])
353
+ end
354
+
310
355
  def result(status, records, message = nil) = Result.new(status:, records:, message:)
311
356
  end
312
357
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "process_info"
4
4
  require_relative "scope"
5
+ require_relative "tree"
5
6
 
6
7
  require "yaml"
7
8
  require "time"
@@ -25,7 +26,7 @@ module Agent
25
26
  # ---
26
27
  # Rewriting the installer's filter pair.
27
28
  class Record
28
- FIELDS = %i[id agent_id parent_agent_id scope tree worktree pid started host
29
+ FIELDS = %i[id agent_id parent_agent_id scope tree repo branch worktree pid started host
29
30
  created_at updated_at status frozen_paths].freeze
30
31
 
31
32
  ACTIVE = "active"
@@ -45,18 +46,20 @@ module Agent
45
46
  evidence = identity.evidence
46
47
  new(
47
48
  id: id_for(tree, scope), agent_id: identity.id, parent_agent_id: identity.parent_id,
48
- scope: scope.to_s, tree: tree.root, worktree: tree.worktree?,
49
+ scope: scope.to_s, tree: tree.root, repo: tree.repo, branch: tree.branch, worktree: tree.worktree?,
49
50
  pid: evidence[:pid], started: evidence[:started], host: evidence[:host],
50
51
  created_at: Time.now.utc.iso8601, status: ACTIVE, frozen_paths: [], intent: intent
51
52
  )
52
53
  end
53
54
 
54
- # Derived from the tree and the scope so that a second run looking for
55
- # the same lock finds it without reading every file in the store.
55
+ # Derived from the tree's lock key and the scope so that a second run
56
+ # looking for the same lock finds it without reading every file in the
57
+ # store, and so that two checkouts of one branch, on any machine, are
58
+ # after the same id and cannot both win it.
56
59
  #
57
60
  # @return [String]
58
61
  def id_for(tree, scope)
59
- digest = Digest::SHA256.hexdigest("#{tree.root}\0#{scope}")[0, 8]
62
+ digest = Digest::SHA256.hexdigest("#{tree.lock_key}\0#{scope}")[0, 8]
60
63
  "#{scope.slug}-#{digest}"
61
64
  end
62
65
 
@@ -101,6 +104,24 @@ module Agent
101
104
  "#{YAML.dump(front)}#{SEPARATOR}\n\n#{intent.strip}\n"
102
105
  end
103
106
 
107
+ # This orphan as a live claim again, held by `identity` on the branch
108
+ # `tree` is on now, which need not be the one it was taken on. Its id
109
+ # follows the branch, so the caller has to write it under the new id.
110
+ #
111
+ # @param tree [Tree]
112
+ # @param scope [Scope]
113
+ # @param identity [Identity]
114
+ # @return [Record]
115
+ def resumed(tree:, scope:, identity:)
116
+ evidence = identity.evidence
117
+ with(
118
+ id: self.class.id_for(tree, scope), tree: tree.root, repo: tree.repo, branch: tree.branch,
119
+ worktree: tree.worktree?, status: ACTIVE, updated_at: Time.now.utc.iso8601,
120
+ agent_id: identity.id, parent_agent_id: identity.parent_id,
121
+ pid: evidence[:pid], started: evidence[:started], host: evidence[:host]
122
+ )
123
+ end
124
+
104
125
  # @return [Boolean] the holder is gone, but the work it recorded is not
105
126
  def orphaned? = status == ORPHANED
106
127
 
@@ -127,6 +148,28 @@ module Agent
127
148
  # @return [Scope]
128
149
  def scope_object = @scope_object ||= Scope.new(scope)
129
150
 
151
+ # @return [String] see Tree#lock_key. A record written before `repo` and
152
+ # `branch` were kept has neither, and so falls back to its path on the
153
+ # host that wrote it, which no other host's key can equal.
154
+ def lock_key = Tree.lock_key(repo: repo, branch: branch, root: tree, host: host)
155
+
156
+ # Whether this lock is about the files a tree holds: the same repository
157
+ # on the same branch, from anywhere, or this very checkout on this host,
158
+ # whatever branch it was taken on, since switching branches does not
159
+ # make the files on disk somebody else's.
160
+ #
161
+ # @param checkout [Tree]
162
+ # @return [Boolean]
163
+ def about?(checkout) = lock_key == checkout.lock_key || local_to?(checkout)
164
+
165
+ # Whether this lock was taken in this very checkout, on this host. Only
166
+ # then do its frozen paths name files here: the same relative path in
167
+ # another checkout, or on another machine, is a different file.
168
+ #
169
+ # @param checkout [Tree]
170
+ # @return [Boolean]
171
+ def local_to?(checkout) = tree == checkout.root && same_host?
172
+
130
173
  # Two different questions, deliberately not one.
131
174
  #
132
175
  # Ownership answers "may I release this, write notes in it, and does
@@ -30,6 +30,10 @@ module Agent
30
30
  # @return [String] the bundled skill's directory
31
31
  def source = File.join(ROOT, NAME)
32
32
 
33
+ # @return [Array<String>] the name of every skill the gem ships, so
34
+ # help text can say what `install` puts on disk
35
+ def bundled = Dir.children(ROOT).select { |name| File.directory?(File.join(ROOT, name)) }.sort
36
+
33
37
  # @return [String] where most agents other than Claude Code look for
34
38
  # a user's own skills; the CLI's `--for claude` points at
35
39
  # `~/.claude/skills` instead
@@ -145,14 +145,17 @@ module Agent
145
145
 
146
146
  private
147
147
 
148
- # Keyed by the tree, so one Redis instance serves every checkout on the
149
- # machine without their locks colliding.
148
+ # Keyed by the repository, not the checkout, so that every checkout of
149
+ # it, on every machine sharing this Redis, reads the same locks. It
150
+ # used to be the absolute path, which kept two machines apart even when
151
+ # they were editing the same file. Which of those locks actually
152
+ # collide is decided by Record#about?, not here.
150
153
  def namespace = "#{NAMESPACE}:#{digest}"
151
154
 
152
155
  # @return [String]
153
156
  def url = self.class.url
154
157
 
155
- def digest = ::Digest::SHA256.hexdigest(tree.root)[0, 12]
158
+ def digest = ::Digest::SHA256.hexdigest(tree.repo)[0, 12]
156
159
 
157
160
  # SET NX PX until it takes, backing off with jitter so that processes
158
161
  # which all lost the same round do not all come back for the next one
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "digest"
4
+ require "socket"
4
5
  require_relative "scope"
5
6
 
6
7
  module Agent
@@ -37,6 +38,73 @@ module Agent
37
38
  # @return [Boolean] a linked worktree rather than the original checkout
38
39
  def worktree? = !git_dir.nil? && git_dir != common_dir
39
40
 
41
+ # The repository this tree is a checkout of, named the same way on every
42
+ # machine that has one.
43
+ #
44
+ # The absolute path used to be the name, so `/Users/a/repo` and
45
+ # `/Users/b/repo` were two repositories even on one shared Redis, and two
46
+ # machines never saw each other's locks. A lock is about the repository
47
+ # and the files in it; where the checkout sits on somebody's disk is not
48
+ # part of that. The origin URL is preferred, normalized so that ssh and
49
+ # https spellings agree; then the root commit, which every clone shares
50
+ # even without a remote; and only outside git, the path.
51
+ #
52
+ # @return [String]
53
+ def repo
54
+ @repo ||= self.class.normalize_remote(git("config", "--get", "remote.origin.url")) ||
55
+ root_commit || root
56
+ end
57
+
58
+ # @return [String, nil] the branch checked out, nil on a detached HEAD
59
+ # or outside git
60
+ def branch = defined?(@branch) ? @branch : (@branch = git("symbolic-ref", "--short", "-q", "HEAD"))
61
+
62
+ # What two trees must share for their locks to collide: the repository
63
+ # and the branch. Two machines on `main` are writing the same files, and
64
+ # must see each other. Two worktrees on their own branches are not, and
65
+ # are left alone, which is the point of making a worktree. A detached
66
+ # HEAD has no branch to share, so it keeps to its own checkout on its
67
+ # own host: the path alone is not enough, since two machines can clone
68
+ # to the same path and now read one namespace.
69
+ #
70
+ # @return [String]
71
+ def lock_key = self.class.lock_key(repo: repo, branch: branch, root: root, host: Socket.gethostname)
72
+
73
+ class << self
74
+ # One definition, shared with Record, so that a lock read back from
75
+ # the store is compared on exactly the terms it was written on.
76
+ #
77
+ # @param repo [String, nil]
78
+ # @param branch [String, nil]
79
+ # @param root [String]
80
+ # @param host [String, nil] nil only for a record written before hosts
81
+ # were kept, which then matches by its path on this host alone
82
+ # @return [String]
83
+ def lock_key(repo:, branch:, root:, host:)
84
+ return "#{repo}@#{branch}" if repo && branch
85
+
86
+ host ? "#{host}:#{root}" : root
87
+ end
88
+
89
+ # `git@github.com:a/b.git`, `ssh://git@github.com:22/a/b`, and
90
+ # `https://user@github.com/a/b.git` all come out as `github.com/a/b`.
91
+ #
92
+ # @param url [String, nil]
93
+ # @return [String, nil]
94
+ def normalize_remote(url)
95
+ text = url.to_s.strip
96
+ return nil if text.empty?
97
+
98
+ text = text.sub(%r{\A[a-z][a-z0-9+.-]*://}i, "") # scheme
99
+ text = text.sub(%r{\A[^@/]*@}, "") # user
100
+ text = text.sub(%r{\A([^/:]+):\d*/}, '\1/') # port
101
+ text = text.sub(%r{\A([^/:]+):(?!/)}, '\1/') # scp-style host:path
102
+ text = text.delete_suffix("/").delete_suffix(".git").delete_suffix("/")
103
+ host, path = text.split("/", 2)
104
+ path ? "#{host.downcase}/#{path}" : text
105
+ end
106
+ end
107
+
40
108
  # @description Resolves the directory where locks are stored by either
41
109
  # $AGENT_LOCK_DIR environment variable if defined, or 'agent-locks'
42
110
  # inside .git if available, or the ~/.agent-locks/<tree-digest> in user's
@@ -103,6 +171,13 @@ module Agent
103
171
  absolute
104
172
  end
105
173
 
174
+ # A merged-in history can bring more than one root commit. Any fixed
175
+ # pick will do, since every clone sees the same set, so the lexically
176
+ # first. Nil in a repository with no commits yet.
177
+ #
178
+ # @return [String, nil]
179
+ def root_commit = git("rev-list", "--max-parents=0", "HEAD")&.split("\n")&.min
180
+
106
181
  def git_dir = @git_dir ||= absolute(git("rev-parse", "--git-dir"))
107
182
 
108
183
  def common_dir = @common_dir ||= absolute(git("rev-parse", "--git-common-dir"))
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Agent
4
4
  module Lock
5
- VERSION = "2.1.0"
5
+ VERSION = "3.1.0"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: agent-lock
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.1.0
4
+ version: 3.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Konstantin Gredeskoul
@@ -29,42 +29,42 @@ dependencies:
29
29
  requirements:
30
30
  - - "~>"
31
31
  - !ruby/object:Gem::Version
32
- version: '0.5'
32
+ version: '0.6'
33
33
  type: :runtime
34
34
  prerelease: false
35
35
  version_requirements: !ruby/object:Gem::Requirement
36
36
  requirements:
37
37
  - - "~>"
38
38
  - !ruby/object:Gem::Version
39
- version: '0.5'
39
+ version: '0.6'
40
40
  - !ruby/object:Gem::Dependency
41
41
  name: dry-cli-help
42
42
  requirement: !ruby/object:Gem::Requirement
43
43
  requirements:
44
44
  - - "~>"
45
45
  - !ruby/object:Gem::Version
46
- version: '0.5'
46
+ version: '0.6'
47
47
  type: :runtime
48
48
  prerelease: false
49
49
  version_requirements: !ruby/object:Gem::Requirement
50
50
  requirements:
51
51
  - - "~>"
52
52
  - !ruby/object:Gem::Version
53
- version: '0.5'
53
+ version: '0.6'
54
54
  - !ruby/object:Gem::Dependency
55
55
  name: dry-cli-ui
56
56
  requirement: !ruby/object:Gem::Requirement
57
57
  requirements:
58
58
  - - "~>"
59
59
  - !ruby/object:Gem::Version
60
- version: '0.5'
60
+ version: '0.7'
61
61
  type: :runtime
62
62
  prerelease: false
63
63
  version_requirements: !ruby/object:Gem::Requirement
64
64
  requirements:
65
65
  - - "~>"
66
66
  - !ruby/object:Gem::Version
67
- version: '0.5'
67
+ version: '0.7'
68
68
  - !ruby/object:Gem::Dependency
69
69
  name: pastel
70
70
  requirement: !ruby/object:Gem::Requirement
@@ -118,6 +118,7 @@ extensions: []
118
118
  extra_rdoc_files: []
119
119
  files:
120
120
  - ".claude/CLAUDE.md"
121
+ - ".openlanes.yml"
121
122
  - ".ruby-version"
122
123
  - AGENTS.md
123
124
  - CHANGELOG.md
@@ -140,7 +141,7 @@ files:
140
141
  - lib/agent/lock/cli/commands/release.rb
141
142
  - lib/agent/lock/cli/commands/release_all.rb
142
143
  - lib/agent/lock/cli/commands/resume.rb
143
- - lib/agent/lock/cli/commands/skill.rb
144
+ - lib/agent/lock/cli/commands/skills.rb
144
145
  - lib/agent/lock/cli/commands/version.rb
145
146
  - lib/agent/lock/cli/commands/whoami.rb
146
147
  - lib/agent/lock/error.rb
@@ -182,7 +183,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
182
183
  - !ruby/object:Gem::Version
183
184
  version: '0'
184
185
  requirements: []
185
- rubygems_version: 4.0.21
186
+ rubygems_version: 4.0.23
186
187
  specification_version: 4
187
188
  summary: Advisory locks to prevent race conditions and general mayhem when multiple
188
189
  AI agents unknowinly modify the same souce three.