samagotchi 0.164.0 → 0.166.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 (100) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +88 -1
  3. data/docs/architecture.md +7 -5
  4. data/docs/cli.md +23 -12
  5. data/docs/configuration.md +8 -2
  6. data/docs/guardrails.md +19 -18
  7. data/docs/internals/block-renderers.md +1 -1
  8. data/docs/internals/bridge.md +10 -3
  9. data/docs/internals/bundles.md +4 -2
  10. data/docs/internals/inline-widgets.md +8 -1
  11. data/docs/internals/remote-sessions.md +1 -1
  12. data/docs/internals/web-frontend.md +73 -13
  13. data/docs/memory.md +12 -7
  14. data/docs/plugins.md +6 -4
  15. data/docs/releasing.md +17 -4
  16. data/docs/scheduling.md +25 -3
  17. data/docs/sessions.md +12 -10
  18. data/docs/testing.md +37 -4
  19. data/lib/samagotchi/block_renderers.rb +3 -6
  20. data/lib/samagotchi/bridge/card_store.rb +2 -1
  21. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -8
  22. data/lib/samagotchi/bridge.rb +45 -3
  23. data/lib/samagotchi/bundle_command/installed_check.rb +2 -1
  24. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  25. data/lib/samagotchi/chi_home.rb +44 -2
  26. data/lib/samagotchi/client_id.rb +34 -3
  27. data/lib/samagotchi/compat.rb +34 -0
  28. data/lib/samagotchi/context_command.rb +3 -0
  29. data/lib/samagotchi/context_providers.rb +5 -6
  30. data/lib/samagotchi/context_sources.rb +2 -2
  31. data/lib/samagotchi/continue_intent.rb +50 -5
  32. data/lib/samagotchi/events.rb +4 -4
  33. data/lib/samagotchi/extension_load.rb +2 -1
  34. data/lib/samagotchi/guardrails/approvals.rb +36 -9
  35. data/lib/samagotchi/guardrails/child_boundary.rb +7 -27
  36. data/lib/samagotchi/guardrails/rules.rb +11 -9
  37. data/lib/samagotchi/guardrails/targets.rb +3 -4
  38. data/lib/samagotchi/inline_widgets.rb +16 -1
  39. data/lib/samagotchi/memory_bundle/provenance.rb +46 -4
  40. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  41. data/lib/samagotchi/memory_command.rb +3 -0
  42. data/lib/samagotchi/memory_orphans.rb +4 -7
  43. data/lib/samagotchi/memory_paths.rb +64 -7
  44. data/lib/samagotchi/memory_usage.rb +1 -1
  45. data/lib/samagotchi/plugin/sessions.rb +8 -3
  46. data/lib/samagotchi/project_command.rb +4 -1
  47. data/lib/samagotchi/project_id_clash.rb +37 -26
  48. data/lib/samagotchi/project_init.rb +24 -7
  49. data/lib/samagotchi/reply_wait/poll.rb +4 -14
  50. data/lib/samagotchi/reply_wait.rb +0 -23
  51. data/lib/samagotchi/run_options.rb +1 -1
  52. data/lib/samagotchi/schedules.rb +124 -106
  53. data/lib/samagotchi/send_command.rb +71 -18
  54. data/lib/samagotchi/session.rb +3 -2
  55. data/lib/samagotchi/session_access/local.rb +19 -2
  56. data/lib/samagotchi/session_access/remote.rb +13 -17
  57. data/lib/samagotchi/session_chain/links.rb +109 -0
  58. data/lib/samagotchi/session_chain.rb +7 -19
  59. data/lib/samagotchi/session_continue.rb +138 -54
  60. data/lib/samagotchi/session_inbox.rb +1 -1
  61. data/lib/samagotchi/session_inbox_delivery.rb +57 -38
  62. data/lib/samagotchi/session_manager/delivery.rb +104 -18
  63. data/lib/samagotchi/session_manager/removal.rb +13 -7
  64. data/lib/samagotchi/session_manager.rb +1 -0
  65. data/lib/samagotchi/session_retention.rb +20 -10
  66. data/lib/samagotchi/session_setup.rb +31 -1
  67. data/lib/samagotchi/state_format.rb +12 -8
  68. data/lib/samagotchi/terminal_ui/attach_launcher.rb +6 -7
  69. data/lib/samagotchi/terminal_ui.rb +20 -9
  70. data/lib/samagotchi/tools/delegate.rb +2 -3
  71. data/lib/samagotchi/verify_fresh.rb +4 -1
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/public/activity.js +2 -2
  74. data/lib/samagotchi/web/public/app.js +28 -21
  75. data/lib/samagotchi/web/public/auth_lost.js +3 -1
  76. data/lib/samagotchi/web/public/bar_fold.js +293 -0
  77. data/lib/samagotchi/web/public/card.js +1 -1
  78. data/lib/samagotchi/web/public/chip_popover.js +5 -1
  79. data/lib/samagotchi/web/public/composer_mode.js +5 -7
  80. data/lib/samagotchi/web/public/delivery_line.js +19 -4
  81. data/lib/samagotchi/web/public/index.html +242 -94
  82. data/lib/samagotchi/web/public/info_bar.js +28 -16
  83. data/lib/samagotchi/web/public/info_bar_model.js +76 -2
  84. data/lib/samagotchi/web/public/live_timing.js +3 -0
  85. data/lib/samagotchi/web/public/more_sheet.js +98 -40
  86. data/lib/samagotchi/web/public/resync_reach.js +59 -0
  87. data/lib/samagotchi/web/public/session_fields.js +1 -0
  88. data/lib/samagotchi/web/public/session_state.js +5 -0
  89. data/lib/samagotchi/web/public/stage_frame.js +4 -2
  90. data/lib/samagotchi/web/public/stage_stall.js +134 -0
  91. data/lib/samagotchi/web/public/stage_view.js +78 -7
  92. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  93. data/lib/samagotchi/web/public/turn_events.js +0 -122
  94. data/lib/samagotchi/web/public/turn_model.js +1 -1
  95. data/lib/samagotchi/web/public/widget_picks.js +18 -3
  96. data/lib/samagotchi/web/session_control.rb +15 -2
  97. data/lib/samagotchi/web/session_create.rb +4 -2
  98. data/lib/samagotchi/web/token.rb +2 -2
  99. data/lib/samagotchi/web/update_check.rb +27 -8
  100. metadata +5 -1
