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
@@ -1,20 +1,29 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "error"
4
+ require_relative "store/backend_name"
4
5
  require_relative "store/file_system_store"
5
6
  require_relative "store/redis_store"
7
+ require_relative "store/redis_index"
6
8
 
7
9
  require "fileutils"
10
+ require "securerandom"
8
11
 
9
12
  module Agent
10
13
  module Lock
11
14
  # Where locks are kept. One tree, one store, chosen on purpose.
12
15
  #
13
- # AGENT_LOCK_BACKEND wins when set. Otherwise a tree that already has a
16
+ # A caller that names a backend (`alock --locking-strategy`) wins, then
17
+ # AGENT_LOCK_BACKEND when set. A caller that names the Redis itself
18
+ # (`alock --redis-url`, or AGENT_LOCK_REDIS_URL) has asked for Redis,
19
+ # and for that one alone: no REDIS_URL, no local default. Otherwise a tree that already has a
14
20
  # marker keeps using it. A virgin tree defaults to Redis when one answers
15
21
  # on REDIS_URL or, failing that, on the local default; file when neither
16
22
  # does.
17
23
  #
24
+ # A name that is no backend is refused before any of that, by
25
+ # {BackendName}, so it never reaches the marker.
26
+ #
18
27
  # That default is still never a runtime auto-*switch*: once a marker
19
28
  # exists, every later process in that tree is bound to it regardless of
20
29
  # what Redis is doing, because an agent that quietly moved to a different
@@ -25,49 +34,155 @@ module Agent
25
34
  # The one moment that default is decided is also the one moment two
26
35
  # processes could race: both find a virgin tree, both probe Redis, and a
27
36
  # flaky answer could hand them different defaults before either writes the
28
- # marker. So the marker is claimed atomically (first `O_CREAT|O_EXCL` wins)
37
+ # marker. So the marker is claimed atomically (the first hard link wins)
29
38
  # and every process builds from whatever ends up on disk, never from its
30
39
  # own guess, so a race can pick either backend but never a split.
31
40
  module Store
41
+ # The file in a tree's store directory that records its backend.
32
42
  MARKER = "backend"
33
43
 
44
+ # The environment's `--redis-url`: the one Redis to use, set by a
45
+ # dispatcher for the agents it starts. Its own name, because
46
+ # `REDIS_URL` may belong to the project the agent is working on.
47
+ REDIS_URL_ENV = "AGENT_LOCK_REDIS_URL"
48
+
49
+ # The names a backend marker can hold.
50
+ BACKENDS = %w[file redis].freeze
51
+
52
+ # Raised when a process asks for a backend other than the one the tree
53
+ # already uses, or for one that does not exist.
34
54
  class Mismatch < Error; end
35
55
 
56
+ # Raised when the caller named the Redis to use and it did not answer.
57
+ # Falling back to another one would put this process in a store the
58
+ # caller's other agents are not reading.
59
+ class Unreachable < Error; end
60
+
36
61
  module_function
37
62
 
38
63
  # @param tree [Tree]
64
+ # @param backend [String, nil] "file" or "redis", named by the caller;
65
+ # nil leaves it to AGENT_LOCK_BACKEND, the marker and the default
66
+ # @param redis_url [String, nil] the one Redis to use, with no search
67
+ # and no fallback; nil reads {REDIS_URL_ENV}, and without that
68
+ # searches as {RedisStore.candidate_urls} says
39
69
  # @return [Store::FileSystemStore, Store::RedisStore]
40
- def for(tree)
41
- requested = ENV["AGENT_LOCK_BACKEND"]&.downcase
42
- established = recorded(tree)
70
+ # @raise [Mismatch] when the tree's locks live in the other backend,
71
+ # or a Redis is named beside the file backend
72
+ # @raise [Unreachable] when the named Redis does not answer
73
+ def for(tree, backend: nil, redis_url: nil)
74
+ url = redis_url || named_redis_url
75
+ requested = requested_backend(backend, redis_url, url)
76
+ established = BackendName.marked(recorded(tree), marker_path(tree), offer: requested)
77
+ return build(agreed(established, requested), tree, redis_url: url) if established
78
+
79
+ establish(tree, requested, url)
80
+ end
43
81
 
