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
@@ -0,0 +1,602 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+ require "securerandom"
6
+ require_relative "atomic_file"
7
+ require_relative "session_field"
8
+ require_relative "session_paths"
9
+ require_relative "log"
10
+
11
+ module Samagotchi
12
+ # A session's conversation as its file holds it: how messages are written
13
+ # to <id>.json and read back from it. Session (.load, #save, #to_h) and the
14
+ # readers that parse a session file themselves (TurnExcerpts, SessionStats,
15
+ # `chi bundle try`'s trace) go through it, so a change of where messages
16
+ # live is a change here. A parsed file becomes a Session in one place,
17
+ # Session.from_file (.load, .summary_from_file, MemoryUsage and the
18
+ # report scripts, which parse the files themselves), which asks .of_file.
19
+ #
20
+ # Two forms, string-keyed hashes scrubbed to valid UTF-8 in both (in
21
+ # memory they have symbol keys, .restore):
22
+ #
23
+ # - inline: the file's "messages" key (#save's bytes are pinned by
24
+ # spec/session_messages_spec.rb). What a save writes while
25
+ # session.split_messages is off (the default).
26
+ # - split: the messages in their own file beside it, a generation
27
+ # <id>/messages-<gen8>.jsonl (one JSON.generate per line), which the
28
+ # file names in place of "messages": "messages_log" => {v: 1, file:,
29
+ # count:, bytes:}, the generation's committed lines. <id>.json is the one
30
+ # commit point: bytes past +bytes+ (a torn or unrecorded append) are
31
+ # ignored, and a generation it doesn't name is a stray. A save appends
32
+ # (truncating to the committed bytes first) when only lines were added
33
+ # since its last commit, else writes a new generation (File::EXCL, never
34
+ # changed after); the generation it replaced stays a stray for
35
+ # STRAY_GRACE, so a reader that parsed the older metadata still reads
36
+ # its committed bytes. A session read split is saved split whatever the
37
+ # setting says (Store).
38
+ module SessionMessages
39
+ KEY = "messages"
40
+ LOG_KEY = "messages_log"
41
+ LOG_VERSION = 1
42
+ GENERATION_GLOB = "messages-*.jsonl"
43
+ GENERATION_NAME = /\Amessages-[0-9a-f]{8}\.jsonl\z/
44
+ # How long a generation no metadata names is kept (seconds since its
45
+ # last write or its replacement): an in-flight rewrite's of another
46
+ # process, or the one a reader's metadata named a moment ago.
47
+ STRAY_GRACE = 60
48
+
49
+ # The file's messages can't be read as written. A JSON::ParserError, so
50
+ # every reader that counts a file that doesn't parse as unreadable (or
51
+ # Session.load's "Session file corrupted") counts this alike.
52
+ class Corrupt < JSON::ParserError; end
53
+
54
+ # The generation the metadata named is gone: a later save replaced it
55
+ # and the stray was removed. .parse reads <id>.json again, once.
56
+ class Gone < Corrupt; end
57
+
58
+ # What "messages_log" says: the generation's file and its committed
59
+ # lines (+count+) and bytes.
60
+ Generation = Data.define(:file, :count, :bytes) do
61
+ # @raise [Corrupt] not a version 1 log
62
+ def self.from(raw)
63
+ sizes = raw.is_a?(Hash) ? raw.values_at("count", "bytes") : []
64
+ valid = raw.is_a?(Hash) && raw["v"] == LOG_VERSION && GENERATION_NAME.match?(raw["file"].to_s) &&
65
+ sizes.all? { |size| size.is_a?(Integer) && !size.negative? }
66
+ raise Corrupt, "#{LOG_KEY} is not a version #{LOG_VERSION} log: #{raw.inspect[0, 200]}" unless valid
67
+
68
+ new(file: raw["file"], count: raw["count"], bytes: raw["bytes"])
69
+ end
70
+
71
+ def to_file = { "v" => LOG_VERSION, "file" => file, "count" => count, "bytes" => bytes }
72
+
73
+ # The committed lines of this generation in +dir+ (UTF-8, frozen,
74
+ # without their newline).
75
+ # @raise [Gone] the file isn't there
76
+ # @raise [Corrupt] shorter than +bytes+, or not +count+ whole lines
77
+ def read(dir)
78
+ text = File.open(File.join(dir, file), "rb") do |io|
79
+ raise Corrupt, "#{file} holds #{io.size} of its #{bytes} committed bytes" if io.size < bytes
80
+
81
+ io.read(bytes).to_s.force_encoding(Encoding::UTF_8)
82
+ end
83
+ lines = text.split("\n", -1)
84
+ raise Corrupt, "#{file}'s committed bytes don't end a line" unless lines.pop.to_s.empty?
85
+ raise Corrupt, "#{file} holds #{lines.size} lines, its log says #{count}" unless lines.size == count
86
+
87
+ lines.each(&:freeze)
88
+ rescue Errno::ENOENT
89
+ raise Gone, "#{file} is gone"
90
+ end
91
+ end
92
+
93
+ # A file's messages as .load read them: +generation+ and +lines+ (its
94
+ # committed ones) nil for inline messages.
95
+ Loaded = Data.define(:messages, :generation, :lines)
96
+
97
+ @locks = {}
98
+ @locks_guard = Mutex.new
99
+
100
+ # fcntl(2)'s F_FULLFSYNC (darwin's <sys/fcntl.h>), which Fcntl doesn't name.
101
+ FULLFSYNC = 51
102
+
103
+ module_function
104
+
105
+ # +messages+ (symbol or string keys) as the file has them: string keys
106
+ # (top level; nested hashes keep theirs, JSON writes them alike), valid
107
+ # UTF-8.
108
+ # @return [Array<Hash>]
109
+ def dump(messages) = SessionField.scrub_utf8(messages.map { |msg| SessionField.stringify_keys(msg) })
110
+
111
+ # The file's messages as a session holds them (symbol keys).
112
+ # @param raw [Array<Hash>, nil] as parsed (string keys)
113
+ # @return [Array<Hash>]
114
+ def restore(raw) = Array(raw).map { |msg| symbolize(msg) }
115
+
116
+ # Whether a session not read split is saved split (session.split_messages).
117
+ def split?
118
+ # Here, not at load: the readers that load this file alone (a page's
119
+ # runtime.turn_excerpts) don't load the settings.
120
+ require_relative "config"
121
+ require_relative "degrade"
122
+ Degrade.call(:config, "split_messages_unreadable", fallback: false) { Config.get("session.split_messages") == true }
123
+ end
124
+
125
+ # The saved messages of a session file already parsed (+data+, read from
126
+ # +path+), as written: string keys. [] when +data+ holds none (or isn't a
127
+ # session file's mapping).
128
+ # @return [Array] the entries as they are (callers keep their own Hash checks)
129
+ # @raise [Gone] the generation +data+ names is gone (.parse reads again)
130
+ # @raise [Corrupt] it doesn't hold what +data+ says
131
+ def of_file(data, path:) = load(data, path: path).messages
132
+
133
+ # +data+'s messages (.of_file) with, for split ones, the generation and
134
+ # its committed lines.
135
+ # @return [Loaded]
136
+ def load(data, path:)
137
+ inline = data.is_a?(Hash) && data[KEY].is_a?(Array) ? data[KEY] : []
138
+ return Loaded.new(messages: inline, generation: nil, lines: nil) unless data.is_a?(Hash) && data.key?(LOG_KEY)
139
+
140
+ generation = Generation.from(data[LOG_KEY])
141
+ lines = generation.read(dir_of(path))
142
+ logged = begin
143
+ lines.map { |line| JSON.parse(line) }
144
+ rescue JSON::ParserError => e
145
+ raise Corrupt, "#{generation.file}: #{e.message}"
146
+ end
147
+ Loaded.new(messages: reconcile(logged, inline), generation: generation, lines: lines)
148
+ end
149
+
150
+ # The session file at +path+ parsed, given to the block, whose value
151
+ # this returns. A block that meets its generation gone (Gone) runs once
152
+ # more on a fresh parse, so what it builds never mixes an older file's
153
+ # fields with newer messages; a second miss raises.
154
+ # @raise [JSON::ParserError, SystemCallError] as reading the file does
155
+ def parse(path)
156
+ retried = false
157
+ begin
158
+ yield JSON.parse(File.read(path).force_encoding(Encoding::UTF_8))
159
+ rescue Gone
160
+ raise if retried
161
+
162
+ retried = true
163
+ retry
164
+ end
165
+ end
166
+
167
+ # The saved messages of the session file at +path+ (string keys).
168
+ # @raise [JSON::ParserError, SystemCallError] as reading the file does
169
+ def read(path) = parse(path) { |data| of_file(data, path: path) }
170
+
171
+ # The session folder beside the session file at +path+ (<id>.json).
172
+ def dir_of(path) = path.delete_suffix(SessionPaths::FILE_EXT)
173
+
174
+ # The text of a split session file: +file+ (a session file's mapping)
175
+ # with +generation+'s messages_log in place of its messages.
176
+ def file_text(file, generation)
177
+ meta = file.except(LOG_KEY).to_h { |key, value| key == KEY ? [LOG_KEY, generation.to_file] : [key, value] }
178
+ "#{JSON.pretty_generate(meta)}\n"
179
+ end
180
+
181
+ # Convert the session file at +path+ to split in place (StorageMigration,
182
+ # the compatibility corpus): its messages (inline, or an older chi's
183
+ # inline ones read after the log beside them, .reconcile) into a new
184
+ # generation +name+, then <id>.json naming it, every other key as it was
185
+ # (not a save: updated_at and written_by stay). Whatever the setting says.
186
+ # @return [String] the generation's file name
187
+ # @raise [ArgumentError] not a session file's mapping, or already split
188
+ # @raise [JSON::ParserError, SystemCallError] as reading or writing does
189
+ def split_file!(path, name: "messages-#{SecureRandom.hex(4)}.jsonl")
190
+ data = JSON.parse(File.read(path).force_encoding(Encoding::UTF_8))
191
+ raise ArgumentError, "#{path} is not a session file" unless data.is_a?(Hash)
192
+ raise ArgumentError, "#{path} is split already" if data.key?(LOG_KEY) && !data.key?(KEY)
193
+
194
+ messages = of_file(data, path: path)
195
+ content = messages.map { |message| "#{JSON.generate(message)}\n" }.join
196
+ dir = dir_of(path)
197
+ FileUtils.mkdir_p(dir)
198
+ target = File.join(dir, name)
199
+ File.open(target, File::WRONLY | File::CREAT | File::EXCL | File::BINARY, 0o666) do |io|
200
+ io.write(content)
201
+ io.flush
202
+ sync!(io) # on the disk before <id>.json names it: a conversion is a one-off per session
203
+ generation = Generation.new(file: name, count: messages.size, bytes: content.bytesize)
204
+ AtomicFile.write(path, file_text(data.key?(KEY) ? data : data.merge(KEY => []), generation))
205
+ rescue StandardError
206
+ FileUtils.rm_f(target)
207
+ raise
208
+ end
209
+ name
210
+ end
211
+
212
+ # +io+'s bytes on the disk (#split_file!'s generation, not a save's):
213
+ # F_FULLFSYNC on macOS, which flushes the drive's cache too (fsync
214
+ # there doesn't), else, or where it is refused, fsync.
215
+ def sync!(io)
216
+ return io.fsync unless RUBY_PLATFORM.include?("darwin")
217
+
218
+ begin
219
+ io.fcntl(FULLFSYNC)
220
+ rescue Errno::ENOTSUP, Errno::EOPNOTSUPP, Errno::EINVAL, Errno::ENOTTY
221
+ io.fsync
222
+ end
223
+ end
224
+
225
+ # compat shim messages_inline_beside_log: chi 0.201.0 and older read a
226
+ # split file as no messages, and save the turns they ran inline beside
227
+ # the messages_log they keep (an unknown key). Those came after the
228
+ # log's: the log's messages, then the inline ones, the inline system
229
+ # head (role system, no kind) first, in place of the log's if it has one.
230
+ def reconcile(logged, inline)
231
+ return logged if inline.empty?
232
+
233
+ return logged + inline unless system_head?(inline.first)
234
+
235
+ [inline.first, *(system_head?(logged.first) ? logged.drop(1) : logged), *inline.drop(1)]
236
+ end
237
+
238
+ def system_head?(message) = message.is_a?(Hash) && message["role"] == "system" && message["kind"].nil?
239
+
240
+ # One save at a time per session file in this process, across Session
241
+ # objects (Session.mark_error saves a fresh one beside a worker's).
242
+ def locked(path, &)
243
+ lock = @locks_guard.synchronize { @locks[File.expand_path(path)] ||= Mutex.new }
244
+ lock.synchronize(&)
245
+ end
246
+
247
+ # How +now+ (a save's messages, comparable entries) differs from
248
+ # +before+ (the last saved; nil for none): the save_shape fields.
249
+ def shape_of(before, now)
250
+ return { shape: "new", count: now.size } unless before
251
+
252
+ common = [before.size, now.size].min
253
+ at = (0...common).find { |index| before[index] != now[index] } || common
254
+ added = now.size - before.size
255
+ shape = if at == before.size
256
+ added.zero? ? { shape: "same" } : { shape: "append", added: added }
257
+ elsif at.zero? && added >= 0 && before.drop(1) == now[1, before.size - 1]
258
+ { shape: "head", added: added }
259
+ else
260
+ { shape: "rewrite", at: at }
261
+ end
262
+ shape.merge(saved: before.size, count: now.size)
263
+ end
264
+
265
+ # A message as the file has it, with symbol keys; so do a chat turn's
266
+ # tool_calls ({id:, name:, arguments:}; the arguments keep the model's
267
+ # string keys) and image refs ({file:, mime:, width:, …}).
268
+ def symbolize(hash)
269
+ message = hash.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
270
+ %i[tool_calls images].each do |key|
271
+ next unless message[key].is_a?(Array)
272
+
273
+ message[key] = message[key].map do |entry|
274
+ entry.is_a?(Hash) ? entry.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } : entry
275
+ end
276
+ end
277
+ symbolize_empty_answer(message)
278
+ end
279
+
280
+ # An empty-answer note's marker (TurnNote.empty), its steps and its
281
+ # refusal, as they were saved.
282
+ def symbolize_empty_answer(message)
283
+ marker = message[:empty_answer]
284
+ return message unless marker.is_a?(Hash)
285
+
286
+ marker = marker.transform_keys(&:to_sym)
287
+ marker[:steps] = marker[:steps].map { |step| step.is_a?(Hash) ? step.transform_keys(&:to_sym) : step } if marker[:steps].is_a?(Array)
288
+ marker[:refusal] = marker[:refusal].transform_keys(&:to_sym) if marker[:refusal].is_a?(Hash)
289
+ message.merge(empty_answer: marker)
290
+ end
291
+ private_class_method :symbolize_empty_answer
292
+
293
+ # A Session's messages on disk: how its #save writes them and what it
294
+ # wrote (or read) last. One per Session, used under its save lock;
295
+ # .from_file makes the one of a session read from its file.
296
+ #
297
+ # Inline (the setting off, never read split): the whole file, and the
298
+ # save-shape counter's record. Split: the save's messages serialized
299
+ # line by line and compared with the lines it committed last, at the
300
+ # same path, which <id>.json still names (anything else wrote since:
301
+ # another Session object, another process, an older chi inline): only
302
+ # lines added, an append into the same generation; anything else, a new
303
+ # generation. Each split save logs its save_shape record from that
304
+ # comparison, with store=split, by=append|rewrite (what it wrote) and
305
+ # wrote= (bytes, metadata and messages).
306
+ class Store
307
+ # The generation an append was writing was unlinked before its
308
+ # metadata named it again (a rewrite elsewhere replaced it): rewrite.
309
+ class Superseded < StandardError; end
310
+ # The session was deleted while a rewrite wrote its new generation.
311
+ class Deleted < StandardError; end
312
+ private_constant :Superseded, :Deleted
313
+
314
+ # What <id>.json holds as a split save starts: its messages_log as
315
+ # written (+log+) and its inline messages (+inline+; nil without the
316
+ # key, [] for one that isn't a list).
317
+ OnDisk = Data.define(:log, :inline) do
318
+ def self.read(path)
319
+ data = JSON.parse(File.read(path))
320
+ return new(log: nil, inline: nil) unless data.is_a?(Hash)
321
+
322
+ inline = data[KEY].is_a?(Array) ? data[KEY] : [] if data.key?(KEY)
323
+ new(log: data[LOG_KEY], inline: inline)
324
+ rescue JSON::ParserError, SystemCallError
325
+ new(log: nil, inline: nil)
326
+ end
327
+
328
+ # Whether it is +generation+'s commit (a store's last): its log, no
329
+ # inline messages (an older chi's save beside the log is foreign).
330
+ def names?(generation) = !generation.nil? && log == generation.to_file && inline.nil?
331
+
332
+ # The generation it names (a rewrite keeps it a fresh stray), if any.
333
+ def generation_file = log.is_a?(Hash) && GENERATION_NAME.match?(log["file"].to_s) ? log["file"] : nil
334
+ end
335
+ private_constant :OnDisk
336
+
337
+ # The store of a session read from +path+ (parsed: +data+); +messages+
338
+ # false: read without them (#left_out?), and never written.
339
+ def self.from_file(data, path:, messages:)
340
+ return new(left_out: true) unless messages
341
+
342
+ loaded = SessionMessages.load(data, path: path)
343
+ new(read: loaded.messages, path: path, generation: loaded.generation, lines: loaded.lines)
344
+ end
345
+
346
+ # @param read [Array, nil] the messages the file held (string keys),
347
+ # kept until the first save (a split save's first baseline)
348
+ # @param generation [Generation, nil] the split file's, as read
349
+ # @param lines [Array<String>, nil] its committed lines
350
+ def initialize(read: nil, left_out: false, path: nil, generation: nil, lines: nil)
351
+ @read = read
352
+ @left_out = left_out
353
+ @save_shape = SaveShape.new(read: generation ? nil : read)
354
+ @path = path && File.expand_path(path)
355
+ @generation = generation
356
+ @lines = lines
357
+ @swept = false
358
+ end
359
+
360
+ # Read without its messages: #messages is not the conversation, so a
361
+ # save would write [] over it (Session#save refuses).
362
+ def left_out? = @left_out
363
+
364
+ # The messages read, as a session holds them (symbol keys).
365
+ def messages = SessionMessages.restore(@read)
366
+
367
+ # Write +file+ (Session#to_h) as the session file at +path+, and log
368
+ # its save-shape record. A +persisted+ session (read from its file or
369
+ # saved once) whose file is gone was deleted: nothing is written, the
370
+ # skip logged (save_skipped_deleted).
371
+ # @return [Boolean] whether it wrote
372
+ def write(path, file, sid:, persisted:)
373
+ SessionMessages.locked(path) do
374
+ next deleted(sid) if persisted && !File.exist?(path)
375
+
376
+ @generation || SessionMessages.split? ? write_split(path, file, sid, persisted) : write_inline(path, file, sid)
377
+ end
378
+ end
379
+
380
+ private
381
+
382
+ def deleted(sid)
383
+ Log.warn(:worker, "save_skipped_deleted", sid: sid)
384
+ false
385
+ end
386
+
387
+ # What it read is in the file now (or replaced): dropped, so a long
388
+ # session doesn't keep a second copy of its messages. A split save
389
+ # after the setting is turned on reads its baseline from the file.
390
+ def write_inline(path, file, sid)
391
+ shape = @save_shape.measure(file[KEY])
392
+ AtomicFile.write(path, "#{JSON.pretty_generate(file)}\n")
393
+ @save_shape.saved(shape, sid: sid)
394
+ @read = nil
395
+ true
396
+ end
397
+
398
+ def write_split(path, file, sid, persisted)
399
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
400
+ lines = file[KEY].map { |message| JSON.generate(message).freeze }
401
+ dir = SessionMessages.dir_of(path)
402
+ disk = OnDisk.read(path)
403
+ before = prior_lines(path, disk)
404
+ base = before if @lines && same_path?(path) && disk.names?(@generation)
405
+ written = append(path, dir, file, lines, base) if base && lines.first(base.size) == base
406
+ written ||= rewrite(path, dir, file, lines, persisted: persisted, replaced: disk.generation_file)
407
+ return deleted(sid) if written == :deleted
408
+
409
+ sweep(dir) unless @swept
410
+ @path = File.expand_path(path)
411
+ @lines = lines
412
+ @read = nil
413
+ by, wrote = written
414
+ ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000.0
415
+ fields = SessionMessages.shape_of(before, lines).merge(store: "split", by: by, wrote: wrote, ms: ms)
416
+ Log.log(SaveShape::LEVEL, :worker, "save_shape", sid: sid, **fields)
417
+ true
418
+ end
419
+
420
+ # The lines this store last committed at +path+; for one not saved
421
+ # split yet, the inline messages the file holds (or the ones it read)
422
+ # serialized: the save-shape record's baseline only. nil for none.
423
+ def prior_lines(path, disk)
424
+ return nil unless same_path?(path)
425
+
426
+ @lines || (disk.inline || @read)&.map { |message| JSON.generate(message) }
427
+ end
428
+
429
+ def same_path?(path) = @path == File.expand_path(path)
430
+
431
+ # The lines past the committed ones, appended to the same generation
432
+ # after cutting it to its committed bytes (a torn or unrecorded tail).
433
+ # @return [Array(Symbol, Integer), Symbol, nil] [:append, bytes];
434
+ # :deleted when the session went; nil when it must rewrite (the
435
+ # file shorter than its committed bytes, gone, or replaced)
436
+ def append(path, dir, file, lines, base)
437
+ tail = lines.drop(base.size).map { |line| "#{line}\n" }.join
438
+ File.open(File.join(dir, @generation.file), File::WRONLY | File::BINARY) do |io|
439
+ return nil if io.size < @generation.bytes
440
+
441
+ io.truncate(@generation.bytes)
442
+ io.seek(@generation.bytes)
443
+ io.write(tail)
444
+ io.flush # in the file before <id>.json names it
445
+ generation = @generation.with(count: lines.size, bytes: @generation.bytes + tail.bytesize)
446
+ meta = commit(path, file, generation) { raise Superseded if io.stat.nlink.zero? }
447
+ @generation = generation
448
+ [:append, meta + tail.bytesize]
449
+ end
450
+ rescue Superseded
451
+ nil
452
+ rescue Errno::ENOENT
453
+ File.exist?(path) ? nil : :deleted
454
+ end
455
+
456
+ # Every line into a new generation, then the metadata naming it. The
457
+ # one it replaces (this store's, or the one <id>.json named:
458
+ # +replaced+) is kept as a fresh stray (its time set to now) for a
459
+ # reader that parsed the older metadata. A +persisted+ session deleted
460
+ # meanwhile is not brought back: its new generation (and the folder,
461
+ # when that leaves it empty) goes.
462
+ # @return [Array(Symbol, Integer), Symbol] [:rewrite, bytes]; :deleted
463
+ def rewrite(path, dir, file, lines, persisted:, replaced:)
464
+ gone = -> { persisted && !File.exist?(path) }
465
+ return :deleted if gone.call
466
+
467
+ FileUtils.mkdir_p(dir)
468
+ content = lines.map { |line| "#{line}\n" }.join
469
+ name = "messages-#{SecureRandom.hex(4)}.jsonl"
470
+ target = File.join(dir, name)
471
+ File.open(target, File::WRONLY | File::CREAT | File::EXCL | File::BINARY, 0o666) do |io|
472
+ io.write(content)
473
+ rescue StandardError
474
+ FileUtils.rm_f(target)
475
+ raise
476
+ end
477
+ generation = Generation.new(file: name, count: lines.size, bytes: content.bytesize)
478
+ meta = begin
479
+ commit(path, file, generation) { raise Deleted if gone.call }
480
+ rescue StandardError => e
481
+ FileUtils.rm_f(target)
482
+ raise unless e.is_a?(Deleted) || (e.is_a?(Errno::ENOENT) && gone.call)
483
+
484
+ return remove_empty(dir)
485
+ end
486
+ now = Time.now
487
+ [@generation&.file, replaced].compact.uniq.each do |old|
488
+ File.utime(now, now, File.join(dir, old))
489
+ rescue SystemCallError
490
+ nil
491
+ end
492
+ @generation = generation
493
+ sweep(dir)
494
+ [:rewrite, meta + content.bytesize]
495
+ rescue Errno::ENOENT
496
+ raise unless gone.call
497
+
498
+ :deleted
499
+ end
500
+
501
+ # A deleted session's folder this save made again, once empty.
502
+ # @return [Symbol] :deleted
503
+ def remove_empty(dir)
504
+ Dir.rmdir(dir)
505
+ :deleted
506
+ rescue SystemCallError
507
+ :deleted
508
+ end
509
+
510
+ # <id>.json naming +generation+ in place of the messages (the yield is
511
+ # AtomicFile's last check before the rename).
512
+ # @return [Integer] its bytes
513
+ def commit(path, file, generation, &)
514
+ text = SessionMessages.file_text(file, generation)
515
+ AtomicFile.write(path, text, &)
516
+ text.bytesize
517
+ end
518
+
519
+ # Remove the generations the metadata doesn't name that are older
520
+ # than STRAY_GRACE (a crashed rewrite's, a replaced one).
521
+ def sweep(dir)
522
+ cutoff = Time.now - STRAY_GRACE
523
+ Dir.glob(File.join(dir, GENERATION_GLOB)).each do |stray|
524
+ File.unlink(stray) if File.basename(stray) != @generation&.file && File.mtime(stray) < cutoff
525
+ rescue SystemCallError
526
+ nil
527
+ end
528
+ @swept = true
529
+ end
530
+ end
531
+
532
+ # The save-shape counter: how each Session#save's messages differ from
533
+ # the ones the session last saved (or read from its file), as one
534
+ # `save_shape` record in the debug log under the session's sid. It
535
+ # measures what an append-only messages file would write, and writes
536
+ # nothing itself:
537
+ #
538
+ # shape=new the session's first save (nothing saved before)
539
+ # shape=same the messages saved are the ones saved last
540
+ # shape=append only new messages at the end (added=)
541
+ # shape=head the system head (index 0) changed, the rest kept, new
542
+ # messages possibly added at the end (added=)
543
+ # shape=rewrite a message before the end changed or went (at= the
544
+ # first one; at=count is a cut of the tail)
545
+ #
546
+ # with saved= and count= (the message counts before and after) and ms=
547
+ # (the counter's own time). A message is compared by a digest of its
548
+ # JSON (the file form, SessionMessages.dump): an edit in place shows
549
+ # whatever object it touched. One Session holds one, used under its
550
+ # save lock.
551
+ class SaveShape
552
+ # The counter's records' level: info, the default log.level, so the
553
+ # records are there to count without a debug log.
554
+ LEVEL = :info
555
+
556
+ Measure = Data.define(:digests, :fields)
557
+
558
+ # @param read [Array, nil] the messages the session's file held when it
559
+ # was loaded (string keys, as parsed); nil for a session not read from
560
+ # a file. Digested at the first save, so a load that never saves pays
561
+ # nothing.
562
+ def initialize(read: nil)
563
+ @read = read
564
+ @digests = nil
565
+ end
566
+
567
+ # How +dumped+ (the messages a save writes, file form) differs from
568
+ # the last saved ones; nil when the records wouldn't be written.
569
+ # @return [Measure, nil]
570
+ def measure(dumped)
571
+ return nil unless Log.level?(LEVEL)
572
+
573
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
574
+ before = saved_digests
575
+ now = dumped.map { |message| digest(message) }
576
+ fields = SessionMessages.shape_of(before, now)
577
+ fields[:ms] = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000.0
578
+ Measure.new(digests: now, fields: fields)
579
+ rescue StandardError # degrade-ok: a measurement, never in a save's way
580
+ nil
581
+ end
582
+
583
+ # After the save wrote: log +measure+ and take its messages as the
584
+ # saved ones.
585
+ def saved(measure, sid:)
586
+ @read = nil
587
+ return unless measure
588
+
589
+ @digests = measure.digests
590
+ Log.log(LEVEL, :worker, "save_shape", sid: sid, **measure.fields)
591
+ end
592
+
593
+ private
594
+
595
+ def saved_digests
596
+ @digests ||= @read&.map { |message| digest(message) }
597
+ end
598
+
599
+ def digest(message) = JSON.generate(message).hash
600
+ end
601
+ end
602
+ end
@@ -18,7 +18,7 @@ require_relative "session_metrics/cost"
18
18
  require_relative "session_metrics/usage"
