samagotchi 0.173.0 → 0.174.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 (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -1
  3. data/docs/architecture.md +2 -2
  4. data/docs/cli.md +9 -2
  5. data/docs/internals/background-tasks.md +0 -3
  6. data/docs/internals/participants.md +3 -1
  7. data/docs/internals/remote-sessions.md +8 -0
  8. data/docs/internals/web-frontend.md +24 -3
  9. data/docs/plugins.md +1 -3
  10. data/docs/scheduling.md +9 -3
  11. data/docs/sessions.md +3 -1
  12. data/docs/testing.md +6 -0
  13. data/lib/samagotchi/bridge.rb +1 -1
  14. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  15. data/lib/samagotchi/child_move.rb +11 -4
  16. data/lib/samagotchi/continued_from.rb +51 -0
  17. data/lib/samagotchi/engine.rb +1 -1
  18. data/lib/samagotchi/note_move.rb +11 -4
  19. data/lib/samagotchi/schedules.rb +13 -16
  20. data/lib/samagotchi/session_access/contract.rb +1 -0
  21. data/lib/samagotchi/session_access/local.rb +9 -1
  22. data/lib/samagotchi/session_access/remote.rb +26 -3
  23. data/lib/samagotchi/session_chain/delete.rb +405 -0
  24. data/lib/samagotchi/session_chain/delete_preview.rb +96 -0
  25. data/lib/samagotchi/session_chain/links.rb +38 -0
  26. data/lib/samagotchi/session_command_catalog.rb +2 -2
  27. data/lib/samagotchi/session_commands.rb +3 -13
  28. data/lib/samagotchi/session_continue.rb +51 -13
  29. data/lib/samagotchi/session_delete_command.rb +82 -17
  30. data/lib/samagotchi/session_manager/removal.rb +137 -31
  31. data/lib/samagotchi/session_stores.rb +2 -0
  32. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +2 -2
  33. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  34. data/lib/samagotchi/terminal_ui/exit_lines.rb +16 -0
  35. data/lib/samagotchi/terminal_ui/local_link.rb +7 -1
  36. data/lib/samagotchi/terminal_ui.rb +3 -3
  37. data/lib/samagotchi/testing/boundary.rb +0 -5
  38. data/lib/samagotchi/testing/bundle.rb +1 -1
  39. data/lib/samagotchi/tools/task_runtime.rb +0 -5
  40. data/lib/samagotchi/version.rb +1 -1
  41. data/lib/samagotchi/web/app.rb +7 -1
  42. data/lib/samagotchi/web/public/app.js +13 -3
  43. data/lib/samagotchi/web/public/chains.js +3 -3
  44. data/lib/samagotchi/web/public/data.js +12 -0
  45. data/lib/samagotchi/web/public/delete_sheet.js +344 -0
  46. data/lib/samagotchi/web/public/format.js +1 -1
  47. data/lib/samagotchi/web/public/index.html +27 -0
  48. data/lib/samagotchi/web/public/info_bar.js +3 -2
  49. data/lib/samagotchi/web/public/lists_view.js +2 -2
  50. data/lib/samagotchi/web/public/more_sheet.js +42 -5
  51. data/lib/samagotchi/web/public/session_actions.js +50 -6
  52. data/lib/samagotchi/web/server.rb +13 -13
  53. data/lib/samagotchi/web/session_control.rb +58 -5
  54. metadata +5 -1
@@ -15,6 +15,7 @@ require_relative "context_move"
15
15
  require_relative "note_move"
16
16
  require_relative "archive_store"
17
17
  require_relative "continue_intent"
18
+ require_relative "continued_from"
18
19
  require_relative "recap_store"
19
20
  require_relative "bridge_client"
20
21
  require_relative "worker_link"
@@ -83,8 +84,12 @@ module Samagotchi
83
84
  CarryContext = Data.define(:previous, :to, :state_dir, :move)
84
85
  # What an undo works on: the previous link's id, the failed link (nil in
85
86
  # :moved_back, which looks it up itself), the delegates the plan moved,
86
- # and what the forward carry kept (#run's +carried+, by step name).
87
- UndoContext = Data.define(:from, :link, :state_dir, :moved, :carried)
87
+ # what the forward carry kept (#run's +carried+, by step name), and why
88
+ # (ChildMove.apply's undo: :failed_continue, or :deleted_link for
89
+ # #undo_deleted_link).
90
+ UndoContext = Data.define(:from, :link, :state_dir, :moved, :carried, :reason) do
91
+ def initialize(from:, link:, state_dir:, moved:, carried:, reason: :failed_continue) = super
92
+ end
88
93
 
89
94
  # When a failed continue undoes each step, in time order: :moved_back
90
95
  # while the failed link's worker may still run (before
@@ -240,7 +245,8 @@ module Samagotchi
240
245
  carried = {}
241
246
  begin
242
247
  link = spawn_continuation(previous, prompt: prompt, preview: preview, choice: checked.choice, state_dir: state_dir,
243
- move: plan.move, client_id: client_id, carried: carried, session_id: successor_id)
248
+ move: plan.move, archived: archived, client_id: client_id, carried: carried,
249
+ session_id: successor_id)
244
250
  rescue StandardError, Interrupt
