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
@@ -28,6 +28,11 @@ require_relative "project_scope"
28
28
  require_relative "guardrails/parent_levels"
29
29
 
30
30
  module Samagotchi
31
+ # Loaded on first use (the first session built or read), not with this
32
+ # file: keeps the bundle test kit's load budget
33
+ # (spec/samagotchi/testing/sandbox_spec.rb).
34
+ autoload :SessionMessages, File.expand_path("session_messages", __dir__)
35
+
31
36
  # Loaded on first use (a Verify fresh child): keeps the bundle test kit's
32
37
  # load budget (spec/samagotchi/testing/sandbox_spec.rb).
33
38
  autoload :VerifyFreshOrigin, File.expand_path("verify_fresh_origin", __dir__)
@@ -82,7 +87,6 @@ module Samagotchi
82
87
  NAMES = ->(names) { name_list(names) }
83
88
  LIST = ->(value) { Array(value) }
84
89
  ID = ->(value) { value&.to_s }
85
- MESSAGES = ->(messages) { SessionField.scrub_utf8(messages.map { |msg| SessionField.stringify_keys(msg) }) }
86
90
  # A text the user typed or pasted (a prompt, a title): the file gets it
87
91
  # as valid UTF-8 (nil stays nil), the session keeps what it was given.
88
92
  SCRUBBED = ->(value) { SessionField.scrub_utf8(value) }
@@ -108,7 +112,7 @@ module Samagotchi
108
112
  else level
109
113
  end
110
114
  end
111
- private_constant :BOOLEAN, :NAMES, :LIST, :ID, :MESSAGES, :SCRUBBED, :VERDICTS, :TOOLKIT_ORIGIN, :TOOLKIT_ORIGIN_UNREAD, :KEPT_FIRST,
115
+ private_constant :BOOLEAN, :NAMES, :LIST, :ID, :SCRUBBED, :VERDICTS, :TOOLKIT_ORIGIN, :TOOLKIT_ORIGIN_UNREAD, :KEPT_FIRST,
112
116
  :PARENT_ANSWERS
113
117
 
114
118
  # The fields of <id>.json, in the order #save writes them: key => its
@@ -145,9 +149,10 @@ module Samagotchi
145
149
  # nil. The models: lookup takes it (HostRegistry#lookup_names).
146
150
  SessionField.plain("model_typed", nil),
147
151
  SessionField.plain("working_directory", REQUIRED),
148
- # The conversation (symbol keys in memory; .from_h symbolizes a
149
- # file's); a running turn's checkpoint is saved in its place (#to_h).
150
- SessionField.plain("messages", [], fresh: REQUIRED, write: MESSAGES),
152
+ # The conversation (symbol keys in memory; how the file holds it is
153
+ # SessionMessages'); a running turn's checkpoint is saved in its place
154
+ # (#to_h).
155
+ SessionField.plain("messages", [], fresh: REQUIRED, write: ->(messages) { SessionMessages.dump(messages) }),
151
156
  SessionField.plain("created_at", REQUIRED),
152
157
  SessionField.plain("updated_at", REQUIRED),
153
158
  SessionField.plain("status", STATUS_IDLE),
@@ -510,6 +515,9 @@ module Samagotchi
510
515
  # file is there to rewrite, and one gone was deleted (#save doesn't
511
516
  # bring it back).
512
517
  @persisted = false
518
+ # How #save writes the messages, and what it wrote last (.from_file
519
+ # gives it the file's).
520
+ @messages_store = SessionMessages::Store.new
513
521
  end
514
522
 
515
523
  # Whether a chi newer than this one saved the loaded file: its
@@ -650,14 +658,17 @@ module Samagotchi
650
658
  valid_id?(session_id) && File.exist?(session_path(session_id, state_dir: state_dir))
651
659
  end
652
660
 
661
+ # +messages+ false leaves the conversation out (#messages is [], and
662
+ # #save raises LoadedWithoutMessages): for a caller that reads only the
663
+ # rest of the session.
653
664
  # @raise [NotFound] no such session (an id that isn't one too)
654
- def self.load(session_id, state_dir: default_state_dir)
665
+ def self.load(session_id, state_dir: default_state_dir, messages: true)
655
666
  raise NotFound, session_id unless valid_id?(session_id)
656
667
 
657
668
  path = session_path(session_id, state_dir: state_dir)
658
669
  raise NotFound, session_id unless File.exist?(path)
659
670
 
660
- session = from_h(JSON.parse(File.read(path)))
671
+ session = SessionMessages.parse(path) { |data| from_file(data, path: path, messages: messages) }
661
672
  session.persisted!
662
673
  session.loaded_status = session.status
663
674
  session.status = STATUS_STOPPED if stopped_marker?(session.id, state_dir: state_dir)