44
- if established
45
- if requested && requested != established
46
- raise Mismatch, "this tree's locks live in #{established}, not #{requested}, " \
47
- "release them before switching backends"
48
- end
82
+ # @return [String, nil] {REDIS_URL_ENV}, when it is set to something
83
+ def named_redis_url
84
+ url = ENV.fetch(REDIS_URL_ENV, "").strip
85
+ url.empty? ? nil : url
86
+ end
49
87
 
50
- return build(established, tree)
51
- end
88
+ # A backend the caller passed wins over a URL the caller passed, which
89
+ # wins over the environment. A Redis named beside the file backend is
90
+ # refused, never quietly dropped: one of the two is a mistake, and
91
+ # guessing which puts this process in a store nobody else reads.
92
+ #
93
+ # @param backend [String, nil] the caller's
94
+ # @param redis_url [String, nil] the caller's
95
+ # @param url [String, nil] the Redis named by the caller or the environment
96
+ # @return [String, nil] "file", "redis", or nil for the tree's own choice
97
+ # @raise [Mismatch] also for a name that is not a backend
98
+ def requested_backend(backend, redis_url, url)
99
+ requested = BackendName.canonical(backend) || ("redis" if redis_url) || BackendName.from_environment
100
+ return requested unless url
101
+ return "redis" unless requested == "file"
102
+
103
+ raise Mismatch, "a Redis URL (#{RedisStore.safe(url)}) does not go with the file backend"
104
+ end
105
+
106
+ # @param established [String] the backend the tree's marker records
107
+ # @param requested [String, nil] the backend this process asked for
108
+ # @return [String] `established`
109
+ # @raise [Mismatch] when they differ
110
+ def agreed(established, requested)
111
+ return established if requested.nil? || requested == established
112
+
113
+ # `.for` passes on a real backend or none, but this is callable on
114
+ # its own. Only a real backend goes into a command somebody will paste.
115
+ raise Mismatch.new("this tree's locks live in #{established}, not #{requested}",
116
+ command: ("switch-backend #{requested}" if BACKENDS.include?(requested)))
117
+ end
118
+
119
+ # Points the tree at another backend, for `switch-backend` and nothing
120
+ # else. Written beside the marker and renamed over it, so a reader sees
121
+ # the old name or the new one, never an empty file. The caller is the
122
+ # one who made sure the old store holds nothing that still counts.
123
+ #
124
+ # @param tree [Tree]
125
+ # @param name [String] "file" or "redis"
126
+ # @return [String] `name`
127
+ def rebind(tree, name)
128
+ path = marker_path(tree)
129
+ FileUtils.mkdir_p(File.dirname(path))
130
+ temp = "#{path}.#{Process.pid}.#{SecureRandom.hex(6)}.tmp"
131
+ File.write(temp, "#{name}\n")
132
+ File.rename(temp, path)
133
+ name
134
+ ensure
135
+ FileUtils.rm_f(temp) if temp
136
+ end
52
137
 
53
- build(claim(tree, requested || default_backend), tree)
138
+ # Claims a virgin tree. A Redis that was asked for is connected to
139
+ # before the marker is written: a tree bound to a Redis that never
140
+ # answered would refuse every later command. What `claim` hands back
141
+ # is checked too, since another process may have claimed the tree for
142
+ # the other backend in between.
143
+ #
144
+ # @param tree [Tree]
145
+ # @param requested [String, nil]
146
+ # @param redis_url [String, nil]
147
+ # @return [Store::FileSystemStore, Store::RedisStore]
148
+ # @raise [Unreachable] when Redis was asked for and does not answer
149
+ # @raise [Mismatch] when another process claimed the tree for the other backend
150
+ def establish(tree, requested, redis_url)
151
+ store = build("redis", tree, redis_url:) if requested == "redis"
152
+ claimed = agreed(claim(tree, requested || default_backend), requested)
153
+ store || build(claimed, tree, redis_url:)
54
154
  end
55
155
 
156
+ # @param name [String] "file" or "redis"
157
+ # @param tree [Tree]
158
+ # @param redis_url [String, nil] see {.for}
56
159
  # @return [Store::FileSystemStore, Store::RedisStore]
57
- def build(name, tree)
160
+ # @raise [Mismatch] for any other name
161
+ # @raise [Unreachable] when `redis_url` does not answer
162
+ def build(name, tree, redis_url: nil)
58
163
  case name