245
251
  # Nothing started: the delegates go back, what this archived goes
246
252
  # back to the lists, and a new link saved before its worker failed
@@ -345,13 +351,15 @@ module Samagotchi
345
351
  end
346
352
 
347
353
  # The delegates a failed #run moved, or began to (its
348
- # intent names them), go back to the previous link.
354
+ # intent names them), go back to the previous link; a deleted link's
355
+ # (#undo_deleted_link) the ones its caller names.
349
356
  private_class_method def self.undo_move(ctx)
350
357
  id = ctx.from
351
358
  state_dir = ctx.state_dir
352
- link = SessionChain.next_of(id, state_dir: state_dir) or return
353
- ids = ChildMove.read_intent(link, state_dir: state_dir)&.ids || ctx.moved
354
- ChildMove.apply(ids, from: link, to: id, state_dir: state_dir, undo: true)
359
+ link = ctx.link || SessionChain.next_of(id, state_dir: state_dir) or return
360
+ # A deleted link's caller names exactly the ones still under it.
361
+ ids = (ctx.reason == :failed_continue && ChildMove.read_intent(link, state_dir: state_dir)&.ids) || ctx.moved
362
+ ChildMove.apply(ids, from: link, to: id, state_dir: state_dir, undo: ctx.reason)
355
363
  ChildMove.clear_intent(link, state_dir: state_dir)
356
364
  rescue StandardError => e
357
365
  Log.warn(:worker, "continue_undo_move_failed", sid: id, error: e.class.name, msg: e.message)
@@ -388,17 +396,43 @@ module Samagotchi
388
396
  end
389
397
 
390
398
  ctx = UndoContext.new(from: id, link: orphan, state_dir: state_dir, moved: moved, carried: carried)
391
- undo_carry(:link_stopped, ctx)
392
- FileUtils.rm_f(Session.session_file(orphan, state_dir: state_dir))
393
- undo_carry(:link_unlinked, ctx)
394
- SessionManager.delete_session(orphan, state_dir: state_dir, allow_scheduled: true)
395
- undo_carry(:link_deleted, ctx)
399
+ unlink(ctx) { SessionManager.delete_session(orphan, state_dir: state_dir, allow_scheduled: true) }
396
400
  rescue SessionManager::DeleteRefused
397
401
  raise
398
402
  rescue StandardError => e
399
403
  Log.warn(:worker, "continue_cleanup_failed", sid: id, error: e.class.name, msg: e.message)
400
404
  end
401
405
 
406
+ # The undo's phases once the link's worker is stopped, shared by a
407
+ # failed continue (#discard_failed_link) and a deleted link
408
+ # (#undo_deleted_link): :link_stopped, its session file goes (out of the
409
+ # chain), :link_unlinked, the block removes the rest (neither caller
410
+ # recurses: each passes its own removal), :link_deleted.
411
+ private_class_method def self.unlink(ctx)
412
+ undo_carry(:link_stopped, ctx)
413
+ FileUtils.rm_f(Session.session_file(ctx.link, state_dir: ctx.state_dir))
414
+ undo_carry(:link_unlinked, ctx)
415
+ yield
416
+ undo_carry(:link_deleted, ctx)
417
+ end
418
+
419
+ # Deleting +link+, the chain's newest link, undoes the continue +from+ →
420
+ # +link+ (SessionChain::Delete, D5) once +link+'s worker is stopped:
421
+ # +moved+ go back to +from+ (:moved_back, their note says the link was
422
+ # deleted), then #unlink: the rings and every note waiting in +link+
423
+ # but the continue's own go to +from+ (NoteMove.give_back, moved: []),
424
+ # and the block removes +link+'s files. +from+ is not woken (unlike a
425
+ # failed continue): the reports wait for its next start. Unarchiving
426
+ # is the caller's.
427
+ # @yieldreturn the block's value is returned
428
+ def self.undo_deleted_link(from:, link:, moved:, state_dir:)
429
+ ctx = UndoContext.new(from: from, link: link, state_dir: state_dir, moved: moved, carried: {}, reason: :deleted_link)
430
+ undo_carry(:moved_back, ctx)
431
+ removed = nil
432
+ unlink(ctx) { removed = yield }
433
+ removed
434
+ end
435
+
402
436
  # A failed link's folder an older chi's note brought back after its
403
437
  # delete: the note goes back to +id+, the folder goes again.
404
438
  private_class_method def self.give_back_strays(ctx)
@@ -425,12 +459,16 @@ module Samagotchi
425
459
  # it (spawn_session marks it starting before its file is saved:
426
460
  # StartingMarker.fresh?).
427
461
  # @param carried [Hash] gets what each CARRY step took to it, by name
462
+ # @param archived [Array<String>] what the archive of +previous+ hid
463
+ # (ContinuedFrom's record, written first in before_spawn: no crash
464
+ # window between the link's save and the record)
428
465
  private_class_method def self.spawn_continuation(previous, prompt:, preview:, choice:, state_dir:, move:, carried:,
429
- session_id:, client_id: nil)
466
+ session_id:, archived: [], client_id: nil)
430
467
  recap = RecapStore.read(Session.session_dir(previous.id, state_dir: state_dir))