@@ -241,10 +241,18 @@ module Samagotchi
241
241
  end
242
242
  end
243
243
 
244
+ # Local#discard_images' counterpart: nothing. chi web has no route
245
+ # to take an upload back, so a refused send's copies stay there
246
+ # unused, as a web composer's removed upload does.
247
+ def discard_images(_id, _refs) = nil
248
+
244
249
  # @return [SessionManager::DeliverResult]
245
250
  # @raise [SessionManager::OwnedByTUI]
246
- def deliver_turn(id, prompt:, client_id:, images:, delivery: nil)
251
+ # @param follow [Boolean] +id+ is the head #head resolved: sent only
252
+ # when true (an older chi web ignores it and delivers as before)
253
+ def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false)
247
254
  body = { prompt: prompt, client_id: client_id, history: false }
255
+ body[:follow] = true if follow
248
256
  body[:images] = images.map { |ref| { file: ref[:file], name: ref[:name] } } unless images.empty?
249
257
  body[:check_vision] = true unless images.empty?
250
258
  body[:delivery] = delivery if delivery
@@ -722,25 +730,13 @@ module Samagotchi
722
730
  reply.status == 404 && reply.error == "not_found" && reply.json["detail"].to_s.start_with?("not found: /")
723
731
  end
724
732
 
725
- def context_missing?(reply)
726
- return false unless reply.status == 404
727
- return true if reply.error == "context_missing"
728
-
729
- # Older chi web used not_found for a missing context source.
730
- reply.error == "not_found" && reply.json["detail"].to_s.start_with?("no source")
731
- end
733
+ def context_missing?(reply) = reply.status == 404 && reply.error == "context_missing"
732
734
 
733
- def no_provider?(reply)
734
- return true if reply.error == "no_provider"
735
-
736
- # Older chi web didn't give this refusal its own error code.
737
- reply.json["detail"].to_s.start_with?("no installed bundle resolves")
738
- end
735
+ def no_provider?(reply) = reply.error == "no_provider"
739
736
 
740
737
  # chi web's 404 not_found detail for a session it doesn't have:
