samagotchi 0.190.1 → 0.192.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 (106) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/docs/architecture.md +13 -11
  4. data/docs/bundles.md +1 -1
  5. data/docs/cli.md +17 -6
  6. data/docs/configuration.md +6 -1
  7. data/docs/context.md +8 -1
  8. data/docs/internals/attached-context.md +3 -1
  9. data/docs/internals/inline-widgets.md +2 -1
  10. data/docs/internals/participants.md +1 -5
  11. data/docs/internals/peers.md +15 -3
  12. data/docs/internals/remote-sessions.md +5 -2
  13. data/docs/internals/session-lifecycle.md +233 -18
  14. data/docs/internals/web-frontend.md +107 -9
  15. data/docs/peers.md +3 -1
  16. data/docs/plugins.md +2 -1
  17. data/docs/scheduling.md +31 -7
  18. data/docs/sessions.md +12 -12
  19. data/docs/sub-agent.md +1 -1
  20. data/docs/testing.md +1 -2
  21. data/docs/thin-clients.md +98 -12
  22. data/lib/samagotchi/bridge.rb +3 -4
  23. data/lib/samagotchi/bundles/mcp/manifest.yml +4 -2
  24. data/lib/samagotchi/bundles/mcp/plugin.rb +7 -398
  25. data/lib/samagotchi/bundles/mcp/server_config.rb +158 -0
  26. data/lib/samagotchi/bundles/mcp/sign_in.rb +261 -0
  27. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  28. data/lib/samagotchi/client_id.rb +2 -19
  29. data/lib/samagotchi/compat.rb +1 -7
  30. data/lib/samagotchi/config.rb +3 -0
  31. data/lib/samagotchi/context_command.rb +5 -1
  32. data/lib/samagotchi/context_sources.rb +28 -0
  33. data/lib/samagotchi/continue_intent.rb +23 -43
  34. data/lib/samagotchi/delivery.rb +1 -5
  35. data/lib/samagotchi/hold_stop.rb +5 -2
  36. data/lib/samagotchi/participants.rb +13 -5
  37. data/lib/samagotchi/peer_say.rb +29 -14
  38. data/lib/samagotchi/plugin/sessions.rb +9 -5
  39. data/lib/samagotchi/schedule_command.rb +6 -1
  40. data/lib/samagotchi/schedules/prune_part.rb +162 -41
  41. data/lib/samagotchi/schedules.rb +32 -15
  42. data/lib/samagotchi/send_command.rb +6 -6
  43. data/lib/samagotchi/session.rb +7 -0
  44. data/lib/samagotchi/session_access/ask.rb +9 -3
  45. data/lib/samagotchi/session_access/exchange.rb +6 -2
  46. data/lib/samagotchi/session_access/local.rb +103 -32
  47. data/lib/samagotchi/session_access/remote.rb +10 -9
  48. data/lib/samagotchi/session_access/remote_peers.rb +2 -2
  49. data/lib/samagotchi/session_access.rb +17 -7
  50. data/lib/samagotchi/session_chain/delete.rb +100 -47
  51. data/lib/samagotchi/session_chain/delete_preview.rb +9 -5
  52. data/lib/samagotchi/session_chain/successor.rb +78 -0
  53. data/lib/samagotchi/session_continue.rb +112 -42
  54. data/lib/samagotchi/session_inbox.rb +1 -1
  55. data/lib/samagotchi/session_inbox_delivery.rb +111 -25
  56. data/lib/samagotchi/session_lifecycle/allowed.rb +20 -1
  57. data/lib/samagotchi/session_lifecycle/reading.rb +9 -3
  58. data/lib/samagotchi/session_lifecycle.rb +17 -2
  59. data/lib/samagotchi/session_manager/delivery.rb +61 -29
  60. data/lib/samagotchi/session_manager/emptiness.rb +5 -2
  61. data/lib/samagotchi/session_manager/lifecycle.rb +68 -19
  62. data/lib/samagotchi/session_manager/listing.rb +2 -1
  63. data/lib/samagotchi/session_manager/removal.rb +67 -13
  64. data/lib/samagotchi/session_manager/spawn.rb +16 -9
  65. data/lib/samagotchi/session_manager.rb +4 -0
  66. data/lib/samagotchi/session_retention.rb +28 -7
  67. data/lib/samagotchi/session_row.rb +2 -0
  68. data/lib/samagotchi/session_transition.rb +361 -0
  69. data/lib/samagotchi/sessions_command.rb +1 -1
  70. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -0
  71. data/lib/samagotchi/tools/cancel_schedule.rb +10 -6
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/app.rb +13 -3
  74. data/lib/samagotchi/web/ask_create.rb +138 -0
  75. data/lib/samagotchi/web/ask_routes.rb +56 -9
  76. data/lib/samagotchi/web/last_ask.rb +78 -0
  77. data/lib/samagotchi/web/peer_routes.rb +5 -2
  78. data/lib/samagotchi/web/public/answer_refs.js +3 -9
  79. data/lib/samagotchi/web/public/answer_write.js +28 -0
  80. data/lib/samagotchi/web/public/app.js +72 -96
  81. data/lib/samagotchi/web/public/block_fix.js +30 -12
  82. data/lib/samagotchi/web/public/chains.js +3 -1
  83. data/lib/samagotchi/web/public/command_list.js +5 -3
  84. data/lib/samagotchi/web/public/composer.js +9 -6
  85. data/lib/samagotchi/web/public/composer_mount.js +18 -11
  86. data/lib/samagotchi/web/public/draft_keys.js +10 -0
  87. data/lib/samagotchi/web/public/drafts.js +278 -0
  88. data/lib/samagotchi/web/public/owner_claim.js +7 -12
  89. data/lib/samagotchi/web/public/prompt_history.js +6 -0
  90. data/lib/samagotchi/web/public/send_turn.js +51 -20
  91. data/lib/samagotchi/web/public/session_actions.js +80 -16
  92. data/lib/samagotchi/web/public/session_prefs.js +9 -3
  93. data/lib/samagotchi/web/public/session_view.js +7 -2
  94. data/lib/samagotchi/web/public/turn_events.js +0 -2
  95. data/lib/samagotchi/web/public/unqueue.js +22 -9
  96. data/lib/samagotchi/web/public/viewer_self.js +1 -6
  97. data/lib/samagotchi/web/public/views.js +12 -1
  98. data/lib/samagotchi/web/session_access_routes.rb +11 -5
  99. data/lib/samagotchi/web/session_control.rb +8 -1
  100. data/lib/samagotchi/web/session_create.rb +51 -34
  101. data/lib/samagotchi/web/session_hub.rb +52 -36
  102. data/lib/samagotchi/web/session_summary.rb +45 -7
  103. data/lib/samagotchi/web/start_dir.rb +6 -4
  104. data/lib/samagotchi/worker_boot.rb +28 -6
  105. data/lib/samagotchi/worker_presence.rb +22 -6
  106. metadata +10 -1
