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
@@ -3,8 +3,10 @@
3
3
  require_relative "session"
4
4
  require_relative "session_inbox"
5
5
  require_relative "archive_store"
6
+ require_relative "client_id"
6
7
  require_relative "worker_presence"
7
8
  require_relative "continue_intent"
9
+ require_relative "session_chain/links"
8
10
 
9
11
  module Samagotchi
10
12
  # Loaded on first use: this autoload keeps SessionManager and its ~80
@@ -64,8 +66,10 @@ module Samagotchi
64
66
  # What a delivery of one kind may do to a session's worker: one frozen
65
67
  # row per kind (ROWS), decided on WorkerPresence's predicates alone, in
66
68
  # one order for every kind (#decide).
67
- # @!attribute kind [Symbol] :send, :note, :push, :ring, :fresh_verdict or
68
- # :leave (WorkerBoot's respawn, not a delivery)
69
+ # @!attribute kind [Symbol] :send, :note, :push, :ring, :fresh_verdict,
70
+ # :leave (WorkerBoot's respawn, not a delivery), or a turn delivery's
71
+ # unattended sender (deliver_turn, #for_sender): :schedule, :plugin,
72
+ # :delegate, :participant, :automatic
69
73
  # @!attribute resolves [Symbol] which link it goes to (Head.resolve):
70
74
  # :pinned the id named; :head the chain's newest link from it; :reader
71
75
  # the link that reads the named one's file (a ring: the file stays with
@@ -73,9 +77,9 @@ module Samagotchi
73
77
  # rings, so the wake goes one hop at most)
74
78
  # @!attribute starts [Boolean] it may start a worker
75
79
  # @!attribute unstops [Boolean] it starts a stopped session (a resume
76
- # clears the stop): send only
80
+ # clears the stop): send only (a person's)
77
81
  # @!attribute starts_archived [Boolean] it starts an archived link
78
- # (input from a person un-archives it): send only
82
+ # (input from a person un-archives it): send (and leave) only
79
83
  # @!attribute refuse_tui [Boolean] a one-turn chi run's session refuses it
80
84
  # @!attribute refuse_scratch [Boolean] a chi scratch session refuses it
81
85
  WakePolicy = Data.define(:kind, :resolves, :starts, :unstops, :starts_archived, :refuse_tui, :refuse_scratch) do
@@ -83,6 +87,11 @@ module Samagotchi
83
87
  # @raise [ArgumentError] no such kind
84
88
  def self.for(kind) = WakePolicy::ROWS.fetch(kind) { raise ArgumentError, "no inbox kind #{kind.inspect}" }
85
89
 
90
+ # The row a turn delivery from +client_id+ reads: its kind by the
91
+ # sender (ClientId.wake_kind), never a caller's flag.
92
+ # @return [WakePolicy]
93
+ def self.for_sender(client_id) = self.for(ClientId.wake_kind(client_id))
94
+
86
95
  # Why the delivery is refused before anything is written, else nil:
87
96
  # :gone (no session), :owned (a one-turn chi run's), :scratch.
88
97
  # @param load [#call, nil] the session, read only when the scratch
@@ -126,12 +135,15 @@ module Samagotchi
126
135
  end
127
136
 
128
137
  # A send follows a chain as a note does: input for a continued link
129
- # goes to its chain's newest link (chi send resolves it once up front,
130
- # SessionAccess#head; SessionManager.deliver_turn resolves nothing).
138
+ # goes to its chain's newest link (chi send resolves it up front,
139
+ # SessionAccess#head; SessionManager.deliver_turn resolves nothing, but
140
+ # refuses that followed send when a continue took the archived link
141
+ # since, and chi send resolves again: deliver_turn's follow:).
131
142
  # What stays on the id it names doesn't ask Head: the web composer (a
132
143
  # person on that page means that session), a participant's grant (one