@@ -665,18 +676,30 @@ module Samagotchi
665
676
  session
666
677
  rescue JSON::ParserError => e
667
678
  raise ArgumentError, "Session file corrupted (#{session_id}): #{e.message}"
679
+ rescue Errno::ENOENT
680
+ raise NotFound, session_id
668
681
  end
669
682
 
670
- # A session from a parsed session file. +messages+ false leaves the
671
- # conversation out (the lists' lightweight summaries).
683
+ # The session file at +path+, parsed (+data+), as a Session: the one
684
+ # place a file becomes one (SessionMessages::Store.from_file reads the
685
+ # messages). +messages+ false leaves them out unread: #save then raises.
686
+ # @raise [KeyError] for a missing REQUIRED field
687
+ def self.from_file(data, path:, messages: true)
688
+ store = SessionMessages::Store.from_file(data, path: path, messages: messages)
689
+ from_h(data, messages: false).tap { |session| session.messages_store = store }
690
+ end
691
+
692
+ # A session from a session file's mapping, its messages inline (a #to_h
693
+ # round trip; a file is read with .from_file). +messages+ false leaves
694
+ # the conversation out.
672
695
  # @raise [KeyError] for a missing REQUIRED field
673
696
  def self.from_h(data, messages: true)
674
697
  attrs = FIELDS.to_h do |key, field|
675
698
  [key.to_sym, field.required? ? data.fetch(key) : data.fetch(key, field.default)]
676
699
  end
677
700
  attrs[:settings] = SessionConfig::Settings.new(core: attrs.delete(:config_settings), bundles: attrs.delete(:bundle_settings))
678
- attrs[:messages] = messages ? Array(attrs[:messages]).map { |msg| symbolize_message_keys(msg) } : []
679
- attrs[:extra_fields] = data.reject { |key, _| FIELDS.key?(key) }
701
+ attrs[:messages] = messages ? SessionMessages.restore(attrs[:messages]) : []
702
+ attrs[:extra_fields] = data.reject { |key, _| FIELDS.key?(key) || key == SessionMessages::LOG_KEY }
680
703
  new(**attrs)
681
704
  end
682
705
 
@@ -691,6 +714,13 @@ module Samagotchi
691
714
  end
692
715
  end
693
716
 
717
+ # #save of a session .load read without its messages.
718
+ class LoadedWithoutMessages < StandardError
719
+ def initialize(id)
720
+ super("session #{id} was loaded without its messages (Session.load(messages: false)): saving it would drop them")
721
+ end
722
+ end
723
+
694
724
  # What every surface says when an id (or a prefix) names no session:
695
725
  # this class owns the words, callers add their context around
696
726
  # #message. +given+ is what was asked for, as given.
@@ -737,6 +767,13 @@ module Samagotchi
737
767
  raise AmbiguousId.new("session id #{id} matches #{matches.size} sessions:\n#{lines.join("\n")}", ids: matches)
738
768
  end
739
769
 
770
+ # A created_at/updated_at as .list, the hub's snapshot and Links' rows sort it (unparsed: the epoch).
771
+ def self.sort_time(value)
772
+ Time.iso8601(value.to_s)
773
+ rescue ArgumentError
774
+ Time.at(0)
775
+ end
776
+
740
777
  # Return all saved sessions sorted by updated_at desc by default (newest first).
741
778
  # Supports sort: created_at|updated_at and order: asc|desc.
742
779
  # +project_root+ keeps only that project's sessions (Session#project_root),
@@ -755,22 +792,19 @@ module Samagotchi
755
792
 
756
793
  paths = Dir.glob(File.join(state_dir, "*#{SessionPaths::FILE_EXT}"))
757
794
  paths = paths.select { |path| changed_after?(path, changed_since) } if changed_since
795
+ archived = Hash.new { |known, id| known[id] = ArchiveStore.archived?(session_dir(id, state_dir: state_dir)) }
796
+ # An archived session's file is left unread, known by its name (its id);
797
+ # a file whose name isn't an id is read, and judged by the id inside.
798
+ paths = paths.reject { |path| valid_id?(id = File.basename(path, SessionPaths::FILE_EXT)) && archived[id] } unless include_archived
758
799
  sessions = paths.filter_map { |path| summary_from_file(path) }
759
- sessions.each { |s| s.archived = ArchiveStore.archived?(session_dir(s.id, state_dir: state_dir)) }
800
+ sessions.each { |s| s.archived = archived[s.id] }
760
801
  sessions.reject!(&:archived) unless include_archived
761
802
  if project_root
762
803
  roots = {}
763
804
  sessions.select! { |s| s.project_root(cache: roots) == project_root }