431
468
  start = prompt.to_s.strip.empty? ? nil : prompt
432
469
  preview = previous.first_preview if preview.to_s.strip.empty? && start.nil?
433
470
  before_spawn = lambda do |link|
471
+ ContinuedFrom.write(link.id, previous_id: previous.id, archived_ids: archived, moved_ids: move, state_dir: state_dir)
434
472
  ctx = CarryContext.new(previous: previous, to: link.id, state_dir: state_dir, move: move)
435
473
  CARRY.each { |step| carried[step.name] = send(step.carry, ctx) }
436
474
  end
@@ -14,15 +14,22 @@ module Samagotchi
14
14
  include CLI::Command
15
15
 
16
16
  USAGE = <<~TEXT
17
- Usage: chi sessions delete [--force] (ID|PREFIX)...
17
+ Usage: chi sessions delete [--force] [--chain] (ID|PREFIX)...
18
18
  Deletes each session: its history, notes, images and queued input.
19
- This can't be undone.
19
+ This can't be undone. Deleting a chain's newest link undoes its
20
+ continue: the previous link comes back to the lists (not started),
21
+ with the delegates and notes that had moved on.
20
22
  -f, --force stop a session's running worker first (without it,
21
23
  a live session is refused); a session in a one-turn
22
24
  chi run (chi --non-interactive) is always refused
25
+ --chain delete every link of the session's chain, with their
26
+ delegates; running delegates are left running
23
27
  TEXT
24
28
  PREVIEW_LIMIT = 60
25
- FLAGS = CLI::Flags.new(help: CLI::Command::HELP_WORDS) { |f| f.switch "-f", "--force" }
29
+ FLAGS = CLI::Flags.new(help: CLI::Command::HELP_WORDS) do |f|
30
+ f.switch "-f", "--force"
31
+ f.switch "--chain"
32
+ end
26
33
 
27
34
  # @param argv [Array<String>] the arguments after "sessions delete"
28
35
  # @param access [SessionAccess::Local, nil] where the sessions are;
@@ -41,7 +48,10 @@ module Samagotchi
41
48
  options = parse
42
49
  return options if options.is_a?(Integer)
43
50
 
44
- options[:ids].uniq.map { |given| delete(given, force: options[:force]) }.all? ? 0 : 1
51
+ gone = options[:ids].uniq.map do |given|
52
+ options[:chain] ? delete_chain(given, force: options[:force]) : delete(given, force: options[:force])
53
+ end
54
+ gone.all? ? 0 : 1
45
55
  end
46
56
 
47
57
  private
@@ -51,7 +61,7 @@ module Samagotchi
51
61
  # @return [Hash, Integer] the options, or the exit status after the
52
62
  # help or a usage error
53
63
  def parse
54
- parsed = parse_flags(FLAGS, @argv, force: false)
64
+ parsed = parse_flags(FLAGS, @argv, force: false, chain: false)
55
65
  return parsed if parsed.is_a?(Integer)
56
66
  return usage_error("give session ids") if parsed.args.empty?
57
67
 
@@ -64,19 +74,11 @@ module Samagotchi
64
74
  short = id[0, 8]
65
75
  preview = preview_of(id)
66
76
  result = @access.delete(id, force: force)
67
- @stdout.puts(["#{short} deleted#{" (stopped its worker)" if result[:stopped]}", preview].compact.join(" "))
77
+ @stdout.puts(["#{short} deleted#{" (stopped its worker)" if result[:stopped]}#{revived(result)}#{delegates(result, id)}",
78
+ preview].compact.join(" "))
68
79
  true
69
- rescue SessionManager::OwnedByTUI
70
- @stdout.puts("#{short} refused: it is #{OwnerLock::TUI_BUSY}; let it finish first")
71
- false
72
- rescue SessionManager::DeleteRefused => e
73
- line = case e.reason
74
- when :still_stopping then "its worker is still shutting down; try again in a moment"
75
- when :scheduled then e.message
76
- else "its worker is running (--force stops it first)"
77
- end
78
- @stdout.puts("#{short} refused: #{line}")
79
- false
80
+ rescue SessionManager::OwnedByTUI, SessionManager::DeleteRefused => e
81
+ refused(e.session_id && e.session_id != id ? e.session_id[0, 8] : short, e)
80
82
  rescue ArgumentError => e
81
83
  error_line("chi sessions delete: #{e.message}")
82
84
  false
@@ -85,6 +87,69 @@ module Samagotchi
85
87
  false
86
88
  end
87
89
 