@@ -11,6 +11,7 @@ require_relative "log"
11
11
  require_relative "model_profile"
12
12
  require_relative "session_manager"
13
13
  require_relative "session_protection"
14
+ require_relative "session_transition"
14
15
  require_relative "system_one/runs"
15
16
 
16
17
  module Samagotchi
@@ -95,9 +96,12 @@ module Samagotchi
95
96
 
96
97
  unless dry_run
97
98
  policy = SessionManager::RunningTasks::Policy.stop(by: "retention")
98
- SessionManager.remove_files(name, path, dir, state_dir: state_dir, purge_runs: false,
99
- still: -> { orphan_dir?(path, dir) }, running_tasks: policy)
99
+ gone = unheld(name, state_dir) do
100
+ SessionManager.remove_files(name, path, dir, state_dir: state_dir, purge_runs: false,
101
+ still: -> { orphan_dir?(path, dir) }, running_tasks: policy)
102
+ end
100
103
  SessionManager::RunningTasks.log_automatic!(policy)
104
+ next unless gone
101
105
  end
102
106
  name
103
107
  rescue SessionManager::DeleteRefused, SystemCallError
@@ -121,6 +125,20 @@ module Samagotchi
121
125
  StartingMarker.fresh?(session_id, state_dir: state_dir)
122
126
  end
123
127
 
128
+ # The block under +session_id+'s transition lock held exclusively
129
+ # (kind :delete, one try, before the owner lock the removal takes): a
130
+ # transition or an arrival holding it now (a continue, a delete, a
131
+ # send's shared hold) keeps the session for a later sweep.
132
+ # @return [Boolean] whether the block ran
133
+ private_class_method def self.unheld(session_id, state_dir)
134
+ SessionTransition.exclusive([session_id], kind: :delete, state_dir: state_dir, deadline: 0) do
135
+ yield
136
+ true
137
+ end
138
+ rescue SessionTransition::Busy
139
+ false
140
+ end
141
+
124
142
  # Being started or owned now (+alive_check+, when given, reads the owner).
