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
@@ -26,15 +26,79 @@ module Agent
26
26
  # ---
27
27
  # Rewriting the installer's filter pair.
28
28
  class Record
29
- FIELDS = %i[id agent_id parent_agent_id scope tree repo branch worktree pid started host
29
+ # The front-matter keys, in the order they are written. Each one is
30
+ # also a reader on the record.
31
+ FIELDS = %i[id agent_id parent_agent_id scope tree repo branch worktree pid started started_at host
30
32
  created_at updated_at status frozen_paths].freeze
31
33
 
34
+ # The status of a live claim.
32
35
  ACTIVE = "active"
36
+
37
+ # The status of a lock whose holder died with notes in it: it blocks
38
+ # nobody, but is kept until somebody resumes or breaks it.
33
39
  ORPHANED = "orphaned"
40
+
41
+ # What fences the YAML front matter off from the body.
34
42
  SEPARATOR = "---"
43
+
44
+ # The heading `note` appends under.
35
45
  NOTES_HEADING = "## Progress"
36
46
 
37
- attr_reader(*FIELDS, :intent, :path)
47
+ # What `note` leaves in the body: the heading on a line of its own and,
48
+ # straight under it, an entry that opens with the time it was written.
49
+ # Finding this, not the heading's words, is what makes a dead holder's
50
+ # lock worth orphaning rather than deleting: an intent that mentioned
51
+ # `## Progress` used to pass for notes, and the lock of a holder that
52
+ # wrote none was kept as interrupted work until somebody broke it.
53
+ NOTES_SECTION = /^#{Regexp.escape(NOTES_HEADING)}\n- \d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ(?: |$)/
54
+
55
+ # A line of an intent that is the heading and nothing else, give or
56
+ # take the whitespace around it. Matches the empty spot in front of
57
+ # the `##`, which is where {.escape_heading} puts its backslash.
58
+ HEADING_LINE = /^[ \t]*\K(?=#{Regexp.escape(NOTES_HEADING)}[ \t\r]*$)/
59
+
60
+ # @!attribute [r] id
61
+ # @return [String] `<scope slug>-<digest>`, the same on every clone of a branch
62
+ # @!attribute [r] agent_id
63
+ # @return [String] who holds it, see {Identity#id}
64
+ # @!attribute [r] parent_agent_id
65
+ # @return [String, nil] the session that spawned the holder, if any
66
+ # @!attribute [r] scope
67
+ # @return [String] the normalized glob, relative to the tree root
68
+ # @!attribute [r] tree
69
+ # @return [String] the absolute root of the checkout that took it
70
+ # @!attribute [r] repo
71
+ # @return [String, nil] the repository it was taken in, see {Tree#repo}
72
+ # @!attribute [r] branch
73
+ # @return [String, nil] the branch it was taken on; nil on a detached HEAD
74
+ # @!attribute [r] worktree
75
+ # @return [Boolean] whether the checkout was a linked worktree
76
+ # @!attribute [r] pid
77
+ # @return [Integer, nil] the holder's session process, used to reap it
78
+ # @!attribute [r] started
79
+ # @return [String, nil] where a 4.0.0 gem kept that process's start time, as `ps` printed
80
+ # it in the holder's own time zone and locale. Read, and no longer written: a 4.0.0 gem
81
+ # reading a lock without it goes by the pid alone, and so never reaps a live holder
82
+ # @!attribute [r] started_at
83
+ # @return [String, nil] that process's start time, ISO 8601 and UTC, so a recycled pid
84
+ # is not mistaken for it
85
+ # @!attribute [r] host
86
+ # @return [String, nil] the machine the holder runs on
87
+ # @!attribute [r] created_at
88
+ # @return [String] ISO 8601, UTC
89
+ # @!attribute [r] updated_at
90
+ # @return [String, nil] ISO 8601, UTC, the last note or resume
91
+ # @!attribute [r] status
92
+ # @return [String] {ACTIVE} or {ORPHANED}
93
+ # @!attribute [r] frozen_paths
94
+ # @return [Array<String>] files `--enforce` froze, so a release can thaw them
95
+ FIELDS.each { |field| attr_reader(field) }
96
+
97
+ # @return [String] the body: what the holder is doing, then its notes
98
+ attr_reader :intent
99
+
100
+ # @return [String, nil] the file it was read from; nil outside the file store
101
+ attr_reader :path
38
102
 
39
103
  class << self
40
104
  # @param scope [Scope]
@@ -47,16 +111,33 @@ module Agent
47
111
  new(
48
112
  id: id_for(tree, scope), agent_id: identity.id, parent_agent_id: identity.parent_id,
49
113
  scope: scope.to_s, tree: tree.root, repo: tree.repo, branch: tree.branch, worktree: tree.worktree?,
50
- pid: evidence[:pid], started: evidence[:started], host: evidence[:host],
51
- created_at: Time.now.utc.iso8601, status: ACTIVE, frozen_paths: [], intent: intent
114
+ pid: evidence[:pid], started_at: evidence[:started_at], host: evidence[:host],
115
+ created_at: Time.now.utc.iso8601, status: ACTIVE, frozen_paths: [], intent: escape_heading(intent)
52
116
  )
53
117
  end
54
118
 
119
+ # An intent that cannot pass for notes. The body is one markdown
120
+ # text, the intent and then the notes, so an intent that pasted a
121
+ # notes section (the output of `alock show`, say) read as notes
122
+ # nobody wrote. A line that is the heading gets markdown's own
123
+ # escape, `\## Progress`: the words stay readable and stop being a
124
+ # heading, here and in a renderer.
125
+ #
126
+ # Stripped first because every store strips the body, which would
127
+ # otherwise uncover a heading behind leading whitespace only after
128
+ # this had looked.
129
+ #
130
+ # @param intent [String, nil] as the caller gave it
131
+ # @return [String]
132
+ def escape_heading(intent) = intent.to_s.strip.gsub(HEADING_LINE) { "\\" }
133
+
55
134
  # Derived from the tree's lock key and the scope so that a second run
56
135
  # looking for the same lock finds it without reading every file in the
57
136
  # store, and so that two checkouts of one branch, on any machine, are
58
137
  # after the same id and cannot both win it.
59
138
  #
139
+ # @param tree [Tree]
140
+ # @param scope [Scope]
60
141
  # @return [String]
61
142
  def id_for(tree, scope)
62
143
  digest = Digest::SHA256.hexdigest("#{tree.lock_key}\0#{scope}")[0, 8]
@@ -72,6 +153,7 @@ module Agent
72
153
  end
73
154
 
74
155
  # @param text [String] a lock document, from a file or from Redis
156
+ # @param path [String, nil] the file it was read from, for the file store
75
157
  # @return [Record, nil]
76
158
  def parse(text, path: nil)
77
159
  _, front, body = text.to_s.split(/^#{SEPARATOR}\s*$/, 3)
@@ -84,6 +166,9 @@ module Agent
84
166
  end
85
167
  end
86
168
 
169
+ # @param intent [String] the body: what the holder is doing, plus its notes
170
+ # @param path [String, nil] the file it was read from, for the file store
171
+ # @param fields [Hash{Symbol => Object}] any of {FIELDS}
87
172
  def initialize(intent: "", path: nil, **fields)
88
173
  FIELDS.each { |field| instance_variable_set(:"@#{field}", fields[field]) }
89
174
  @frozen_paths = Array(@frozen_paths)
@@ -91,6 +176,7 @@ module Agent
91
176
  @path = path
92
177
  end
93
178
 
179
+ # @param intent [String] the body, unchanged unless given
94
180
  # @param changes [Hash] fields to replace
95
181
  # @return [Record] a copy, since a record on disk is not edited in place
96
182
  def with(intent: self.intent, **changes)
@@ -118,7 +204,7 @@ module Agent
118
204
  id: self.class.id_for(tree, scope), tree: tree.root, repo: tree.repo, branch: tree.branch,
119
205
  worktree: tree.worktree?, status: ACTIVE, updated_at: Time.now.utc.iso8601,
120
206
  agent_id: identity.id, parent_agent_id: identity.parent_id,
121
- pid: evidence[:pid], started: evidence[:started], host: evidence[:host]
207
+ pid: evidence[:pid], started: nil, started_at: evidence[:started_at], host: evidence[:host]
122
208
  )
123
209
  end
124
210
 
@@ -142,8 +228,12 @@ module Agent
142
228
  with(intent: "#{body}\n- #{Time.now.utc.iso8601} #{text.strip}", updated_at: Time.now.utc.iso8601)
143
229
  end
144
230
 
231
+ # Whether {#note} ever wrote in this lock. Asked of {NOTES_SECTION},
232
+ # the shape `note` writes, rather than of the heading's words, which
233
+ # an intent can hold without a note under them.
234
+ #
145
235
  # @return [Boolean] whether anything worth keeping was written down
146
- def notes? = intent.include?(NOTES_HEADING)
236
+ def notes? = intent.match?(NOTES_SECTION)
147
237
 
148
238
  # @return [Scope]
149
239
  def scope_object = @scope_object ||= Scope.new(scope)
@@ -170,6 +260,13 @@ module Agent
170
260
  # @return [Boolean]
171
261
  def local_to?(checkout) = tree == checkout.root && same_host?
172
262
 
263
+ # Whether this lock was taken on this host in one of these checkouts,
264
+ # which is {#local_to?} for every worktree of a repository at once.
265
+ #
266
+ # @param roots [Array<String>] see Tree#worktree_roots
267
+ # @return [Boolean]
268
+ def taken_in?(roots) = roots.include?(tree) && same_host?
269
+
173
270
  # Two different questions, deliberately not one.
174
271
  #
175
272
  # Ownership answers "may I release this, write notes in it, and does
@@ -199,9 +296,9 @@ module Agent
199
296
 
200
297
  # @return [Boolean] the holder's process is still running, on this host
201
298
  def alive?
202
- return true unless same_host?
299
+ return true unless verifiable?
203
300
 
204
- ProcessInfo.alive?(pid, started: started)
301
+ ProcessInfo.alive?(pid, started_at: started_at, started: started)
205
302
  end
206
303
 
207
304
  # Whether the claim is void, so reaping it takes nothing from anybody.
@@ -212,11 +309,13 @@ module Agent
212
309
  # hours into a refactor lost its lock mid-edit and the next agent walked
213
310
  # straight in. A holder on another host cannot be asked, so time is all
214
311
  # there is, measured from its last write so that notes act as a
215
- # heartbeat.
312
+ # heartbeat. The same goes for a holder that named no process: a
313
+ # session known by name (`session_name:`) outlives any one process,
314
+ # so a restart of its host must not void its locks.
216
315
  #
217
316
  # @param minutes [Integer] how long an unverifiable lock is trusted
218
317
  # @return [Boolean]
219
- def expired?(minutes) = same_host? ? !alive? : untouched_for?(minutes)
318
+ def expired?(minutes) = verifiable? ? !alive? : untouched_for?(minutes)
220
319
 
221
320
  # A claim still standing, whose holder has not touched it in longer than
222
321
  # anybody should need. Reported, never acted on: the holder may be alive
@@ -234,18 +333,33 @@ module Agent
234
333
 
235
334
  private
236
335
 
336
+ # @param identity [Identity]
337
+ # @return [Boolean]
237
338
  def mine?(identity) = agent_id == identity.id
238
339
 
239
340
  # The lock belongs to the session that spawned this one.
341
+ #
342
+ # @param identity [Identity]
343
+ # @return [Boolean]
240
344
  def ancestor_of?(identity) = !identity.parent_id.nil? && agent_id == identity.parent_id
241
345
 
242
346
  # The lock belongs to a sub-agent this session spawned.
347
+ #
348
+ # @param identity [Identity]
349
+ # @return [Boolean]
243
350
  def descendant_of?(identity) = !parent_agent_id.nil? && parent_agent_id == identity.id
244
351
 
352
+ # @return [Boolean] true too when the record names no host
245
353
  def same_host? = host.nil? || host == Socket.gethostname
246
354
 
355
+ # @return [Boolean] whether there is a process on this host to ask
356
+ def verifiable? = same_host? && !pid.nil?
357
+
247
358
  # A lock with no readable timestamp is left alone rather than guessed
248
359
  # at: reaping on a parse error would delete live claims.
360
+ #
361
+ # @param minutes [Integer]
362
+ # @return [Boolean]
249
363
  def untouched_for?(minutes)
250
364
  touched = updated_at || created_at
251
365
  return false if touched.nil?
@@ -17,6 +17,19 @@ module Agent
17
17
  # intersect two globs is deliberate: glob intersection has answers nobody
18
18
  # can predict, and the failure it would buy is two agents editing one file.
19
19
  # This errs the other way, toward refusing work that might have been safe.
20
+ #
21
+ # Names are compared with their case folded, on every filesystem. APFS and
22
+ # NTFS find `README.md` under `readme.md` too, so compared byte for byte
23
+ # those were two scopes that never met, and two agents each held "the"
24
+ # file. Asking the checkout's filesystem instead was rejected: a Mac and
25
+ # a Linux box sharing one Redis would then disagree about whether a lock
26
+ # is in the way, and the one that cannot see it writes anyway. On a
27
+ # filesystem that does keep two such files apart, a lock on one now
28
+ # stands in front of both, which is the same error in the safe direction.
29
+ #
30
+ # Only the comparison folds. The pattern stays as it was typed, and so
31
+ # does the lock id made from it, which is what existing locks are filed
32
+ # under.
20
33
  class Scope
21
34
  # A scope the tree cannot honestly lock: empty, or somewhere else. Raised
22
35
  # rather than guessed at, since every guess so far locked the wrong thing
@@ -24,12 +37,14 @@ module Agent
24
37
  # message, which is written for the agent that has to fix its argument.
25
38
  class Invalid < Error; end
26
39
 
40
+ # The glob that claims the whole tree.
27
41
  ALL = "**"
28
42
 
29
43
  # The spellings of the whole tree, taken literally wherever the agent
30
44
  # stands.
31
45
  WHOLE_TREE = [".", "*", ALL].freeze
32
46
 
47
+ # The refusal for an empty scope, which is usually an unset variable.
33
48
  EMPTY = "empty scope: pass ** to claim the whole tree"
34
49
 
35
50
  # @return [String] the pattern, relative to the tree root
@@ -108,6 +123,7 @@ module Agent
108
123
  end
109
124
  end
110
125
 
126
+ # @param pattern [String, #to_s] a glob relative to the tree root, normalized here
111
127
  def initialize(pattern)
112
128
  @pattern = pattern.to_s.squeeze("/").delete_prefix("./")
113
129
  end
@@ -123,9 +139,9 @@ module Agent
123
139
  # @param other [Scope]
124
140
  # @return [Boolean]
125
141
  def conflicts_with?(other)
126
- return true if pattern == other.pattern
142
+ return true if same_as?(other)
127
143
 
128
- contains?(fixed_part, other.fixed_part) || contains?(other.fixed_part, fixed_part)
144
+ contains?(folded_fixed_part, other.folded_fixed_part) || contains?(other.folded_fixed_part, folded_fixed_part)
129
145
  end
130
146
 
131
147
  # Whether holding this scope already means holding `other`, which is a
@@ -141,11 +157,23 @@ module Agent
141
157
  # @param other [Scope]
142
158
  # @return [Boolean]
143
159
  def covers?(other)
144
- return true if pattern == other.pattern
160
+ return true if same_as?(other)
145
161
 
146
- recursive? && contains?(fixed_part, other.fixed_part)
162
+ recursive? && contains?(folded_fixed_part, other.folded_fixed_part)
147
163
  end
148
164
 
165
+ # Whether `other` is this claim, whatever case either was typed in. A
166
+ # looser question than #==, which is asked of the text: a lock is
167
+ # stored, and filed, under the spelling its holder used.
168
+ #
169
+ # @example
170
+ # Scope.new("README.md").same_as?(Scope.new("readme.md")) # => true
171
+ # Scope.new("README.md") == Scope.new("readme.md") # => false
172
+ #
173
+ # @param other [Scope]
174
+ # @return [Boolean]
175
+ def same_as?(other) = folded_pattern == other.folded_pattern
176
+
149
177
  # @return [Boolean] the whole tree, or everything under one directory
150
178
  def recursive? = [ALL, "#{fixed_part}/#{ALL}"].include?(pattern)
151
179
 
@@ -156,12 +184,29 @@ module Agent
156
184
  text.empty? ? "tree" : text[0, 60]
157
185
  end
158
186
 
187
+ # @return [String] the normalized pattern, relative to the tree root
159
188
  def to_s = pattern
160
189
 
190
+ # @param other [Object]
191
+ # @return [Boolean] the same pattern, letter for letter. The same claim
192
+ # in another case is #same_as?
161
193
  def ==(other) = other.is_a?(Scope) && pattern == other.pattern
162
194
 
195
+ protected
196
+
197
+ # `:fold` rather than a plain downcase, since it is what comparing
198
+ # without case means past ASCII: it is the folding `casecmp?` does.
199
+ #
200
+ # @return [String] the pattern as it is compared, never as it is stored
201
+ def folded_pattern = @folded_pattern ||= pattern.downcase(:fold)
202
+
203
+ # @return [String] {#fixed_part} as it is compared
204
+ def folded_fixed_part = @folded_fixed_part ||= fixed_part.downcase(:fold)
205
+
163
206
  private
164
207
 
208
+ # @param outer [String] a fixed part
209
+ # @param inner [String] a fixed part
165
210
  # @return [Boolean] whether `outer` is `inner` or an ancestor of it
166
211
  def contains?(outer, inner)
167
212
  return true if outer.empty? || outer == inner
@@ -17,6 +17,10 @@ module Agent
17
17
  # The skill's directory name, which is also the name it answers to.
18
18
  NAME = "agent-lock"
19
19
 
20
+ # The home-relative directory each agent keeps its skills under. Any
21
+ # agent not named here reads the shared `~/.agents`.
22
+ AGENT_DIRS = { "claude" => ".claude" }.freeze
23
+
20
24
  # Where the gem keeps its skills, one directory each.
21
25
  ROOT = File.expand_path("../../../skills", __dir__)
22
26
 
@@ -34,10 +38,10 @@ module Agent
34
38
  # help text can say what `install` puts on disk
35
39
  def bundled = Dir.children(ROOT).select { |name| File.directory?(File.join(ROOT, name)) }.sort
36
40
 
37
- # @return [String] where most agents other than Claude Code look for
38
- # a user's own skills; the CLI's `--for claude` points at
39
- # `~/.claude/skills` instead
40
- def default_into = File.join(Dir.home, ".agents", "skills")
41
+ # @param agent [String, nil] the agent the skill is for, e.g. `claude`
42
+ # @return [String] the skills directory that agent reads: `~/.claude/skills`
43
+ # for Claude Code, and the shared `~/.agents/skills` for any other or none
44
+ def default_into(agent = nil) = File.join(Dir.home, AGENT_DIRS.fetch(agent.to_s, ".agents"), "skills")
41
45
  end
42
46
 
43
47
  # @return [String] the skills directory being installed into
@@ -62,10 +66,10 @@ module Agent
62
66
  # that links every skill it manages; replacing either without being
63
67
  # asked is the silent last-writer-wins this gem exists to prevent.
64
68
  #
65
- # @param force [Boolean] replace a copy that differs; never a symlink
69
+ # @param overwrite [Boolean] replace a copy that differs; never a symlink
66
70
  # @return [Result] :installed, :current, :differs or :linked
67
- def install(force: false)
68
- refused = refusal(force)
71
+ def install(overwrite: false)
72
+ refused = refusal(overwrite)
69
73
  return refused if refused
70
74
 
71
75
  FileUtils.rm_rf(target)
@@ -76,13 +80,13 @@ module Agent
76
80
 
77
81
  private
78
82
 
79
- # @param force [Boolean]
83
+ # @param overwrite [Boolean]
80
84
  # @return [Result, nil] why nothing should be copied, or nil to go ahead
81
- def refusal(force)
85
+ def refusal(overwrite)
82
86
  return result(:linked) if File.symlink?(target)
83
87
  return result(:current) if current?
84
88
 
85
- result(:differs) if File.exist?(target) && !force
89
+ result(:differs) if File.exist?(target) && !overwrite
86
90
  end
87
91
 
88
92
  # @param status [Symbol]
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../facade/strategies"
4
+
5
+ module Agent
6
+ module Lock
7
+ module Store
8
+ # A backend's name as somebody spelled it, read in one place so that
9
+ # nothing but "file" or "redis" can reach {Store.claim}.
10
+ #
11
+ # AGENT_LOCK_BACKEND used to reach the marker as typed, only
12
+ # downcased, and was checked after: `bogus`, `filesystem` or a
13
+ # variable exported empty bound the tree to a store that does not
14
+ # exist, and every later command read the name back and refused it.
15
+ module BackendName
16
+ # The variable that names the backend when no caller does.
17
+ VARIABLE = "AGENT_LOCK_BACKEND"
18
+
19
+ module_function
20
+
21
+ # A blank name is no name at all. `filesystem` is `file`, as it is
22
+ # for `--locking-strategy`.
23
+ #
24
+ # @param name [String, nil] as the caller or the environment spelled it
25
+ # @param from [String, nil] where it was read, said when it is refused
26
+ # @return [String, nil] "file" or "redis"; nil when `name` is blank
27
+ # @raise [Mismatch] when it names anything else
28
+ def canonical(name, from = nil)
29
+ spelled = name.to_s.strip
30
+ return if spelled.empty?
31
+
32
+ Facade::Strategies.canonical(spelled.downcase)
33
+ rescue ArgumentError
34
+ raise Mismatch, "unknown backend #{spelled.inspect}#{" in #{from}" if from}, expected file or redis"
35
+ end
36
+
37
+ # @return [String, nil] what {VARIABLE} asks for; nil when it is unset or blank
38
+ # @raise [Mismatch] when it names no backend
39
+ def from_environment = canonical(ENV.fetch(VARIABLE, nil), VARIABLE)
40
+
41
+ # What a tree's marker holds, as long as that is a backend. A marker
42
+ # an older `alock` wrote from a mistyped {VARIABLE} was refused by
43
+ # every command with the name and nothing more, though
44
+ # `switch-backend` rebinds such a tree: so that command is offered,
45
+ # with the file store unless the caller asked for redis, since file
46
+ # needs nothing to answer.
47
+ #
48
+ # @param name [String, nil] what the marker holds; nil for a virgin tree
49
+ # @param path [String] the marker, said when the name is refused
50
+ # @param offer [String, nil] "file" or "redis", the backend the caller asked for
51
+ # @return [String, nil] `name`
52
+ # @raise [Mismatch] when it names no backend
53
+ def marked(name, path, offer: nil)
54
+ return name if name.nil? || BACKENDS.include?(name)
55
+
56
+ raise Mismatch.new("unknown backend #{name.inspect} in #{path}, expected file or redis",
57
+ command: "switch-backend #{offer || "file"}")
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -4,6 +4,7 @@ require_relative "../error"
4
4
  require_relative "../record"
5
5
 
6
6
  require "fileutils"
7
+ require "securerandom"
7
8
 
8
9
  module Agent
9
10
  module Lock
@@ -11,7 +12,10 @@ module Agent
11
12
  # Locks as files, which is the default and the one that needs nothing
12
13
  # installed. See Tree#store_dir for why they live inside `.git`.
13
14
  class FileSystemStore
15
+ # Every lock file ends in this, which is what `all` globs for.
14
16
  SUFFIX = ".lock.md"
17
+
18
+ # The file `flock`ed around every claim, beside the locks.
15
19
  MUTEX = ".mutex"
16
20
 
17
21
  # Seconds. A claim's critical section is a directory scan and one
@@ -20,6 +24,7 @@ module Agent
20
24
 
21
25
  attr_reader :tree
22
26
 
27
+ # @param tree [Tree] the checkout whose store directory holds the locks
23
28
  def initialize(tree)
24
29
  @tree = tree
25
30
  end
@@ -30,6 +35,16 @@ module Agent
30
35
  # @return [String] how a listing names this store
31
36
  def describe = dir
32
37
 
38
+ # @return [String] what the tree's backend marker says for this store
39
+ def backend = "file"
40
+
41
+ # Every lock here. The store sits in the git common dir, so each one
42
+ # was taken in a checkout that shares this tree's backend marker, a
43
+ # worktree removed since included.
44
+ #
45
+ # @return [Array<Record>] the locks a switch of this tree's backend strands
46
+ def bound = all
47
+
33
48
  # FNM_DOTMATCH is load-bearing. A scope like `.plans/**` slugs to a
34
49
  # filename that starts with a dot, and a plain glob skips it, so the
35
50
  # lock was written, listed nowhere, and blocked nobody. Redis matches
@@ -94,11 +109,15 @@ module Agent
94
109
  # reader never sees half a document, and so a crash mid-write leaves
95
110
  # the previous version rather than nothing.
96
111
  #
112
+ # The temp name is unique per write, not per process: threads in one
113
+ # process (a facade) used to share `<pid>.tmp`, and the first rename
114
+ # left the others renaming a file that was gone.
115
+ #
97
116
  # @param record [Record]
98
117
  # @return [void]
99
118
  def update(record)
100
119
  path = record.path || path_for(record.id)
101
- temp = "#{path}.#{Process.pid}.tmp"
120
+ temp = "#{path}.#{Process.pid}.#{SecureRandom.hex(6)}.tmp"
102
121
  File.write(temp, record.to_markdown)
103
122
  File.rename(temp, path)
104
123
  end