133
- # session), delegate follow-ups, Plugin::Sessions and Schedules (their
134
- # own rule).
144
+ # session), delegate follow-ups, Plugin::Sessions and Schedules (the
145
+ # chain's end, SessionChain::Links#latest: a firing continues the end,
146
+ # and never un-archives a retired chain).
135
147
  WakePolicy::ROWS = {
136
148
  send: WakePolicy.new(kind: :send, resolves: :head, starts: true, unstops: true, starts_archived: true,
137
149
  refuse_tui: true, refuse_scratch: true),
@@ -148,7 +160,16 @@ module Samagotchi
148
160
  # lock's release). A stop wins; an archived session's input still
149
161
  # starts it, as a send's would have.
150
162
  leave: WakePolicy.new(kind: :leave, resolves: :pinned, starts: true, unstops: false, starts_archived: true,
151
- refuse_tui: false, refuse_scratch: false)
163
+ refuse_tui: false, refuse_scratch: false),
164
+ # A turn delivery's unattended senders (deliver_turn reads the row by
165
+ # the sender, ClientId.wake_kind): they start an idle session as a send
166
+ # does, but a stop and an archive are the owner's (the sender is
167
+ # refused, SessionManager::DeliverResult::STOPPED / ARCHIVED). They
168
+ # stay on the id they name. :automatic is any sender chi doesn't name.
169
+ **%i[schedule plugin delegate participant automatic].to_h do |kind|
170
+ [kind, WakePolicy.new(kind: kind, resolves: :pinned, starts: true, unstops: false, starts_archived: false,
171
+ refuse_tui: true, refuse_scratch: true)]
172
+ end
152
173
  }.freeze
153
174
 
154
175
  # Which link of a chain a delivery goes to.
@@ -162,10 +183,11 @@ module Samagotchi
162
183
  # file could make ends where it started); a :reader kind goes one hop
163
184
  # at most. Then, for a kind that would un-archive the link it reaches
164
185
  # (a send: WakePolicy#starts_archived), a continue of that link in
165
- # flight (ContinueIntent.in_flight: its successor not saved yet) gives
166
- # :continuing, the successor's id. A note needs no such check: written
167
- # to the link before NoteMove.move it moves, after it the new link's
168
- # worker adopts it (NoteMove.adoption).
186
+ # flight (ContinueIntent.in_flight) gives the successor's id: via
187
+ # :continuing while it is not saved yet, :head once it is
188
+ # (#continuing). A note needs no such check: written to the link
189
+ # before NoteMove.move it moves, after it the new link's worker adopts
190
+ # it (NoteMove.adoption).
169
191
  # @return [Resolved]
170
192
  def resolve(kind, id, state_dir:)
171
193
  policy = WakePolicy.for(kind)
@@ -175,38 +197,35 @@ module Samagotchi
175
197
  (continuing(resolved, state_dir) if policy.starts_archived) || resolved
176
198
  end
177
199
 
200
+ # The chain walk is SessionChain::Links': #first_live for :head (the
201
+ # send/note rule: the first live link, not the chain's end that a
202
+ # schedule fires at, Links#latest), its successor alone for :reader.
178
203
  def walk(how, id, state_dir)
179
- same = Resolved.new(id: id, asked: id, via: :same)
180
- return same unless archived?(id, state_dir)
181
-
182
- nexts = successors(state_dir)
183
- seen = [id]
184
- while (following = nexts[seen.last]) && !seen.include?(following)
185
- seen << following
186
- break if how == :reader || !archived?(following, state_dir)
187
- end
188
- seen.size == 1 ? same : Resolved.new(id: seen.last, asked: id, via: :head)
204
+ links = SessionChain::Links.new(state_dir: state_dir)
205
+ reached = how == :reader ? reader(links, id) : links.first_live(id)
206
+ reached == id ? Resolved.new(id: id, asked: id, via: :same) : Resolved.new(id: reached, asked: id, via: :head)
189
207
  end
190
208
 
191
- # +resolved+'s link being continued, its successor not saved yet: the
192
- # successor, via :continuing; else nil (none in flight, or saved: the
193
- # walk reached it).
194
- def continuing(resolved, state_dir)
195
- successor = ContinueIntent.in_flight(resolved.id, state_dir: state_dir)
196
- return nil if successor.nil? || Session.exist?(successor, state_dir: state_dir)
209
+ # The link that reads an archived +id+'s file: its successor, one hop.
210
+ def reader(links, id)
211
+ return id unless links.archived?(id)
197
212
 
198
- Resolved.new(id: successor, asked: resolved.asked, via: :continuing)
213
+ links.next_of(id) || id
199
214
  end
200
215
 
201
- def archived?(id, state_dir)
202
- Session.valid_id?(id) && ArchiveStore.archived?(Session.session_dir(id, state_dir: state_dir))
203
- end
216
+ # +resolved+'s link being continued: its successor, via :continuing
217
+ # while it is not saved yet, via :head once it is (saved after the
218
+ # walk's listing: the walk still named the old link, which a send
219
+ # would un-archive beside it); else nil (none in flight). A continue
220
+ # that ends after this look is deliver_turn's to catch (a followed
221
+ # send to an archived link with a successor is refused, and chi send
222
+ # resolves again).
223
+ def continuing(resolved, state_dir)
224
+ successor = ContinueIntent.in_flight(resolved.id, state_dir: state_dir)
225
+ return nil if successor.nil?
204
226
 