59
- when "redis" then RedisStore.new(tree)
164
+ when "redis" then redis_url ? RedisStore.at(tree, redis_url) : RedisStore.found(tree)
60
165
  when "file" then FileSystemStore.new(tree)
61
166
  else raise Mismatch, "unknown backend #{name.inspect}, expected file or redis"
62
167
  end
63
168
  end
64
169
 
170
+ # A marker that is missing, or still empty, is none. One that exists
171
+ # but cannot be read is an error, named as such: taken for none, it
172
+ # ended up reported as "exists but is empty", or, before that, let a
173
+ # caller pick its own backend.
174
+ #
175
+ # @param tree [Tree]
65
176
  # @return [String, nil] the backend this tree already uses
177
+ # @raise [Mismatch] when the marker exists but cannot be read
66
178
  def recorded(tree)
67
179
  path = marker_path(tree)
68
- File.exist?(path) ? File.read(path).strip : nil
69
- rescue SystemCallError
180
+ value = File.read(path).strip
181
+ value.empty? ? nil : value
182
+ rescue Errno::ENOENT, Errno::ENOTDIR
70
183
  nil
184
+ rescue SystemCallError => e
185
+ raise Mismatch, "cannot read #{path}: #{e.message}; fix its permissions or delete it"
71
186
  end
72
187
 
73
188
  # Atomically claims the marker for a virgin tree with `name`, or, when a
@@ -75,20 +190,65 @@ module Agent
75
190
  # process wrote instead. Either way, every caller ends up building the
76
191
  # same backend for this tree.
77
192
  #
193
+ # The marker is written to a temp file and hard-linked into place, so
194
+ # it never exists empty. Created with `O_EXCL` and written afterwards,
195
+ # a loser of the race could read it in between, take "" for the
196
+ # winner's backend, and refuse a tree that was about to agree with it.
197
+ #
78
198
  # @param tree [Tree]
79
199
  # @param name [String] this process's proposed backend
80
200
  # @return [String] the backend actually recorded, which may not be `name`
81
201
  def claim(tree, name)
82
202
  path = marker_path(tree)
83
203
  FileUtils.mkdir_p(File.dirname(path))
84
- File.write(path, "#{name}\n", mode: File::WRONLY | File::CREAT | File::EXCL)
204
+ publish(path, name)
85
205
  name
86
206
  rescue Errno::EEXIST
87
- recorded(tree) || name
207
+ # Falling back to `name` here would let every caller keep its own
208
+ # guess about a marker that stays empty: a silent split.
209
+ settled(tree) || raise(Mismatch, "#{marker_path(tree)} exists but is empty; " \
210
+ "write file or redis into it, or delete it")
88
211
  rescue SystemCallError
89
212
  name
90
213
  end
91
214
 
215
+ # @param path [String] the marker
216
+ # @param name [String]
217
+ # @return [void]
218
+ # @raise [Errno::EEXIST] when another process claimed the tree first
219
+ def publish(path, name)
220
+ temp = "#{path}.#{Process.pid}.#{SecureRandom.hex(6)}.tmp"
221
+ File.write(temp, "#{name}\n")
222
+ begin
223
+ File.link(temp, path)
224
+ rescue Errno::EEXIST
225
+ raise
226
+ rescue SystemCallError
227
+ # Any filesystem that cannot hard-link falls back to the exclusive
228
+ # create, whose create-then-write window `settled` covers.
229
+ File.write(path, "#{name}\n", mode: File::WRONLY | File::CREAT | File::EXCL)
230
+ end
231
+ ensure
232
+ FileUtils.rm_f(temp) if temp
233
+ end
234
+
235
+ # Waits briefly for a marker that exists but is still empty: an older
236
+ # `alock` creates it first and writes its name a moment later.
237
+ #
238
+ # @param tree [Tree]
239
+ # @return [String, nil] the recorded backend, or nil if none appeared
240
+ def settled(tree)
241
+ 50.times do
242
+ value = recorded(tree)
243
+ return value if value
244
+
245
+ sleep 0.01
246
+ end
247
+ nil
248
+ end
249
+
250
+ # @param tree [Tree]
251
+ # @return [String] where the tree's backend marker lives
92
252
  def marker_path(tree) = File.join(tree.store_dir, MARKER)
93
253
 
94
254
  # @return [String] "redis" when one answers on REDIS_URL or, failing
@@ -97,6 +257,7 @@ module Agent
97
257
  local_redis_available? ? "redis" : "file"