764
805
  end
765
806
 
766
- sorted = sessions.sort_by do |s|
767
- val = sort_key == "created_at" ? s.created_at : s.updated_at
768
- begin
769
- Time.iso8601(val.to_s)
770
- rescue ArgumentError
771
- Time.at(0)
772
- end
773
- end
807
+ sorted = sessions.sort_by { |s| sort_time(sort_key == "created_at" ? s.created_at : s.updated_at) }
774
808
  sorted.reverse! if sort_order == "desc"
775
809
  # Apply offset/limit if given
776
810
  off = offset.to_i
@@ -790,8 +824,9 @@ module Samagotchi
790
824
  private_class_method :changed_after?
791
825
 
792
826
  # One session file as .list reads it: the session without its messages
793
- # (the list is lightweight). The session hub reads files the same way,
794
- # so both agree on which files count.
827
+ # (the list is lightweight; #save raises LoadedWithoutMessages). The
828
+ # session hub reads files the same way, so both agree on which files
829
+ # count.
795
830
  # @return [Session, nil] nil for a file that is corrupt, missing a
796
831
  # required field, or gone
797
832
  def self.summary_from_file(path)
@@ -799,7 +834,7 @@ module Samagotchi
799
834
  # An id that isn't one (hand-edited, or not ours) would be a path.
800
835
  return nil unless valid_id?(data["id"])
801
836
 
802
- session = from_h(data, messages: false)
837
+ session = from_file(data, path: path, messages: false)
803
838
  session.persisted!
804
839
  session.loaded_status = session.status
805
840
  session.status = STATUS_STOPPED if stopped_marker?(session.id, state_dir: File.dirname(path))
@@ -813,6 +848,12 @@ module Samagotchi
813
848
  # a deleted one).
814
849
  def persisted! = (@persisted = true)
815
850
 
851
+ # Its messages as .from_file read them (SessionMessages::Store).
852
+ def messages_store=(store)
853
+ @messages = store.messages
854
+ @messages_store = store
855
+ end
856
+
816
857
  # Persist the session atomically. Updates +updated_at+ in place.
817
858
  #
818
859
  # One save at a time per Session: a worker saves its session from the
@@ -827,11 +868,15 @@ module Samagotchi
827
868
  #
828
869
  # A session read from its file, or saved once, whose file is gone was
829
870
  # deleted (SessionManager.delete_session, the retention sweep): the save
830
- # is skipped (and logged) rather than bring it back. Only a new
831
- # session's first save creates the file.
871
+ # is skipped (and logged, SessionMessages::Store#write) rather than
872
+ # bring it back. Only a new session's first save creates the file.
832
873
  # @param now [Time, nil] the updated_at to stamp (a spec's clock); nil,
833
874
  # the time the lock is taken
875
+ # @raise [LoadedWithoutMessages] read without its messages
876
+ # (.load(messages: false), .summary_from_file)
834
877
  def save(state_dir: self.class.default_state_dir, now: nil)
878
+ raise LoadedWithoutMessages, @id if @messages_store.left_out?
879
+
835
880
  @save_lock.synchronize do
836
881
  @updated_at = (now || Time.now).iso8601(3)
837
882
  # Persist with current metadata version so new flag is written
@@ -843,13 +888,7 @@ module Samagotchi
843
888
  # Auto-compute first_preview if not yet cached and messages contain a user entry.
844
889
  compute_first_preview!
845
890
 
846
- if @persisted && !File.exist?(path)
847
- Log.warn(:worker, "save_skipped_deleted", sid: @id)
848
- return self
849
- end
850
-
851
- AtomicFile.write(path, JSON.pretty_generate(to_h) + "\n")
852
- @persisted = true
891
+ @persisted = true if @messages_store.write(path, to_h, sid: @id, persisted: @persisted)
853
892
  end
854
893
  self
855
894
  end
@@ -1029,33 +1068,6 @@ module Samagotchi
1029
1068
  class << self
1030
1069
  private
1031
1070
 
1032
- # A chat turn's tool_calls get symbol keys too ({id:, name:,
1033
- # arguments:}); the arguments keep the model's string keys. So do
1034
- # image refs ({file:, mime:, width:, …}).
1035
- def symbolize_message_keys(hash)
1036
- message = hash.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
1037
- %i[tool_calls images].each do |key|
1038
- next unless message[key].is_a?(Array)
1039
-
1040
- message[key] = message[key].map do |entry|
1041
- entry.is_a?(Hash) ? entry.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } : entry
1042
- end
1043
- end
1044
- symbolize_empty_answer(message)
1045
- end
1046
-
1047
- # An empty-answer note's marker (TurnNote.empty), its steps and its
1048
- # refusal, as they were saved.
1049
- def symbolize_empty_answer(message)
1050
- marker = message[:empty_answer]
1051
- return message unless marker.is_a?(Hash)
1052
-
1053
- marker = marker.transform_keys(&:to_sym)
1054
- marker[:steps] = marker[:steps].map { |step| step.is_a?(Hash) ? step.transform_keys(&:to_sym) : step } if marker[:steps].is_a?(Array)
1055
- marker[:refusal] = marker[:refusal].transform_keys(&:to_sym) if marker[:refusal].is_a?(Hash)
1056
- message.merge(empty_answer: marker)
1057
- end
1058
-
1059
1071
  def session_path(session_id, state_dir:)