205
- # id → the session that continues it (SessionChain.next_of's: the
206
- # earliest one, archived ones too).
207
- def successors(state_dir)
208
- Session.list(state_dir: state_dir, sort: "created_at", order: "asc", include_archived: true)
209
- .each_with_object({}) { |s, nexts| nexts[s.continues] ||= s.id if s.continues }
227
+ via = Session.exist?(successor, state_dir: state_dir) ? :head : :continuing
228
+ Resolved.new(id: successor, asked: resolved.asked, via: via)
210
229
  end
211
230
  end
212
231
 
@@ -44,7 +44,8 @@ module Samagotchi
44
44
  # tool's follow-up says it after "Error: session <id8>".
45
45
  # @return [String]
46
46
  def refusal_text
47
- refused = error == Delivery::QUEUE_UNAVAILABLE["error"] || DeliverResult::REMOTE_REFUSALS.include?(error)
47
+ refused = error == Delivery::QUEUE_UNAVAILABLE["error"] || continued? || wake_refused? ||
48
+ DeliverResult::REMOTE_REFUSALS.include?(error)
48
49
  "#{refused ? "refused" : "failed"}: #{detail || "could not queue it"}"
49
50
  end
50
51
 
@@ -53,6 +54,14 @@ module Samagotchi
53
54
  # input file or a worker older than delivery.
54
55
  def delivery = ack["delivery"]
55
56
 
57
+ # A followed send refused: a continue took the archived link it named
58
+ # (deliver_turn's follow:); the sender resolves the head again.
59
+ def continued? = error == DeliverResult::CONTINUED
60
+
61
+ # A stopped or archived session its sender may not wake
62
+ # (DeliverResult::STOPPED / ARCHIVED: only a person's message does).
63
+ def wake_refused? = DeliverResult::WAKE_REFUSALS.include?(error)
64
+
56
65
  # A --cut's outcome ("now", "waits", "off"), nil when nothing was cut.
57
66
  def cut = ack["cut"]
58
67
 
@@ -66,6 +75,18 @@ module Samagotchi
66
75
  # DeliverResult, not inside its Data.define block, where a constant
67
76
  # would land on SessionManager.
68
77
  DeliverResult::REMOTE_REFUSALS = %w[parent_answers_refused parent_continue_refused no_vision].freeze
78
+ # A followed send's refusal (DeliverResult#continued?), here and from a
79
+ # remote's turn route alike.
80
+ DeliverResult::CONTINUED = "link_continued"
81
+ # An unattended sender's turn (a schedule, a plugin, a delegate
82
+ # follow-up, a participant: ClientId.wake_kind) to a session its owner
83
+ # stopped or archived: refused, nothing written (a 409 from chi web).
84
+ # The one wording of each; a caller adds who and which session.
85
+ DeliverResult::STOPPED = { "error" => "session_stopped",
86
+ "detail" => "the session is stopped; only its owner's message starts it again" }.freeze
87
+ DeliverResult::ARCHIVED = { "error" => "session_archived",
88
+ "detail" => "the session is archived; only its owner's message brings it back" }.freeze
89
+ DeliverResult::WAKE_REFUSALS = [DeliverResult::STOPPED["error"], DeliverResult::ARCHIVED["error"]].freeze
69
90
 
70
91
  # The unclaimed input files +author+ wrote.
71
92
  PARTICIPANT_QUEUE_LOCK = "participants.lock"
@@ -79,14 +100,14 @@ module Samagotchi
79
100
  # the worker polls. Reused by the bridge's POST surface so a turn is
80
101
  # fire-and-forget and never calls run_turn across the thread/process
81
102
  # boundary. The file is JSON carrying the sender's ids.
82
- # @param client_id [String, nil] the sending UI
103
+ # @param client_id [String] the sender (ClientId), always named
83
104
  # @param enqueued_id [String, nil] the id its ACK / :turn_enqueued carry
84
105
  # @param delivery [String, nil] the wire value: "next_step" (default),
85
106
  # "cut" or "queue"
86
107
  # @param images [Array<Hash>] image refs ({file:, name:}) in the
87
108
  # session's images/
88
109
  # @return [String, false] the input file's path, or false.