741
- # "no session X" (Session::NotFound), or "Session not found: X" from
742
- # chi web 0.155.0 and older (compat N-1: the same line either way).
743
- SESSION_NOT_FOUND = /\A(?:no session |Session not found: )(.+)\z/m
738
+ # "no session X" (Session::NotFound).
739
+ SESSION_NOT_FOUND = /\Ano session (.+)\z/m
744
740
 
745
741
  # Session::NotFound for a missing session's 404, else an
746
742
  # ArgumentError with chi web's words (another route's 404). chi web
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../archive_store"
4
+ require_relative "../session"
5
+
6
+ module Samagotchi
7
+ module SessionChain
8
+ # The one walker of "who continues whom": every chain walk (SessionChain.latest
9
+ # and .next_of, SessionInbox::Head, Schedules' tick) goes through one of
10
+ # these. Built over one Session.list (archived ones too, created_at asc),
11
+ # made on the first question that needs it, so asking only #archived? of
12
+ # one id lists nothing. A link's successor is the earliest session that
13
+ # continues it (a fork a hand edit or an old race made keeps the first);
14
+ # a walk that comes back to a link it passed (a loop a hand-edited file
15
+ # could make) ends where it would repeat. A walk stops where no listed
16
+ # session continues the link: past a deleted middle link nothing is
17
+ # reached.
18
+ #
19
+ # The walks, and who uses which (not unified on purpose: a schedule
20
+ # firing must continue the chain's end, SessionContinue refuses a link
21
+ # already continued; input from a person goes to the first link still
22
+ # live, and a send un-archives an archived end, a schedule never does):
23
+ # - #latest: the chain's end (SessionChain.latest, `last:<id>`, Schedules)
24
+ # - #first_live: the first link not archived, or the end (Head: send, note)
25
+ # - #root: back to the first link (Schedules' one firing per chain)
26
+ #
27
+ # The listing is a snapshot: one Links per question, or per tick.
28
+ class Links
29
+ attr_reader :state_dir
30
+
31
+ def initialize(state_dir:)
32
+ @state_dir = state_dir
33
+ @by_id = nil
34
+ @nexts = nil
35
+ @archived = {}
36
+ end
37
+
38
+ # The listed session +id+ (a Session summary), or nil.
39
+ def session(id) = by_id[id]
40
+
41
+ # Not in the listing (pruned, deleted, never existed).
42
+ def gone?(id) = by_id[id].nil?
43
+
44
+ # Whether +id+ is archived: from the listing once it is made (it read
45
+ # the flags), else one ArchiveStore check, kept.
46
+ def archived?(id)
47
+ return @archived[id] if @archived.key?(id)
48
+ return @archived[id] = by_id[id]&.archived || false if @by_id
49
+
50
+ @archived[id] = Session.valid_id?(id) && ArchiveStore.archived?(Session.session_dir(id, state_dir: @state_dir))
51
+ end
52
+
53
+ # The session +id+ continues, or nil (a first link, or not listed).
54
+ def continues(id) = by_id[id]&.continues
55
+
56
+ # The session that continues +id+, or nil. Archived ones count: an
57
+ # archived link is still a link.
58
+ def next_of(id) = nexts[id]
59
+
60
+ # The chain's end from +id+ on: +id+ itself when nobody continues it.
61
+ def latest(id) = walk(id).last
62
+
63
+ # From +id+ forward over archived links: +id+ when it is not archived,
64
+ # else the first link after it that is not, or the chain's end. Only an
65
+ # archived +id+ makes the listing.
66
+ def first_live(id)
67
+ return id unless archived?(id)
68
+
69
+ walk(id) { |link| !archived?(link) }.last
70
+ end
71
+
72
+ # The chain's first link: back through `continues` to a link with no
73
+ # predecessor listed. A predecessor that is gone ends the walk on its
74
+ # id, so every link after it names the same root.
75
+ def root(id)
76
+ seen = [id]
77
+ while (previous = continues(seen.last)) && !seen.include?(previous)
78
+ seen << previous
79
+ end
80
+ seen.last
81
+ end
82
+
83
+ private
84
+
85
+ # +id+ and the links after it, in order, until none follows, a link
86
+ # would repeat, or the block says stop at the one just reached.
87
+ def walk(id)
88
+ seen = [id]
89
+ while (following = nexts[seen.last]) && !seen.include?(following)
90
+ seen << following
91
+ break if block_given? && yield(following)
92
+ end
93
+ seen
94
+ end
95
+
96
+ def by_id
97
+ @by_id ||= Session.list(state_dir: @state_dir, sort: "created_at", order: "asc", include_archived: true)
98
+ .to_h { |session| [session.id, session] }
99
+ end
100
+
101
+ # id → the session that continues it: the earliest created.
102
+ def nexts
103
+ @nexts ||= by_id.each_value.with_object({}) do |session, nexts|
104
+ nexts[session.continues] ||= session.id if session.continues
105
+ end
106
+ end
107
+ end
108
+ end
109
+ end
@@ -7,6 +7,7 @@ require_relative "config"
7
7
  require_relative "log"