1060
1072
  session_file(session_id, state_dir: state_dir)
1061
1073
  end
@@ -23,6 +23,12 @@ module Samagotchi
23
23
  SUPPORTED = :supported
24
24
  LOCAL_ONLY = :local_only
25
25
 
26
+ # chi web's 404 for a path no route takes (Web::App#serve_static's):
27
+ # its `reason` beside `error: "not_found"` and the words ("not found:
28
+ # /path"), which Remote#missing_route? reads first; an older chi web's
29
+ # 404 has no reason, and its words are the fallback.
30
+ NO_ROUTE = "no_route"
31
+
26
32
  # bin/chi subcommands that act on this machine: never sessions. chi
27
33
  # remote (this machine's list of remotes) runs here under a remote too
28
34
  # (Dispatch); the others are refused there.
@@ -129,6 +135,7 @@ module Samagotchi
129
135
  "sessions prune" => LOCAL_ONLY,
130
136
  "sessions clean" => LOCAL_ONLY,
131
137
  "sessions stats" => LOCAL_ONLY,
138
+ "sessions migrate" => LOCAL_ONLY,
132
139
 
133
140
  # Participants (docs/internals/participants.md): the remote's link,
134
141
  # through its chi web's participants routes.
@@ -23,7 +23,7 @@ module Samagotchi
23
23
  CONTINUING_POLL = 0.2
24
24
 
25
25
  # +given+ named a session: +target+ where input for it goes (a
26
- # SessionInbox::Resolved), +waited+ whether a continue in flight was
26
+ # InboxDelivery::Resolved), +waited+ whether a continue in flight was
27
27
  # waited for on the way.
28
28
  Located = Data.define(:target, :waited)
29
29
 
@@ -92,13 +92,13 @@ module Samagotchi
92
92
  def show(id) = Session.load(id, **dir)
93
93
 
94
94
  # Where input for +id+ goes: its chain's newest link when it was
95
- # continued (SessionInbox::Head's send walk; :continuing while a
95
+ # continued (InboxDelivery::Head's send walk; :continuing while a
96
96
  # continue of it is in flight), else +id+.
97
- # @return [SessionInbox::Resolved]
98
- def head(id) = SessionInbox::Head.resolve(:send, id, state_dir: state_dir!)
97
+ # @return [InboxDelivery::Resolved]
98
+ def head(id) = InboxDelivery::Head.resolve(:send, id, state_dir: state_dir!)
99
99
 
100
100
  # @return [OwnerLock::Owner, nil] the worker or one-turn chi run that owns it
101
- def owner(id) = SessionManager.session_owner(id, **dir)
101
+ def owner(id) = OwnerLock.for_session(id, state_dir: @state_dir || Session.default_state_dir)
102
102
 
103
103
  # Whether +turn+ (an enqueued id) waits as an unclaimed input file of
104
104
  # session +id+ (Ask's request_id check: such a turn with no worker
@@ -666,7 +666,7 @@ module Samagotchi
666
666
  def peer_list(id) = PeerRoster.build(Session.exist?(id, **dir) ? peer_head(id) : id, state_dir: state_dir!)
667
667
 
668
668
  # A message from +peer+ into session +id+, as a delivery
669
- # (SessionInbox.deliver :peer), run on +id+'s chain's live link when
669
+ # (InboxDelivery.deliver :peer), run on +id+'s chain's live link when
670
670
  # +id+ was continued (#peer_head; the line names it). Refused before
671
671
  # anything is written for a gone session, a continued one whose live
672
672
  # link isn't paired (an older chi's continue: it names that link), no
@@ -698,7 +698,7 @@ module Samagotchi
698
698
 
699
699
  # The link a peer command of +id+ runs on: +id+, or, when it is
700
700
  # archived, its chain's first live link from it (SessionChain::Links
701
- # #first_live, SessionInbox::Head's walk; the chain's end when every
701
+ # #first_live, InboxDelivery::Head's walk; the chain's end when every
702
702
  # link after it is archived). Only an archived id lists the sessions.