89
- def write_turn_input(session_id, prompt:, client_id: nil, enqueued_id: nil, no_interrupt: false, state_dir: nil,
110
+ def write_turn_input(session_id, prompt:, client_id:, enqueued_id: nil, no_interrupt: false, state_dir: nil,
90
111
  images: [], delivery: nil, author: nil, anchors: nil)
91
112
  session_dir = Session.session_dir(session_id, state_dir: state_dir || Session.default_state_dir)
92
113
  SessionInbox.write_input(session_dir, prompt: prompt, client_id: client_id, enqueued_id: enqueued_id,
@@ -100,6 +121,12 @@ module Samagotchi
100
121
  # to the input file when the Bridge is gone (a worker closing it on idle
101
122
  # exit). Race-safe against a TUI taking the session, or the worker
102
123
  # exiting, between the resume and the write.
124
+ # @param client_id [String] the sender (ClientId), always named: its
125
+ # kind picks the wake row (ClientId.wake_kind): a person's (chi send,
126
+ # a web tab, a TUI) un-stops a stopped session and starts an archived
127
+ # link; a schedule's, a plugin's, a delegate's, a participant's or an
128
+ # unknown one's is refused there (:refused 409, DeliverResult::STOPPED
129
+ # / ARCHIVED, nothing written)
103
130
  # @param images [Array<Hash>] refs ({file:, name:}) already in images/
104
131
  # @param delivery [String, nil] what the message asks the running turn
105
132
  # for: "next_step" (default), "cut" or "queue"
@@ -116,6 +143,12 @@ module Samagotchi
116
143
  # @param anchors [TurnAnchors, Hash, nil] a Verify turn's claim, a Revise
117
144
  # turn's draft: each refused (409, its UNAVAILABLE) by a worker without
118
145
  # its feature
146
+ # @param follow [Boolean] the sender resolved +session_id+ as its
147
+ # chain's head (chi send: SessionAccess#head), so an archived link a
148
+ # continue took since is refused (:refused 409 link_continued, nothing
149
+ # written: #follow_guard) rather than un-archived beside its new link;
150
+ # the sender resolves again. Others name the id they mean (the web
151
+ # composer, schedules, delegates, plugins, participants).
119
152
  # @param manager [#resume_session, #write_turn_input] this class, or a
120
153
  # stand-in (the web's specs); #session_owner is optional
121
154
  # @param bridge [#call, nil] returns the BridgeClient or nil; defaults to
@@ -127,9 +160,46 @@ module Samagotchi
127
160
  # when it took the request but never answered (no file then), or
128
161
  # :failed when the input file couldn't be written
129
162
  # @raise [OwnedByTUI] a one-turn chi run owns the session
130
- # @raise [ArgumentError] no such session
131
- def deliver_turn(session_id, prompt:, client_id: nil, images: [], delivery: nil, no_interrupt: false,
132
- author: nil, pending_limit: nil, anchors: nil, state_dir: nil, manager: self, bridge: nil)
163
+ # @raise [ArgumentError] no such session, or no client_id
164
+ def deliver_turn(session_id, prompt:, client_id:, images: [], delivery: nil, no_interrupt: false,
165
+ author: nil, pending_limit: nil, anchors: nil, follow: false, state_dir: nil, manager: self,
166
+ bridge: nil)
167
+ raise ArgumentError, "deliver_turn needs the sender's client_id" if client_id.to_s.empty?
168
+
169
+ follow_guard(session_id, state_dir, follow) do
170
+ deliver_turn_now(session_id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
171
+ no_interrupt: no_interrupt, author: author, pending_limit: pending_limit,
172
+ anchors: anchors, state_dir: state_dir, manager: manager, bridge: bridge)
173
+ end
174
+ end
175
+
176
+ # A followed send (deliver_turn's follow:) to an archived link: refused
177
+ # when a continue took it (a successor saved, or a continue holding its
178
+ # lock now: its successor comes), else the delivery under a shared hold
179
+ # of the continue lock (ContinueIntent.hold), so no continue starts
180
+ # between this check and the input going in. Any other delivery, or
181
+ # a link not archived, is the block alone. Head.resolve answers the
182
+ # sender before the delivery: a continue that ends or starts in
183
+ # between is caught here, and chi send resolves again (SendCommand#target).
184
+ # @return [DeliverResult] the block's, or the refusal
185
+ private def follow_guard(session_id, state_dir, follow)
186
+ sd = state_dir || Session.default_state_dir
187
+ return yield unless follow && Session.valid_id?(session_id) &&
188
+ ArchiveStore.archived?(Session.session_dir(session_id, state_dir: sd))
189
+
190
+ ContinueIntent.hold(session_id, state_dir: sd) do |held|
191
+ successor = SessionChain::Links.new(state_dir: sd).next_of(session_id) if held
192
+ next yield if held && successor.nil?
193
+
194
+ words = successor ? "being continued as #{successor[0, 8]}" : "being continued"
195
+ DeliverResult.new(status: :refused, code: 409,
196
+ ack: { "error" => DeliverResult::CONTINUED, "detail" => "#{words}; send again in a moment",
197
+ "session_id" => session_id, "successor_id" => successor }.compact)
198
+ end
199
+ end
200
+
201
+ private def deliver_turn_now(session_id, prompt:, client_id:, images:, delivery:, no_interrupt:, author:,
202
+ pending_limit:, anchors:, state_dir:, manager:, bridge:)
133
203
  anchors = TurnAnchors.from(anchors)
134
204
  session_dir = Session.session_dir(session_id, state_dir: state_dir || Session.default_state_dir)
135
205
  bridge ||= lambda do
@@ -138,7 +208,9 @@ module Samagotchi
138
208
  end
139
209
  # Its refusals (no session, a one-turn run's, a scratch one) are
140
210
  # resume_session's to raise, in their one wording.
141
- start_for_send(manager, session_id, state_dir, before: true)
211
+ refused = start_for_send(manager, session_id, state_dir, client_id, before: true)
212
+ return refused if refused
213
+
142
214
  enqueued_id = SessionInbox.new_enqueued_id
143
215
  if (client = bridge.call)
144
216
  if (missing = anchors.present.find { |anchor| !worker_has?(client, anchor.class::FEATURE) })
@@ -215,7 +287,7 @@ module Samagotchi
215
287
  # A worker that idle-exited since the resume never reads it either:
216
288
  # wake a new one. (The exiting worker also looks for input it left;
217
289
  # one the first resume spawned that is still starting is left be.)
218
- start_for_send(manager, session_id, state_dir, before: false) do
290
+ start_for_send(manager, session_id, state_dir, client_id, before: false) do
219
291
  FileUtils.rm_f(path) if path.is_a?(String)
220
292
  raise OwnedByTUI, session_id
221
293
  end
@@ -223,9 +295,13 @@ module Samagotchi
223
295
  ack: { "status" => "accepted", "enqueued_id" => enqueued_id, "session_id" => session_id })
224
296
  end
225
297
 
226
- # deliver_turn's two liveness checks, on the session inbox's send row
227
- # (SessionInbox::WakePolicy: send un-stops and starts an archived
228
- # link). The row follows a chain, deliver_turn doesn't: it acts on
298
+ # deliver_turn's two liveness checks, on the sender's row of the session
299
+ # inbox (SessionInbox::WakePolicy.for_sender: a person's send un-stops
300
+ # and starts an archived link; an unattended sender's does neither,
301
+ # and +before+ the write it gets DeliverResult::STOPPED / ARCHIVED,
302
+ # nothing written; after it, a stop or archive that landed since wins
303
+ # and the input waits for the next start). The row follows a chain,
304
+ # deliver_turn doesn't: it acts on
229
305
  # the id it is given, and a caller that follows (chi send) resolves
230
306
  # the head first (SessionAccess#head): resume_session unless a
231
307
  # worker holds the session or one is being started. Its refusals (no
@@ -237,24 +313,34 @@ module Samagotchi
237
313
  # is leaving (OwnerLock::Owner#leaving?: its Bridge closed, the lock
238
314
  # held for its last work) has its input served by its own respawn
239
315
  # (WorkerBoot's leave): a stop that landed before this send is
240
- # cleared, as resume_session clears it (a send un-stops); one that
241
- # lands after it still wins.
242
- private def start_for_send(manager, session_id, state_dir, before:)
316
+ # cleared, as resume_session clears it (a person's send un-stops); one
317
+ # that lands after it still wins.
318
+ # @return [DeliverResult, nil] the refusal of a wake the sender may not
319
+ # make (+before+ only), else nil
320
+ private def start_for_send(manager, session_id, state_dir, client_id, before:)
243
321
  presence = delivery_presence(manager, session_id, state_dir)
244
- policy = SessionInbox::WakePolicy.for(:send)
322
+ policy = SessionInbox::WakePolicy.for_sender(client_id)
245
323
  outcome = policy.decide(presence)
246
324
  yield if outcome == :owned && block_given?
247
- if !before && outcome == :live && presence.stop_marked? && presence.owner&.leaving?
325
+ if %i[stopped archived].include?(outcome)
326
+ return nil unless before
327
+
328
+ refusal = outcome == :stopped ? DeliverResult::STOPPED : DeliverResult::ARCHIVED
329
+ Log.info(:worker, "send_wake_refused", sid: session_id[0, 8], kind: policy.kind, outcome: outcome)
330
+ return DeliverResult.new(status: :refused, code: 409, ack: refusal)
331
+ end
332
+ if !before && outcome == :live && policy.unstops && presence.stop_marked? && presence.owner&.leaving?
248
333
  Session.clear_stopped(session_id, state_dir: state_dir || Session.default_state_dir)
249
334
  Log.info(:worker, "send_unstopped_leaving", sid: session_id[0, 8])
250
335
  end
251
336
  if %i[live starting].include?(outcome)
252
- return unless before
337
+ return nil unless before
253
338
 
254
339
  load = -> { Session.load(session_id, state_dir: state_dir || Session.default_state_dir) }
255
- return unless policy.refusal(presence, load: load)
340
+ return nil unless policy.refusal(presence, load: load)
256
341
  end
257
342
  manager.resume_session(session_id, state_dir: state_dir)
343
+ nil
258
344
  end
259
345
 
260
346
  # Whether the worker +client+ talks to names +feature+: the features of
@@ -3,8 +3,9 @@
3
3
  module Samagotchi
4
4
  class SessionManager
5
5
  # A delete that would pull the session from under its live worker.
6
- # reason: :worker_running (not asked to stop it) or :still_stopping
7
- # (stopped, but the worker outlived the wait).
6
+ # reason: :worker_running (not asked to stop it), :still_stopping
7
+ # (stopped, but the worker outlived the wait) or :changed (the caller's
8
+ # +still:+ check, read again under the owner lock, no longer holds).
8
9
  class DeleteRefused < StandardError
9
10
  attr_reader :session_id, :reason, :schedule_id
10
11
 
@@ -14,6 +15,7 @@ module Samagotchi
14
15
  @schedule_id = schedule_id
15
16
  message ||= case reason
16
17
  when :still_stopping then "session #{session_id}'s worker is still shutting down"
18
+ when :changed then "session #{session_id} changed since it was checked"
17
19
  when :scheduled
18
20
  "this session is the target of an enabled schedule" \
19
21
  "#{"; cancel it with chi schedule cancel #{schedule_id}" if schedule_id}"
@@ -199,14 +201,17 @@ module Samagotchi
199
201
 
200
202
  # Remove every store with state scoped to +id+. The file and sidecar
201
203
  # directory keep the deleting owner lock; the other stores have their
202
- # own locking where they need it.
204
+ # own locking where they need it. +still+, when given, is the caller's
205
+ # own check, read again under that lock (the session files go first, so
206
+ # a refusal leaves every store as it was).
203
207
  # @return [Array<String>] the session file, sidecar and context paths removed
204
- def remove_files(id, path, dir, state_dir:, purge_runs: true)
208
+ # @raise [DeleteRefused] see #remove_session_files
209
+ def remove_files(id, path, dir, state_dir:, purge_runs: true, still: nil)
205
210
  removed = []
206
211
  SESSION_STATE_STORES.each do |store|
207
212
  case store
208
213
  when :session_files
209
- removed.concat(remove_session_files(id, path, dir, state_dir: state_dir))
214
+ removed.concat(remove_session_files(id, path, dir, state_dir: state_dir, still: still))
210
215
  when :plugin_session_state
211
216
  PluginSessionState.remove(id)
212
217
  when :context_sources
@@ -245,11 +250,12 @@ module Samagotchi
245
250
  # the retention sweep and failed-continue cleanup use #remove_files.
246
251
  # @return [Array<String>] the paths removed
247
252
  # @raise [DeleteRefused] a worker took the lock, or a start was
248
- # claimed, after the caller's check
249
- def remove_session_files(id, path, dir, state_dir:)
253
+ # claimed, after the caller's check, or +still+ no longer holds
254
+ def remove_session_files(id, path, dir, state_dir:, still: nil)
250
255
  lock = Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0) : nil