8
8
  require_relative "session"
9
9
  require_relative "session_inbox"
10
+ require_relative "session_chain/links"
10
11
  require_relative "steer"
11
12
  require_relative "recap_store"
12
13
 
@@ -16,7 +17,8 @@ module Samagotchi
16
17
  # follow +continues+ back for the earlier links, forward (the session whose
17
18
  # +continues+ names this one) for the later ones. A link is continued at
18
19
  # most once (SessionContinue.run refuses a second), so the
19
- # chain's latest link is the one nobody continues.
20
+ # chain's latest link is the one nobody continues. Every walk is
21
+ # SessionChain::Links'.
20
22
  module SessionChain
21
23
  # `--continues last:<id>`: the latest link of the chain <id> is in.
22
24
  LAST_PREFIX = "last:"
@@ -36,28 +38,14 @@ module Samagotchi
36
38
  module_function
37
39
 
38
40
  # The session that continues +id+, else nil. Archived ones count: an
39
- # archived link is still a link.
41
+ # archived link is still a link (Links#next_of).
40
42
  # @return [String, nil]
41
- def next_of(id, state_dir:)
42
- Session.list(state_dir: state_dir, sort: "created_at", order: "asc", include_archived: true)
43
- .find { |s| s.continues == id }&.id
44
- end
43
+ def next_of(id, state_dir:) = Links.new(state_dir: state_dir).next_of(id)
45
44
 
46
45
  # The chain's latest link from +id+ on: +id+ itself when nobody
47
- # continues it. One listing, walked forward (a loop a hand-edited file
48
- # could make ends where it started).
46
+ # continues it (Links#latest: one listing, walked forward).
49
47
  # @return [String]
50
- def latest(id, state_dir:)
51
- nexts = {}
52
- Session.list(state_dir: state_dir, sort: "created_at", order: "asc", include_archived: true).each do |s|
53
- nexts[s.continues] ||= s.id if s.continues
54
- end
55
- seen = [id]
56
- while (following = nexts[seen.last]) && !seen.include?(following)
57
- seen << following
58
- end
59
- seen.last
60
- end
48
+ def latest(id, state_dir:) = Links.new(state_dir: state_dir).latest(id)
61
49
 
62
50
  # A session to continue as the CLI and the web name it: an id, a unique
63
51
  # prefix, or `last:<id or prefix>` for that chain's latest link.
@@ -68,6 +68,67 @@ module Samagotchi
68
68
  # moved the chain's end while it waited for the lock.
69
69
  TRIES = 3
70
70
 