125
143
  private_class_method def self.held?(session_id, state_dir, alive_check)
126
144
  starting?(session_id, state_dir) || alive_check&.call(session_id) == true
@@ -338,11 +356,14 @@ module Samagotchi
338
356
  else
339
357
  policy = SessionManager::RunningTasks::Policy.stop(by: "retention")
340
358
  begin
341
- # Under the owner lock, the start read again (as a delete).
342
- SessionManager.remove_files(session.id, path, File.join(state_dir, session.id), state_dir: state_dir,
343
- purge_runs: false, running_tasks: policy)
344
- deleted << session.id
345
- purge_ids << session.id
359
+ # Under its transition lock (held: kept) and the owner lock, the
360
+ # start read again (as a delete).
361
+ gone = unheld(session.id, state_dir) do
362
+ SessionManager.remove_files(session.id, path, File.join(state_dir, session.id), state_dir: state_dir,
363
+ purge_runs: false, running_tasks: policy)
364
+ end
365
+ (gone ? deleted : kept) << session.id
366
+ purge_ids << session.id if gone
346
367
  rescue SessionManager::DeleteRefused
347
368
  kept << session.id
348
369
  rescue StandardError
@@ -22,6 +22,8 @@ module Samagotchi
22
22
  # The liveness rule: +live+ is WorkerLink's worker_owned? (a worker holds
23
23
  # the lock, its Bridge up or on its way); +busy+ and +waiting+ need it,
24
24
  # +status+ is Session#displayed_status (a dead worker's "running" is idle).
25
+ # The session hub shows neither this live nor its question: it reads
26
+ # SessionSummary.shown (the lifecycle state).
25
27
  SessionRow = Data.define(:id, :desc, :preview, :title, :cwd, :project, :updated_at, :status, :saved_status, :live,
26
28
  :busy, :owner, :recap, :auto_title, :ctx_pct, :parent_id, :continues, :delegate, :archived,
27
29
  :scratch, :test_run, :stopped_by, :waiting, :waiting_id, :relayed_to)