19
19
  require_relative "session_metrics/side_totals"
20
20
  require_relative "side_usage"
21
- require_relative "steer"
21
+ require_relative "speaker"
22
22
  require_relative "turn_origin"
23
23
 
24
24
  module Samagotchi
@@ -841,13 +841,16 @@ module Samagotchi
841
841
  # What turn_failed's line is made of (format.js failedTurnText): a
842
842
  # provider error's summary, else the message (capped: a server's error
843
843
  # page can be long) and class, and the steps that stayed (kept_steps).
844
+ # Its error_kind (the event's code, TurnEndings#failed_event) rides
845
+ # beside the words, so SessionStats classifies by it before any regex.
844
846
  def failure_fields(event)
847
+ kind = event[:error_kind]&.to_s
845
848
  summary = event[:summary].to_s
846
- return { summary: summary, kept_steps: event[:kept_steps] }.compact unless summary.empty?
849
+ return { summary: summary, error_kind: kind, kept_steps: event[:kept_steps] }.compact unless summary.empty?
847
850
 
848
851
  message = event[:message].to_s
849
852
  message = "#{message[0, FAILURE_MESSAGE_CHARS - 1]}…" if message.length > FAILURE_MESSAGE_CHARS
850
- { message: message.empty? ? nil : message, error_class: event[:error_class]&.to_s,
853
+ { message: message.empty? ? nil : message, error_class: event[:error_class]&.to_s, error_kind: kind,
851
854
  kept_steps: event[:kept_steps] }.compact
852
855
  end
853
856
 
@@ -1345,7 +1348,7 @@ module Samagotchi
1345
1348
  end
1346
1349
 
1347
1350
  def count_author(record)
1348
- author = Steer.sender_author(record[:author]) or return
1351
+ author = Speaker.sender_author(record[:author]) or return
1349
1352
 
1350
1353
  row = @author_turns[author] || { turns: 0, cost: 0.0 }
1351
1354
  @author_turns[author] = { turns: row[:turns] + 1, cost: row[:cost] + SessionMetrics.record_cost(record) }
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "steer"
3
+ require_relative "speaker"
4
4
 
5
5
  module Samagotchi
6
6
  # Loaded only when a session is read: it brings Grants.
@@ -48,10 +48,10 @@ module Samagotchi
48
48
  # +author+'s Participants::Entry (their name, cap, grant mode), nil for
49
49
  # none; read again on a miss, as #name_for.
50
50
  def entry_for(author, session: nil)
51
- return nil unless Steer.participant_author?(author)
51
+ return nil unless Speaker.participant_author?(author)
52
52
 
53
53
  refresh!(session) if session && source_id(session) != @session_id
54
- id = Steer.participant_id(author)
54
+ id = Speaker.participant_id(author)
55
55
  @entries.find { |e| e.id == id } || (@entries = read).find { |e| e.id == id }
56
56
  end
57
57
 
@@ -77,7 +77,7 @@ module Samagotchi
77
77
  def fresh_prompt_mode(fresh, active)
78
78
  return nil unless fresh.participant?
79
79
 
80
- id = Steer.participant_id(fresh.author)
80
+ id = Speaker.participant_id(fresh.author)
81
81
  active.any? { |entry| entry.id == id } && fresh.pair? ? :pair : nil
82
82
  end
83
83