71
+ # One thing a continue carries from the previous link to the new one.
72
+ # +carry+ names the method run in spawn_session's before_spawn (once the
73
+ # link and its chain note are saved, before its worker spawns): it takes
74
+ # a CarryContext and returns what the step carried, kept in #run's
75
+ # +carried+ under +name+. +undo+ maps an UNDO_PHASES phase to the method
76
+ # (taking an UndoContext) that gives it back when the continue fails;
77
+ # empty when there is nothing to undo (CARRY's comment says why).
78
+ # +store+ is the SessionManager::SESSION_STATE_STORES store it carries.
79
+ CarryStep = Data.define(:name, :store, :carry, :undo)
80
+ # What a carry step works on: the previous link (a Session), the new
81
+ # link's id, the delegates moving (ChildMove::Plan#move).
82
+ CarryContext = Data.define(:previous, :to, :state_dir, :move)
83
+ # What an undo works on: the previous link's id, the failed link (nil in
84
+ # :moved_back, which looks it up itself), the delegates the plan moved,
85
+ # and what the forward carry kept (#run's +carried+, by step name).
86
+ UndoContext = Data.define(:from, :link, :state_dir, :moved, :carried)
87
+
88
+ # When a failed continue undoes each step, in time order: :moved_back
89
+ # while the failed link's worker may still run (before
90
+ # #discard_failed_link), :link_stopped once its worker is stopped,
91
+ # :link_unlinked once its session file is gone (out of the chain: a note
92
+ # to the previous link stays there), :link_deleted once its folder is
93
+ # gone. Within a phase, the steps undo in reverse CARRY order.
94
+ UNDO_PHASES = %i[moved_back link_stopped link_unlinked link_deleted].freeze
95
+
96
+ # What a continue carries, in order (the forward carry runs them first
97
+ # to last, in the new link's before_spawn). A new per-session store a
98
+ # continue should carry is added here, with its undo.
99
+ CARRY = [
100
+ # Its open delegates (ChildMove): given back to the previous link
101
+ # first, then the rings one rang the link with just before the undo.
102
+ CarryStep.new(name: :children, store: :session_files, carry: :carry_children,
103
+ undo: { moved_back: :undo_move, link_stopped: :return_rings }),
104
+ # Its movable context too, with a note saying what moved and stayed.
105
+ # No undo: ContextSources.move copies (the previous link keeps its
106
+ # sources), and the link's copies go with its delete (remove_files).
107
+ CarryStep.new(name: :context, store: :context_sources, carry: :carry_context, undo: {}),
108
+ # Its objectives: the list reads as the latest word. No undo: a note
109
+ # written into the link only (NoteMove::CONTINUE_SOURCES: never given
110
+ # back), which goes with its delete.
111
+ CarryStep.new(name: :objectives, store: :session_files, carry: :carry_objectives, undo: {}),
112
+ # Its waiting notes last: the carry above read a pending /objectives
113
+ # edit from them first. They keep their names, so they still sort
114
+ # ahead of the link's own notes. A note sent to the previous link
115
+ # from here on goes to this one (SessionInbox::Head), and a
116
+ # straggler is adopted by its worker (NoteMove.adoption). Given back
117
+ # once the link is out of the chain, and again for a note an older chi
118
+ # wrote after its folder went.
119
+ CarryStep.new(name: :notes, store: :session_files, carry: :carry_notes,
120
+ undo: { link_unlinked: :give_back_notes, link_deleted: :give_back_strays })
121
+ ].freeze
122
+
123
+ # The SessionManager::SESSION_STATE_STORES a continue deliberately
124
+ # leaves with the previous link, and why: every store is in CARRY or here.
125
+ NOT_CARRIED = {
126
+ plugin_session_state: "a bundle's per-session state (ctx.session_dir) stays with the archived link",
127
+ participants: "the archive ends the previous link's review (D8); a continue copies no grants",
128
+ system_one_runs: "System 1's saved runs record the previous link's own turns",
129
+ context_candidates_log: "the candidates log records the previous link's own turns"
130
+ }.freeze
131
+
71
132
  # The model a new link runs on (#model_for): the name to spawn it with,
72
133
  # and why it isn't the previous link's (nil when it is, or was given).
73
134
  ModelChoice = Data.define(:model, :warning)
@@ -174,24 +235,22 @@ module Samagotchi
174
235
  end
175
236
  successor_id = SecureRandom.uuid
176
237
  intent_path = continue_intent_path(id, state_dir)
177
- intent_data = { successor_id: successor_id, previously_archived: already }
178
- AtomicFile.write(intent_path, "#{JSON.generate(intent_data)}\n", perm: 0o600)
238
+ ContinueIntent.write(intent_path, successor_id: successor_id, previously_archived: already)
179
239
  archive = SessionManager.archive_session(id, state_dir: state_dir, wait: archive_wait, except: plan.move)
180
240
  archived = archive.archived - already
181
- intent_data[:archived_ids] = archived
182
- AtomicFile.write(intent_path, "#{JSON.generate(intent_data)}\n", perm: 0o600)
183
- # The notes the new link took from this one (NoteMove.move).
184
- notes = []
241
+ ContinueIntent.write(intent_path, successor_id: successor_id, previously_archived: already, archived_ids: archived)
242
+ # What each CARRY step took to the new link, by name.
243
+ carried = {}
185
244
  begin