90
+ # "; the previous link 1a2b3c4d is back in the lists" (D1), with the
91
+ # delegates that went back to it.
92
+ def revived(result)
93
+ back = Array(result[:unarchived]).first
94
+ return "" unless back
95
+
96
+ moved = Array(result[:moved_back]).size
97
+ "; the previous link #{back[0, 8]} is back in the lists" \
98
+ "#{" with #{moved} delegate#{"s" unless moved == 1}" if moved.positive?}"
99
+ end
100
+
101
+ # "; 2 delegates deleted with it; 1 left running: 9d0e1f2a" (D7, a
102
+ # chained link's own delegates).
103
+ def delegates(result, id)
104
+ gone = Array(result[:deleted]).size - (Array(result[:deleted]).include?(id) ? 1 : 0)
105
+ running = Array(result[:left_running])
106
+ words = []
107
+ words << "#{gone} delegate#{"s" unless gone == 1} deleted with it" if gone.positive?
108
+ words << "#{running.size} left running: #{running.map { |sid| sid[0, 8] }.join(", ")}" unless running.empty?
109
+ words.empty? ? "" : "; #{words.join("; ")}"
110
+ end
111
+
112
+ # --chain: one line per link deleted, then a summary.
113
+ # @return [Boolean] whether every link went
114
+ def delete_chain(given, force:)
115
+ id = @access.resolve_id(given)
116
+ result = @access.delete_chain(id, force: force)
117
+ result[:deleted].each { |sid| @stdout.puts("#{sid[0, 8]} deleted#{" (stopped its worker)" if result[:stopped].include?(sid)}") }
118
+ @stdout.puts(chain_summary(result))
119
+ result[:left].empty?
120
+ rescue SessionManager::OwnedByTUI, SessionManager::DeleteRefused => e
121
+ refused((e.session_id || id).to_s[0, 8], e)
122
+ rescue ArgumentError => e
123
+ error_line("chi sessions delete: #{e.message}")
124
+ false
125
+ end
126
+
127
+ def chain_summary(result)
128
+ parts = ["#{result[:deleted].size} deleted"]
129
+ parts << "#{result[:left].size} links kept: #{result[:refusal]}" unless result[:left].empty?
130
+ parts << "back in the lists: #{result[:unarchived].map { |sid| sid[0, 8] }.join(", ")}" unless result[:unarchived].empty?
131
+ unless result[:left_running].empty?
132
+ parts << "left running, without a parent: #{result[:left_running].map { |sid| sid[0, 8] }.join(", ")}"
133
+ end
134
+ parts << "earlier links, cut off by a deleted link, are kept (archived)" if result[:cut_off]
135
+ "chain: #{parts.join("; ")}"
136
+ end
137
+
138
+ # @return [false]
139
+ def refused(short, error)
140
+ line = case error
141
+ when SessionManager::OwnedByTUI then "it is #{OwnerLock::TUI_BUSY}; let it finish first"
142
+ else
143
+ case error.reason
144
+ when :still_stopping then "its worker is still shutting down; try again in a moment"
145
+ when :worker_running then "its worker is running (--force stops it first)"
146
+ else error.message
147
+ end
148
+ end
149
+ @stdout.puts("#{short} refused: #{line}")
150
+ false
151
+ end
152
+
88
153
  def preview_of(id)
89
154
  text = @access.show(id).display_title.gsub(/\s+/, " ").strip
90
155
  return nil if text.empty?
@@ -4,26 +4,44 @@ require_relative "../session_stores"
4
4
 
5
5
  module Samagotchi
6
6
  class SessionManager
7
- # A delete that would pull the session from under its live worker.
8
- # reason: :worker_running (not asked to stop it), :still_stopping
9
- # (stopped, but the worker outlived the wait) or :changed (the caller's
10
- # +still:+ check, read again under the owner lock, no longer holds).
7
+ # A delete that can't happen now, one message per reason:
8
+ # :worker_running (not asked to stop it), :still_stopping (stopped, but
9
+ # the worker outlived the wait), :changed (the caller's +still:+ check,
10
+ # read again under the owner lock, no longer holds), :scheduled (an
11
+ # enabled schedule's target, anchor or head: +schedule_id+),
12
+ # :continuing (a continue of +session_id+ is in flight: this link, or
13
+ # the previous one a delete would bring back), :delegate_unmovable (a
14
+ # delegate the deleted link's continue moved can't go back: +ids+,
15
+ # +detail+ says why), :chain_scheduled (a schedule is on the chain a
16
+ # chain delete would take: +schedule_id+).
11
17
  class DeleteRefused < StandardError
12
- attr_reader :session_id, :reason, :schedule_id
18
+ attr_reader :session_id, :reason, :schedule_id, :ids
13
19
 
14
- def initialize(session_id, reason, message: nil, schedule_id: nil)
20
+ def initialize(session_id, reason, message: nil, schedule_id: nil, ids: [], detail: nil)
15
21
  @session_id = session_id
16
22
  @reason = reason
17
23
  @schedule_id = schedule_id