251
256
  raise DeleteRefused.new(id, :worker_running) if Dir.exist?(dir) && lock.nil?
252
257
  raise DeleteRefused.new(id, :worker_running) if StartingMarker.fresh?(id, state_dir: state_dir)
258
+ raise DeleteRefused.new(id, :changed) if still && !still.call
253
259
 
254
260
  removed = []
255
261
  if File.exist?(path)
@@ -51,6 +51,7 @@ require_relative "recap_store"
51
51
  require_relative "session_row"
52
52
  require_relative "reminder_carry"
53
53
  require_relative "archive_store"
54
+ require_relative "continue_intent"
54
55
  require_relative "continue_offer"
55
56
  require_relative "image_store"
56
57
  require_relative "plugin_session_state"
@@ -10,8 +10,6 @@ require_relative "config"
10
10
  require_relative "log"
11
11
  require_relative "model_profile"
12
12
  require_relative "session_manager"
13
- require_relative "plugin_session_state"
14
- require_relative "context_sources"
15
13
  require_relative "system_one/runs"
16
14
 
17
15
  module Samagotchi
@@ -78,27 +76,39 @@ module Samagotchi
78
76
 
79
77
  # Directories with no session file and nothing but the skeleton, nobody
80
78
  # owning them: a one-shot killed before its first save, or a worker woken