186
245
  link = spawn_continuation(previous, prompt: prompt, preview: preview, choice: checked.choice, state_dir: state_dir,
187
- move: plan.move, client_id: client_id, notes: notes, session_id: successor_id)
246
+ move: plan.move, client_id: client_id, carried: carried, session_id: successor_id)
188
247
  rescue StandardError, Interrupt
189
248
  # Nothing started: the delegates go back, what this archived goes
190
249
  # back to the lists, and a new link saved before its worker failed
191
250
  # to spawn goes (left, it would hold the chain: "continued already",
192
251
  # last: to it), its notes given back first.
193
- undo_failed_continue(id, state_dir, moved: plan.move, archived: archived) do
194
- discard_failed_link(id, state_dir, notes: notes)
252
+ undo_failed_continue(id, state_dir, moved: plan.move, archived: archived, carried: carried) do
253
+ discard_failed_link(id, state_dir, moved: plan.move, carried: carried)
195
254
  end
196
255
  FileUtils.rm_f(intent_path)
197
256
  raise
@@ -211,18 +270,11 @@ module Samagotchi
211
270
  next unless lock.flock(File::LOCK_EX | File::LOCK_NB)
212
271
  next unless File.file?(path)
213
272
 
214
- intent = JSON.parse(File.read(path))
215
- intent = {} unless intent.is_a?(Hash)
216
- successor_id = intent["successor_id"]
217
- successor_path = Session.session_file(successor_id, state_dir: state_dir) if Session.valid_id?(successor_id)
273
+ intent = ContinueIntent.read(path)
274
+ successor_path = Session.session_file(intent.successor_id, state_dir: state_dir) if intent.successor_id
218
275
  successor = JSON.parse(File.read(successor_path)) if successor_path && File.file?(successor_path)
219
276
  unless successor.is_a?(Hash) && successor["continues"] == session.id
220
- previously_archived = Array(intent["previously_archived"]).select { |id| Session.valid_id?(id) }
221
- archived = if intent["archived_ids"].is_a?(Array)
222
- intent["archived_ids"].select { |id| Session.valid_id?(id) }
223
- else
224
- archived_descendants(session.id, sessions, state_dir) - previously_archived
225
- end
277
+ archived = intent.archived_ids || (archived_descendants(session.id, sessions, state_dir) - intent.previously_archived)
226
278
  undo_failed_continue(session.id, state_dir, moved: [], archived: archived)
227
279
  end
228
280
  FileUtils.rm_f(path)
@@ -259,8 +311,8 @@ module Samagotchi
259
311
  end
260
312
  end
261
313
 
262
- private_class_method def self.undo_failed_continue(id, state_dir, moved:, archived:)
263
- undo_move(id, state_dir, moved: moved)
314
+ private_class_method def self.undo_failed_continue(id, state_dir, moved:, archived:, carried: {})
315
+ undo_carry(:moved_back, UndoContext.new(from: id, link: nil, state_dir: state_dir, moved: moved, carried: carried))
264
316
  begin
265
317
  yield if block_given?
266
318
  ensure
@@ -269,41 +321,81 @@ module Samagotchi
269
321
  end
270
322
  end
271
323
 
324
+ # The CARRY steps' undos for +phase+ (UNDO_PHASES), in reverse CARRY order.
325
+ private_class_method def self.undo_carry(phase, ctx)
326
+ CARRY.reverse_each do |step|
327
+ method = step.undo[phase]
328
+ send(method, ctx) if method
329
+ end
330
+ end
331
+
332
+ # CARRY's forward steps (CarryContext).
333
+ private_class_method def self.carry_children(ctx)
334
+ ChildMove.apply(ctx.move, from: ctx.previous.id, to: ctx.to, state_dir: ctx.state_dir)
335
+ end
336
+
337
+ private_class_method def self.carry_context(ctx)
338
+ ContextMove.call(from: ctx.previous.id, to: ctx.to, mode: :continue, state_dir: ctx.state_dir)
339
+ end
340
+
341
+ private_class_method def self.carry_objectives(ctx)
342
+ Objectives.carry(ctx.previous, to: ctx.to, state_dir: ctx.state_dir)
343
+ end
344
+
345
+ # @return [Array<String>] the names of the notes moved to the link
346
+ private_class_method def self.carry_notes(ctx)
347
+ NoteMove.move(from: ctx.previous.id, to: ctx.to, state_dir: ctx.state_dir)
348
+ end
349
+
272
350
  # The delegates a failed #run moved, or began to (its
