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.
- checksums.yaml +4 -4
- data/.gitleaks.toml +23 -0
- data/AGENTS.md +11 -17
- data/CHANGELOG.md +124 -3
- data/README.md +496 -100
- data/Rakefile +13 -6
- data/docs/badges/coverage_badge.svg +21 -0
- data/docs/badges/yardoc.svg +1 -0
- data/docs/img/alock-sequence.avif +0 -0
- data/docs/img/alock-sequence.md +29 -0
- data/docs/img/alock-sequence.png +0 -0
- data/lefthook.yml +39 -0
- data/lib/agent/lock/cli/commands/acquire.rb +25 -19
- data/lib/agent/lock/cli/commands/base.rb +59 -23
- data/lib/agent/lock/cli/commands/break.rb +12 -7
- data/lib/agent/lock/cli/commands/check.rb +10 -9
- data/lib/agent/lock/cli/commands/completion.rb +15 -32
- data/lib/agent/lock/cli/commands/list.rb +46 -37
- data/lib/agent/lock/cli/commands/listing.rb +170 -0
- data/lib/agent/lock/cli/commands/mine.rb +7 -5
- data/lib/agent/lock/cli/commands/note.rb +13 -9
- data/lib/agent/lock/cli/commands/release.rb +10 -7
- data/lib/agent/lock/cli/commands/release_all.rb +7 -5
- data/lib/agent/lock/cli/commands/resume.rb +13 -7
- data/lib/agent/lock/cli/commands/show.rb +172 -0
- data/lib/agent/lock/cli/commands/skills.rb +28 -19
- data/lib/agent/lock/cli/commands/switch_backend.rb +205 -0
- data/lib/agent/lock/cli/commands/tree_command.rb +72 -0
- data/lib/agent/lock/cli/commands/version.rb +2 -1
- data/lib/agent/lock/cli/commands/whoami.rb +7 -3
- data/lib/agent/lock/cli.rb +63 -19
- data/lib/agent/lock/error.rb +52 -1
- data/lib/agent/lock/facade/async.rb +83 -0
- data/lib/agent/lock/facade/backend.rb +133 -0
- data/lib/agent/lock/facade/memo.rb +30 -0
- data/lib/agent/lock/facade/refusal.rb +78 -0
- data/lib/agent/lock/facade/session.rb +142 -0
- data/lib/agent/lock/facade/strategies.rb +36 -0
- data/lib/agent/lock/facade.rb +369 -0
- data/lib/agent/lock/freeze.rb +59 -5
- data/lib/agent/lock/identity.rb +63 -5
- data/lib/agent/lock/launcher.rb +17 -1
- data/lib/agent/lock/manager/enforcement.rb +98 -0
- data/lib/agent/lock/manager/switch.rb +91 -0
- data/lib/agent/lock/manager/thaw.rb +68 -0
- data/lib/agent/lock/manager.rb +176 -79
- data/lib/agent/lock/process_info/legacy_start.rb +60 -0
- data/lib/agent/lock/process_info.rb +42 -11
- data/lib/agent/lock/record.rb +124 -10
- data/lib/agent/lock/scope.rb +49 -4
- data/lib/agent/lock/skill.rb +14 -10
- data/lib/agent/lock/store/backend_name.rb +62 -0
- data/lib/agent/lock/store/file_system_store.rb +20 -1
- data/lib/agent/lock/store/redis_index.rb +179 -0
- data/lib/agent/lock/store/redis_store.rb +191 -33
- data/lib/agent/lock/store.rb +180 -19
- data/lib/agent/lock/text.rb +62 -0
- data/lib/agent/lock/tree.rb +143 -16
- data/lib/agent/lock/version.rb +2 -1
- data/lib/agent/lock.rb +3 -0
- data/skills/agent-lock/SKILL.md +75 -10
- metadata +41 -22
- data/justfile +0 -127
- data/sig/agent/lock.rbs +0 -6
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "facade/backend"
|
|
4
|
+
require_relative "facade/session"
|
|
5
|
+
require_relative "facade/refusal"
|
|
6
|
+
require_relative "facade/memo"
|
|
7
|
+
require_relative "facade/async"
|
|
8
|
+
|
|
9
|
+
module Agent
|
|
10
|
+
# {Facade} and the process-wide facades {.local} and {.distributed}.
|
|
11
|
+
module Lock
|
|
12
|
+
# Every `alock` command as a method, run in this process, so a caller
|
|
13
|
+
# pays for no new Ruby process per call. (`git` and `ps` still run, as
|
|
14
|
+
# they do under the CLI, to find the checkout and check holders.)
|
|
15
|
+
#
|
|
16
|
+
# One facade is one locker. It picks its backend when it is built and
|
|
17
|
+
# keeps it, so every thread calling it takes locks in the same store. A
|
|
18
|
+
# second facade with another `redis_url` is a separate locker. Building
|
|
19
|
+
# one never touches {Agent::Lock.local} or {Agent::Lock.distributed}.
|
|
20
|
+
#
|
|
21
|
+
# Thread-safe: a facade is frozen, and each call builds its own
|
|
22
|
+
# {Manager}, so threads share nothing but the store, whose mutex
|
|
23
|
+
# serializes the writes.
|
|
24
|
+
#
|
|
25
|
+
# A lock method returns the {Manager::Result} on success. Where the CLI
|
|
26
|
+
# would print a refusal on stderr, it raises {Refused}, whose `result` is
|
|
27
|
+
# the same {Manager::Result}. `:not_found` from {#release},
|
|
28
|
+
# {#break_lock} and {#resume} is returned, although the CLI exits 1 on
|
|
29
|
+
# it: nothing was there, so nothing was refused.
|
|
30
|
+
#
|
|
31
|
+
# Every lock method also takes these keywords, which override the
|
|
32
|
+
# facade's defaults for that one call:
|
|
33
|
+
#
|
|
34
|
+
# - `dir:` [String] a directory inside the checkout (default: the current one)
|
|
35
|
+
# - `agent_id:` [String] who holds the lock
|
|
36
|
+
# - `parent_id:` [String, false] that holder's parent session; `false` for none
|
|
37
|
+
# - `stale_minutes:` [Integer] when an unverifiable lock counts as stale
|
|
38
|
+
# - `session_name:` [String] the session's name, tied to no process
|
|
39
|
+
#
|
|
40
|
+
# The checkout's backend marker binds a facade just as it binds `alock`:
|
|
41
|
+
# a facade claims a virgin checkout for its backend, and raises
|
|
42
|
+
# {Store::Mismatch} in one already claimed for the other, so a facade
|
|
43
|
+
# and the CLI can never take the same scope in two stores.
|
|
44
|
+
#
|
|
45
|
+
# `async: true` adds {#async}, which runs any lock method on
|
|
46
|
+
# concurrent-ruby's I/O pool and returns a `Concurrent::Promises::Future`:
|
|
47
|
+
# `value!` is the result or re-raises, `value` is nil when the call raised
|
|
48
|
+
# and `reason` holds why. Arguments, keywords and blocks pass through as
|
|
49
|
+
# on a direct call, and direct calls stay synchronous. concurrent-ruby is
|
|
50
|
+
# not a dependency of this gem; add it to the Gemfile to use this.
|
|
51
|
+
#
|
|
52
|
+
# @example File store, signed by a sub-agent
|
|
53
|
+
# locks = Agent::Lock.local
|
|
54
|
+
# locks.acquire("lib/**", "rewriting billing", agent_id: "luke-backend")
|
|
55
|
+
#
|
|
56
|
+
# @example Redis, falling back to the file store when it does not answer
|
|
57
|
+
# locks = Agent::Lock::Facade.new(
|
|
58
|
+
# strategies: %w[redis file],
|
|
59
|
+
# redis_url: ENV.fetch("REDIS_URL", "redis://127.0.0.1:6379/0")
|
|
60
|
+
# )
|
|
61
|
+
class Facade
|
|
62
|
+
# Tried in this order when the caller does not pass `strategies`.
|
|
63
|
+
DEFAULT_STRATEGIES = %w[redis file].freeze
|
|
64
|
+
|
|
65
|
+
# Used when `redis_url` is omitted and neither `AGENT_LOCK_REDIS_URL`
|
|
66
|
+
# nor `REDIS_URL` is set. It is the local Redis `alock` itself tries,
|
|
67
|
+
# by the same constant, so the two cannot drift apart again: this was
|
|
68
|
+
# `redis://localhost:6379`, a second spelling of the same server.
|
|
69
|
+
DEFAULT_REDIS_URL = Store::RedisStore::LOCAL_URL
|
|
70
|
+
|
|
71
|
+
# The Redis a facade uses, by the rule `alock` follows: what the
|
|
72
|
+
# caller named, then `AGENT_LOCK_REDIS_URL`, then `REDIS_URL`.
|
|
73
|
+
#
|
|
74
|
+
# A blank `REDIS_URL` counts as unset, as it does for `alock`
|
|
75
|
+
# ({Store::RedisStore.candidate_urls}). Taken for a URL, `REDIS_URL=""`
|
|
76
|
+
# sent a facade to the file store beside a local Redis that `alock`
|
|
77
|
+
# went on to use, so the two could claim one new checkout for
|
|
78
|
+
# different backends.
|
|
79
|
+
#
|
|
80
|
+
# @param redis_url [String, nil] the caller's
|
|
81
|
+
# @return [String]
|
|
82
|
+
def self.redis_url(redis_url = nil)
|
|
83
|
+
ambient = ENV.fetch("REDIS_URL", "").strip
|
|
84
|
+
redis_url || Store.named_redis_url || (ambient.empty? ? DEFAULT_REDIS_URL : ambient)
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# @param strategies [Array<String, Symbol>] backends to try, in order:
|
|
88
|
+
# `redis`, and `file` (or `filesystem`)
|
|
89
|
+
# @param redis_url [String, nil] defaults as {.redis_url} says:
|
|
90
|
+
# `AGENT_LOCK_REDIS_URL`, then `REDIS_URL`, then {DEFAULT_REDIS_URL}
|
|
91
|
+
# @param async [Boolean] offer {#async}; needs the concurrent-ruby gem
|
|
92
|
+
# @param defaults [Hash] what a call uses when it does not say:
|
|
93
|
+
# @option defaults [String] :agent_id signs locks when a call does not name its own
|
|
94
|
+
# @option defaults [String, false] :parent_id that holder's parent,
|
|
95
|
+
# likewise. `false` says it has none: a top-level service that
|
|
96
|
+
# names itself is otherwise the child of whatever started it, and
|
|
97
|
+
# is not blocked by that session's locks
|
|
98
|
+
# @option defaults [Integer] :stale_minutes nil reads `AGENT_LOCK_STALE_MINUTES`
|
|
99
|
+
# @option defaults [Symbol] :holder `:process` (default) ties a lock's
|
|
100
|
+
# liveness to this Ruby process, so locks left by a crashed host are
|
|
101
|
+
# reaped; `:session` ties it to the first non-shell ancestor, as `alock` does
|
|
102
|
+
# @option defaults [String] :session_name the session's name, such as a
|
|
103
|
+
# plan id, in place of `CLAUDE_SESSION_ID` and the fingerprint, and
|
|
104
|
+
# in place of `holder:`. Its locks are tied to no process: they
|
|
105
|
+
# survive a restart and lapse when untouched for `stale_minutes`
|
|
106
|
+
# @raise [RedisUnavailableError] when no strategy but `redis` is left and it does not answer
|
|
107
|
+
# @raise [ArgumentError] when `strategies` is empty or names an unknown
|
|
108
|
+
# backend, `holder` is not `:process` or `:session` or is given
|
|
109
|
+
# beside `session_name`, or a default is not one of those five
|
|
110
|
+
# @raise [LoadError] when `async` is true and concurrent-ruby is not installed
|
|
111
|
+
def initialize(strategies: DEFAULT_STRATEGIES, redis_url: nil, async: false, **defaults)
|
|
112
|
+
@backend = Backend.new(strategies:, redis_url: Facade.redis_url(redis_url))
|
|
113
|
+
@session = Session.new(@backend, **defaults)
|
|
114
|
+
@async = async ? Async.tap(&:load!).new(self) : nil
|
|
115
|
+
freeze
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# @return [String] "redis" or "file", chosen once at construction
|
|
119
|
+
def backend_name = @backend.name
|
|
120
|
+
|
|
121
|
+
# @return [String] the Redis URL this facade was given, used or not
|
|
122
|
+
def redis_url = @backend.redis_url
|
|
123
|
+
|
|
124
|
+
# The lock methods again, each returning a future instead of waiting.
|
|
125
|
+
#
|
|
126
|
+
# @example
|
|
127
|
+
# locks = Agent::Lock::Facade.new(strategies: %w[file], async: true)
|
|
128
|
+
# future = locks.async.acquire("lib/**", "rewriting billing", agent_id: "luke-backend")
|
|
129
|
+
# future.value!.status # => :acquired
|
|
130
|
+
#
|
|
131
|
+
# @return [Async]
|
|
132
|
+
# @raise [ArgumentError] when the facade was built without `async: true`
|
|
133
|
+
def async = @async || raise(ArgumentError, "build the facade with async: true to call #async")
|
|
134
|
+
|
|
135
|
+
# `alock acquire`: claim a scope before writing in it.
|
|
136
|
+
#
|
|
137
|
+
# With a block, yields the {Manager::Result} and returns the block's
|
|
138
|
+
# value. The lock is released afterwards only when this call took it
|
|
139
|
+
# (`:acquired`). `:already_mine` yields and leaves the lock you already
|
|
140
|
+
# held, so a nested block does not drop the outer one. A refusal raises
|
|
141
|
+
# before the block runs. An exception from the block releases, then
|
|
142
|
+
# propagates. When that release is itself refused (somebody broke the
|
|
143
|
+
# lock and took the scope while the block ran), the block's exception
|
|
144
|
+
# still wins: replacing it with the release's {Refused} hid the bug
|
|
145
|
+
# the caller actually had.
|
|
146
|
+
#
|
|
147
|
+
# @param scope [String] a path, a directory, or a glob such as `lib/**`
|
|
148
|
+
# @param intent [String, nil] what the holder is about to do
|
|
149
|
+
# @param enforce [Boolean] also freeze the matched files (macOS only)
|
|
150
|
+
# @param allow_wide [Boolean] let `enforce` freeze more than {Freeze::LIMIT} files
|
|
151
|
+
# @param session [Hash] `dir:`, `agent_id:`, `parent_id:`, `stale_minutes:`,
|
|
152
|
+
# `session_name:`
|
|
153
|
+
# @yieldparam result [Manager::Result] `:acquired`, or `:already_mine`
|
|
154
|
+
# @return [Manager::Result] without a block: `:acquired`, or `:already_mine`
|
|
155
|
+
# @return [Object] with a block: the block's value
|
|
156
|
+
# @raise [Refused] held by another agent, interrupted work, or exactly your parent's scope
|
|
157
|
+
# @raise [Scope::Invalid] when the scope is empty or outside the checkout
|
|
158
|
+
# @raise [Freeze::TooBroad] when `enforce` exceeds the limit without `allow_wide`
|
|
159
|
+
def acquire(scope, intent = nil, enforce: false, allow_wide: false, **session)
|
|
160
|
+
result = Refusal.check!(
|
|
161
|
+
@session.manager(**session).acquire(scope, intent: intent || "unspecified", enforce:, wide: allow_wide),
|
|
162
|
+
scope:
|
|
163
|
+
)
|
|
164
|
+
return result unless block_given?
|
|
165
|
+
return yield(result) unless result.status == :acquired
|
|
166
|
+
|
|
167
|
+
within(scope, session) { yield result }
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# `alock release`.
|
|
171
|
+
#
|
|
172
|
+
# @param scope [String]
|
|
173
|
+
# @param session [Hash] `dir:`, `agent_id:`, `parent_id:`, `stale_minutes:`,
|
|
174
|
+
# `session_name:`
|
|
175
|
+
# @return [Manager::Result] `:released`, or `:not_found` when nothing is locked there
|
|
176
|
+
# @raise [Refused] when another agent holds it
|
|
177
|
+
def release(scope, **session) = Refusal.check!(@session.manager(**session).release(scope), scope:)
|
|
178
|
+
|
|
179
|
+
# `alock check`: may I write here?
|
|
180
|
+
#
|
|
181
|
+
# @param scope [String]
|
|
182
|
+
# @param session [Hash] `dir:`, `agent_id:`, `parent_id:`, `stale_minutes:`,
|
|
183
|
+
# `session_name:`
|
|
184
|
+
# @return [Manager::Result] `:free`, or `:mine`
|
|
185
|
+
# @raise [Refused] when another agent holds an overlapping scope
|
|
186
|
+
def check(scope, **session) = Refusal.check!(@session.manager(**session).check(scope), scope:)
|
|
187
|
+
|
|
188
|
+
# `alock list`.
|
|
189
|
+
#
|
|
190
|
+
# @param session [Hash] `dir:`, `agent_id:`, `parent_id:`, `stale_minutes:`,
|
|
191
|
+
# `session_name:`
|
|
192
|
+
# @return [Manager::Result] every lock in this facade's store
|
|
193
|
+
def list(**session) = @session.manager(**session).list
|
|
194
|
+
|
|
195
|
+
# `alock mine`.
|
|
196
|
+
#
|
|
197
|
+
# @param session [Hash] `dir:`, `agent_id:`, `parent_id:`, `stale_minutes:`,
|
|
198
|
+
# `session_name:`
|
|
199
|
+
# @return [Manager::Result] locks held by this identity and its sub-agents
|
|
200
|
+
def mine(**session) = @session.manager(**session).mine
|
|
201
|
+
|
|
202
|
+
# `alock release-all`.
|
|
203
|
+
#
|
|
204
|
+
# @param session [Hash] `dir:`, `agent_id:`, `parent_id:`, `stale_minutes:`,
|
|
205
|
+
# `session_name:`
|
|
206
|
+
# @return [Manager::Result] what was released
|
|
207
|
+
def release_all(**session) = @session.manager(**session).release_all
|
|
208
|
+
|
|
209
|
+
# `alock break`: drop somebody else's lock. Announce it first. Never
|
|
210
|
+
# raises a refusal: breaking a free scope returns `:not_found`.
|
|
211
|
+
#
|
|
212
|
+
# @param scope [String]
|
|
213
|
+
# @param session [Hash] `dir:`, `agent_id:`, `parent_id:`, `stale_minutes:`,
|
|
214
|
+
# `session_name:`
|
|
215
|
+
# @return [Manager::Result] `:broken`, or `:not_found`
|
|
216
|
+
def break_lock(scope, **session) = @session.manager(**session).break_lock(scope)
|
|
217
|
+
|
|
218
|
+
# `alock note`: leave a note on a lock you hold.
|
|
219
|
+
#
|
|
220
|
+
# @param scope [String]
|
|
221
|
+
# @param text [String]
|
|
222
|
+
# @param session [Hash] `dir:`, `agent_id:`, `parent_id:`, `stale_minutes:`,
|
|
223
|
+
# `session_name:`
|
|
224
|
+
# @return [Manager::Result] `:noted`
|
|
225
|
+
# @raise [Refused] when nothing is locked there, or another agent holds it
|
|
226
|
+
def note(scope, text, **session)
|
|
227
|
+
Refusal.check!(@session.manager(**session).note(scope, text), scope:, also: %i[not_found])
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
# `alock resume`: take back interrupted work, notes and all.
|
|
231
|
+
#
|
|
232
|
+
# @param scope [String]
|
|
233
|
+
# @param session [Hash] `dir:`, `agent_id:`, `parent_id:`, `stale_minutes:`,
|
|
234
|
+
# `session_name:`
|
|
235
|
+
# @return [Manager::Result] `:resumed`, or `:not_found` when there is nothing to resume
|
|
236
|
+
# @raise [Refused] when another agent holds an overlapping scope, or the
|
|
237
|
+
# interrupted work could not be moved onto this scope
|
|
238
|
+
def resume(scope, **session) = Refusal.check!(@session.manager(**session).resume(scope), scope:)
|
|
239
|
+
|
|
240
|
+
# `alock whoami`: who a lock taken through this facade would name.
|
|
241
|
+
#
|
|
242
|
+
# @param session [Hash] `agent_id:`, `parent_id:`, `session_name:`
|
|
243
|
+
# @return [Identity]
|
|
244
|
+
def whoami(**session) = @session.identity(**session)
|
|
245
|
+
|
|
246
|
+
# `alock skills path`.
|
|
247
|
+
#
|
|
248
|
+
# @return [String] the directory of the bundled skill
|
|
249
|
+
def skills_path = Skill.source
|
|
250
|
+
|
|
251
|
+
# `alock skills install`.
|
|
252
|
+
#
|
|
253
|
+
# @param into [String, nil] skills directory; wins over `agent` when both are given
|
|
254
|
+
# @param agent [String, nil] the CLI's `--for`: `claude` installs into ~/.claude/skills,
|
|
255
|
+
# anything else into ~/.agents/skills
|
|
256
|
+
# @param overwrite [Boolean] replace an installed copy that differs
|
|
257
|
+
# @return [Skill::Result] `:installed` or `:current`
|
|
258
|
+
# @raise [Refused] when the installed copy differs, or is a symlink
|
|
259
|
+
def skills_install(into: nil, agent: nil, overwrite: false)
|
|
260
|
+
Refusal.check!(Skill.new(into: into || Skill.default_into(agent)).install(overwrite:))
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
# `alock version`.
|
|
264
|
+
#
|
|
265
|
+
# @return [String] {VERSION}
|
|
266
|
+
def version = VERSION
|
|
267
|
+
|
|
268
|
+
# `alock show repos`. Redis only: the file store keeps one checkout's locks
|
|
269
|
+
# and has no list of repositories.
|
|
270
|
+
#
|
|
271
|
+
# @param redis_url [String, nil] that one Redis, with no fallback when given
|
|
272
|
+
# @return [Array<Store::RedisIndex::Repo>]
|
|
273
|
+
# @raise [Store::Unreachable] when Redis does not answer
|
|
274
|
+
def show_repos(redis_url: nil) = Store::RedisIndex.open(redis_url).repos
|
|
275
|
+
|
|
276
|
+
# `alock show repo [owner/name]`. Redis only, same as {#show_repos}.
|
|
277
|
+
#
|
|
278
|
+
# @param repo [String, nil] `owner/name`, `github.com/owner/name`, or
|
|
279
|
+
# `host/owner/name` on another forge; nil for the checkout `dir` is in
|
|
280
|
+
# @param dir [String] the checkout whose origin remote names the
|
|
281
|
+
# repository when `repo` is nil
|
|
282
|
+
# @param redis_url [String, nil]
|
|
283
|
+
# @return [Array<Store::RedisIndex::Lock>]
|
|
284
|
+
# @raise [Error] when `repo` is a bare name, or is nil and `dir` is in
|
|
285
|
+
# no checkout with an origin remote
|
|
286
|
+
# @raise [Store::Unreachable] when Redis does not answer
|
|
287
|
+
def show_repo(repo = nil, dir: Dir.pwd, redis_url: nil)
|
|
288
|
+
Store::RedisIndex.open(redis_url).locks(repo || Store::RedisIndex.slug_for(dir))
|
|
289
|
+
end
|
|
290
|
+
|
|
291
|
+
private
|
|
292
|
+
|
|
293
|
+
# Run the block of an {#acquire} that took the lock, then release it.
|
|
294
|
+
# `ensure`, so a `break`, `throw` or exception still releases. Only a
|
|
295
|
+
# block that finished lets a refused release raise; otherwise the
|
|
296
|
+
# refusal is swallowed and whatever was unwinding carries on.
|
|
297
|
+
#
|
|
298
|
+
# @param scope [String]
|
|
299
|
+
# @param session [Hash]
|
|
300
|
+
# @return [Object] the block's value
|
|
301
|
+
def within(scope, session)
|
|
302
|
+
finished = false
|
|
303
|
+
value = yield
|
|
304
|
+
finished = true
|
|
305
|
+
value
|
|
306
|
+
ensure
|
|
307
|
+
begin
|
|
308
|
+
release(scope, **session)
|
|
309
|
+
rescue Refused
|
|
310
|
+
raise if finished
|
|
311
|
+
end
|
|
312
|
+
end
|
|
313
|
+
end
|
|
314
|
+
|
|
315
|
+
# Built on first use, once per process; see {.local} and {.distributed}.
|
|
316
|
+
LOCAL_FACADE = Facade::Memo.new { Facade.new(strategies: %w[file]) }
|
|
317
|
+
# One per Redis URL, each built once.
|
|
318
|
+
DISTRIBUTED_FACADES = Facade::Memo.new { {} }
|
|
319
|
+
DISTRIBUTED_MUTEX = Mutex.new
|
|
320
|
+
private_constant :LOCAL_FACADE, :DISTRIBUTED_FACADES, :DISTRIBUTED_MUTEX
|
|
321
|
+
|
|
322
|
+
class << self
|
|
323
|
+
# The process-wide file-store facade, built on first use. Thread-safe,
|
|
324
|
+
# and independent of {.distributed} and of every {Facade.new}.
|
|
325
|
+
#
|
|
326
|
+
# @return [Facade]
|
|
327
|
+
def local = LOCAL_FACADE.value
|
|
328
|
+
|
|
329
|
+
# The process-wide Redis facade for one Redis, built on first use and
|
|
330
|
+
# kept per URL, so a host whose Redis comes from its own flag or
|
|
331
|
+
# config file gets the same locker on every call. Thread-safe. A
|
|
332
|
+
# failed build is not kept: the next call tries Redis again.
|
|
333
|
+
#
|
|
334
|
+
# @param redis_url [String, nil] nil resolves as {Facade.redis_url}
|
|
335
|
+
# says: `AGENT_LOCK_REDIS_URL`, then `REDIS_URL`, then the default
|
|
336
|
+
# @return [Facade]
|
|
337
|
+
# @raise [RedisUnavailableError] when that Redis does not answer
|
|
338
|
+
def distributed(redis_url: nil)
|
|
339
|
+
url = Facade.redis_url(redis_url)
|
|
340
|
+
DISTRIBUTED_MUTEX.synchronize do
|
|
341
|
+
DISTRIBUTED_FACADES.value[url] ||= Facade.new(strategies: %w[redis], redis_url: url)
|
|
342
|
+
end
|
|
343
|
+
end
|
|
344
|
+
|
|
345
|
+
# A new facade, defaulting like `alock`: Redis when it answers, the
|
|
346
|
+
# file store when it does not. Never memoized.
|
|
347
|
+
#
|
|
348
|
+
# @param strategies [Array<String, Symbol>] see {Facade#initialize}
|
|
349
|
+
# @param redis_url [String, nil] see {Facade#initialize}
|
|
350
|
+
# @param async [Boolean] see {Facade#initialize}
|
|
351
|
+
# @param defaults [Hash] `agent_id:`, `parent_id:`, `stale_minutes:`,
|
|
352
|
+
# `holder:`, `session_name:`; see {Facade#initialize}
|
|
353
|
+
# @return [Facade]
|
|
354
|
+
def facade(strategies: Facade::DEFAULT_STRATEGIES, redis_url: nil, async: false, **defaults)
|
|
355
|
+
Facade.new(strategies:, redis_url:, async:, **defaults)
|
|
356
|
+
end
|
|
357
|
+
|
|
358
|
+
# Forget {.local} and {.distributed}, so the next call builds each anew.
|
|
359
|
+
# For tests. A process whose `REDIS_URL` changed needs no reset: the
|
|
360
|
+
# new URL is a new facade.
|
|
361
|
+
#
|
|
362
|
+
# @return [void]
|
|
363
|
+
def reset_facades!
|
|
364
|
+
LOCAL_FACADE.reset
|
|
365
|
+
DISTRIBUTED_FACADES.reset
|
|
366
|
+
end
|
|
367
|
+
end
|
|
368
|
+
end
|
|
369
|
+
end
|
data/lib/agent/lock/freeze.rb
CHANGED
|
@@ -25,23 +25,63 @@ module Agent
|
|
|
25
25
|
# How many paths one `chflags` invocation is given.
|
|
26
26
|
BATCH = 200
|
|
27
27
|
|
|
28
|
+
# Raised when a freeze cannot or should not run: not on macOS, or wider
|
|
29
|
+
# than {LIMIT} files without `wide: true`. The lock it was asked for is
|
|
30
|
+
# dropped first, so no claim is left behind half-enforced.
|
|
28
31
|
class TooBroad < Error; end
|
|
29
32
|
|
|
33
|
+
# Path segments no scope may freeze through, at any depth.
|
|
34
|
+
#
|
|
35
|
+
# `.git` is git's bookkeeping, not content: with the index or a ref
|
|
36
|
+
# frozen, `git add` and `git commit` fail with "Operation not
|
|
37
|
+
# permitted", and a linked worktree whose `.git` file is frozen cannot
|
|
38
|
+
# be removed. That holds just as well one level down, for a submodule's
|
|
39
|
+
# `.git` file or the `.git` directory of a clone dropped into the tree,
|
|
40
|
+
# so those are left alone too, while the files beside them are frozen
|
|
41
|
+
# like any others. `.` and `..` are a second spelling of a path: `.*`
|
|
42
|
+
# matches `.` itself, so `.*/**` used to answer `./lib/cli.rb`.
|
|
43
|
+
UNTOUCHABLE = %w[. .. .git].freeze
|
|
44
|
+
|
|
30
45
|
module_function
|
|
31
46
|
|
|
32
47
|
# @return [Boolean]
|
|
33
48
|
def supported? = RUBY_PLATFORM.include?("darwin")
|
|
34
49
|
|
|
50
|
+
# Dotfiles match like any other file. Without `FNM_DOTMATCH`, `*` and
|
|
51
|
+
# `**` skip them, so `conf/.env` stayed writable while the command
|
|
52
|
+
# reported `conf/**` frozen, and `.env` and credential keys are what
|
|
53
|
+
# this is most often pointed at. Each file is answered once, since two
|
|
54
|
+
# alternatives of a brace can match one file, and it would then count
|
|
55
|
+
# twice toward {LIMIT}.
|
|
56
|
+
#
|
|
35
57
|
# @param scope [Scope]
|
|
36
58
|
# @param tree [Tree]
|
|
37
59
|
# @return [Array<String>] the files it would freeze, relative to the root
|
|
38
60
|
def matches(scope, tree)
|
|
39
|
-
|
|
61
|
+
store = store_prefix(tree)
|
|
62
|
+
Dir.glob(recursive(scope.pattern), base: tree.root, flags: File::FNM_EXTGLOB | File::FNM_DOTMATCH)
|
|
63
|
+
.reject { |rel| rel.split("/").intersect?(UNTOUCHABLE) || (store && rel.start_with?(store)) }
|
|
40
64
|
.select { |rel| File.file?(File.join(tree.root, rel)) }
|
|
41
|
-
.
|
|
65
|
+
.uniq
|
|
42
66
|
.sort
|
|
43
67
|
end
|
|
44
68
|
|
|
69
|
+
# Where the lock store sits when it sits inside the tree, which it does
|
|
70
|
+
# outside git for a tree rooted at or above the home directory, and wherever
|
|
71
|
+
# `$AGENT_LOCK_DIR` says. Inside git it is under `.git`, which is
|
|
72
|
+
# already left alone. The file store renames a lock into place, and a
|
|
73
|
+
# frozen lock refuses that, so the freeze that had just run would be
|
|
74
|
+
# recorded nowhere.
|
|
75
|
+
#
|
|
76
|
+
# @param tree [Tree]
|
|
77
|
+
# @return [String, nil] relative to the root, with a trailing slash;
|
|
78
|
+
# nil when the store is outside the tree
|
|
79
|
+
def store_prefix(tree)
|
|
80
|
+
dir = tree.store_dir
|
|
81
|
+
dir = File.realpath(dir) if File.exist?(dir)
|
|
82
|
+
"#{dir.delete_prefix("#{tree.root}/")}/" if dir.start_with?("#{tree.root}/")
|
|
83
|
+
end
|
|
84
|
+
|
|
45
85
|
# A trailing `**` means "everything under here" to this gem, and to
|
|
46
86
|
# anybody typing it. It does not mean that to Dir.glob, where a bare
|
|
47
87
|
# `**` at the end matches one level, exactly like `*`. Only `**/` walks
|
|
@@ -53,12 +93,15 @@ module Agent
|
|
|
53
93
|
|
|
54
94
|
# @param paths [Array<String>] relative to the tree root
|
|
55
95
|
# @param tree [Tree]
|
|
56
|
-
# @param
|
|
96
|
+
# @param wide [Boolean] allow a freeze wider than LIMIT
|
|
57
97
|
# @return [Array<String>] what was frozen
|
|
58
|
-
def apply(paths, tree:,
|
|
98
|
+
def apply(paths, tree:, wide: false)
|
|
59
99
|
raise TooBroad, "--enforce needs macOS; this is #{RUBY_PLATFORM}" unless supported?
|
|
60
100
|
return [] if paths.empty?
|
|
61
|
-
|
|
101
|
+
|
|
102
|
+
if paths.size > LIMIT && !wide
|
|
103
|
+
raise TooBroad, "#{paths.size} files is wider than a freeze should be (limit #{LIMIT}); pass --allow-wide"
|
|
104
|
+
end
|
|
62
105
|
|
|
63
106
|
chflags("uchg", paths, tree)
|
|
64
107
|
end
|
|
@@ -66,6 +109,8 @@ module Agent
|
|
|
66
109
|
# Best effort on purpose: a path that has since been deleted or already
|
|
67
110
|
# thawed is not a reason to leave the rest frozen.
|
|
68
111
|
#
|
|
112
|
+
# @param paths [Array<String>, nil] relative to the tree root
|
|
113
|
+
# @param tree [Tree]
|
|
69
114
|
# @return [Array<String>] what was thawed
|
|
70
115
|
def clear(paths, tree:)
|
|
71
116
|
return [] if paths.nil? || paths.empty?
|
|
@@ -80,6 +125,9 @@ module Agent
|
|
|
80
125
|
# batch as frozen would leave the lock claiming protection it does not
|
|
81
126
|
# have. Reporting the whole batch as failed would be just as wrong.
|
|
82
127
|
#
|
|
128
|
+
# @param flag [String] `uchg` or `nouchg`
|
|
129
|
+
# @param paths [Array<String>] relative to the tree root
|
|
130
|
+
# @param tree [Tree]
|
|
83
131
|
# @return [Array<String>] relative paths that are now flagged
|
|
84
132
|
def chflags(flag, paths, tree)
|
|
85
133
|
return [] unless supported?
|
|
@@ -89,11 +137,15 @@ module Agent
|
|
|
89
137
|
.map { |path| path.delete_prefix("#{tree.root}/") }
|
|
90
138
|
end
|
|
91
139
|
|
|
140
|
+
# @param batch [Array<String>] relative to the tree root
|
|
141
|
+
# @param tree [Tree]
|
|
92
142
|
# @return [Array<String>] absolute paths that are still there to flag
|
|
93
143
|
def existing(batch, tree)
|
|
94
144
|
batch.map { |rel| File.join(tree.root, rel) }.select { |path| File.exist?(path) }
|
|
95
145
|
end
|
|
96
146
|
|
|
147
|
+
# @param flag [String] `uchg` or `nouchg`
|
|
148
|
+
# @param absolute [Array<String>] absolute paths
|
|
97
149
|
# @return [Array<String>] the ones the command accepted
|
|
98
150
|
def flag_batch(flag, absolute)
|
|
99
151
|
return [] if absolute.empty?
|
|
@@ -102,6 +154,8 @@ module Agent
|
|
|
102
154
|
absolute.select { |path| run(flag, [path]) }
|
|
103
155
|
end
|
|
104
156
|
|
|
157
|
+
# @param flag [String] `uchg` or `nouchg`
|
|
158
|
+
# @param paths [Array<String>] absolute paths
|
|
105
159
|
# @return [Boolean] whether the command reported success
|
|
106
160
|
def run(flag, paths) = system("chflags", flag, *paths, out: File::NULL, err: File::NULL) || false
|
|
107
161
|
end
|
data/lib/agent/lock/identity.rb
CHANGED
|
@@ -18,6 +18,7 @@ module Agent
|
|
|
18
18
|
# In order of preference:
|
|
19
19
|
#
|
|
20
20
|
# AGENT_ID what a human or a harness set on purpose
|
|
21
|
+
# session name what a library caller named its session (`session_name:`)
|
|
21
22
|
# CLAUDE_SESSION_ID the session, which survives --resume
|
|
22
23
|
# fingerprint the first ancestor process that is not a shell
|
|
23
24
|
#
|
|
@@ -27,7 +28,12 @@ module Agent
|
|
|
27
28
|
# human is typing in. Its pid and start time, hashed, are stable for as
|
|
28
29
|
# long as that session lives and different for anybody else's.
|
|
29
30
|
class Identity
|
|
31
|
+
# Process names skipped while walking up to the session's own process:
|
|
32
|
+
# every agent command runs in a fresh shell, so a shell is never the
|
|
33
|
+
# session itself.
|
|
30
34
|
SHELLS = %w[sh bash zsh ksh csh tcsh fish dash].freeze
|
|
35
|
+
# How many ancestors the walk climbs before giving up, so a process
|
|
36
|
+
# tree of nothing but shells cannot loop it forever.
|
|
31
37
|
MAX_HOPS = 10
|
|
32
38
|
|
|
33
39
|
class << self
|
|
@@ -47,8 +53,24 @@ module Agent
|
|
|
47
53
|
end
|
|
48
54
|
|
|
49
55
|
# @param env [Hash]
|
|
50
|
-
|
|
56
|
+
# @param liveness_pid [Integer, nil] the process a lock lives and dies
|
|
57
|
+
# with. nil is the session's own process, found by walking up from
|
|
58
|
+
# the parent past the shells, which is right for the CLI, where the
|
|
59
|
+
# parent is the agent's throwaway shell. An in-process caller passes
|
|
60
|
+
# its own pid: walking up from a library host finds the host's
|
|
61
|
+
# parent, which outlives a crashed host and keeps its locks from ever
|
|
62
|
+
# being reaped. It is evidence only. The name a lock is signed with,
|
|
63
|
+
# and the parent inferred from it, still come from the session, so a
|
|
64
|
+
# script an agent runs is the same holder as that agent's `alock`.
|
|
65
|
+
# @param session_name [String, nil] the session's name, used as given
|
|
66
|
+
# in place of `CLAUDE_SESSION_ID` and the fingerprint: a plan id, a
|
|
67
|
+
# job id. A session known by name alone is tied to no process, so
|
|
68
|
+
# its evidence carries no pid and its locks are trusted for the
|
|
69
|
+
# stale window from their last write: see {Record#expired?}
|
|
70
|
+
def initialize(env: ENV, liveness_pid: nil, session_name: nil)
|
|
51
71
|
@env = env
|
|
72
|
+
@liveness_pid = liveness_pid
|
|
73
|
+
@session_name = session_name
|
|
52
74
|
end
|
|
53
75
|
|
|
54
76
|
# @return [String] the holder name written into a lock
|
|
@@ -67,11 +89,16 @@ module Agent
|
|
|
67
89
|
# would answer to without it, the session is, by elimination, the
|
|
68
90
|
# parent.
|
|
69
91
|
#
|
|
92
|
+
# A holder can also say it has none: AGENT_PARENT_ID set, and empty. A
|
|
93
|
+
# top-level service that names itself is otherwise taken for a child of
|
|
94
|
+
# whatever terminal or agent started it, and a lock that session holds
|
|
95
|
+
# would not block it.
|
|
96
|
+
#
|
|
70
97
|
# @return [String, nil]
|
|
71
98
|
def parent_id
|
|
72
99
|
return @parent_id if defined?(@parent_id)
|
|
73
100
|
|
|
74
|
-
@parent_id = declared_parent || inferred_parent
|
|
101
|
+
@parent_id = parentless? ? nil : declared_parent || inferred_parent
|
|
75
102
|
end
|
|
76
103
|
|
|
77
104
|
# Where #id came from, so a session can check what it is being taken for
|
|
@@ -88,8 +115,14 @@ module Agent
|
|
|
88
115
|
# Where #parent_id came from. An inferred parent is a guess a human may
|
|
89
116
|
# want to overrule with AGENT_PARENT_ID, so it is reported as one.
|
|
90
117
|
#
|
|
91
|
-
#
|
|
118
|
+
# A parent declared absent is told apart from one there was nothing to
|
|
119
|
+
# infer: an AGENT_PARENT_ID exported empty by accident looks the same
|
|
120
|
+
# in a lock record, and this is where it can be seen.
|
|
121
|
+
#
|
|
122
|
+
# @return [Symbol, nil] :explicit, :inferred, :none when the holder
|
|
123
|
+
# said it has no parent, or nil when there is none to infer
|
|
92
124
|
def parent_source
|
|
125
|
+
return :none if parentless?
|
|
93
126
|
return :explicit if declared_parent
|
|
94
127
|
|
|
95
128
|
:inferred if parent_id
|
|
@@ -101,15 +134,22 @@ module Agent
|
|
|
101
134
|
#
|
|
102
135
|
# @return [Hash{Symbol => Object}]
|
|
103
136
|
def evidence
|
|
104
|
-
|
|
137
|
+
pid = @liveness_pid || (session_pid unless @session_name)
|
|
138
|
+
{ pid: pid, started_at: ProcessInfo.started_at(pid), host: Socket.gethostname }
|
|
105
139
|
end
|
|
106
140
|
|
|
107
141
|
private
|
|
108
142
|
|
|
143
|
+
# @return [String, nil] AGENT_ID, when set to something
|
|
109
144
|
def explicit = presence(@env["AGENT_ID"])
|
|
110
145
|
|
|
146
|
+
# @return [String, nil] AGENT_PARENT_ID, when set to something
|
|
111
147
|
def declared_parent = presence(@env["AGENT_PARENT_ID"])
|
|
112
148
|
|
|
149
|
+
# @return [Boolean] whether AGENT_PARENT_ID is set and names nobody,
|
|
150
|
+
# which says "no parent" where unset says "work it out"
|
|
151
|
+
def parentless? = @env.key?("AGENT_PARENT_ID") && declared_parent.nil?
|
|
152
|
+
|
|
113
153
|
# What this session answers to when nobody names it, which is the
|
|
114
154
|
# orchestrator's id. The session id counts as well as the fingerprint:
|
|
115
155
|
# under a harness that exports CLAUDE_SESSION_ID the orchestrator's locks
|
|
@@ -125,7 +165,11 @@ module Agent
|
|
|
125
165
|
own unless own == explicit
|
|
126
166
|
end
|
|
127
167
|
|
|
168
|
+
# @return [String, nil] the name the caller gave the session, else
|
|
169
|
+
# e.g. "session-1f4c8a02", from CLAUDE_SESSION_ID
|
|
128
170
|
def session
|
|
171
|
+
return @session_name if @session_name
|
|
172
|
+
|
|
129
173
|
value = presence(@env["CLAUDE_SESSION_ID"])
|
|
130
174
|
value && "session-#{value[0, 8]}"
|
|
131
175
|
end
|
|
@@ -133,13 +177,25 @@ module Agent
|
|
|
133
177
|
# @return [String] e.g. "claude-1f4c8a02"
|
|
134
178
|
def fingerprint
|
|
135
179
|
pid = session_pid
|
|
136
|
-
name = ProcessInfo.command(pid)
|
|
180
|
+
name = label(ProcessInfo.command(pid))
|
|
137
181
|
digest = Digest::SHA256.hexdigest(
|
|
138
182
|
[pid, ProcessInfo.started_at(pid), Etc.getpwuid(::Process.uid)&.name, Socket.gethostname].join("|")
|
|
139
183
|
)
|
|
140
184
|
"#{name}-#{digest[0, 8]}"
|
|
141
185
|
end
|
|
142
186
|
|
|
187
|
+
# A process may retitle itself: on macOS `ps -o comm=` reports a Claude
|
|
188
|
+
# Code background job as `claude bg-spare`. A holder id with a space in
|
|
189
|
+
# it cannot be pasted back into a shell, so only the first word is kept,
|
|
190
|
+
# reduced to the characters an id may hold.
|
|
191
|
+
#
|
|
192
|
+
# @param command [String, nil] ProcessInfo.command
|
|
193
|
+
# @return [String] e.g. "claude", or "agent" when nothing usable is left
|
|
194
|
+
def label(command)
|
|
195
|
+
word = command.to_s.split.first.to_s.gsub(/[^\w.-]/, "")
|
|
196
|
+
word.empty? ? "agent" : word
|
|
197
|
+
end
|
|
198
|
+
|
|
143
199
|
# The first ancestor that is not a shell, which is the process that lasts
|
|
144
200
|
# as long as the session does.
|
|
145
201
|
#
|
|
@@ -160,6 +216,8 @@ module Agent
|
|
|
160
216
|
end
|
|
161
217
|
end
|
|
162
218
|
|
|
219
|
+
# @param value [String, nil]
|
|
220
|
+
# @return [String, nil] the value stripped, or nil when blank
|
|
163
221
|
def presence(value) = value.nil? || value.strip.empty? ? nil : value.strip
|
|
164
222
|
end
|
|
165
223
|
end
|