98
258
  end
99
259
 
260
+ # @return [Boolean] whether a Redis client connected without error
100
261
  def local_redis_available?
101
262
  client, error = RedisStore.create_client
102
263
  !client.nil? && error.nil?
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "shellwords"
4
+
5
+ module Agent
6
+ module Lock
7
+ # Text read from a store, made safe to print.
8
+ #
9
+ # A lock record is whatever some host sharing the store wrote, and a
10
+ # shared Redis lets any process that can reach it write one. Printed raw,
11
+ # its fields reach the operator's terminal and every log a harness keeps:
12
+ # an escape sequence in an agent ID can clear the screen, rewrite lines
13
+ # already printed, or show a link that goes somewhere else, and a scope
14
+ # with `; curl ... | sh` in it turns a suggested `alock break` line into
15
+ # a command somebody pastes. So every field goes through {.printable}
16
+ # before it is printed, and through {.shell} when it lands inside a
17
+ # command. The record itself is never rewritten: `release` and `break`
18
+ # still have to match it exactly.
19
+ module Text
20
+ # C0 and C1 control characters, DEL, and the Unicode marks that reorder
21
+ # how a line displays (the "Trojan Source" bidi overrides), which make
22
+ # a line read differently from the bytes it holds.
23
+ UNSAFE = /[[:cntrl:]‎‏‪-‮⁦-⁩]/
24
+
25
+ module_function
26
+
27
+ # @param value [#to_s] a field read from a store
28
+ # @param lines [Boolean] keep newlines, for a multi-line body such as
29
+ # an intent with notes; any other control character is still escaped
30
+ # @return [String] valid UTF-8 in which every unsafe character, and every
31
+ # byte that is not UTF-8, shows as an escape (`\x1b`, `\u{202e}`), so a
32
+ # planted sequence is visible to the operator instead of acted on
33
+ def printable(value, lines: false)
34
+ text = value.to_s.dup.force_encoding(Encoding::UTF_8).scrub { |bytes| escape_bytes(bytes) }
35
+ text.gsub(UNSAFE) { |char| lines && char == "\n" ? char : escape(char) }
36
+ end
37
+
38
+ # What a shell takes literally, so a value made only of these needs no
39
+ # quotes: `lib/billing.rb` stays as it is typed.
40
+ BARE = %r{\A[\w.,/:@%+=-]+\z}
41
+
42
+ # @param value [#to_s] a field that lands inside a suggested command
43
+ # @return [String] {.printable}, then single-quoted unless {BARE}, so it
44
+ # pastes as one argument. Single quotes rather than `Shellwords.escape`,
45
+ # which is just as safe but prints `docs/**` as `docs/\*\*`; and some
46
+ # quoting is needed, since `docs/**` pasted bare is a glob the shell
47
+ # expands into file names.
48
+ def shell(value)
49
+ text = printable(value)
50
+ text.match?(BARE) ? text : "'#{text.gsub("'") { "'\\''" }}'"
51
+ end
52
+
53
+ # @param char [String] one character
54
+ # @return [String] `\x1b` below U+0100, `\u{202e}` above
55
+ def escape(char) = char.ord < 0x100 ? format("\\x%02x", char.ord) : format("\\u{%x}", char.ord)
56
+
57
+ # @param bytes [String] bytes that are not valid UTF-8
58
+ # @return [String] each one as `\xNN`
59
+ def escape_bytes(bytes) = bytes.bytes.map { |byte| format("\\x%02x", byte) }.join
60
+ end
61
+ end
62
+ end
@@ -19,6 +19,22 @@ module Agent
19
19
  # Outside a repository the store falls back to `~/.agent-locks`, keyed by a
20
20
  # digest of the tree, since there is no `.git` to hide in.
21
21
  class Tree