18
- message ||= case reason
19
- when :still_stopping then "session #{session_id}'s worker is still shutting down"
20
- when :changed then "session #{session_id} changed since it was checked"
21
- when :scheduled
22
- "this session is the target of an enabled schedule" \
23
- "#{"; cancel it with chi schedule cancel #{schedule_id}" if schedule_id}"
24
- else "session #{session_id}'s worker is running"
25
- end
26
- super(message)
24
+ @ids = ids
25
+ super(message || refused_message(detail))
26
+ end
27
+
28
+ private
29
+
30
+ def refused_message(detail)
31
+ short = @session_id.to_s[0, 8]
32
+ cancel = "; cancel it with chi schedule cancel #{@schedule_id}" if @schedule_id
33
+ case @reason
34
+ when :worker_running then "session #{@session_id}'s worker is running"
35
+ when :still_stopping then "session #{@session_id}'s worker is still shutting down"
36
+ when :changed then "session #{@session_id} changed since it was checked"
37
+ when :scheduled then "this session is the target of an enabled schedule#{cancel}"
38
+ when :continuing then "a continue of #{short} is under way; try again in a moment"
39
+ when :delegate_unmovable
40
+ "#{@ids.map { |id| id[0, 8] }.join(", ")}, moved here by the continue, can't go back to the previous link" \
41
+ "#{": #{detail}" if detail}"
42
+ when :chain_scheduled then "an enabled schedule runs on this chain#{cancel}"
43
+ else "session #{@session_id} can't be deleted now (#{@reason})"
44
+ end
27
45
  end
28
46
  end
29
47
 
@@ -165,8 +183,18 @@ module Samagotchi
165
183
  # its candidate-log lines; a session a worker left empty has none worth
166
184
  # the read
167
185
  # @param allow_scheduled [Boolean] internal rollback of a failed continue
186
+ # @param revive_previous [Boolean] a user's delete (CLI, web, TUI) of a
187
+ # chain's newest link brings the previous one back to the lists and
188
+ # undoes the continue (SessionChain::Delete.link, D2/D5); any chained
189
+ # link's own delegates follow SessionChain::Delete::DELEGATES. The
190
+ # result then also has unarchived:, moved_back:, deleted: and
191
+ # left_running: (ids)
192
+ # @param refuse_continuing [Boolean] a user's delete refuses
193
+ # (:continuing) while a continue of the session is in flight
194
+ # @raise [DeleteRefused] also :scheduled for a schedule's anchor or
195
+ # head, and with the keywords :continuing and :delegate_unmovable
168
196
  def delete_session(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT, purge_runs: true,
169
- allow_scheduled: false)
197
+ allow_scheduled: false, revive_previous: false, refuse_continuing: false)
170
198
  sd = state_dir || Session.default_state_dir
171
199
  given = id_or_prefix.to_s
172
200
  # Only a plain id: anything else could name a path outside the state dir.
@@ -178,25 +206,101 @@ module Samagotchi
178
206
  # A folder with no file left is still deleted (not resolve!).
179
207
  raise Session::NotFound, given unless File.exist?(path) || Dir.exist?(dir)
180
208
 
181
- unless allow_scheduled
182
- require_relative "../schedules"
183
- schedule = Schedules.new(state_dir: sd).protecting(id)
184
- if schedule
185
- raise DeleteRefused.new(id, :scheduled, schedule_id: schedule.id)
186
- end
209
+ if revive_previous || refuse_continuing
210
+ require_relative "../session_chain/delete"
211
+ return SessionChain::Delete.link(id, state_dir: sd, stop: stop, wait: wait, revive_previous: revive_previous,
212
+ refuse_continuing: refuse_continuing)
187
213
  end
188
214
 
189
- presence = WorkerPresence.read(id, state_dir: sd, owner: session_owner(id, state_dir: sd))
215
+ delete_resolved(id, state_dir: sd, stop: stop, wait: wait, purge_runs: purge_runs, allow_scheduled: allow_scheduled)
216
+ end
217
+
218
+ # Delete every link of +id+'s chain with their delegates
219
+ # (SessionChain::Delete.chain, D4/D7): all or nothing for the
220
+ # refusals, newest link first.
221
+ # @param stop [Boolean] stop the links' live workers first (the web
222
+ # always does; the CLI's --force)
223
+ # @return [Hash] SessionChain::Delete.chain's
224
+ # @raise [ArgumentError] unknown id (Session::AmbiguousId for a prefix of several)
225
+ # @raise [DeleteRefused, OwnedByTUI] nothing was deleted
226
+ def delete_chain(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT)
227
+ sd = state_dir || Session.default_state_dir
228
+ given = id_or_prefix.to_s
229
+ raise Session::NotFound, given unless Session.valid_id?(given)
230
+
231
+ id = Session.resolve_id(given, state_dir: sd)
232
+ raise Session::NotFound, given unless Session.exist?(id, state_dir: sd)
233
+
234
+ require_relative "../session_chain/delete"
235
+ SessionChain::Delete.chain(id, state_dir: sd, stop: stop, wait: wait)
236
+ end
237
+
238
+ # #delete_session's checks and removal for a full id that exists:
239
+ # the schedule refusal, the one-turn run, the worker (stopped with
240
+ # +stop+), then #remove_files. SessionChain::Delete's last step.
241
+ # @return [Hash] {id:, removed:, stopped:}
242
+ def delete_resolved(id, state_dir:, stop: false, wait: STOP_WAIT, purge_runs: true, allow_scheduled: false)
243
+ sd = state_dir
244
+ path = Session.session_file(id, state_dir: sd)
245
+ dir = Session.session_dir(id, state_dir: sd)
246
+ refuse_scheduled!(id, sd) unless allow_scheduled
247
+
248
+ held = release_for_delete!(id, state_dir: sd, stop: stop, wait: wait)
249
+ removed = remove_files(id, path, dir, state_dir: sd, purge_runs: purge_runs)
250
+ { id: id, removed: removed, stopped: held }
251
+ end
252
+
253
+ # +id+ free for a delete: a one-turn run refuses, a worker that owns it
254
+ # or is being started for it is stopped with +stop+ (else refused).
255
+ # @return [Boolean] whether there was one to stop
256
+ # @raise [OwnedByTUI, DeleteRefused] :worker_running, :still_stopping
257
+ def release_for_delete!(id, state_dir:, stop:, wait:)
258
+ presence = WorkerPresence.read(id, state_dir: state_dir, owner: session_owner(id, state_dir: state_dir))
190
259
  raise OwnedByTUI, id if presence.tui_owned?