@@ -0,0 +1,361 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require_relative "session"
5
+
6
+ module Samagotchi
7
+ # A session's transition lock: the one code that flocks a session folder's
8
+ # LOCK (continue.lock). A multi-step lifecycle transition (a continue
9
+ # today) holds it exclusively; an arrival or a check that must not overlap
10
+ # one (a followed send, a link or chain delete) takes it shared and
11
+ # non-blocking, and a read-only caller only probes it (#held?).
12
+ #
13
+ # Rules (docs/internals/session-lifecycle.md, "Locks and crash repair"):
14
+ # - Order: transition locks (several ids sorted) before any owner.lock.
15
+ # - The hold is the current thread's (Thread#thread_variable_*, not
16
+ # fiber-local and never per process: chi web is multi-threaded). A
17
+ # thread holding an id exclusively passes through #exclusive and #shared
18
+ # of that id without touching the file (each acquisition is a fresh open:
19
+ # a second flock on a held fd, or a dup of it, would convert the lock).
20
+ # Work handed to another thread does not carry the hold: it takes it
21
+ # again, or is refused.
22
+ # - No fork while held: a forked child keeps the flock. Workers start
23
+ # through Process.spawn, whose descriptors are close-on-exec.
24
+ module SessionTransition
25
+ # The lock file in a session's folder. The name stays continue.lock: an
26
+ # older chi's continue, follow_guard and delete honour it.
27
+ LOCK = "continue.lock"
28
+ # How often an exclusive try with a deadline tries again.
29
+ RETRY = 0.01
30
+ # The thread variable holding this thread's exclusive holds
31
+ # ({ lock path => true }).
32
+ REGISTRY = :samagotchi_session_transition
33
+
34
+ # What #exclusive yields: the ids it holds and why.
35
+ Token = Data.define(:ids, :kind)
36
+
37
+ # An exclusive hold not taken by its deadline, or an arrival that met
38
+ # one. It owns its refusal text, which names the holder (.held) when it
39
+ # can be told: a continue ("being continued", "as X" once its intent
40
+ # names the new link), a delete ("being deleted"), a stop ("being
41
+ # stopped"), an archive ("being archived"), else "busy with another
42
+ # change" (a shared holder, an older chi's, a kind this chi doesn't
43
+ # name). A nil +session_id+ says "this session" (a peer's line,
44
+ # which carries no id).
45
+ #
46
+ # #retry_message is those words with "; try again in a moment". A
47
+ # stop's (+taker+ :stop) that met a transition (#transition?: one that
48
+ # won't let go soon) says what to do instead: "session X is being
49
+ # deleted", "… being archived", "… being continued as Y: stop that one".
50
+ # Every other taker's #message is #retry_message.
51
+ class Busy < StandardError
52
+ WORDS = { continue: "being continued", delete: "being deleted", stop: "being stopped", archive: "being archived",
53
+ nil => "busy with another change" }.freeze
54
+ # The holders a stop doesn't wait for (#transition?): a delete or an
55
+ # archive, a continue once it names its new link.
56
+ TRANSITIONS = %i[delete archive continue].freeze
57
+
58
+ # +kind+ the holder's (nil: not told), +successor_id+ the new link a
59
+ # continue holding it names, +taker+ the kind of the hold that met it
60
+ # (nil: an arrival, or not told).
61
+ attr_reader :session_id, :kind, :successor_id, :taker
62
+
63
+ def initialize(session_id, kind: nil, successor_id: nil, taker: nil)
64
+ @session_id = session_id
65
+ @kind = kind
66
+ @successor_id = successor_id
67
+ @taker = taker
68
+ super(taker == :stop && transition? ? stop_words : retry_message)
69
+ end
70
+
71
+ # The refusal of an arrival or a taker that met +session_id+'s lock
72
+ # held: the one place that says who holds it. The kind the exclusive
73
+ # holder recorded (SessionTransition.holder) first: a delete, a stop
74
+ # or an archive is said as such whatever else is on disk (a crashed
75
+ # continue's intent); else a continue in flight
76
+ # (ContinueIntent.in_flight: an older chi's records no kind) names
77
+ # its new link. +taker+ is the kind of the hold that met it.
78
+ # @return [Busy]
79
+ def self.held(session_id, state_dir:, taker: nil)
80
+ kind = SessionTransition.holder(session_id, state_dir: state_dir)
81
+ return new(session_id, kind: kind, taker: taker) if SessionTransition.other_than_continue?(kind)
82
+
83
+ require_relative "continue_intent"
84
+ successor = session_id && ContinueIntent.in_flight(session_id, state_dir: state_dir)
85
+ new(session_id, kind: successor ? :continue : kind, successor_id: successor, taker: taker)
86
+ end
87
+
88
+ # Whether the holder is a transition that won't let go soon: a delete,
89
+ # an archive, a continue that names its new link. A stop, a repair, a
90
+ # holder that names nothing (an older chi's, a continue before its
91
+ # intent names the new link, the new link's own hold) and every
92
+ # shared hold (a send) are short, or can't be told: waited out.
93
+ def transition?
94
+ TRANSITIONS.include?(@kind) && (@kind != :continue || !@successor_id.nil?)
95
+ end
96
+
97
+ # The holder's words, "; try again in a moment".
98
+ def retry_message = "#{words}; try again in a moment"
99
+
100
+ private
101
+
102
+ def words
103
+ if @successor_id
104
+ require_relative "session_chain/successor"
105
+ return SessionChain::Continued.new(@session_id, @successor_id, in_flight: true).message
106
+ end
107
+
108
+ subject = @session_id ? "session #{@session_id.to_s[0, 8]}" : "this session"
109
+ "#{subject} is #{WORDS.fetch(@kind, WORDS[nil])}"
110
+ end
111
+
112
+ # A stop's words for a transition: a continue's new link is the one
113
+ # to stop; a delete or an archive leaves nothing to stop.
114
+ def stop_words = @successor_id ? "#{words}: stop that one" : words
115
+ end
116
+
117
+ module_function
118
+
119
+ # The block under an exclusive hold of every id's lock, taken in sorted
120
+ # order, each folder created when missing. Ids this thread already holds
121
+ # are passed through. +deadline+ nil blocks until each lock is free;
122
+ # seconds try each until then. With +refuse_transitions+ (a stop's:
123
+ # +deadline+ required) each failed try reads the holder again, and one
124
+ # that is a transition (Busy#transition?: a delete, an archive, a
125
+ # continue naming its new link) is refused at once rather than waited
126
+ # for; a short hold (a send's shared one) or one that names nothing is
127
+ # still waited out to the deadline.
128
+ # @yieldparam token [Token]
129
+ # @return the block's value
130
+ # @raise [Busy] an id not taken in time, or held by a transition with
131
+ # +refuse_transitions+ (the ids taken before it are let go); its
132
+ # +taker+ is +kind+
133
+ # @raise [ArgumentError] an id that isn't a session id, or
134
+ # +refuse_transitions+ with no +deadline+ (a blocking flock reads no
135
+ # holder)
136
+ def exclusive(ids, kind:, state_dir:, deadline: nil, refuse_transitions: false)
137
+ ids = Array(ids).uniq.sort
138
+ bad = ids.reject { |id| Session.valid_id?(id) }
139
+ raise ArgumentError, "not a session id: #{bad.first.inspect}" unless bad.empty?
140
+ raise ArgumentError, "refuse_transitions needs a deadline" if refuse_transitions && deadline.nil?
141
+
142
+ ends_at = monotonic + deadline if deadline
143
+ taken = []
144
+ ids.each do |id|
145
+ path = lock_path(id, state_dir)
146
+ next if holds.key?(path)
147
+
148
+ FileUtils.mkdir_p(File.dirname(path))
149
+ file = File.open(path, File::RDWR | File::CREAT, 0o600) # rubocop:disable Style/FileOpen -- held past this loop, closed in the ensure
150
+ taken << [path, file]
151
+ refuse = if refuse_transitions
152
+ lambda {
153
+ busy = Busy.held(id, state_dir: state_dir, taker: kind)
154
+ raise busy if busy.transition?
155
+ }
156
+ end
157
+ lock_until(file, ends_at, refuse: refuse) or raise Busy.held(id, state_dir: state_dir, taker: kind)
158
+ holds[path] = true
159
+ mark(file, kind)
160
+ end
161
+ yield Token.new(ids: ids, kind: kind)
162
+ ensure
163
+ # Only ids this call took: none of them was held before it. A kind is
164
+ # cleared only from a lock this call held (never another holder's).
165
+ taken&.reverse_each do |path, file|
166
+ mark(file, nil) if holds.delete(path)
167
+ file.close
168
+ end
169
+ end
170
+
171
+ # The block under an exclusive hold of +id+'s lock taken in one try,
172
+ # its argument nil when it isn't (another holder, this thread's included:
173
+ # a crash repair never undoes the continue running on its own thread).
174
+ # The folder is not created (its lock file is). Crash repair's
175
+ # (SessionContinue.repair_interrupted).
176
+ # @yieldparam token [Token, nil]
177
+ # @raise [Errno::ENOENT] the folder is gone
178
+ def try_exclusive(id, kind:, state_dir:)
179
+ return yield(nil) unless Session.valid_id?(id)
180
+
181
+ path = lock_path(id, state_dir)
182
+ return yield(nil) if holds.key?(path)
183
+
184
+ File.open(path, File::RDWR | File::CREAT, 0o600) do |file|
185
+ next yield(nil) unless file.flock(File::LOCK_EX | File::LOCK_NB)
186
+
187
+ holds[path] = true
188
+ mark(file, kind)
189
+ begin
190
+ yield Token.new(ids: [id], kind: kind)
191
+ ensure
192
+ holds.delete(path)
193
+ mark(file, nil)
194
+ end
195
+ end
196
+ end
197
+
198
+ # The block under a shared hold of +id+'s lock, so no transition of it
199
+ # starts until the block returns; its argument is false when another
200
+ # holds it exclusively now (not waited for: nothing is held then) or
201
+ # +id+ isn't a session id, true when this thread holds it. The lock
202
+ # file is created when missing, and the folder only for a session whose
203
+ # file is there: a deleted session's folder is never made again
204
+ # (nothing is held, true: no transition holds a lock in a folder that
205
+ # isn't there) and the caller's own gone refusal follows. A lock file this call made for a
206
+ # session whose file is gone once the block returns (a delete that
207
+ # removed it meanwhile, a folder with no session) is taken back
208
+ # (#forget). A caller that may not write the session folder (a peer's
209
+ # chi behind the mailbox door: the sessions folder read-only) holds an
210
+ # existing lock file opened read-only, and, with none there to open,
211
+ # holds nothing (true).
212
+ # @yieldparam held [Boolean]
213
+ # @return the block's value
214
+ def shared(id, state_dir:)
215
+ return yield(false) unless Session.valid_id?(id)
216
+
217
+ path = lock_path(id, state_dir)
218
+ return yield(true) if holds.key?(path)
219
+
220
+ made = !File.exist?(path)
221
+ file = open_shared(id, path, state_dir) or return yield(true)
222
+ begin
223
+ yield(file.flock(File::LOCK_SH | File::LOCK_NB) ? true : false)
224
+ ensure
225
+ file.close
226
+ forget(id, state_dir: state_dir) if made
227
+ end
228
+ end
229
+
230
+ # Whether +id+'s lock is held exclusively now, by anyone (this thread
231
+ # too: a kernel probe, the registry is not read). Creates nothing; the
232
+ # shared try is let go at once.
233
+ def held?(id, state_dir:)
234
+ return false unless Session.valid_id?(id)
235
+
236
+ File.open(lock_path(id, state_dir), File::RDONLY) { |file| !file.flock(File::LOCK_SH | File::LOCK_NB) }
237
+ rescue Errno::ENOENT
238
+ false
239
+ end
240
+
241
+ # The kind the exclusive holder of +id+'s lock recorded (#exclusive's
242
+ # and #try_exclusive's +kind+, written into the lock file while held),
243
+ # one of Busy::WORDS' kinds: nil when nobody holds it exclusively now (a
244
+ # shared holder, such as a send, is no transition), or the holder
245
+ # recorded none this chi names (an older chi, a raw flock). Read only
246
+ # behind a failed shared try (#held?), so a crash's leftover is never
247
+ # believed.
248
+ # @return [Symbol, nil]
249
+ def holder(id, state_dir:)
250
+ return nil unless held?(id, state_dir: state_dir)
251
+
252
+ recorded = File.read(lock_path(id, state_dir), 64).to_s.strip
253
+ Busy::WORDS.keys.compact.find { |kind| kind.to_s == recorded }
254
+ rescue SystemCallError
255
+ nil
256
+ end
257
+
258
+ # Whether +kind+ (#holder's) is a transition this chi names that is no
259
+ # continue (a delete, a stop, an archive): its hold names no new link,
260
+ # whatever intent a crashed continue left.
261
+ def other_than_continue?(kind) = !kind.nil? && kind != :continue
262
+
263
+ # Whether the current thread holds +id+ exclusively (the registry).
264
+ def holding?(id, state_dir:)
265
+ Session.valid_id?(id) && holds.key?(lock_path(id, state_dir))
266
+ end
267
+
268
+ # Take back the lock file #exclusive left in the folder of a session
269
+ # with no session file (a continue's successor never saved, a link
270
+ # deleted while a continue waited for it), and the folder when that
271
+ # leaves it empty: an empty folder holding only the lock is no session.
272
+ # Only when nobody holds it (one try; held, it stays) and this thread
273
+ # doesn't; a saved session's lock is never touched.
274
+ # @return [Boolean] whether the lock file went
275
+ def forget(id, state_dir:)
276
+ return false unless Session.valid_id?(id) && !Session.exist?(id, state_dir: state_dir)
277
+
278
+ path = lock_path(id, state_dir)
279
+ return false if holds.key?(path)
280
+
281
+ gone = File.open(path, File::RDWR) do |file|
282
+ next false unless file.flock(File::LOCK_EX | File::LOCK_NB)
283
+
284
+ File.unlink(path)
285
+ true
286
+ end
287
+ begin
288
+ Dir.rmdir(File.dirname(path))
289
+ rescue Errno::ENOTEMPTY, Errno::EEXIST, Errno::ENOENT
290
+ nil
291
+ end
292
+ gone
293
+ rescue Errno::ENOENT
294
+ false
295
+ end
296
+
297
+ def lock_path(id, state_dir) = File.join(Session.session_dir(id, state_dir: state_dir), LOCK)
298
+
299
+ # #shared's descriptor: made when missing (its folder too, only for a
300
+ # session whose file is there), else (no write access) the file opened
301
+ # read-only, or nil when there is nothing to open.
302
+ def open_shared(id, path, state_dir)
303
+ begin
304
+ File.open(path, File::RDWR | File::CREAT, 0o600)
305
+ rescue Errno::ENOENT
306
+ return nil unless Session.exist?(id, state_dir: state_dir)
307
+
308
+ FileUtils.mkdir_p(File.dirname(path))
309
+ File.open(path, File::RDWR | File::CREAT, 0o600)
310
+ end
311
+ rescue Errno::ENOENT
312
+ nil
313
+ rescue Errno::EACCES, Errno::EPERM, Errno::EROFS
314
+ begin
315
+ File.open(path, File::RDONLY)
316
+ rescue Errno::ENOENT, Errno::EACCES
317
+ nil
318
+ end
319
+ end
320
+
321
+ # Record +kind+ (nil: none) as the holder's in a lock file this thread
322
+ # holds exclusively (#holder reads it). The file is the lock's only
323
+ # content: an older chi only flocks it. Never fatal.
324
+ def mark(file, kind)
325
+ file.truncate(0)
326
+ file.rewind
327
+ file.write(kind.to_s) if kind
328
+ file.flush
329
+ rescue IOError, SystemCallError
330
+ nil
331
+ end
332
+
333
+ # This thread's holds.
334
+ def holds
335
+ Thread.current.thread_variable_get(REGISTRY) || Thread.current.thread_variable_set(REGISTRY, {})
336
+ end
337
+
338
+ # Lock +file+ exclusively: blocking when +ends_at+ is nil, else tried
339
+ # until that monotonic time, +refuse+ (when given) called after each
340
+ # failed try (it raises to give up at once). Whether it was taken.
341
+ def lock_until(file, ends_at, refuse: nil)
342
+ unless ends_at
343
+ file.flock(File::LOCK_EX)
344
+ return true
345
+ end
346
+
347
+ loop do
348
+ return true if file.flock(File::LOCK_EX | File::LOCK_NB)
349
+
350
+ refuse&.call
351
+ return false if monotonic >= ends_at
352
+
353
+ sleep RETRY
354
+ end
355
+ end
356
+
357
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
358
+
359
+ private_class_method :lock_path, :open_shared, :mark, :holds, :lock_until, :monotonic
360
+ end
361
+ end
@@ -289,7 +289,7 @@ module Samagotchi
289
289
  begin