22
+ # What `git rev-parse --local-env-vars` lists: the variables that point
23
+ # git at a repository other than the one around the directory it is given.
24
+ # A git hook exports GIT_DIR and GIT_INDEX_FILE, so `alock` called from a
25
+ # pre-commit hook, with `--dir` naming another checkout, resolved that
26
+ # checkout's root but the hook's own git dir, and kept its locks in the
27
+ # wrong store. Every git call here unsets them: the directory decides.
28
+ LOCAL_GIT_ENV = %w[
29
+ GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_CONFIG GIT_CONFIG_PARAMETERS GIT_CONFIG_COUNT
30
+ GIT_OBJECT_DIRECTORY GIT_DIR GIT_WORK_TREE GIT_IMPLICIT_WORK_TREE GIT_GRAFT_FILE
31
+ GIT_INDEX_FILE GIT_NO_REPLACE_OBJECTS GIT_REPLACE_REF_BASE GIT_PREFIX
32
+ GIT_SHALLOW_FILE GIT_COMMON_DIR
33
+ ].freeze
34
+
35
+ # The environment every git call runs with: LOCAL_GIT_ENV unset.
36
+ GIT_ENV = LOCAL_GIT_ENV.to_h { |name| [name, nil] }.freeze
37
+
22
38
  class << self
23
39
  # @param dir [String] anywhere inside the tree
24
40
  # @return [Tree]
@@ -29,6 +45,7 @@ module Agent
29
45
  # cannot become two names for one tree
30
46
  attr_reader :root
31
47
 
48
+ # @param dir [String] anywhere inside the tree
32
49
  def initialize(dir = Dir.pwd)
33
50
  @dir = File.realpath(dir)
34
51
  @root = git("rev-parse", "--show-toplevel") || @dir
@@ -38,6 +55,16 @@ module Agent
38
55
  # @return [Boolean] a linked worktree rather than the original checkout
39
56
  def worktree? = !git_dir.nil? && git_dir != common_dir
40
57
 
58
+ # Every checkout that shares this one's git common dir, and with it the
59
+ # lock store and the backend marker. Just this root outside git.
60
+ #
61
+ # @return [Array<String>] absolute roots, symlinks resolved where they exist
62
+ def worktree_roots
63
+ listed = git("worktree", "list", "--porcelain").to_s.lines
64
+ .filter_map { |line| line[/\Aworktree (.+)$/, 1] }
65
+ [root, *listed.map { |path| absolute(path) || path }].uniq
66
+ end
67
+
41
68
  # The repository this tree is a checkout of, named the same way on every
42
69
  # machine that has one.
43
70
  #
@@ -50,9 +77,14 @@ module Agent
50
77
  # even without a remote; and only outside git, the path.
51
78
  #
52
79
  # @return [String]
53
- def repo
54
- @repo ||= self.class.normalize_remote(git("config", "--get", "remote.origin.url")) ||
55
- root_commit || root
80
+ def repo = @repo ||= origin || root_commit || root
81
+
82
+ # @return [String, nil] the origin remote as `host/owner/name`, nil when
83
+ # the checkout has no origin or is not in git
84
+ def origin
85
+ return @origin if defined?(@origin)
86
+
87
+ @origin = self.class.normalize_remote(git("config", "--get", "remote.origin.url"))
56
88
  end
57
89
 
58
90
  # @return [String, nil] the branch checked out, nil on a detached HEAD
@@ -70,6 +102,45 @@ module Agent
70
102
  # @return [String]
71
103
  def lock_key = self.class.lock_key(repo: repo, branch: branch, root: root, host: Socket.gethostname)
72
104
 