191
260
 
192
261
  held = presence.owned? || presence.starting?
193
262
  if held
194
263
  raise DeleteRefused.new(id, :worker_running) unless stop
195
- raise DeleteRefused.new(id, :still_stopping) unless stop_held(id, state_dir: sd, wait: wait)
264
+ raise DeleteRefused.new(id, :still_stopping) unless stop_held(id, state_dir: state_dir, wait: wait)
196
265
  end
266
+ held
267
+ end
197
268
 
198
- removed = remove_files(id, path, dir, state_dir: sd, purge_runs: purge_runs)
199
- { id: id, removed: removed, stopped: held }
269
+ # Delete these ids safely, in this order: #delete_session for each (it
270
+ # re-checks the one-turn run, the starting marker and the owner lock),
271
+ # and the expensive session-scoped logs (#purge_removal_stores) once
272
+ # for the batch, for the ids deleted even when a later one is refused.
273
+ # No eligibility policy: each caller (Schedules#prune, the chain
274
+ # delete) decides which ids, and keeps its own checks and log tags.
275
+ # @param ids [Array<String>] full ids, in the order to delete them
276
+ # @return [Array<Hash>] #delete_session's result for each
277
+ # @raise [DeleteRefused, OwnedByTUI, Session::NotFound] the first
278
+ # refusal; the ids before it are deleted
279
+ def delete_ids(ids, state_dir: nil, stop: false, wait: STOP_WAIT)
280
+ sd = state_dir || Session.default_state_dir
281
+ results = []
282
+ # Not a map: the ids deleted before a refusal must reach the ensure's purge.
283
+ ids.each do |id| # rubocop:disable Style/MapIntoArray
284
+ results << delete_session(id, state_dir: sd, stop: stop, wait: wait, purge_runs: false)
285
+ end
286
+ results
287
+ ensure
288
+ purge_removal_stores(results.map { |result| result[:id] }, state_dir: sd) if results
289
+ end
290
+
291
+ # +id+'s delegate subtree and +id+, in the order a delete takes them:
292
+ # the descendants deepest first, +id+ last. A delete refused part-way
293
+ # leaves nothing above what it took, so a retry finds the same tree.
294
+ # @return [Array<String>]
295
+ def delete_tree_ids(id, state_dir) = [*descendant_ids(id, state_dir).reverse, id]
296
+
297
+ # DeleteRefused :scheduled when an enabled schedule's target, anchor
298
+ # or head is +id+: deleting a head would make the schedule fall back to
299
+ # an archived link and lose the links after it.
300
+ def refuse_scheduled!(id, state_dir)
301
+ require_relative "../schedules"
302
+ schedule = Schedules.new(state_dir: state_dir).protecting_link(id)
303
+ raise DeleteRefused.new(id, :scheduled, schedule_id: schedule.id) if schedule
200
304
  end
201
305
 
202
306
  # Remove every store with state scoped to +id+. The file and sidecar
@@ -206,12 +310,14 @@ module Samagotchi
206
310
  # a refusal leaves every store as it was).
207
311
  # @return [Array<String>] the session file, sidecar and context paths removed
208
312
  # @raise [DeleteRefused] see #remove_session_files
209
- def remove_files(id, path, dir, state_dir:, purge_runs: true, still: nil)
313
+ # @param locked [Boolean] the caller holds +id+'s owner lock (kind
314
+ # deleting) already: SessionChain::Delete, across its undo
315
+ def remove_files(id, path, dir, state_dir:, purge_runs: true, still: nil, locked: false)
210
316
  removed = []
211
317
  SESSION_STATE_STORES.each do |store|
212
318
  case store
213
319
  when :session_files
214
- removed.concat(remove_session_files(id, path, dir, state_dir: state_dir, still: still))
320
+ removed.concat(remove_session_files(id, path, dir, state_dir: state_dir, still: still, locked: locked))
215
321
  when :plugin_session_state
216
322
  PluginSessionState.remove(id)
217
323
  when :context_sources