703
703
  def peer_head(id) = SessionChain::Links.new(state_dir: state_dir!).first_live(id)
704
704
 
@@ -754,7 +754,7 @@ module Samagotchi
754
754
  end
755
755
  return unpaired unless PeerMailbox.link(id, peer, state_dir: state_dir!)
756
756
 
757
- SessionInbox.deliver(:peer, id, state_dir: state_dir!) do
757
+ InboxDelivery.deliver(:peer, id, state_dir: state_dir!) do
758
758
  message = PeerMailbox.post(id, peer, text: text, summary: summary, wake: wake, re: re, state_dir: state_dir!,
759
759
  taken: PeerReceipts.taken(id, peer, state_dir: state_dir!))
760
760
  message.wake
@@ -844,7 +844,7 @@ module Samagotchi
844
844
  PeerSay.new(status: :received, serial: serial, wake: at_once, receipt: receipt, earlier: earlier, turns: turns)
845
845
  end
846
846
 
847
- # A session source's push, as a push delivery (SessionInbox.deliver
847
+ # A session source's push, as a push delivery (InboxDelivery.deliver
848
848
  # :push): the text recorded, then a wake when it asks one (a change
849
849
  # with wake, context.wake on, the source not woken lately) as the
850
850
  # push WakePolicy decides (an idle-exited session starts; a stopped
@@ -853,7 +853,7 @@ module Samagotchi
853
853
  def push_delivery(session_id, name, fetched, location, record)
854
854
  before = written = asked = nil
855
855
  delivered = begin
856
- SessionInbox.deliver(:push, session_id, state_dir: state_dir!) do
856
+ InboxDelivery.deliver(:push, session_id, state_dir: state_dir!) do
857
857
  before, written = record.call
858
858
  asked = fetched.wake && before != written.revision && context_wake_allowed?(location, name)
859
859
  end
@@ -161,11 +161,11 @@ module Samagotchi
161
161
  # gone since) is the send's to report: +id+ itself (:same, as before
162
162
  # it followed). A participant never
163
163
  # asks: their grant is for one session (:pinned).
164
- # @return [SessionInbox::Resolved]
164
+ # @return [InboxDelivery::Resolved]
165
165
  def head(id)
166
- return SessionInbox::Resolved.new(id: id, asked: id, via: :pinned) if participant?
166
+ return InboxDelivery::Resolved.new(id: id, asked: id, via: :pinned) if participant?
167
167
 
168
- same = SessionInbox::Resolved.new(id: id, asked: id, via: :same)
168
+ same = InboxDelivery::Resolved.new(id: id, asked: id, via: :same)
169
169
  reply = request(:get, "/api/sessions/resolve", query: { id: id.to_s, head: 1 })
170
170
  return same unless reply.status == 200
171
171
 
@@ -173,10 +173,10 @@ module Samagotchi
173
173
  via = HEAD_VIAS[json["via"]] if json.is_a?(Hash)
174
174
  return same unless via && Session.valid_id?(json["id"])
175
175
 
176
- SessionInbox::Resolved.new(id: json["id"], asked: id, via: via)
176
+ InboxDelivery::Resolved.new(id: json["id"], asked: id, via: via)
177
177
  end
178
178
 
179
- # The ways resolve?head=1 answers (SessionInbox::Resolved#via).
179
+ # The ways resolve?head=1 answers (InboxDelivery::Resolved#via).
180
180
  HEAD_VIAS = { "same" => :same, "head" => :head, "continuing" => :continuing }.freeze
181
181
 
182
182
  # @return [SessionView]
@@ -262,7 +262,7 @@ module Samagotchi
262
262
  def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false, anchors: nil)
263
263
  raise BadRequest.new("a turn's anchors run on this machine only: run it on #{name}", code: "local_only") unless anchors.nil? || TurnAnchors.from(anchors).empty?
264
264
 
265
- body = { prompt: prompt, client_id: sent_id(client_id), history: false }
265
+ body = { prompt: prompt, client_id: client_id, history: false }
266
266
  body[:follow] = true if follow
267
267
  body[:images] = images.map { |ref| { file: ref[:file], name: ref[:name] } } unless images.empty?
268
268
  body[:check_vision] = true unless images.empty?
@@ -750,17 +750,6 @@ module Samagotchi
750
750
  reply
751
751
  end
752
752
 
753
- # compat shim agent_client_id: +client_id+ as that chi web reads it:
754
- # an agent's (agent:<name>) to one from before agent: senders goes as
755
- # chi send's, today's owner row (Delivery::AGENT_FEATURE in its
756
- # /api/info features).
757
- def sent_id(client_id)
758
- return client_id unless ClientId.agent?(client_id)
759
-
760
- check_server!
761
- Array(@features).include?(Delivery::AGENT_FEATURE) ? client_id : ClientId::CLI_SEND
762
- end
763
-
764
753
  def check_server!
