samagotchi 0.201.0 → 0.202.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 (175) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +57 -1
  3. data/docs/architecture.md +47 -7
  4. data/docs/cli.md +20 -1
  5. data/docs/configuration.md +2 -1
  6. data/docs/internals/bridge.md +4 -4
  7. data/docs/internals/engine.md +9 -6
  8. data/docs/internals/knowledge.md +26 -6
  9. data/docs/internals/objectives.md +2 -2
  10. data/docs/internals/pages.md +4 -2
  11. data/docs/internals/participants.md +1 -1
  12. data/docs/internals/peers.md +9 -7
  13. data/docs/internals/remote-sessions.md +6 -6
  14. data/docs/internals/session-lifecycle.md +37 -15
  15. data/docs/internals/web-frontend.md +18 -7
  16. data/docs/pages.md +6 -3
  17. data/docs/plugins.md +2 -2
  18. data/docs/scheduling.md +40 -12
  19. data/docs/sessions.md +48 -6
  20. data/docs/sub-agent.md +1 -2
  21. data/docs/testing.md +92 -8
  22. data/lib/samagotchi/answer_display.rb +3 -2
  23. data/lib/samagotchi/answer_tail.rb +4 -4
  24. data/lib/samagotchi/bridge/card_places.rb +5 -5
  25. data/lib/samagotchi/bridge/turn_accumulator.rb +5 -5
  26. data/lib/samagotchi/bridge/turn_drawings/synth.rb +5 -5
  27. data/lib/samagotchi/bridge/turn_drawings.rb +2 -2
  28. data/lib/samagotchi/bridge/turn_ranges.rb +15 -8
  29. data/lib/samagotchi/bridge.rb +5 -5
  30. data/lib/samagotchi/broadcast_command.rb +3 -3
  31. data/lib/samagotchi/bundle_command/try/trace.rb +18 -6
  32. data/lib/samagotchi/bundles/knowledge/embedder.rb +2 -0
  33. data/lib/samagotchi/bundles/knowledge/github.rb +19 -0
  34. data/lib/samagotchi/bundles/knowledge/manifest.yml +6 -6
  35. data/lib/samagotchi/bundles/knowledge/plugin.rb +26 -54
  36. data/lib/samagotchi/bundles/knowledge/refresh.rb +89 -14
  37. data/lib/samagotchi/bundles/knowledge/store.rb +36 -2
  38. data/lib/samagotchi/bundles/schedules/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +24 -3
  40. data/lib/samagotchi/bundles/system/config_modification_protocol.md +1 -1
  41. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  42. data/lib/samagotchi/bundles/system/skill_pages.md +1 -1
  43. data/lib/samagotchi/chi_invocation.rb +1 -1
  44. data/lib/samagotchi/child_move.rb +6 -3
  45. data/lib/samagotchi/child_reports.rb +3 -3
  46. data/lib/samagotchi/children_status.rb +4 -2
  47. data/lib/samagotchi/client_id.rb +2 -2
  48. data/lib/samagotchi/compat.rb +4 -6
  49. data/lib/samagotchi/config.rb +3 -0
  50. data/lib/samagotchi/context_note.rb +1 -1
  51. data/lib/samagotchi/continue_intent.rb +1 -1
  52. data/lib/samagotchi/continue_offer.rb +2 -2
  53. data/lib/samagotchi/continue_repair_backoff.rb +71 -0
  54. data/lib/samagotchi/delivery.rb +1 -4
  55. data/lib/samagotchi/engine/participants.rb +1 -1
  56. data/lib/samagotchi/engine/recap.rb +1 -1
  57. data/lib/samagotchi/engine/turn_end.rb +1 -1
  58. data/lib/samagotchi/grants.rb +2 -2
  59. data/lib/samagotchi/guardrail_wiring.rb +1 -1
  60. data/lib/samagotchi/guardrails/approval.rb +3 -3
  61. data/lib/samagotchi/guardrails/pair_boundary.rb +3 -3
  62. data/lib/samagotchi/guardrails/participant_refusal.rb +2 -2
  63. data/lib/samagotchi/idle_recap.rb +6 -6
  64. data/lib/samagotchi/kernel_loop.rb +1 -1
  65. data/lib/samagotchi/last_turn.rb +9 -6
  66. data/lib/samagotchi/llm/chat_loop.rb +5 -2
  67. data/lib/samagotchi/mcp_command.rb +2 -2
  68. data/lib/samagotchi/memory_usage.rb +7 -6
  69. data/lib/samagotchi/note_command.rb +1 -1
  70. data/lib/samagotchi/note_delivery.rb +5 -5
  71. data/lib/samagotchi/objectives_backing.rb +3 -3
  72. data/lib/samagotchi/objectives_record.rb +2 -2
  73. data/lib/samagotchi/objectives_track.rb +2 -2
  74. data/lib/samagotchi/owner_lock.rb +28 -2
  75. data/lib/samagotchi/owner_prompt.rb +3 -3
  76. data/lib/samagotchi/pages/runtime.rb +9 -4
  77. data/lib/samagotchi/participant_revise.rb +6 -6
  78. data/lib/samagotchi/peer_receipts.rb +11 -4
  79. data/lib/samagotchi/plugin/side_question.rb +1 -1
  80. data/lib/samagotchi/recap_place.rb +5 -5
  81. data/lib/samagotchi/reply_for.rb +3 -3
  82. data/lib/samagotchi/reply_wait/liveness.rb +2 -2
  83. data/lib/samagotchi/reply_wait/poll.rb +3 -3
  84. data/lib/samagotchi/schedule_command.rb +1 -1
  85. data/lib/samagotchi/schedule_display.rb +4 -3
  86. data/lib/samagotchi/schedules/busy_part.rb +29 -5
  87. data/lib/samagotchi/schedules/history_part.rb +47 -7
  88. data/lib/samagotchi/schedules/marks_part.rb +52 -29
  89. data/lib/samagotchi/schedules/notices_part.rb +31 -4
  90. data/lib/samagotchi/schedules/protection_part.rb +69 -11
  91. data/lib/samagotchi/schedules/prune_part.rb +3 -2
  92. data/lib/samagotchi/schedules.rb +37 -47
  93. data/lib/samagotchi/send_command.rb +12 -12
  94. data/lib/samagotchi/session.rb +71 -59
  95. data/lib/samagotchi/session_access/contract.rb +7 -0
  96. data/lib/samagotchi/session_access/exchange.rb +1 -1
  97. data/lib/samagotchi/session_access/local.rb +9 -9
  98. data/lib/samagotchi/session_access/remote.rb +20 -24
  99. data/lib/samagotchi/session_access.rb +1 -1
  100. data/lib/samagotchi/session_chain/delete.rb +15 -8
  101. data/lib/samagotchi/session_chain/delete_preview.rb +3 -3
  102. data/lib/samagotchi/session_chain/links.rb +18 -4
  103. data/lib/samagotchi/session_chain/successor.rb +1 -1
  104. data/lib/samagotchi/session_chain.rb +3 -3
  105. data/lib/samagotchi/session_continue.rb +83 -32
  106. data/lib/samagotchi/session_inbox.rb +6 -17
  107. data/lib/samagotchi/session_inbox_delivery.rb +36 -13
  108. data/lib/samagotchi/session_lifecycle/allowed.rb +5 -5
  109. data/lib/samagotchi/session_manager/delegate_rule.rb +2 -2
  110. data/lib/samagotchi/session_manager/delivery.rb +13 -38
  111. data/lib/samagotchi/session_manager/emptiness.rb +35 -15
  112. data/lib/samagotchi/session_manager/lifecycle.rb +3 -2
  113. data/lib/samagotchi/session_manager/listing.rb +35 -10
  114. data/lib/samagotchi/session_manager/removal.rb +16 -0
  115. data/lib/samagotchi/session_manager/spawn.rb +9 -6
  116. data/lib/samagotchi/session_manager.rb +6 -4
  117. data/lib/samagotchi/session_messages.rb +602 -0
  118. data/lib/samagotchi/session_metrics.rb +7 -4
  119. data/lib/samagotchi/session_participants.rb +4 -4
  120. data/lib/samagotchi/session_protection.rb +16 -2
  121. data/lib/samagotchi/session_retention.rb +26 -12
  122. data/lib/samagotchi/session_row.rb +1 -1
  123. data/lib/samagotchi/session_stats.rb +17 -8
  124. data/lib/samagotchi/session_stores.rb +5 -0
  125. data/lib/samagotchi/session_transition.rb +3 -2
  126. data/lib/samagotchi/sessions_command.rb +55 -3
  127. data/lib/samagotchi/steer.rb +16 -50
  128. data/lib/samagotchi/storage_migration.rb +234 -0
  129. data/lib/samagotchi/terminal_ui/attached_loop.rb +3 -3
  130. data/lib/samagotchi/terminal_ui/formatting.rb +5 -5
  131. data/lib/samagotchi/terminal_ui/join_replay.rb +3 -3
  132. data/lib/samagotchi/terminal_ui/question_prompt.rb +2 -2
  133. data/lib/samagotchi/toolkit_report_command.rb +1 -1
  134. data/lib/samagotchi/tools/ask_session.rb +2 -2
  135. data/lib/samagotchi/tools/send_note.rb +1 -1
  136. data/lib/samagotchi/turn_context.rb +3 -3
  137. data/lib/samagotchi/turn_endings.rb +17 -0
  138. data/lib/samagotchi/turn_excerpts.rb +7 -4
  139. data/lib/samagotchi/turn_flow.rb +1 -1
  140. data/lib/samagotchi/turn_note.rb +30 -2
  141. data/lib/samagotchi/turn_origin.rb +7 -7
  142. data/lib/samagotchi/turn_outcome.rb +11 -0
  143. data/lib/samagotchi/turn_stages/verify_anchors.rb +4 -4
  144. data/lib/samagotchi/verify_fresh.rb +6 -6
  145. data/lib/samagotchi/verify_fresh_origin.rb +4 -4
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +4 -3
  148. data/lib/samagotchi/web/last_ask.rb +2 -2
  149. data/lib/samagotchi/web/message_display.rb +12 -12
  150. data/lib/samagotchi/web/page_routes.rb +9 -3
  151. data/lib/samagotchi/web/participant_view.rb +4 -4
  152. data/lib/samagotchi/web/participants_admin.rb +1 -1
  153. data/lib/samagotchi/web/public/bubbles.js +1 -1
  154. data/lib/samagotchi/web/public/composer_fold.js +0 -3
  155. data/lib/samagotchi/web/public/composer_grip.js +0 -2
  156. data/lib/samagotchi/web/public/page_view.js +29 -4
  157. data/lib/samagotchi/web/public/participant_model.js +1 -1
  158. data/lib/samagotchi/web/public/peer_wait.js +2 -4
  159. data/lib/samagotchi/web/public/schedule_marks.js +2 -5
  160. data/lib/samagotchi/web/public/schedule_name.js +14 -0
  161. data/lib/samagotchi/web/public/session_actions.js +5 -0
  162. data/lib/samagotchi/web/public/start_page.js +1 -1
  163. data/lib/samagotchi/web/public/stop_sheet.js +2 -4
  164. data/lib/samagotchi/web/public/working_set_rail.js +0 -3
  165. data/lib/samagotchi/web/push/attention.rb +1 -1
  166. data/lib/samagotchi/web/session_create.rb +1 -1
  167. data/lib/samagotchi/web/session_hub.rb +68 -20
  168. data/lib/samagotchi/web/session_summary.rb +18 -14
  169. data/lib/samagotchi/web/verify_fresh_routes.rb +4 -4
  170. data/lib/samagotchi/worker/turn_drain.rb +158 -0
  171. data/lib/samagotchi/worker.rb +8 -144
  172. data/lib/samagotchi/worker_boot.rb +21 -5
  173. data/lib/samagotchi/worker_participant_gate.rb +5 -5
  174. data/lib/samagotchi/worker_presence.rb +24 -1
  175. metadata +6 -1