@@ -251,9 +357,9 @@ module Samagotchi
251
357
  # @return [Array<String>] the paths removed
252
358
  # @raise [DeleteRefused] a worker took the lock, or a start was
253
359
  # claimed, after the caller's check, or +still+ no longer holds
254
- def remove_session_files(id, path, dir, state_dir:, still: nil)
255
- lock = Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0) : nil
256
- raise DeleteRefused.new(id, :worker_running) if Dir.exist?(dir) && lock.nil?
360
+ def remove_session_files(id, path, dir, state_dir:, still: nil, locked: false)
361
+ lock = !locked && Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0) : nil
362
+ raise DeleteRefused.new(id, :worker_running) if !locked && Dir.exist?(dir) && lock.nil?
257
363
  raise DeleteRefused.new(id, :worker_running) if StartingMarker.fresh?(id, state_dir: state_dir)
258
364
  raise DeleteRefused.new(id, :changed) if still && !still.call
259
365
 
@@ -45,6 +45,8 @@ module Samagotchi
45
45
  continue: "drawings describe turns in the previous link", corpus_dir: "sessions/compat-drawn"),
46
46
  Store.new(file: "move.json", owner: "ChildMove", removal: :session_files, cross_version: true,
47
47
  continue: "an interrupted move belongs to the previous continue", corpus_dir: SIDE_CAR),
48
+ Store.new(file: "continued_from.json", owner: "ContinuedFrom", removal: :session_files, cross_version: true,
49
+ continue: "the record names the continue that made this link", corpus_dir: SIDE_CAR),
48
50
  Store.new(file: "continue.json", owner: "ContinueIntent", removal: :session_files, cross_version: true,
49
51
  continue: "the intent records the previous link's continue", corpus_dir: SIDE_CAR),