81
- # just as its session was discarded.
79
+ # just as its session was discarded. Removed as a delete removes
80
+ # (SessionManager.remove_files: every SESSION_STATE_STORES store), which
81
+ # reads the owner lock, the starting marker and #orphan_dir? again under
82
+ # that lock: a worker or a start that took the session since the check,
83
+ # or a session file or content written meanwhile, keeps it.
82
84
  # @return [Array<String>] their ids
83
85
  private_class_method def self.prune_orphan_dirs(state_dir, dry_run:)
84
86
  return [] unless Dir.exist?(state_dir)
85
87
 
86
- Dir.children(state_dir).filter_map do |name|
88
+ removed = Dir.children(state_dir).filter_map do |name|
87
89
  dir = File.join(state_dir, name)
90
+ path = File.join(state_dir, "#{name}#{SessionPaths::FILE_EXT}")
88
91
  next unless Session.valid_id?(name) && File.directory?(dir)
89
- next if File.exist?(File.join(state_dir, "#{name}#{SessionPaths::FILE_EXT}"))
90
- next unless Time.now - File.mtime(dir) > EMPTY_GRACE_SECONDS && SessionManager.empty_session_dir?(dir)
92
+ next unless Time.now - File.mtime(dir) > EMPTY_GRACE_SECONDS && orphan_dir?(path, dir)
91
93
  next if owned?(name, state_dir) || starting?(name, state_dir)