765
754
  return if @checked
766
755
 
@@ -793,9 +782,16 @@ module Samagotchi
793
782
  def strategy_or_hard(json) = strategy_of(json) || Guardrails::ParentPolicy.strategy(Guardrails::ParentPolicy::HARD)
794
783
 
795
784
  # chi web's 404 for a path no route takes (#serve_static's), not a
796
- # route's own "no such session".
785
+ # route's own "no such session": its reason (Contract::NO_ROUTE), the
786
+ # words for an older chi web's 404, which has none (a remote runs
787
+ # another version).
797
788
  def missing_route?(reply)
798
- reply.status == 404 && reply.error == "not_found" && reply.json["detail"].to_s.start_with?("not found: /")
789
+ return false unless reply.status == 404 && reply.error == "not_found"
790
+
791
+ reason = reply.json["reason"]
792
+ return reason == Contract::NO_ROUTE unless reason.nil?
793
+
794
+ reply.json["detail"].to_s.start_with?("not found: /")
799
795
  end
800
796
 
801
797
  def context_missing?(reply) = reply.status == 404 && reply.error == "context_missing"
@@ -838,8 +834,9 @@ module Samagotchi
838
834
  when "context_busy" then raise ContextSources::Held, message.to_s
839
835
  when "busy", "scratch"
840
836
  raise SessionManager::ArchiveRefused.new(sid, reason, busy_id: json["busy_id"], message: (message if reason == :transition_held)) if reason
841
- when "continued", "open_children", "folder_gone", "transition_busy"
842
- raise SessionContinue::Refused.new(sid, reason, ids: Array(json["ids"]), detail: (message if reason == :transition_busy))
837
+ when "continued", "open_children", "folder_gone", "transition_busy", "undo_pending"
838
+ raise SessionContinue::Refused.new(sid, reason, ids: Array(json["ids"]),
839
+ detail: (message if %i[transition_busy undo_pending].include?(reason)))
843
840
  when "held", "not_running", "unsupported", "failed"
844
841
  if reason
845
842
  raise SessionManager::RestartRefused.new(sid, reason, version: json["version"], holds: json["holds"],
@@ -881,7 +878,7 @@ module Samagotchi
881
878
  end
882
879
 
883
880
  def create_body(spec)
884
- body = { model: spec.model_name, client_id: sent_id(spec.client_id), history: false }
881
+ body = { model: spec.model_name, client_id: spec.client_id, history: false }
885
882
  if spec.preview || spec.idle
886
883
  body.merge!(idle: true, preview: spec.preview)
887
884
  else
@@ -893,8 +890,7 @@ module Samagotchi
893
890
  else
894
891
  body[:dir] = spec.working_directory
895
892
  body.merge!(setup_body(spec.setup)) if spec.setup
896
- # An older chi web ignores it: no driver named (its creator's id
897
- # downgraded too, #sent_id).
893
+ # An older chi web ignores it: no driver named.
898
894
  body[:driver] = spec.driver if spec.driver
899
895
  end
900
896
  body.compact
@@ -273,7 +273,7 @@ module Samagotchi
273
273
  # session was continued, as +next_id+, or is being continued, +in_flight+:
274
274
  # nothing was written) or :busy (another change of the session holds
275
275
  # its transition lock: nothing was written). +wake+:
276
- # what a push that asked for a wake did (SessionInbox.deliver :push:
276
+ # what a push that asked for a wake did (InboxDelivery.deliver :push:
277
277
  # :woken, :live, :stopped, :starting, :archived, :scratch, :owned,
278
278
  # :gone), nil when it asked none (or an older chi web's answer has none).
279
279
  ContextPush = Data.define(:status, :before, :revision, :next_id, :wake, :in_flight) do
@@ -190,9 +190,11 @@ module Samagotchi
190
190
  # task the link or such a delegate started that still runs.
191
191
  # @raise [SessionManager::DeleteRefused, SessionManager::OwnedByTUI]
192
192
  def check_link!(plan, state_dir, running_tasks: SessionManager::RunningTasks::Policy::IGNORE)
193
- SessionManager.refuse_protected!(plan.id, state_dir)
193
+ # One protection read for the link and its delegates, checked in order.
194
+ protection = SessionManager.protection_check([plan.id, *plan.delegates.delete], state_dir)
195
+ protection.call(plan.id)
194
196
  refuse_unmovable!(plan.id, plan.moved, state_dir)
195
- precheck!(plan.delegates.delete, state_dir)
197
+ precheck!(plan.delegates.delete, state_dir, protection: protection)
196
198
  SessionManager::RunningTasks.check!([*plan.delegates.delete, plan.id], state_dir: state_dir,
197
199
  policy: running_tasks) do |listing|
198
200
  SessionManager::DeleteRefused.new(plan.id, :tasks_running, tasks: listing)
@@ -258,12 +260,17 @@ module Samagotchi
258
260
 
259
261
  # The refusals of every id a batch would delete, before the first
260
262
  # goes: a schedule's target, anchor or head (the refusal names that
261
- # delegate), a one-turn run.
263
+ # delegate), a one-turn run, id by id. The schedules are read once for
264
+ # the batch (+protection+, a SessionManager.protection_check covering
265
+ # +ids+, else made here).
262
266
  # @raise [SessionManager::DeleteRefused, SessionManager::OwnedByTUI]
263
- def precheck!(ids, state_dir)
267
+ def precheck!(ids, state_dir, protection: nil)
268
+ return if ids.empty?
269
+
270
+ protection ||= SessionManager.protection_check(ids, state_dir)
264
271
  ids.each do |sid|
265
272
  begin
266
- SessionManager.refuse_protected!(sid, state_dir)
273
+ protection.call(sid)
267
274
  rescue SessionManager::DeleteRefused => e
268
275
  # Only a schedule names the delegate; any other refusal keeps its words.
269
276
  raise unless e.reason == :scheduled
@@ -274,7 +281,7 @@ module Samagotchi
274
281
  "cancel it with chi schedule cancel #{e.schedule_id}"
275
282
  )