50
52
  Store.new(file: "objectives.lock", owner: "Objectives", removal: :session_files, cross_version: false,
@@ -99,8 +99,8 @@ module Samagotchi
99
99
  # An empty session: the worker deletes it as it leaves.
100
100
  return detach(ExitLines::EMPTY_EXIT) if ExitLines.discards?(reply)
101
101
 
102
- @link.delete_session
103
- detach("Detached; deleted session #{id}.")
102
+ result = @link.delete_session
103
+ detach("Detached; deleted session #{id}.#{ExitLines.deleted_tail(result, id)}")
104
104
  rescue SystemCallError, IOError => e
105
105
  detach("#{ExitLines.exit_failed_line(e.message, via: via, session_id: id)} Not deleted.")
106
106
  rescue SessionManager::DeleteRefused, SessionManager::OwnedByTUI, ArgumentError => e
@@ -118,7 +118,7 @@ module Samagotchi
118
118
  def initialize(screen:, client_id:, client: nil, first_prompt: nil, first_command: nil, no_interrupt: false,
119
119
  default_input: false, wait_at_eof: false, as_parent: false, scratch: false,
120
120
  clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }, now: -> { MessageTime.now },
121
- delete_session: ->(id) { SessionManager.delete_session(id, stop: true, wait: LocalLink::DELETE_WAIT) },
121
+ delete_session: LocalLink::DELETE,
122
122
  archive_session: ->(id) { SessionManager.archive_session(id, wait: LocalLink::DELETE_WAIT) },
123
123
  installed_version: -> { InstalledVersions.new.newest },
124
124
  state_dir: Session.default_state_dir,
@@ -10,6 +10,22 @@ module Samagotchi
10
10
  module ExitLines
11
11
  module_function
12
12
 
13
+ # What /exit --delete's line adds from the delete's result: the previous
14
+ # link back in the lists (D2), the delegates deleted with it and the
15
+ # ones left running (D7). "" for a plain delete.
16
+ def deleted_tail(result, id)
17
+ return "" unless result.is_a?(Hash)
18
+
19
+ back = Array(result[:unarchived]).first
20
+ gone = Array(result[:deleted]).reject { |sid| sid == id }.size
21
+ running = Array(result[:left_running])
22
+ parts = []
23
+ parts << " The previous link #{back[0, 8]} is back in the lists." if back
24
+ parts << " #{gone} delegate#{"s" unless gone == 1} deleted with it." if gone.positive?
25
+ parts << " #{running.size} left running: #{running.map { |sid| sid[0, 8] }.join(", ")}." unless running.empty?
26
+ parts.join
27
+ end
28
+
13
29
  # Why a request the Bridge read after its deadline didn't go through.
14
30
  LATE = "worker not answering in time"
15
31
  # An exit the worker agreed to in an empty session. Said before it has
@@ -26,6 +26,12 @@ module Samagotchi
26
26
  # How long /exit --delete and /archive wait for the worker to let go
27
27
  # (AttachedLoop's defaults too).
28
28
  DELETE_WAIT = 10
29
+ # /exit --delete on this machine (LocalLink's and AttachedLoop's
30
+ # default): a user's delete, so a chain's newest link is undone and the
31
+ # previous one comes back (SessionManager.delete_session's keywords).
32
+ DELETE = lambda do |id|
33
+ SessionManager.delete_session(id, stop: true, wait: DELETE_WAIT, revive_previous: true, refuse_continuing: true)
34
+ end
29
35
 
30
36
  attr_reader :client
31
37
 
@@ -37,7 +43,7 @@ module Samagotchi
37
43
  # @param installed_version [#call] -> the newest chi installed
38
44
  # @param children_counts [#call] session id -> ChildrenStatus::Counts
39
45
  def initialize(client:, state_dir: Session.default_state_dir,
40
- delete_session: ->(id) { SessionManager.delete_session(id, stop: true, wait: DELETE_WAIT) },
46
+ delete_session: DELETE,
41
47
  archive_session: ->(id) { SessionManager.archive_session(id, wait: DELETE_WAIT) },
42
48
  installed_version: -> { InstalledVersions.new.newest },
43
49
  children_counts: ->(id) { ChildrenStatus.counts(id, state_dir: state_dir) })
@@ -198,7 +198,7 @@ module Samagotchi
198
198
  # A UI-only command (/stats, /exit …) isn't run without a terminal,
199
199
  # and isn't a prompt either: refused as chi send refuses it, before
200
200
  # any session is made (bin/chi exits 1).
201
- return refuse_one_shot_ui_command if SessionCommands.ui_only_entry(@prompt)
201
+ return refuse_one_shot_ui_command if SessionCommandCatalog.ui_only_entry(@prompt)
202
202
 
203
203
  session = @resume_session || @engine.store_model!(Session.new_session(
204
204
  mode: "assist",
@@ -356,8 +356,8 @@ module Samagotchi
356
356
  # `chi -p /stats --non-interactive`: why it doesn't run, on stderr.
357
357
  # @return [Symbol] :turn_failed
358
358
  def refuse_one_shot_ui_command
359
- name = SessionCommands.ui_only_entry(@prompt).name
360
- warn "chi: refused: #{SessionCommands.ui_only_refusal(name, @resume_session&.id, runner: "--non-interactive")}"
359
+ name = SessionCommandCatalog.ui_only_entry(@prompt).name
360
+ warn "chi: refused: #{SessionCommandCatalog.ui_only_refusal(name, @resume_session&.id, runner: "--non-interactive")}"
361
361
  :turn_failed
362
362
  end
363
363
 
@@ -38,11 +38,6 @@ module Samagotchi
38
38
  Allowed.new(name: "Samagotchi::Tools::Execute.timeout_seconds", file: "samagotchi/tools/execute"),
39
39
  Allowed.new(name: "Samagotchi::TaskFiles::TASKS_DIR", file: "samagotchi/task_files"),
40
40
  Allowed.new(name: "Samagotchi::TaskFiles::EXIT_CODE_FILENAME", file: "samagotchi/task_files"),
41
- # The two names' old home, forwarding to TaskFiles for one release:
42
- # remove these entries with TaskRuntime's two constants in the
43
- # release after the one that ships TaskFiles.
44
- Allowed.new(name: "Samagotchi::Tools::TaskRuntime::TASKS_DIR", file: "samagotchi/tools/task_runtime"),
45
- Allowed.new(name: "Samagotchi::Tools::TaskRuntime::EXIT_CODE_FILENAME", file: "samagotchi/tools/task_runtime"),
46
41
  Allowed.new(name: "Samagotchi::AtomicFile.write", file: "samagotchi/atomic_file"),
47
42
  Allowed.new(name: "Samagotchi::Log.warn", file: "samagotchi/log"),
48
43
  Allowed.new(name: "Samagotchi::Log.debug", file: "samagotchi/log"),
@@ -99,7 +99,7 @@ module Samagotchi
99
99
  # @return [Plugin::Registries]
100
100
  def registries(**fields)
101
101
  Plugin::Registries.new(
102
- commands: SessionCommands.register_builtins(Commands::Registry.new), tools: Tools::Builtins.registry,
102
+ commands: SessionCommandCatalog.register_builtins(Commands::Registry.new), tools: Tools::Builtins.registry,
103
103
  services: Plugin::Services.new, stage_tools: ->(*) {}, toolkits: [], tool_index: Tools::ToolIndex.new,
104
104
  peer_sources: PeerSources.new, prompt_sections: Plugin::PromptSections.new,
105
105
  judgments: SystemOne::Judgments.new, **fields
@@ -19,11 +19,6 @@ require_relative "task_record"
19
19
  module Samagotchi
20
20
  module Tools
21
21
  module TaskRuntime
22
- # Moved to TaskFiles; kept here one release for bundles that name
23
- # them (the boundary's stable list). Remove in the release after the
24
- # one that ships TaskFiles, with their stable-list entries.
25
- TASKS_DIR = TaskFiles::TASKS_DIR
26
- EXIT_CODE_FILENAME = TaskFiles::EXIT_CODE_FILENAME
27
22
  STOP_GRACE_SEC = 3.0
28
23
  STOP_POLL_INTERVAL_SEC = 0.1
29
24
  METADATA_VERSION = TaskRecord::METADATA_VERSION
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.173.0"
4
+ VERSION = "0.174.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end