290
290
  id = @access.resolve_id(given)
291
291
  released = @access.stop(id, wait: Samagotchi::SessionManager::STOP_WAIT)
292
- rescue Samagotchi::SessionManager::OwnedByTUI => e
292
+ rescue Samagotchi::SessionManager::OwnedByTUI, Samagotchi::SessionTransition::Busy => e
293
293
  @stdout.flush
294
294
  @stderr.puts e.message
295
295
  next false
@@ -146,6 +146,8 @@ module Samagotchi
146
146
  options[:no_interrupt] = true if @no_interrupt
147
147
  options[:images] = images unless images.empty?
148
148
  options[:delivery] = delivery if delivery
149
+ # Transition hold: worker-side (its live worker's Bridge); over
150
+ # --remote, chi web's turn route (deliver_turn's :shared seat).
149
151
  reply = @client.post_turn(**options)
150
152
  if reply.status == 202
151
153
  enqueued_id = reply.json&.fetch("enqueued_id", nil)
@@ -31,9 +31,8 @@ module Samagotchi
31
31
 
32
32
  # nil: gone since the lookup (another cancel in between).
33
33
  if want_all || peers&.session_id.nil?
34
- return "No schedule named #{name}." unless schedules.cancel(name)
35
-
36
- return "Cancelled #{entry.id} (#{entry.title || entry.recurrence_words})."
34
+ cancelled = schedules.cancel(name)
35
+ return cancelled ? cancelled_answer(entry, cancelled) : "No schedule named #{name}."
37
36
  end