276
283
  end
277
- raise SessionManager::OwnedByTUI, sid if SessionManager.session_owner(sid, state_dir: state_dir)&.tui?
284
+ raise SessionManager::OwnedByTUI, sid if OwnerLock.for_session(sid, state_dir: state_dir)&.tui?
278
285
  end
279
286
  end
280
287
 
@@ -343,7 +350,7 @@ module Samagotchi
343
350
  # can't go back): none is in a one-turn chi run, which can't be stopped
344
351
  # from here. The 409 and the preview say it.
345
352
  def stoppable?(ids, state_dir)
346
- ids.none? { |sid| SessionManager.session_owner(sid, state_dir: state_dir)&.tui? }
353
+ ids.none? { |sid| OwnerLock.for_session(sid, state_dir: state_dir)&.tui? }
347
354
  end
348
355
 
349
356
  def refuse_unmovable!(id, moved, state_dir)
@@ -427,7 +434,7 @@ module Samagotchi
427
434
  SessionManager.refuse_protected!(plan.id, state_dir, chain: true)
428
435
 
429
436
  plan.links.each do |link|
430
- presence = WorkerPresence.read(link, state_dir: state_dir, owner: SessionManager.session_owner(link, state_dir: state_dir))
437
+ presence = WorkerPresence.read(link, state_dir: state_dir, owner: OwnerLock.for_session(link, state_dir: state_dir))
431
438
  raise SessionManager::OwnedByTUI, link if presence.tui_owned?
432
439
  raise SessionManager::DeleteRefused.new(link, :worker_running) if !stop && (presence.owned? || presence.starting?)
433
440
  end
@@ -33,7 +33,7 @@ module Samagotchi
33
33
  def call(id, state_dir:)
34
34
  state_dir ||= Session.default_state_dir
35
35
  links = Links.new(state_dir: state_dir)
36
- rows = SessionManager.session_rows(state_dir: state_dir, include_tests: true, include_archived: true)
36
+ rows = SessionManager.fleet_rows(state_dir: state_dir)
37
37
  this = Delete.link_plan(id, state_dir: state_dir, links: links, rows: rows)
38
38
  return { chained: false, session_id: id, link: link_json(this, links, nil, 0, state_dir, rows: rows) } unless Delete.chained?(id, links)
39
39
 
@@ -64,7 +64,7 @@ module Samagotchi
64
64
  # "turn" when a worker owns +id+ and its saved status is running,
65
65
  # "idle" when a worker owns it or is being started for it, else nil.
66
66
  def link_worker(id, state_dir)
67
- presence = WorkerPresence.read(id, state_dir: state_dir, owner: SessionManager.session_owner(id, state_dir: state_dir))
67
+ presence = WorkerPresence.read(id, state_dir: state_dir, owner: OwnerLock.for_session(id, state_dir: state_dir))
68
68
  return nil unless presence.owned? || presence.starting?
69
69
  return "idle" unless presence.owned?
70
70
 
@@ -114,7 +114,7 @@ module Samagotchi
114
114
  end
115
115
 
116
116
  def tui!(id, state_dir)