@@ -11,8 +11,9 @@ module Samagotchi
11
11
  # hold the words).
12
12
  #
13
13
  # A protector is what a PROTECTORS entry builds for a state dir, answering
14
- # three questions: #protected_ids (Array<String>), #hold(session_id) and
15
- # #chain_hold(session_id) (a Hold or nil). Schedules is the one protector
14
+ # four questions: #protected_ids (Array<String>), #hold(session_id) and
15
+ # #chain_hold(session_id) (a Hold or nil), and #holds(ids) (#hold of each,
16
+ # read once for the batch: id => Hold, the held ones only). Schedules is the one protector
16
17
  # (Schedules::ProtectionPart: an enabled schedule's anchor, head and
17
18
  # resolved target).
18
19
  #
@@ -69,6 +70,19 @@ module Samagotchi
69
70
  first_hold(session_id, state_dir) { |protector| protector.hold(session_id) }
70
71
  end
71
72
 
73
+ # #hold of each of +ids+, each protector asked once for the whole batch
74
+ # (a batch delete's check: one read of its store, one session listing);
75
+ # the first protector's hold wins per id. Fail-closed as #hold: one that
76
+ # raises raises for the batch. No ids asks no protector.
77
+ # @return [Hash{String => Hold}] the held ids only
78
+ def holds(ids, state_dir:)
79
+ return {} if ids.empty?
80
+
81
+ PROTECTORS.each_with_object({}) do |(name, build), held|
82
+ ask(name, build, state_dir) { |protector| protector.holds(ids) }.each { |sid, found| held[sid] ||= found }
83
+ end
84
+ end
85
+
72
86
  # @return [Hold, nil] the first protector's hold on a delete of the chain