92
94
 
93
95
  unless dry_run
94
- FileUtils.rm_rf(dir)
95
- PluginSessionState.remove(name)
96
- ContextSources.remove_session(name, state_dir: state_dir)
96
+ SessionManager.remove_files(name, path, dir, state_dir: state_dir, purge_runs: false,
97
+ still: -> { orphan_dir?(path, dir) })
97
98
  end
98
99
  name
99
- rescue SystemCallError
100
+ rescue SessionManager::DeleteRefused, SystemCallError
100
101
  nil
101
102
  end
103
+ SessionManager.purge_removal_stores(removed, state_dir: state_dir) unless dry_run
104
+ removed
105
+ end
106
+
107
+ # No session file, and a folder holding only the skeleton. Not its age:
108
+ # read again under the owner lock, whose file the lock may have just
109
+ # made.
110
+ private_class_method def self.orphan_dir?(path, dir)
111
+ !File.exist?(path) && SessionManager.empty_session_dir?(dir)
102
112
  end
103
113
 
104
114
  # A worker is being started for it (every spawn marks it, a new
@@ -33,7 +33,8 @@ module Samagotchi
33
33
  # It doesn't save itself: the session keeps each setting in its own field
34
34
  # and file key, and resolves it on its own. A delegate child starts
35
35
  # without one (but the toolkit its delegate call named, and its parent's
36
- # parent_answers); a continue and a fork copy their session's (.of).
36
+ # parent_answers); a continue and a fork copy their session's (.of); a
37
+ # person's new-session request builds one with .from_request.
37
38
  SessionSetup = Data.define(:llm_context, :thinking, :reasoning_history, :appended_prompt_files,
38
39
  :preloaded_memory_names, :muted_memory_names, :toolkit, :toolkit_origin, :settings,
39
40
  :parent_answers, :working_set_pins) do
@@ -52,6 +53,35 @@ module Samagotchi
52
53
  # Every member at its default: none of the session's own settings.
53
54
  def empty? = self == self.class.new
54
55
 