117
- presence = WorkerPresence.read(id, state_dir: state_dir, owner: SessionManager.session_owner(id, state_dir: state_dir))
117
+ presence = WorkerPresence.read(id, state_dir: state_dir, owner: OwnerLock.for_session(id, state_dir: state_dir))
118
118
  raise SessionManager::OwnedByTUI, id if presence.tui_owned?
119
119
  end
120
120
 
@@ -7,7 +7,7 @@ require_relative "../session"
7
7
  module Samagotchi
8
8
  module SessionChain
9
9
  # The one walker of "who continues whom": every chain walk (SessionChain.latest
10
- # and .next_of, SessionInbox::Head, Schedules' tick) goes through one of
10
+ # and .next_of, InboxDelivery::Head, Schedules' tick) goes through one of
11
11
  # these. Built over one Session.list (archived ones too, created_at asc),
12
12
  # made on the first question that needs it, so asking only #archived? of
13
13
  # one id lists nothing. A link's successor is the earliest session that
@@ -39,23 +39,37 @@ module Samagotchi
39
39
  # never reach the schedule's head through it.
40
40
  #
41
41
  # The listing is a snapshot: one Links per question, or per tick.
42
+ #
43
+ # Or given (+sessions:+): rows a caller already holds (chi web's session
44
+ # hub, Web::SessionHub.chain_row, for Schedules.session_marks), so the
45
+ # walks read no session file and no archive marker. A given row answers
46
+ # #session(id) with itself, not a Session: the readers that need a full
47
+ # one (Schedules' busy check and prune) keep a read listing.
42
48
  class Links
49
+ # What a walk needs of one session: its id (the one inside its file),
50
+ # the link it continues, its archive flag and its created_at (the
51
+ # successor of a fork is the earliest).
52
+ Row = Data.define(:id, :continues, :archived, :created_at)
53
+
43
54
  attr_reader :state_dir
44
55
 
45
56
  # @param anchor_heads [Hash{String => Array<String>}, nil] anchor →
46
57
  # the heads of the schedules on it (Schedules#anchor_heads); nil reads
47
58
  # them from the schedules file the first time a walk dead-ends at an
48
59
  # archived link
49
- def initialize(state_dir:, anchor_heads: nil)
60
+ # @param sessions [Enumerable, nil] the listing given: anything that
61
+ # answers id, continues, archived and created_at (Row), any order;
62
+ # nil lists the state dir on the first question that needs it
63
+ def initialize(state_dir:, anchor_heads: nil, sessions: nil)
50
64
  @state_dir = state_dir
51
- @by_id = nil
65
+ @by_id = sessions && sessions.sort_by { |row| Session.sort_time(row.created_at) }.to_h { |row| [row.id, row] }
52
66
  @nexts = nil
53
67
  @archived = {}
54
68
  @anchor_heads = anchor_heads
55
69
  @anchor_head = {}
56
70
  end
57
71
 
58
- # The listed session +id+ (a Session summary), or nil.
72
+ # The listed session +id+ (a Session summary, or the given row), or nil.
59
73
  def session(id) = by_id[id]
60
74
 
61
75
  # Not in the listing (pruned, deleted, never existed).
@@ -18,7 +18,7 @@ module Samagotchi
18
18
  # without the anchor), SessionContinue's check (.of, no in-flight: it
19
19
  # holds the lock itself),
20
20
  # follow_guard (.of without the anchor while it holds the lock, as it
21
- # always asked; .in_flight when it can't), SessionInbox::Head#continuing
21
+ # always asked; .in_flight when it can't), InboxDelivery::Head#continuing
22
22
  # and Schedules#continuing_reason (.in_flight alone: their walk already
23
23
  # crossed the saved links).
24
24
  Successor = Data.define(:id, :via) do
@@ -8,7 +8,7 @@ require_relative "log"
8
8
  require_relative "session"
9
9
  require_relative "session_inbox"
10
10
  require_relative "session_chain/links"
11
- require_relative "steer"
11
+ require_relative "speaker"
12
12
  require_relative "recap_store"
13
13
 
14
14
  module Samagotchi
@@ -118,7 +118,7 @@ module Samagotchi
118
118
  # A turn's opening, not a `!shell` line: a command the user ran after
119
119
  # the answer leaves it the last word.
120
120
  def later_turn?(message)
121
- Steer.turn_opening?(message)
121
+ Speaker.turn_opening?(message)
122
122
  end
123
123
 
124
124
  # At most +max+ bytes of +text+'s start, cut on a character.
@@ -170,7 +170,7 @@ module Samagotchi
170
170
 
171
171
  text = msg[:content]
172
172
  next unless text.is_a?(String) && !text.strip.empty?
173
- next if Steer.shell_line?(msg)
173
+ next if Speaker.shell_line?(msg)
174
174
 
175
175
  return text.strip
176
176
  end