73
87
  # +session_id+ belongs to
74
88
  def chain_hold(session_id, state_dir:)
@@ -3,6 +3,7 @@
3
3
  require "fileutils"
4
4
  require "time"
5
5
  require_relative "session"
6
+ require_relative "analytics_file"
6
7
  require_relative "archive_store"
7
8
  require_relative "worker_presence"
8
9
  require_relative "starting_marker"
@@ -58,14 +59,14 @@ module Samagotchi
58
59
  alive_check: ->(sid) { owned?(sid, sd) },
59
60
  empty_check: discard ? ->(sid) { left_empty?(sid, state_dir: sd, default_model: default_model) } : nil
60
61
  )
61
- result[:deleted].concat(prune_orphan_dirs(sd, dry_run: dry_run)) if discard && !test_only
62
+ result[:deleted].concat(prune_orphan_dirs(sd, dry_run: dry_run, days: days)) if discard && !test_only
62
63
  result
63
64
  end
64
65
 
65
66
  # Someone holds the session's owner lock (a worker, a one-turn run).
66
67
  private_class_method def self.owned?(session_id, state_dir)
67
68
  WorkerPresence.read(session_id, state_dir: state_dir,
68
- owner: SessionManager.session_owner(session_id, state_dir: state_dir)).owned?
69
+ owner: OwnerLock.for_session(session_id, state_dir: state_dir)).owned?
69
70
  end
70
71
 
71
72
  private_class_method def self.left_empty?(session_id, state_dir:, default_model:)
@@ -78,27 +79,32 @@ module Samagotchi
78
79
 
79
80
  # Directories with no session file and nothing but the skeleton, nobody
80
81
  # owning them: a one-shot killed before its first save, or a worker woken
81
- # just as its session was discarded. Removed as a delete removes
82
+ # just as its session was discarded. Also, once older than +days+
83
+ # (session.retention_days: the age a saved session goes at; 0 keeps
84
+ # them), one holding the skeleton and an analytics.json with turns
85
+ # (SessionManager.analytics_only_dir?): what a session whose file went
86
+ # left behind; nothing reads it without the file. Removed as a delete removes
82
87
  # (SessionManager.remove_files: every SESSION_STATE_STORES store), which
83
88
  # reads the owner lock, the starting marker and #orphan_dir? again under
84
89
  # that lock: a worker or a start that took the session since the check,
85
90
  # or a session file or content written meanwhile, keeps it.
86
91
  # @return [Array<String>] their ids
87
- private_class_method def self.prune_orphan_dirs(state_dir, dry_run:)
92
+ private_class_method def self.prune_orphan_dirs(state_dir, dry_run:, days:)
88
93
  return [] unless Dir.exist?(state_dir)
89
94
 
95
+ window = days.to_i.positive? ? days.to_i * 86_400 : nil
90
96
  removed = Dir.children(state_dir).filter_map do |name|
91
97
  dir = File.join(state_dir, name)