38
37
 
39
38
  unless schedules.chain_of(peers.session_id).any? { |id| id == entry.anchor || id == entry.head }
@@ -41,13 +40,18 @@ module Samagotchi
41
40
  "chi schedule cancel #{entry.id} cancels it, or say all: true if you meant it."
42
41
  end
43
42
 
44
- return "No schedule named #{name}." unless schedules.cancel(name)
45
-
46
- "Cancelled #{entry.id} (#{entry.title || entry.recurrence_words})."
43
+ cancelled = schedules.cancel(name)
44
+ cancelled ? cancelled_answer(entry, cancelled) : "No schedule named #{name}."
47
45
  rescue StandardError => e
48
46
  "Error: #{e.message}"
49
47
  end
50
48
 
49
+ # The answer for a cancelled +entry+, with the Schedules::Cancelled line
50
+ # naming the chain's newest link when the cancel ended a pruned anchor's bridge.
51
+ def self.cancelled_answer(entry, cancelled)
52
+ ["Cancelled #{entry.id} (#{entry.title || entry.recurrence_words}).", cancelled.warning].compact.join("\n")
53
+ end
54
+
51
55
  # @return [String] the answer for +name+ when no readable entry has it
52
56
  def self.cancel_unreadable(schedules, name, want_all, peers)