273
- # intent names them), go back to +id+.
274
- private_class_method def self.undo_move(id, state_dir, moved:)
351
+ # intent names them), go back to the previous link.
352
+ private_class_method def self.undo_move(ctx)
353
+ id = ctx.from
354
+ state_dir = ctx.state_dir
275
355
  link = SessionChain.next_of(id, state_dir: state_dir) or return
276
- ids = ChildMove.read_intent(link, state_dir: state_dir)&.ids || moved
356
+ ids = ChildMove.read_intent(link, state_dir: state_dir)&.ids || ctx.moved
277
357
  ChildMove.apply(ids, from: link, to: id, state_dir: state_dir, undo: true)
278
358
  ChildMove.clear_intent(link, state_dir: state_dir)
279
359
  rescue StandardError => e
280
360
  Log.warn(:worker, "continue_undo_move_failed", sid: id, error: e.class.name, msg: e.message)
281
361
  end
282
362
 
363
+ # The rings a moved delegate wrote into the failed link just before the
364
+ # undo go back to the previous link.
365
+ private_class_method def self.return_rings(ctx)
366
+ ChildMove.return_rings(from: ctx.link, to: ctx.from, state_dir: ctx.state_dir)
367
+ end
368
+
369
+ # The notes the link took (CARRY's :notes), with any sent to it meanwhile.
370
+ private_class_method def self.give_back_notes(ctx)
371
+ NoteMove.give_back(from: ctx.link, to: ctx.from, moved: Array(ctx.carried[:notes]), state_dir: ctx.state_dir)
372
+ end
373
+
283
374
  # The link a failed #run saved (no other continues +id+:
284
375
  # check! made sure under the lock): its worker stopped if one
285
376
  # started, then the rings a moved delegate wrote into it just before
286
- # the undo go back to +id+. Then its session file goes first, so the
287
- # link is out of the chain (a note to +id+ stays there:
288
- # SessionInbox::Head) and a writer that resolved it before finds it gone,
289
- # then the notes it moved there (+notes+) go back with any sent to it
290
- # meanwhile (NoteMove.give_back), then the link's folder goes, and one
291
- # last look gives back a note an older chi wrote after the delete
292
- # (its write_note recreates the folder). A worker that outlives the
293
- # stop is raised (SessionManager::DeleteRefused): the link stays, and
294
- # the caller hears it.
295
- private_class_method def self.discard_failed_link(id, state_dir, notes:)
377
+ # the undo go back to +id+ (CARRY's :link_stopped undos). Then its
378
+ # session file goes first, so the link is out of the chain (a note to
379
+ # +id+ stays there: SessionInbox::Head) and a writer that resolved it
380
+ # before finds it gone, then the notes it moved there go back with any
381
+ # sent to it meanwhile (:link_unlinked: NoteMove.give_back), then the
382
+ # link's folder goes, and one last look gives back a note an older chi
383
+ # wrote after the delete (:link_deleted; its write_note recreates the
384
+ # folder). A worker that outlives the stop is raised
385
+ # (SessionManager::DeleteRefused): the link stays, and the caller hears it.
386
+ private_class_method def self.discard_failed_link(id, state_dir, moved:, carried:)
296
387
  orphan = SessionChain.next_of(id, state_dir: state_dir) or return
297
388
  if SessionManager.refuse_tui!(orphan, state_dir: state_dir) &&
298
389
  !SessionManager.stop_session(orphan, state_dir: state_dir, wait: SessionManager::STOP_WAIT)
299
390
  raise SessionManager::DeleteRefused.new(orphan, :still_stopping)
300
391
  end
301
392
 
302
- ChildMove.return_rings(from: orphan, to: id, state_dir: state_dir)
393
+ ctx = UndoContext.new(from: id, link: orphan, state_dir: state_dir, moved: moved, carried: carried)
394
+ undo_carry(:link_stopped, ctx)
303
395
  FileUtils.rm_f(Session.session_file(orphan, state_dir: state_dir))
304
- NoteMove.give_back(from: orphan, to: id, moved: notes, state_dir: state_dir)
396
+ undo_carry(:link_unlinked, ctx)
305
397
  SessionManager.delete_session(orphan, state_dir: state_dir, allow_scheduled: true)
306
- give_back_strays(orphan, id, state_dir)
398
+ undo_carry(:link_deleted, ctx)
307
399
  rescue SessionManager::DeleteRefused