92
98
  path = File.join(state_dir, "#{name}#{SessionPaths::FILE_EXT}")
93
99
  next unless Session.valid_id?(name) && File.directory?(dir)
94
- next unless Time.now - File.mtime(dir) > EMPTY_GRACE_SECONDS && orphan_dir?(path, dir)
100
+ next unless Time.now - File.mtime(dir) > EMPTY_GRACE_SECONDS && orphan_dir?(path, dir, window)
95
101
  next if owned?(name, state_dir) || starting?(name, state_dir)
96
102
 
97
103
  unless dry_run
98
104
  policy = SessionManager::RunningTasks::Policy.stop(by: "retention")
99
105
  gone = unheld(name, state_dir) do
100
106
  SessionManager.remove_files(name, path, dir, state_dir: state_dir, purge_runs: false,
101
- still: -> { orphan_dir?(path, dir) }, running_tasks: policy)
107
+ still: -> { orphan_dir?(path, dir, window) }, running_tasks: policy)
102
108
  end
103
109
  SessionManager::RunningTasks.log_automatic!(policy)
104
110
  next unless gone
@@ -111,11 +117,19 @@ module Samagotchi
111
117
  removed
112
118
  end
113
119
 
114
- # No session file, and a folder holding only the skeleton. Not its age:
115
- # read again under the owner lock, whose file the lock may have just
116
- # made.
117
- private_class_method def self.orphan_dir?(path, dir)
118
- !File.exist?(path) && SessionManager.empty_session_dir?(dir)
120
+ # No session file, and a folder holding only the skeleton, or (+window+
121
+ # seconds given) the skeleton and an analytics.json with turns not
122
+ # written for +window+ (the file's own age: the sweep's transition hold makes
123
+ # continue.lock in the folder). Not the skeleton's age: read again under the
124
+ # owner lock, whose file the lock may have just made.
125
+ private_class_method def self.orphan_dir?(path, dir, window)
126
+ return false if File.exist?(path)
127
+ return true if SessionManager.empty_session_dir?(dir)
128
+
129
+ !window.nil? && SessionManager.analytics_only_dir?(dir) &&
130
+ Time.now - File.mtime(AnalyticsFile.path(dir)) > window
131
+ rescue SystemCallError
132
+ false
119
133
  end
120
134
 
121
135
  # A worker is being started for it (every spawn marks it, a new
@@ -188,7 +202,7 @@ module Samagotchi
188
202
  # (the skeleton-only dirs here, the saved runs after).
189
203
  private_class_method def self.skipped_round(state_dir, error)
190
204
  Log.warn(:worker, "retention_skipped", msg: error.message)
191
- prune_orphan_dirs(state_dir, dry_run: false) if SessionManager.discard_empty?
205
+ prune_orphan_dirs(state_dir, dry_run: false, days: resolve_days(nil)) if SessionManager.discard_empty?
192
206
  nil
193
207
  end
194
208
 
@@ -61,7 +61,7 @@ module Samagotchi
61
61
  # @param session [Session] a saved session
62
62
  # @param session_dir [String] its folder
63
63
  # @param owner [OwnerLock::Owner, nil] the lock's holder as read
64
- # (SessionManager.session_owner)
64
+ # (OwnerLock.for_session)
65
65
  # @param link [WorkerLink outcome, nil] resolved with +owner+; nil:
66
66
  # resolved here (one read of bridge.json)
67
67
  # @param roots [Hash] ProjectScope.root_for's cache, shared by a listing
@@ -4,6 +4,7 @@ require "json"
4
4
  require "time"
5
5
  require_relative "session"
6
6
  require_relative "session_paths"
7
+ require_relative "session_messages"
7
8
  require_relative "analytics_file"
8
9
  require_relative "bridge/card_store"
9
10
  require_relative "client_id"
@@ -13,7 +14,6 @@ require_relative "hook_label"
13
14
  require_relative "session_window"
14
15
  require_relative "model_ref"
15
16
  require_relative "message_time"
16
- require_relative "steer"
17
17
  require_relative "speaker"
18
18
  require_relative "paths"
19
19
 
@@ -48,9 +48,12 @@ module Samagotchi
48
48
  # not a plugin's, never counted as one.
49
49
  CHI_OWN_HOOKS = %w[model thinking].freeze
50
50
 
51
- # A failed turn's kind, from its failure line (summary, else message,
52
- # else error class) by the first rule that matches; "none" when it has
53
- # no line at all. Only the word is kept, never the line.
51
+ # A failed turn's kind: by its error_kind (the code SessionMetrics keeps
52
+ # beside the line, KIND_FAILURES) when that names one kind for sure,
53
+ # else from its failure line (summary, else message, else error class)
54
+ # by the first rule that matches (a record from before the code, and
55
+ # the coarse codes: bad_request, provider, connection, chi_error…);
56
+ # "none" when it has no line at all. Only the word is kept, never the line.
54
57
  FAILURE_KINDS = %w[host_model_not_found host_rejected host_error timeout host_unreachable context_overflow
55
58
  empty_answer other none].freeze
56
59
  FAILURE_RULES = [
@@ -62,6 +65,10 @@ module Samagotchi
62
65
  ["context_overflow", /context|too long|exceed/i],
63
66
  ["empty_answer", /empty/i]
64
67
  ].freeze
68
+ # The error kinds (LLM::ProviderError#kind) that are one FAILURE_KINDS
69
+ # word whatever the line says.
70
+ KIND_FAILURES = { "first_token_timeout" => "timeout", "stream_stalled" => "timeout",
71
+ "server" => "host_error" }.freeze
65
72
 
66
73
  # Who stopped a canceled turn: you (the user's Stop or Ctrl-C, a