53
57
  raw = schedules.unreadable_record(name)
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.190.1"
4
+ VERSION = "0.192.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -79,6 +79,7 @@ require_relative "participant_show"
79
79
  require_relative "message_display"
80
80
  require_relative "session_show"
81
81
  require_relative "session_create"
82
+ require_relative "ask_create"
82
83
  require_relative "session_control"
83
84
  require_relative "verify_fresh_routes"
84
85
  require_relative "block_fix_routes"
@@ -121,6 +122,7 @@ module Samagotchi
121
122
  include MessageDisplay
122
123
  include SessionShow
123
124
  include SessionCreate
125
+ include AskCreate
124
126
  include SessionControl
125
127
  include VerifyFreshRoutes
126
128
  include BlockFixRoutes
@@ -1126,7 +1128,7 @@ module Samagotchi
1126
1128
  # delegates: chi --remote sessions delete --dry-run asks for this first.
1127
1129
  DELETE_PLAN_FEATURE = "delete_plan_all"
1128
1130
  INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
1129
- BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE, ASK_FEATURE, McpRoute::FEATURE, Delivery::AGENT_FEATURE, ReplyFor::FEATURE, PeerMailbox::FEATURE].freeze
1131
+ BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE, ASK_FEATURE, ASK_LAST_FEATURE, AskCreate::FEATURE, McpRoute::FEATURE, Delivery::AGENT_FEATURE, ReplyFor::FEATURE, PeerMailbox::FEATURE].freeze
1130
1132
 