105
+ # The repository as it should appear in a Redis key a person can read.
106
+ #
107
+ # A GitHub origin drops the host, so `github.com/kigster/laser-cutter`
108
+ # is `kigster/laser-cutter`. Any other host stays in the label: stripping
109
+ # it would let `gitlab.com/kigster/laser-cutter` wear the GitHub
110
+ # repository's name. `*?[]` are flattened because this string is also a
111
+ # Redis SCAN pattern, and those characters are glob syntax.
112
+ #
113
+ # @return [String]
114
+ def redis_slug
115
+ name = repo.to_s.sub(%r{\Agithub\.com/}, "")
116
+ name = "unknown" if name.empty?
117
+ name.gsub(%r{[^A-Za-z0-9._/-]}, "-")
118
+ end
119
+
120
+ # {#redis_slug}, but only when it names a repository somebody could type.
121
+ # Without an origin the slug is a root commit or a path, which no other
122
+ # clone is filed under by name.
123
+ #
124
+ # @return [String, nil] `owner/name` on GitHub, `host/owner/name`
125
+ # elsewhere, nil without an origin remote
126
+ def origin_slug = origin && redis_slug
127
+
128
+ # What a remote URL opens with, `ssh://` or `https://`, and an scp-style
129
+ # remote (`git@host:path`) does not.
130
+ SCHEME = %r{\A[a-z][a-z0-9+.-]*://}i
131
+
132
+ # A URL's userinfo, once its scheme is gone: everything up to the last
133
+ # `@` before the path. Stopping at the first `@` kept the tail of a
134
+ # password holding an unencoded one (`me:p@ss@github.com`) in the
135
+ # repository's name, and so in its Redis key, `alock show repo` and
136
+ # every lock record, under a name its teammates' clones do not share.
137
+ USERINFO = %r{\A[^/]*@}
138
+
139
+ # The user of an scp-style remote, `git@host:path`: up to the first `@`,
140
+ # since after the host comes the path, which may hold one of its own.
141
+ SCP_USER = %r{\A[^@/]*@}
142
+ private_constant :SCHEME, :USERINFO, :SCP_USER
143
+
73
144
  class << self
74
145
  # One definition, shared with Record, so that a lock read back from
75
146
  # the store is compared on exactly the terms it was written on.
@@ -87,7 +158,25 @@ module Agent
87
158
  end
88
159
 
89
160
  # `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`.
161
+ # `https://user@github.com/a/b.git` all come out as `github.com/a/b`,
162
+ # and so does `https://me:p@ss@github.com/a/b`: no piece of a
163
+ # password survives, even one holding an unencoded `@`.
164
+ #
165
+ # Only a URL that starts with a scheme can carry a port. In the scp
166
+ # form, `[user@]host:path`, whatever follows the colon is the path:
167
+ # the port used to be stripped from both, so `git@github.com:123/app`
168
+ # lost its all-digit owner, stopped agreeing with
169
+ # `https://github.com/123/app`, and shared one name with every other
170
+ # numeric owner's `app` on that host.
171
+ #
172
+ # The whole name is lower-cased, owner and repository included. GitHub
173
+ # and GitLab serve `Acme/App` and `acme/app` as one repository, and a
174
+ # remote keeps the case it was cloned with: with only the host folded,
175
+ # two clones of one repository had two lock keys, and each was told
176
+ # it held the scope. A self-hosted server that does tell the two
177
+ # apart now files both under one name, which errs toward refusing.
178
+ #
179
+ # A remote that names a directory keeps its case: see `local?`.
91
180
  #
92
181
  # @param url [String, nil]
93
182
  # @return [String, nil]
@@ -95,23 +184,37 @@ module Agent
95
184
  text = url.to_s.strip
96
185
  return nil if text.empty?
97
186
 
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
187
+ url_form = text.match?(SCHEME)
188
+ local = local?(text)
189
+ text = text.sub(SCHEME, "")
190
+ text = text.sub(url_form ? USERINFO : SCP_USER, "") # user, and any password
191
+ text = text.sub(%r{\A([^/:]+):\d*/}, '\1/') if url_form # port, which only a URL has
192
+ text = text.sub(%r{\A([^/:]+):/?}, '\1/') # scp-style host:path
102
193
  text = text.delete_suffix("/").delete_suffix(".git").delete_suffix("/")
103
- host, path = text.split("/", 2)
104
- path ? "#{host.downcase}/#{path}" : text
194
+ local ? text : text.downcase
105
195
  end
196
+
197
+ private
198
+
199
+ # Whether a remote names a directory rather than a repository on a
200
+ # host: a `file://` URL, or, as git itself reads it, anything with no
201
+ # scheme and no colon ahead of its first slash. A case-sensitive
202
+ # filesystem keeps `/srv/git/App` and `/srv/git/app` as two
203
+ # repositories, and folding them would file both under one name.
204
+ #
205
+ # @param text [String] a remote as git printed it, stripped
206
+ # @return [Boolean]
207
+ def local?(text) = text.match?(SCHEME) ? text.match?(/\Afile:/i) : !text.match?(%r{\A[^/]*:})
106
208
  end
107
209
 
108
- # @description Resolves the directory where locks are stored by either
109
- # $AGENT_LOCK_DIR environment variable if defined, or 'agent-locks'
110
- # inside .git if available, or the ~/.agent-locks/<tree-digest> in user's
111
- # home folder.
210
+ # Where the file store keeps this tree's locks: `$AGENT_LOCK_DIR` when
211
+ # set to anything but blank, else `agent-locks` inside the git common dir
212
+ # (shared by every worktree), else `~/.agent-locks/<digest of the root>`
213
+ # outside git.
112
214
  # @return [String] where locks for this tree are written
113
215
  def store_dir
114
- return File.expand_path(ENV["AGENT_LOCK_DIR"]) if ENV["AGENT_LOCK_DIR"]
216
+ configured = configured_store_dir
217
+ return configured if configured
115
218
  return File.join(common_dir, "agent-locks") if common_dir
116
219
 
117
220
  File.join(Dir.home, ".agent-locks", ::Digest::SHA256.hexdigest(root)[0, 12])
@@ -142,6 +245,24 @@ module Agent
142
245
 
143
246
  private
144
247
 
248
+ # `$AGENT_LOCK_DIR`, as one directory for the whole tree.
249
+ #
250
+ # It used to be expanded from the working directory. A relative value
251
+ # (`AGENT_LOCK_DIR=locks`) was then one store in `repo/` and another in
252
+ # `repo/sub/`: two agents took the same scope and neither saw the other.
253
+ # An empty value (`export AGENT_LOCK_DIR=`) was the working directory
254
+ # itself, so the marker, the mutex and every lock file landed among the
255
+ # tree's own files. A relative value is now read from the root, which is
256
+ # the same wherever a command runs and whatever `--dir` names, and a
257
+ # blank one is no value at all. `~` and an absolute path are not
258
+ # relative, and mean what they always did.
259
+ #
260
+ # @return [String, nil] absolute, or nil when the variable is unset or blank
261
+ def configured_store_dir
262
+ value = ENV.fetch("AGENT_LOCK_DIR", "")
263
+ File.expand_path(value, root) unless value.strip.empty?
264
+ end
265
+
145
266
  # The prefix test that `delete_prefix` alone got wrong: `/repo-other`
146
267
  # starts with `/repo`, so the root is matched only whole or up to a slash.
147
268
  #
@@ -178,10 +299,14 @@ module Agent
178
299
  # @return [String, nil]
179
300
  def root_commit = git("rev-list", "--max-parents=0", "HEAD")&.split("\n")&.min
180
301
 
302
+ # @return [String, nil] this checkout's own git dir, absolute; nil outside git
181
303
  def git_dir = @git_dir ||= absolute(git("rev-parse", "--git-dir"))
182
304
 
305
+ # @return [String, nil] the git dir every worktree shares, absolute; nil outside git
183
306
  def common_dir = @common_dir ||= absolute(git("rev-parse", "--git-common-dir"))
184
307
 
308
+ # @param dir [String, nil] as git printed it, possibly relative to @dir
309
+ # @return [String, nil] absolute with symlinks resolved, or nil when it does not exist
185
310
  def absolute(dir)
186
311
  return nil if dir.nil?
187
312
 
@@ -190,8 +315,10 @@ module Agent
190
315
  nil
191
316
  end
192
317
 
318
+ # @param args [Array<String>] arguments to `git -C <dir>`
319
+ # @return [String, nil] stripped output, or nil when empty or git failed to run
193
320
  def git(*args)
194
- out = IO.popen(["git", "-C", @dir, *args], err: File::NULL, &:read).to_s.strip
321
+ out = IO.popen(GIT_ENV, ["git", "-C", @dir, *args], err: File::NULL, &:read).to_s.strip
195
322
  out.empty? ? nil : out
196
323
  rescue SystemCallError
197
324
  nil
@@ -2,6 +2,7 @@
2
2
 
3
3
  module Agent
4
4
  module Lock
5
- VERSION = "3.1.0"
5
+ # The gem's version, read by the gemspec and printed by `alock version`.
6
+ VERSION = "4.0.0"
6
7
  end
7
8
  end
data/lib/agent/lock.rb CHANGED
@@ -4,7 +4,9 @@
4
4
 
5
5
  require_relative "lock/version"
6
6
  require_relative "lock/error"
7
+ require_relative "lock/text"
7
8
 
9
+ # The namespace this gem lives in. It defines nothing of its own.
8
10
  module Agent
9
11
  # Advisory locks for the several coding agents that end up in one checkout.
10
12
  #
@@ -26,5 +28,6 @@ require_relative "lock/store"
26
28
  require_relative "lock/store/file_system_store"
27
29
  require_relative "lock/store/redis_store"
28
30
  require_relative "lock/manager"
31
+ require_relative "lock/facade"
29
32
  require_relative "lock/launcher"
30
33
  require_relative "lock/cli"