67
74
  # participant's cancel included), a hook, the worker going mid-turn
@@ -305,6 +312,9 @@ module Samagotchi
305
312
  # @return [String] a FAILURE_KINDS word
306
313
  def failure_kind(failure)
307
314
  failure = {} unless failure.is_a?(Hash)
315
+ by_kind = KIND_FAILURES[failure["error_kind"]]
316
+ return by_kind if by_kind
317
+
308
318
  line = %w[summary message error_class].map { |key| failure[key] }.find { |v| v.is_a?(String) && !v.strip.empty? }
309
319
  return "none" unless line
310
320
 
@@ -317,8 +327,7 @@ module Samagotchi
317
327
  # Only role, kind, source, author, turn_start and the time are looked at.
318
328
  # @return [Array(Integer, Hash, Integer)] lines, steers, unreadable files
319
329
  def message_counts(id, since)
320
- data = JSON.parse(File.read(Session.session_file(id)))
321
- messages = data.is_a?(Hash) && data["messages"].is_a?(Array) ? data["messages"] : []
330
+ messages = SessionMessages.read(Session.session_file(id))
322
331
  lines = 0
323
332
  steers = Hash.new(0)
324
333
  messages.each do |message|
@@ -326,9 +335,9 @@ module Samagotchi
326
335
  next unless (at = time(message[MessageTime::KEY.to_s])) && at >= since
327
336
 
328
337
  case message["kind"]
329
- when Steer::INPUT_KIND
338
+ when Speaker::INPUT_KIND
330
339
  lines += 1 if Speaker.of(message) == :owner && !message["turn_start"]
331
- when Steer::KIND then steers[message["source"].to_s] += 1
340
+ when Speaker::KIND then steers[message["source"].to_s] += 1
332
341
  end
333
342
  end
334
343
  [lines, steers.to_h.freeze, 0]
@@ -30,6 +30,11 @@ module Samagotchi
30
30
  "SessionContinue :peers); a say there goes to the chain's live link"
31
31
 
32
32
  STORES = [
33
+ # The conversation of a split session (session.split_messages): <id>.json names its generation.
34
+ Store.new(file: "messages-<gen>.jsonl", owner: "SessionMessages", removal: :session_files, cross_version: true,
35
+ continue: "the conversation stays with the previous link; the new link saves its own", corpus_dir: nil,
36
+ corpus_exception: "a generation-named file: ReleaseTools records the compat-split session, " \
37
+ "readers_spec loads it"),
33
38
  Store.new(file: "archived", owner: "ArchiveStore", removal: :session_files, cross_version: true,
34
39
  continue: "the archived link remains its own session", corpus_dir: SIDE_CAR),
35
40
  Store.new(file: "state.json", owner: "PluginSessionState", removal: :plugin_session_state, cross_version: false,
@@ -38,7 +38,8 @@ module Samagotchi
38
38
  # one. It owns its refusal text, which names the holder (.held) when it
39
39
  # can be told: a continue ("being continued", "as X" once its intent
40
40
  # names the new link), a delete ("being deleted"), a stop ("being
41
- # stopped"), an archive ("being archived"), else "busy with another
41
+ # stopped"), an archive ("being archived"), a storage migration
42
+ # (StorageMigration: "being migrated"), else "busy with another
42
43
  # change" (a shared holder, an older chi's, a kind this chi doesn't
43
44
  # name). A nil +session_id+ says "this session" (a peer's line,
44
45
  # which carries no id).
@@ -50,7 +51,7 @@ module Samagotchi
50
51
  # Every other taker's #message is #retry_message.
51
52
  class Busy < StandardError
52
53
  WORDS = { continue: "being continued", delete: "being deleted", stop: "being stopped", archive: "being archived",
53
- nil => "busy with another change" }.freeze
54
+ migrate: "being migrated", nil => "busy with another change" }.freeze
54
55
  # The holders a stop doesn't wait for (#transition?): a delete or an
55
56
  # archive, a continue once it names its new link.
56
57
  TRANSITIONS = %i[delete archive continue].freeze
@@ -21,14 +21,14 @@ require_relative "session_access/local"
21
21
 
22
22
  module Samagotchi
23
23
  # `chi sessions`: list, stop, restart, archive/unarchive, delete, prune,
24
- # clean and stats sessions from the shell (bin/chi dispatches here before
24
+ # clean, stats and migrate sessions from the shell (bin/chi dispatches here before
25
25
  # OptionParser; the subcommands have their own flags). Not SessionCommands,
26
26
  # the slash commands a session's worker runs (session_commands.rb).
27
27
  class SessionsCommand
28
28
  include CLI::Command
29
29
 
30
30
  USAGE = <<~TEXT
31
- Usage: chi sessions <list|stop|restart|archive|unarchive|delete|prune|clean|stats> [options]
31
+ Usage: chi sessions <list|stop|restart|archive|unarchive|delete|prune|clean|stats|migrate> [options]
32
32
  list [--sort updated_at|created_at] [--order desc|asc] [--limit N]
33
33
  [--live] [--cwd PATH] [--format text|json|tsv] [--archived]
34
34
  --live: sessions a worker runs now (the ones chi note reaches), 10 unless --limit
@@ -44,6 +44,9 @@ module Samagotchi
44
44
  --all: every session, not only test and scratch ones (by the age and count limits, as prune)
45
45
  stats ID [--format text|json] # a session's cost, tokens, progress and own settings, without running a model turn:
46
46
  a live worker's GET stats, else the snapshot its saved analytics.json rebuilds (never starts a worker)
47
+ migrate [--dry-run] [--id ID]... [--json] # move saved sessions to the current storage format (StorageMigration):
48
+ their messages beside <id>.json (needs session.split_messages on; --dry-run reports either way);
49
+ a session a worker holds is left to convert at its own next save
47
50
  Defaults: days=14 keep=500 keep_status=none (config: session.retention_days, session.max_count, session.keep_status)
48
51
  TEXT
49
52
 
@@ -53,7 +56,7 @@ module Samagotchi
53
56
  # How long `stats` waits for a live worker's GET stats before reading the
54
57
  # saved analytics.json instead (a stuck worker must not hold a driver).
55
58
  STATS_TIMEOUT = 3
56
- SUBCOMMANDS = %w[list stop restart archive unarchive delete prune clean stats].freeze
59
+ SUBCOMMANDS = %w[list stop restart archive unarchive delete prune clean stats migrate].freeze
57
60
 
58
61
  # Each subcommand's flags ("--flag V" or "--flag=V" for a value): an
59
62
  # unknown flag, a value flag with nothing after it or an argument where
@@ -79,6 +82,11 @@ module Samagotchi
79
82
  f.value "--days"
80
83
  f.switch "--dry-run"
81
84
  f.switch "--all"
85
+ end,
86
+ "migrate" => CLI::Flags.new(args: false) do |f|
87
+ f.value "--id", key: :ids, repeat: true
88
+ f.switch "--dry-run"
89
+ f.switch "--json"
82
90
  end
83
91
  }.freeze