56
+ # A new session's setup from what a person's request gave: chi's run
57
+ # flags (attached and the one-shot), chi send --new and chi web's
58
+ # create (a remote's chi send --new and attach reach it there). Every
59
+ # such site calls this, so a member a request can carry is one keyword
60
+ # here and no site picks its own subset: an input a site doesn't take
61
+ # is left out (nil or [] = not given). The members no request carries
62
+ # start at their defaults: reasoning_history (/reasoning-history, after
63
+ # creation), working_set_pins (pinned in the session) and
64
+ # toolkit_origin ("chosen" with a toolkit; without one spawn_session
65
+ # stores config's default, "default").
66
+ # spec/session_setup_entrypoints_spec.rb holds every entrypoint's cell
67
+ # for every member.
68
+ # @param memories [Array<String>, nil] --memory's names
69
+ # @param muted [Array<String>, nil] --mute's names
70
+ # @param llm_context [LLMContextOverride, nil] --llm-context*'s values
71
+ # @param thinking [Symbol, String, nil] a level or a level word
72
+ # (Thinking.session_level: default is none)
73
+ # @param appended_prompt_files [Array<String>, nil] --append-system-prompt's
74
+ # @param toolkit [Toolkit, nil] --toolkit/--tool/--no-tool's
75
+ # @param settings [SessionConfig::Settings, nil] --set's
76
+ # @param parent_answers [String, Symbol, nil] --parent-answers' level
77
+ # @return [SessionSetup]
78
+ def self.from_request(memories: nil, muted: nil, llm_context: nil, thinking: nil, appended_prompt_files: nil,
79
+ toolkit: nil, settings: nil, parent_answers: nil)
80
+ new(preloaded_memory_names: memories, muted_memory_names: muted, llm_context: llm_context,
81
+ thinking: Thinking.session_level(thinking), appended_prompt_files: appended_prompt_files,
82
+ toolkit: toolkit, settings: settings, parent_answers: parent_answers)
83
+ end
84
+
55
85
  # A session's own setup, for a session that starts from it: each
56
86
  # member is the session's field of the same name (Session.new_session
57
87
  # applies them by name), but for SessionSetup::CARRY's. Its toolkit
@@ -60,11 +60,13 @@ module Samagotchi
60
60
  end
61
61
  end
62
62
 
63
+ # @param collection [String, Symbol, nil] the key of the file's records;
64
+ # nil for a file of document members only (no entries)
63
65
  def read(data, collection:)
64
66
  raise InvalidDocument, "the state file must contain a JSON object" unless data.is_a?(Hash)
65
67
 
66
- collection = collection.to_s
67
- entries = Array(data[collection]).map { |raw| read_record(raw) }
68
+ collection = collection&.to_s
69
+ entries = collection ? Array(data[collection]).map { |raw| read_record(raw) } : []
68
70
  attributes = {}
69
71
  document_members.each do |member|
70
72
  key = member.name.to_s
@@ -74,7 +76,7 @@ module Samagotchi
74
76
  default_value(member.default, attributes)
75
77
  end
76
78
  end
77
- known = %w[version updated_at] + [collection] + document_members.map { |member| member.name.to_s }
79
+ known = %w[version updated_at] + [collection].compact + document_members.map { |member| member.name.to_s }
78
80
  stored_version = data["version"]
79
81
  stored_version = 0 unless stored_version.is_a?(Integer) && stored_version >= 0
80
82
 
@@ -83,12 +85,14 @@ module Samagotchi
83
85
  entries: entries, attributes: attributes)
84
86
  end
85
87
 
88
+ # @param collection [String, Symbol, nil] as #read's (nil: no entries written)
89
+ # @param updated_at [String, nil] nil: none written
86
90
  def write(document, collection:, updated_at:)
87
- document.extra.transform_keys(&:to_s).merge(document.attributes.transform_keys(&:to_s)).merge(
88
- "version" => [document.version, @version].max,
89
- "updated_at" => updated_at,
90
- collection.to_s => document.entries.map(&:to_h)
91
- )
91
+ body = document.extra.transform_keys(&:to_s).merge(document.attributes.transform_keys(&:to_s))
92
+ .merge("version" => [document.version, @version].max)
93
+ body["updated_at"] = updated_at if updated_at
94
+ body[collection.to_s] = document.entries.map(&:to_h) if collection
95
+ body
92
96
  end
93
97
 
94
98
  private
@@ -263,13 +263,12 @@ module Samagotchi
263
263
  else
264
264
  SessionManager.spawn_session(prompt: nil, model_name: model && model_ref(model), state_dir: sd,
265
265
  client_id: nil,
266
- setup: SessionSetup.new(preloaded_memory_names: memories,
267
- muted_memory_names: muted_memories,
268
- llm_context: llm_context.empty? ? nil : LLMContextOverride.update(nil, llm_context),
269
- thinking: Thinking.session_level(thinking),
270
- appended_prompt_files: appended_prompt_files,
271
- toolkit: toolkit, settings: settings,
272
- parent_answers: parent_answers),
266
+ setup: SessionSetup.from_request(
267
+ memories: memories, muted: muted_memories,
268
+ llm_context: (LLMContextOverride.update(nil, llm_context) unless llm_context.empty?),
269
+ thinking: thinking, appended_prompt_files: appended_prompt_files,
270
+ toolkit: toolkit, settings: settings, parent_answers: parent_answers
271
+ ),
273
272
  scratch: scratch)
274
273
  end
275
274
  link = WorkerLink.await(session.id, session_dir: Session.session_dir(session.id, state_dir: sd), timeout: wait)