1131
1133
  # The models a new session can start on, spelled as chi spells them
1132
1134
  # elsewhere: bare for the default host (what default.model holds), and
@@ -1497,10 +1499,14 @@ module Samagotchi
1497
1499
  return error_response(422, "no_provider", "no installed bundle resolves #{url[0, 200]}") unless resolved
1498
1500
 
1499
1501
  own = ContextSources.session_location(session.id, state_dir: default_state_dir)
1500
- source = own.add(web_source(resolved, body, own.scope))
1502
+ source = ContextSources.changing(session.id, state_dir: default_state_dir) do
1503
+ own.add(web_source(resolved, body, own.scope))
1504
+ end
1501
1505
  json_response(201, { status: "attached", name: resolved.name, movable: source.movable? })
1502
1506
  rescue ContextProviders::Invalid => e
1503
1507
  error_response(422, "no_provider", e.message)
1508
+ rescue ContextSources::Held => e
1509
+ error_response(423, "context_busy", e.message)
1504
1510
  rescue ContextSources::Invalid => e
1505
1511
  error_response(409, "exists", e.message)
1506
1512
  end
@@ -1552,12 +1558,14 @@ module Samagotchi
1552
1558
  session = @session_class.load(id, state_dir: default_state_dir)
1553
1559
  attached = find_context(session, name) or return error_response(404, "context_missing", "no source #{name[0, 40]}")
1554
1560
  if attached.location.session?
1555
- attached.location.remove(attached.name)
1561
+ ContextSources.changing(id, state_dir: default_state_dir) { attached.location.remove(attached.name) }
1556
1562
  json_response(200, { status: "detached", name: attached.name })
1557
1563
  else
1558
1564
  ContextSources.session_location(id, state_dir: default_state_dir).mute(attached.name)
1559
1565
  json_response(200, { status: "muted", name: attached.name })
1560
1566
  end
1567
+ rescue ContextSources::Held => e
1568
+ error_response(423, "context_busy", e.message)
1561
1569
  end
1562
1570
 
1563
1571
  def context_remove_own(id, name)
@@ -1567,6 +1575,8 @@ module Samagotchi
1567
1575
  error_response(409, "project_source", ContextCommand.project_source_message(name))
1568
1576
  else error_response(404, "context_missing", "no source #{name[0, 40]}")
1569
1577
  end
1578
+ rescue ContextSources::Held => e
1579
+ error_response(423, "context_busy", e.message)
1570
1580
  rescue ContextSources::Invalid
1571
1581
  error_response(404, "context_missing", "no source #{name[0, 40]}")
1572
1582
  end