308
400
  raise
309
401
  rescue StandardError => e
@@ -312,11 +404,13 @@ module Samagotchi
312
404
 
313
405
  # A failed link's folder an older chi's note brought back after its
314
406
  # delete: the note goes back to +id+, the folder goes again.
315
- private_class_method def self.give_back_strays(orphan, id, state_dir)
407
+ private_class_method def self.give_back_strays(ctx)
408
+ orphan = ctx.link
409
+ state_dir = ctx.state_dir
316
410
  dir = Session.session_dir(orphan, state_dir: state_dir)
317
411
  return unless Dir.exist?(dir) && !Session.exist?(orphan, state_dir: state_dir)
318
412
 
319
- NoteMove.give_back(from: orphan, to: id, moved: [], state_dir: state_dir)
413
+ NoteMove.give_back(from: orphan, to: ctx.from, moved: [], state_dir: state_dir)
320
414
  FileUtils.rm_rf(dir)
321
415
  end
322
416
 
@@ -333,25 +427,15 @@ module Samagotchi
333
427
  # The new link, holding off any worker but its own while +move+ goes to
334
428
  # it (spawn_session marks it starting before its file is saved:
335
429
  # StartingMarker.fresh?).
336
- # @param notes [Array<String>] gets the names of the notes moved to it
337
- private_class_method def self.spawn_continuation(previous, prompt:, preview:, choice:, state_dir:, move:, notes:,
430
+ # @param carried [Hash] gets what each CARRY step took to it, by name
431
+ private_class_method def self.spawn_continuation(previous, prompt:, preview:, choice:, state_dir:, move:, carried:,
338
432
  session_id:, client_id: nil)
339
433
  recap = RecapStore.read(Session.session_dir(previous.id, state_dir: state_dir))
340
434
  start = prompt.to_s.strip.empty? ? nil : prompt
341
435
  preview = previous.first_preview if preview.to_s.strip.empty? && start.nil?
342
- moved_context = nil
343
436
  before_spawn = lambda do |link|
344
- ChildMove.apply(move, from: previous.id, to: link.id, state_dir: state_dir)
345
- # Its movable context too, with a note saying what moved and stayed.
346
- moved_context = ContextMove.call(from: previous.id, to: link.id, mode: :continue, state_dir: state_dir)
347
- # Its objectives: the list reads as the latest word.
348
- Objectives.carry(previous, to: link.id, state_dir: state_dir)
349
- # Its waiting notes last: the carry above read a pending /objectives
350
- # edit from them first. They keep their names, so they still sort
351
- # ahead of the link's own notes. A note sent to the previous link
352
- # from here on goes to this one (SessionInbox::Head), and a
353
- # straggler is adopted by its worker (NoteMove.adoption).
354
- notes.concat(NoteMove.move(from: previous.id, to: link.id, state_dir: state_dir))
437
+ ctx = CarryContext.new(previous: previous, to: link.id, state_dir: state_dir, move: move)
438
+ CARRY.each { |step| carried[step.name] = send(step.carry, ctx) }
355
439
  end
356
440
  link = SessionManager.spawn_session(
357
441
  prompt: start, preview: preview, title: previous.title, working_directory: previous.working_directory,
@@ -361,7 +445,7 @@ module Samagotchi
361
445
  session_id: session_id
362
446
  )
363
447
  link.moved_children = move
364
- link.moved_context = moved_context
448
+ link.moved_context = carried[:context]
365
449
  link.opener = SessionChain.opener_for(previous)
366
450
  # The fallback's warning first: spawn_session set its own.
367
451
  warnings = [choice.warning, link.model_warning].compact
@@ -521,7 +521,7 @@ module Samagotchi
521
521
  # (Worker#pending_input_drain): a wait for it (ReplyWait's turn:) then
522
522
  # waits for that turn (Poll#follow_merge). Nothing for an id that
523
523
  # can't name a file, nor for a turn with none; a failed write only
524
- # logs (the wait infers the merge, as for a worker before this).
524
+ # logs (a wait for that input then never follows it to that turn).
525
525
  def self.mark_merged(session_dir, id, into:, now: Time.now)
526
526
  return unless ENQUEUED_ID_NAME.match?(id.to_s) && ENQUEUED_ID_NAME.match?(into.to_s)
527
527