84
92
  INTEGER_OPTIONS = %i[days keep limit].freeze
@@ -125,6 +133,7 @@ module Samagotchi
125
133
  when "stop" then stop(parsed.args)
126
134
  when "restart" then restart(parsed.args)
127
135
  when "stats" then stats(parsed.args)
136
+ when "migrate" then migrate
128
137
  else prune(@sub)
129
138
  end
130
139
  end
@@ -373,6 +382,49 @@ module Samagotchi
373
382
  "Restarted session #{result.session_id} on chi #{result.version}#{from}."
374
383
  end
375
384
 
385
+ # Local only (SessionAccess::Contract): this machine's saved sessions
386
+ # through StorageMigration's steps. A conversion needs
387
+ # session.split_messages on: chi 0.201.0 and older read a split session
388
+ # as empty.
389
+ def migrate
390
+ require_relative "storage_migration"
391
+ dry_run = @opts[:dry_run] == true
392
+ unless dry_run || SessionMessages.split?
393
+ @stderr.puts "chi sessions migrate: split sessions read as empty in chi 0.201.0 and older: " \
394
+ "turn on session.split_messages first (--dry-run reports without it)"
395
+ return 2
396
+ end
397
+
398
+ ids = @opts[:ids]&.map { |id| Session.resolve_id(id) }&.uniq
399
+ unknown = ids&.reject { |id| Session.exist?(id) }
400
+ if unknown&.any?
401
+ @stderr.puts "chi sessions migrate: no session #{unknown.join(", ")}"
402
+ return 1
403
+ end
404
+
405
+ report = StorageMigration.run(dry_run: dry_run, ids: ids)
406
+ @stdout.puts(@opts[:json] ? JSON.generate(report.to_h) : migrate_lines(report))
407
+ report.steps.any? { |step| step.failed.any? } ? 1 : 0
408
+ rescue Session::AmbiguousId => e
409
+ @stderr.puts e.message
410
+ 1
411
+ end
412
+
413
+ def migrate_lines(report)
414
+ lines = report.steps.flat_map do |step|
415
+ moved = report.dry_run ? "would convert #{step.pending.size}" : "converted #{step.converted.size}"
416
+ skipped = step.skipped.map { |reason, ids| "#{reason} #{ids.size}" }.join(", ")
417
+ bytes = report.dry_run ? mb(step.bytes_before) : "#{mb(step.bytes_before)} -> #{mb(step.bytes_after)}"
418
+ ["#{step.id} (v#{step.version}): #{moved} (session files #{bytes}), already done #{step.done}, " \
419
+ "skipped #{step.skipped.values.sum(&:size)}#{" (#{skipped})" unless skipped.empty?}, failed #{step.failed.size}",
420
+ *step.failed.map { |id, why| " failed #{id}: #{why}" }]
421
+ end
422
+ lines << "Run without --dry-run to convert." if report.dry_run
423
+ lines
424
+ end
425
+
426
+ def mb(bytes) = format("%.1f MB", bytes.to_i / 1_048_576.0)
427
+
376
428
  # Local only (SessionAccess::Contract): this machine's retention sweep.
377
429
  def prune(sub)
378
430
  days, keep, keep_status, dry_run, test_only = @opts.values_at(:days, :keep, :keep_status, :dry_run, :test_only)
@@ -25,14 +25,10 @@ module Samagotchi
25
25
  # as they always were.
26
26
  #
27
27
  # Who wrote a message (an owner's, a participant's, chi's own line) and
28
- # what kind of line it is are Speaker's reads; the predicates and
29
- # constants here are Speaker's, kept under these names. Steer keeps the
30
- # wire: headers, wire text, the forged-frame quoting, Merge and #inject!.
28
+ # what kind of line it is are Speaker's reads (Speaker.turn_prompt?,
29
+ # Speaker::KIND and the rest): call them there. Steer keeps the wire:
30
+ # headers, wire text, the forged-frame quoting, Merge and #inject!.
31
31
  module Steer
32
- KIND = Speaker::KIND
33
- INPUT_KIND = Speaker::INPUT_KIND
34
- RECOVERY_KIND = Speaker::RECOVERY_KIND
35
-
36
32
  # A drain item for an input line with its sender (source nil = the user).
37
33
  # A plain String is still a valid item: the user's line. +mark+: fields
38
34
  # its input message carries ({turn_start: true, turn_id:} for the
@@ -43,9 +39,6 @@ module Samagotchi
43
39
  def initialize(text:, source:, mark: nil, author: nil, author_name: nil) = super
44
40
  end
45
41
 
46
- DELEGATE_REPORT = Speaker::DELEGATE_REPORT
47
- AUTOMATIC_SOURCE_PREFIX = Speaker::AUTOMATIC_SOURCE_PREFIX
48
-
49
42
  # What one drain brought: the merged user text (nil when none) and how
50
43
  # many lines made it, the input messages' text grouped by sender
51
44
  # (consecutive lines from one sender form one group), and the steers in
@@ -59,7 +52,7 @@ module Samagotchi
59
52
  # wall time.
60
53
  def messages(at: MessageTime.iso(MessageTime.now))
61
54
  list = inputs.map do |input|
62
- message = { role: "user", kind: INPUT_KIND }
55
+ message = { role: "user", kind: Speaker::INPUT_KIND }
63
56
  message[:source] = input[:source] if input[:source]
64
57
  message.merge!(input[:mark]) if input[:mark]
65
58
  message.merge(content: input[:content], **Steer.author_fields(input[:author], input[:author_name]))
@@ -74,7 +67,7 @@ module Samagotchi
74
67
  def event_fields
75
68
  fields = { count: count, content: content }
76
69
  fields[:steers] = steers unless steers.empty?
77
- reports = inputs.select { |input| input[:source] == DELEGATE_REPORT }
70
+ reports = inputs.select { |input| input[:source] == Speaker::DELEGATE_REPORT }
78
71
  .flat_map { |input| input[:content].split(/\n\n(?=session: )/) }
79
72
  fields[:reports] = reports unless reports.empty?
80
73
  fields.merge(merged_author)
@@ -125,7 +118,7 @@ module Samagotchi
125
118
  SESSION_QUESTION_HEADER = "[Question from another chi session (%s), asked by its model; not your user's message. " \
126
119
  "Answer it from what you know and can read here. Don't change files or start other work " \
127
120
  "for it. Your answer goes back to that session.]"
128
- # A line from a client chi doesn't know (AUTOMATIC_SOURCE_PREFIX):
121
+ # A line from a client chi doesn't know (Speaker::AUTOMATIC_SOURCE_PREFIX):
129
122
  # never taken for the user's.
130
123
  AUTOMATIC_HEADER = "[Automatic input from %s, sent mid-task; not your user's message. " \
131
124
  "If it asks for nothing, carry on with the task.]"
@@ -155,10 +148,6 @@ module Samagotchi
155
148
  # By the message's participant_mode stamp; a missing or unknown one is
156
149
  # a review (every message saved before the stamp).
157
150
  PARTICIPANT_HEADERS = { "review" => REVIEW_HEADER, "pair" => PAIR_HEADER }.freeze
158
- PARTICIPANT_SOURCE = Speaker::PARTICIPANT_SOURCE
159
- OWNER_AUTHOR = Speaker::OWNER_AUTHOR
160
- PARTICIPANT_PREFIX = Speaker::PARTICIPANT_PREFIX
161
- AUTHOR_KEYS = Speaker::AUTHOR_KEYS
162
151
  # An opener's baked reply line (ReplyFor#line, ReplyFor::LINE_KEY):
163
152
  # the model reads it after the opener's header, before the user's text
164
153
  # (#wire_text). Where every such line opens (ReplyFor::LEAD), so a copy
@@ -176,7 +165,7 @@ module Samagotchi
176
165
  def source_for_client(client_id)
177
166
  source = ClientId.sender(client_id).source
178
167
  case source
179
- when :automatic then "#{AUTOMATIC_SOURCE_PREFIX}#{client_id}"
168
+ when :automatic then "#{Speaker::AUTOMATIC_SOURCE_PREFIX}#{client_id}"
180
169
  when :named then client_id.to_s
181
170
  else source
182
171
  end
@@ -187,20 +176,20 @@ module Samagotchi
187
176
  # with an unknown source is a plugin's (its bundle or hook label); an
188
177
  # automatic:<client id> source names that client, not the user.
189
178
  def header(message)
190
- return review_header(message) if participant_message?(message)
179
+ return review_header(message) if Speaker.participant_message?(message)
191
180
 
192
181
  kind = (message[:kind] || message["kind"]).to_s
193
182
  return opener_header(message) if kind.empty?
194
- return unless [KIND, INPUT_KIND].include?(kind)
183
+ return unless [Speaker::KIND, Speaker::INPUT_KIND].include?(kind)
195
184
 
196
185
  source = (message[:source] || message["source"]).to_s
197
186
  return HEADERS[source] if HEADERS.key?(source)
198
187
  return format(AGENT_STEER_HEADER, ClientId.agent_name(source)) if ClientId.agent?(source)
199
188
  return format(SESSION_QUESTION_HEADER, ClientId.session_name(source)) if ClientId.session?(source)
200
- return automatic_header(source.delete_prefix(AUTOMATIC_SOURCE_PREFIX)) if source.start_with?(AUTOMATIC_SOURCE_PREFIX)
189
+ return automatic_header(source.delete_prefix(Speaker::AUTOMATIC_SOURCE_PREFIX)) if source.start_with?(Speaker::AUTOMATIC_SOURCE_PREFIX)
201
190
 
202
191
  source = "user" if source.empty?
203
- sender = SENDERS[source] || (kind == KIND ? "from the #{source} plugin" : SENDERS["user"])
192
+ sender = SENDERS[source] || (kind == Speaker::KIND ? "from the #{source} plugin" : SENDERS["user"])
204
193
  "[Steer #{sender}, #{HEADER_TAIL}"
205
194
  end
206
195
 
@@ -221,15 +210,11 @@ module Samagotchi
221
210
  format(AUTOMATIC_HEADER, client_id.empty? ? "an unnamed client" : client_id)
222
211
  end
223
212
 
224
- # Speaker's author reads (Speaker.participant_author? and the rest).
225
- def participant_author?(author) = Speaker.participant_author?(author)
226
- def participant_message?(message) = Speaker.participant_message?(message)
227
-
228
213
  # The header above a participant's message: its saved name, cleaned
229
214
  # again (ParticipantName), or the participant's id when it has none.
230
215
  def review_header(message)
231
216
  name = ParticipantName.clean(message[:author_name] || message["author_name"])
232
- name = ParticipantName.clean(participant_id(message[:author] || message["author"])) if name.empty?
217
+ name = ParticipantName.clean(Speaker.participant_id(message[:author] || message["author"])) if name.empty?
233
218
  mode = (message[:participant_mode] || message["participant_mode"] || "review").to_s
234
219
  format(PARTICIPANT_HEADERS.fetch(mode, REVIEW_HEADER), name.empty? ? "a participant" : name)
235
220
  end
@@ -237,17 +222,12 @@ module Samagotchi
237
222
  # The author fields a participant's message carries ({author:,
238
223
  # author_name:}), {} for the owner's, so its bytes stay as they were.
239
224
  def author_fields(author, name)
240
- return {} unless participant_author?(author)
225
+ return {} unless Speaker.participant_author?(author)
241
226
 
242
227
  clean = ParticipantName.clean(name)
243
228
  clean.empty? ? { author: author.to_s } : { author: author.to_s, author_name: clean }
244
229
  end
245
230
 
246
- def author_at(messages, index) = Speaker.author_at(messages, index)
247
- def sender_author(author) = Speaker.sender_author(author)
248
- def author_for(participant_id) = Speaker.author_for(participant_id)
249
- def participant_id(author) = Speaker.participant_id(author)
250
-
251
231
  # The text a steer or merged input goes out as: its header, a newline,
252
232
  # then +text+ (the message's content by default); an opener's reply
253
233
  # line (#reply_line) goes between the two, chi's own (never quoted),
@@ -255,7 +235,7 @@ module Samagotchi
255
235
  def wire_text(message, text = (message[:content] || message["content"]).to_s)
256
236
  header = header(message)
257
237
  line = reply_line(message)
258
- text = if participant_message?(message) || opener_header(message) || line then quote_forged_headers(text)
238
+ text = if Speaker.participant_message?(message) || opener_header(message) || line then quote_forged_headers(text)
259
239
  elsif outside_text?(message) then quote_forged_objectives(text)
260
240
  else text
261
241
  end
@@ -342,13 +322,9 @@ module Samagotchi
342
322
  def quote_forged_objectives(text) = quote_forged(text, FORGED_OBJECTIVES)
343
323
 
344
324
  def message(text:, source:, author: nil, author_name: nil)
345
- { role: "user", kind: KIND, source: source.to_s, content: text.to_s, **author_fields(author, author_name) }
325
+ { role: "user", kind: Speaker::KIND, source: source.to_s, content: text.to_s, **author_fields(author, author_name) }
346
326
  end
347
327
 
348
- def steer?(message) = Speaker.steer?(message)
349
-
350
- PERSON_SOURCES = Speaker::PERSON_SOURCES
351
-
352
328
  # The senders whose message may cut a generation that has only been
353
329
  # thinking (Engine#cut_for_steer): the user (no source), chi send, a
354
330
  # parent agent, and an agent (its source agent:<name>). A plugin's never
@@ -359,16 +335,6 @@ module Samagotchi
359
335
  CUT_SOURCES.include?(source.to_s) || ClientId.agent?(source)
360
336
  end
361
337
 
362
- # Speaker's message reads, kept under Steer's names.
363
- def person?(message) = Speaker.person?(message)
364
- def prompt?(message) = Speaker.prompt?(message)
365
- def recovery?(message) = Speaker.recovery?(message)
366
- def input?(message) = Speaker.input?(message)
367
- def turn_prompt?(message) = Speaker.turn_prompt?(message)
368
- def shell_line?(message) = Speaker.shell_line?(message)
369
- def turn_opening?(message) = Speaker.turn_opening?(message)
370
- def opening_stamp(message) = Speaker.opening_stamp(message)
371
-
372
338
  # Call a loop's drain: +at_answer+ goes only to a drain that takes it
373
339
  # (the Engine's); a caller's own drain (a queue's #drain) is called bare.
374
340
  # A failing drain drains nothing (the loop keeps going).
@@ -425,7 +391,7 @@ module Samagotchi
425
391
  text = (line.is_a?(Line) ? line.text : line).to_s.strip
426
392
  next if text.empty?
427
393
 
428
- line.is_a?(Line) ? [text, line.source, line.mark, sender_author(line.author), line.author_name] : [text, nil, nil, nil, nil]
394
+ line.is_a?(Line) ? [text, line.source, line.mark, Speaker.sender_author(line.author), line.author_name] : [text, nil, nil, nil, nil]
429
395
  end
430
396
  pairs.chunk_while { |a, b| a[1] == b[1] && a[3] == b[3] }.map do |run|
431
397
  first = run.first