samagotchi 0.192.0 → 0.194.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 (190) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +128 -1
  3. data/docs/architecture.md +3 -3
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +82 -40
  6. data/docs/cli.md +47 -17
  7. data/docs/configuration.md +75 -8
  8. data/docs/context.md +8 -5
  9. data/docs/desktop.md +3 -0
  10. data/docs/guardrails.md +20 -5
  11. data/docs/hooks.md +1 -0
  12. data/docs/internals/bridge.md +3 -1
  13. data/docs/internals/bundles.md +2 -2
  14. data/docs/internals/engine.md +46 -3
  15. data/docs/internals/pages.md +4 -4
  16. data/docs/internals/panes.md +66 -0
  17. data/docs/internals/participants.md +5 -3
  18. data/docs/internals/peers.md +176 -27
  19. data/docs/internals/prompt-caching.md +6 -1
  20. data/docs/internals/remote-sessions.md +6 -0
  21. data/docs/internals/session-lifecycle.md +12 -4
  22. data/docs/internals/web-frontend.md +106 -22
  23. data/docs/internals/working-set.md +5 -1
  24. data/docs/peers.md +150 -27
  25. data/docs/plugins.md +48 -7
  26. data/docs/releasing.md +30 -2
  27. data/docs/scheduling.md +3 -2
  28. data/docs/sessions.md +16 -7
  29. data/docs/sub-agent.md +6 -4
  30. data/docs/system-one.md +4 -0
  31. data/docs/testing.md +38 -3
  32. data/docs/thin-clients.md +27 -11
  33. data/lib/samagotchi/bridge/card_store.rb +1 -1
  34. data/lib/samagotchi/broadcast/triage_model.rb +17 -0
  35. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  36. data/lib/samagotchi/bundles/claude-peer/plugin.rb +24 -5
  37. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +61 -24
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair +31 -8
  39. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  40. data/lib/samagotchi/bundles/codex-peer/plugin.rb +62 -6
  41. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +57 -19
  42. data/lib/samagotchi/bundles/codex-peer/scripts/pair +28 -7
  43. data/lib/samagotchi/bundles/coordinator/manifest.yml +2 -2
  44. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +31 -0
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  47. data/lib/samagotchi/bundles/mcp/plugin.rb +0 -7
  48. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  49. data/lib/samagotchi/chi_invocation.rb +7 -0
  50. data/lib/samagotchi/client.rb +18 -0
  51. data/lib/samagotchi/codex_rollout.rb +93 -0
  52. data/lib/samagotchi/compat.rb +8 -1
  53. data/lib/samagotchi/config.rb +19 -6
  54. data/lib/samagotchi/continue_offer.rb +13 -1
  55. data/lib/samagotchi/delivery.rb +2 -2
  56. data/lib/samagotchi/effective_model.rb +28 -2
  57. data/lib/samagotchi/engine/cards.rb +9 -4
  58. data/lib/samagotchi/engine/hooks.rb +8 -0
  59. data/lib/samagotchi/engine/models.rb +197 -7
  60. data/lib/samagotchi/engine/plugins.rb +2 -0
  61. data/lib/samagotchi/engine/side_requests.rb +72 -13
  62. data/lib/samagotchi/engine/toolkit.rb +1 -1
  63. data/lib/samagotchi/engine/turn_helpers.rb +1 -1
  64. data/lib/samagotchi/engine.rb +11 -8
  65. data/lib/samagotchi/engine_snapshots.rb +16 -3
  66. data/lib/samagotchi/events.rb +1 -0
  67. data/lib/samagotchi/guardrails/pair_boundary.rb +49 -18
  68. data/lib/samagotchi/hooks.rb +3 -1
  69. data/lib/samagotchi/host_registry.rb +146 -16
  70. data/lib/samagotchi/idle_client.rb +13 -2
  71. data/lib/samagotchi/idle_recap.rb +33 -3
  72. data/lib/samagotchi/idle_target.rb +27 -7
  73. data/lib/samagotchi/jsonl_store.rb +13 -2
  74. data/lib/samagotchi/llm/adapter_common.rb +4 -2
  75. data/lib/samagotchi/llm/anthropic_messages.rb +14 -2
  76. data/lib/samagotchi/llm/errors.rb +35 -4
  77. data/lib/samagotchi/llm/model_listing.rb +19 -0
  78. data/lib/samagotchi/llm/openai_chat.rb +8 -2
  79. data/lib/samagotchi/llm/prompt_cache.rb +5 -0
  80. data/lib/samagotchi/model_binding.rb +46 -4
  81. data/lib/samagotchi/model_catalog.rb +68 -8
  82. data/lib/samagotchi/model_profile.rb +35 -0
  83. data/lib/samagotchi/models_command.rb +8 -4
  84. data/lib/samagotchi/pages/launch.rb +1 -1
  85. data/lib/samagotchi/panes/kitty.rb +122 -0
  86. data/lib/samagotchi/panes.rb +185 -0
  87. data/lib/samagotchi/peer_announce.rb +245 -0
  88. data/lib/samagotchi/peer_cold.rb +92 -0
  89. data/lib/samagotchi/peer_command.rb +121 -20
  90. data/lib/samagotchi/peer_continue.rb +42 -16
  91. data/lib/samagotchi/peer_exchanges.rb +7 -0
  92. data/lib/samagotchi/peer_mailbox.rb +50 -10
  93. data/lib/samagotchi/peer_pair_here.rb +149 -0
  94. data/lib/samagotchi/peer_presence.rb +434 -0
  95. data/lib/samagotchi/peer_receipts.rb +33 -6
  96. data/lib/samagotchi/peer_say.rb +46 -21
  97. data/lib/samagotchi/peer_wait_expiry.rb +47 -0
  98. data/lib/samagotchi/plugin/api.rb +13 -1
  99. data/lib/samagotchi/plugin/card.rb +68 -11
  100. data/lib/samagotchi/plugin/context.rb +33 -2
  101. data/lib/samagotchi/plugin/panes.rb +54 -0
  102. data/lib/samagotchi/plugin/peer.rb +170 -63
  103. data/lib/samagotchi/plugin/peer_pairing.rb +290 -0
  104. data/lib/samagotchi/plugin/peer_start.rb +301 -0
  105. data/lib/samagotchi/plugin/peer_start_hook.rb +207 -0
  106. data/lib/samagotchi/plugin/peers.rb +89 -9
  107. data/lib/samagotchi/recap_setup.rb +40 -3
  108. data/lib/samagotchi/self_report.rb +25 -6
  109. data/lib/samagotchi/send_command.rb +6 -6
  110. data/lib/samagotchi/served_lookup.rb +225 -0
  111. data/lib/samagotchi/served_ref.rb +41 -0
  112. data/lib/samagotchi/session_access/contract.rb +6 -0
  113. data/lib/samagotchi/session_access/local.rb +149 -40
  114. data/lib/samagotchi/session_access/remote.rb +4 -4
  115. data/lib/samagotchi/session_access/remote_peers.rb +8 -5
  116. data/lib/samagotchi/session_chain/links.rb +8 -3
  117. data/lib/samagotchi/session_commands.rb +40 -8
  118. data/lib/samagotchi/session_continue.rb +11 -6
  119. data/lib/samagotchi/session_lifecycle/allowed.rb +4 -2
  120. data/lib/samagotchi/session_manager/delivery.rb +5 -0
  121. data/lib/samagotchi/session_manager/lifecycle.rb +58 -7
  122. data/lib/samagotchi/session_manager/removal.rb +3 -0
  123. data/lib/samagotchi/session_manager/spawn.rb +6 -1
  124. data/lib/samagotchi/session_model_settings.rb +7 -3
  125. data/lib/samagotchi/session_stores.rb +25 -11
  126. data/lib/samagotchi/sessions_command.rb +16 -3
  127. data/lib/samagotchi/system_one/http_backend.rb +111 -10
  128. data/lib/samagotchi/system_one/runs.rb +5 -2
  129. data/lib/samagotchi/system_prompt.rb +11 -4
  130. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -1
  131. data/lib/samagotchi/terminal_ui/formatting.rb +26 -12
  132. data/lib/samagotchi/terminal_ui/status_row.rb +20 -3
  133. data/lib/samagotchi/terminal_ui.rb +1 -1
  134. data/lib/samagotchi/testing/boundary.rb +0 -1
  135. data/lib/samagotchi/testing/bundle.rb +6 -2
  136. data/lib/samagotchi/testing/host.rb +1 -0
  137. data/lib/samagotchi/testing/recorder.rb +3 -0
  138. data/lib/samagotchi/turn_endings.rb +6 -2
  139. data/lib/samagotchi/user_typed.rb +29 -0
  140. data/lib/samagotchi/version.rb +1 -1
  141. data/lib/samagotchi/web/app.rb +8 -20
  142. data/lib/samagotchi/web/participant_review.rb +1 -1
  143. data/lib/samagotchi/web/participant_view.rb +1 -1
  144. data/lib/samagotchi/web/peer_routes.rb +40 -15
  145. data/lib/samagotchi/web/public/agent_rows.js +206 -0
  146. data/lib/samagotchi/web/public/agent_runs.js +595 -0
  147. data/lib/samagotchi/web/public/answer_fold.js +41 -44
  148. data/lib/samagotchi/web/public/app.js +4 -4
  149. data/lib/samagotchi/web/public/block_fix.js +1 -1
  150. data/lib/samagotchi/web/public/card.js +26 -10
  151. data/lib/samagotchi/web/public/cards_place.js +6 -4
  152. data/lib/samagotchi/web/public/context_chips.js +24 -2
  153. data/lib/samagotchi/web/public/copy.js +8 -2
  154. data/lib/samagotchi/web/public/data.js +2 -1
  155. data/lib/samagotchi/web/public/format.js +9 -1
  156. data/lib/samagotchi/web/public/history_reveal.js +5 -2
  157. data/lib/samagotchi/web/public/index.html +56 -2
  158. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  159. data/lib/samagotchi/web/public/model_pick.js +18 -5
  160. data/lib/samagotchi/web/public/model_picker.js +1 -1
  161. data/lib/samagotchi/web/public/page_view.js +1 -1
  162. data/lib/samagotchi/web/public/pages.css +1 -7
  163. data/lib/samagotchi/web/public/peer_chip.js +15 -5
  164. data/lib/samagotchi/web/public/peer_data.js +4 -2
  165. data/lib/samagotchi/web/public/peer_mailbox_api.js +2 -1
  166. data/lib/samagotchi/web/public/peer_note.js +4 -2
  167. data/lib/samagotchi/web/public/peer_row.js +37 -0
  168. data/lib/samagotchi/web/public/peer_wait.js +36 -0
  169. data/lib/samagotchi/web/public/quiet_notes.js +12 -1
  170. data/lib/samagotchi/web/public/revise_stack.js +5 -2
  171. data/lib/samagotchi/web/public/send_turn.js +11 -3
  172. data/lib/samagotchi/web/public/served_ref.js +9 -0
  173. data/lib/samagotchi/web/public/session_fields.js +1 -0
  174. data/lib/samagotchi/web/public/session_state.js +4 -0
  175. data/lib/samagotchi/web/public/stage_missing.js +23 -6
  176. data/lib/samagotchi/web/public/stream_handlers.js +16 -0
  177. data/lib/samagotchi/web/public/turn_block.js +4 -0
  178. data/lib/samagotchi/web/public/version_notices.js +7 -1
  179. data/lib/samagotchi/web/session_control.rb +19 -10
  180. data/lib/samagotchi/web/session_show.rb +20 -0
  181. data/lib/samagotchi/web/update_ops.rb +2 -2
  182. data/lib/samagotchi/worker/command_queue.rb +3 -0
  183. data/lib/samagotchi/worker/mail.rb +24 -1
  184. data/lib/samagotchi/worker.rb +8 -5
  185. data/lib/samagotchi/worker_inbound/mail.rb +34 -6
  186. data/lib/samagotchi/worker_inbound.rb +11 -3
  187. data/lib/samagotchi/worker_link.rb +13 -1
  188. data/lib/samagotchi/worker_wakes.rb +33 -5
  189. metadata +22 -2
  190. data/lib/samagotchi/web/public/pages_group.js +0 -67
@@ -0,0 +1,434 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+ require "securerandom"
6
+ require "time"
7
+ require_relative "archive_store"
8
+ require_relative "atomic_file"
9
+ require_relative "peer_mailbox"
10
+ require_relative "session_paths"
11
+
12
+ module Samagotchi
13
+ # Which peer sessions run here and which chi sessions wait for one, so a
14
+ # pairing needs no id copied by hand (docs/peers.md, Pairing). One folder
15
+ # per peer, inside the mailbox root on purpose (the one folder a sandboxed
16
+ # peer may write; chi's own tools can't, the chi-mailbox guardrail):
17
+ # .here/<peer>/<peer session>.json PeerHere: a peer session that announced itself (chi peer announce)
18
+ # .here/<peer>/waiting/<chi session>.json PeerWaiting: a session that waits for one (/claude pair), 10 minutes
19
+ # .here/<peer>/paired/<peer session>/<chi session> one empty file per pairing made with a peer session
20
+ # Nothing here is trusted: any local process can write it. Every name is
21
+ # checked before it becomes a path, every file read with lstat, a size cap
22
+ # and no link followed; a dead PeerHere is removed by whoever reads it; a
23
+ # stale mark is never removed by a reader (only its session's worker, its
24
+ # unpair and its delete), so its worker still says it timed out. The
25
+ # owner's Pair is what trusts a row. See docs/internals/peers.md.
26
+ module PeerPresence
27
+ DIR = ".here"
28
+ WAITING = "waiting"
29
+ PAIRED = "paired"
30
+ # How long a mark waits (owner decision 3: a constant).
31
+ WAIT_SECONDS = 600
32
+ # A peer session's id as a file name: Claude Code's uuid, a Codex thread.
33
+ PEER_SESSION_RE = /\A[A-Za-z0-9][A-Za-z0-9-]{0,63}\z/
34
+ FILE_MAX_BYTES = 8192
35
+ # A claimed mark's name: <session>.json.claimed-<hex> (never a mark's).
36
+ CLAIMED = ".claimed-"
37
+
38
+ # A peer session that announced itself: its +peer+ name, its +session+
39
+ # id, the +address+ chi sends to (its inbox socket), its +cwd+ and
40
+ # +project+ (MemoryPaths.project_key of the cwd, computed once by the
41
+ # announce), its +pid+ and when (+at+). Never a messaging token.
42
+ PeerHere = Data.define(:peer, :session, :address, :cwd, :project, :pid, :at) do
43
+ def to_h = { "peer" => peer, "session" => session, "address" => address, "cwd" => cwd, "project" => project,
44
+ "pid" => pid, "at" => at }
45
+
46
+ # @return [PeerHere, nil] nil for a value of the wrong shape
47
+ def self.from_h(data)
48
+ return nil unless data.is_a?(Hash) && PeerMailbox.valid_name?(data["peer"])
49
+ return nil unless data["session"].is_a?(String) && data["session"].match?(PEER_SESSION_RE)
50
+ return nil unless %w[address cwd at].all? { |key| data[key].is_a?(String) && !data[key].empty? }
51
+ return nil unless (data["project"].nil? || data["project"].is_a?(String)) && data["pid"].is_a?(Integer)
52
+
53
+ new(peer: data["peer"], session: data["session"], address: data["address"], cwd: data["cwd"],
54
+ project: data["project"], pid: data["pid"], at: data["at"])
55
+ end
56
+ end
57
+
58
+ # A chi +session+ that waits for a peer of its +project+ since +at+.
59
+ PeerWaiting = Data.define(:session, :project, :at) do
60
+ def to_h = { "session" => session, "project" => project, "at" => at }
61
+
62
+ def self.from_h(data)
63
+ return nil unless data.is_a?(Hash) && SessionPaths.valid_id?(data["session"].to_s)
64
+ return nil unless [data["project"], data["at"]].all? { |value| value.nil? || value.is_a?(String) }
65
+
66
+ new(session: data["session"], project: data["project"], at: data["at"])
67
+ end
68
+
69
+ # When the wait ends; nil for an unparsable +at+.
70
+ def until_at
71
+ Time.iso8601(at.to_s) + WAIT_SECONDS
72
+ rescue ArgumentError
73
+ nil
74
+ end
75
+
76
+ # Past its 10 minutes, or an +at+ in the future or unparsable (any
77
+ # peer can write the folder).
78
+ def stale?(now = Time.now)
79
+ ends = until_at or return true
80
+ ends - WAIT_SECONDS > now || now >= ends
81
+ end
82
+ end
83
+
84
+ # A claimed mark: its file, renamed to +claimed+ from +path+.
85
+ Claim = Data.define(:path, :claimed)
86
+
87
+ module_function
88
+
89
+ # <state dir>/mailbox/.here
90
+ def root(state_dir: nil) = File.join(PeerMailbox.root(state_dir: state_dir), DIR)
91
+
92
+ # @raise [PeerMailbox::Invalid] a bad peer name
93
+ def peer_dir(peer, state_dir: nil) = File.join(root(state_dir: state_dir), PeerMailbox.check_name!(peer))
94
+
95
+ def peer_session?(id) = id.is_a?(String) && id.match?(PEER_SESSION_RE)
96
+
97
+ # Writes +entry+ (written whole), and supersedes a live entry with the
98
+ # same address under another session (a /clear gives Claude a new
99
+ # session id on the same socket): removed, its pairing files moved to
100
+ # +entry+'s session.
101
+ # @return [Array<String>] the superseded sessions
102
+ # @raise [PeerMailbox::Invalid] a link where a folder should be, a bad id
103
+ def announce!(entry, state_dir: nil)
104
+ raise PeerMailbox::Invalid, "#{entry.session.to_s[0, 40].inspect} isn't a peer session id" unless peer_session?(entry.session)
105
+
106
+ dir = writable_dir(entry.peer, state_dir: state_dir)
107
+ superseded = here(entry.peer, state_dir: state_dir).select do |other|
108
+ other.address == entry.address && other.session != entry.session
109
+ end
110
+ AtomicFile.write(File.join(dir, "#{entry.session}.json"), "#{JSON.generate(entry.to_h)}\n")
111
+ superseded.each do |other|
112
+ FileUtils.rm_f(File.join(dir, "#{other.session}.json"))
113
+ move_paired(entry.peer, from: other.session, to: entry.session, state_dir: state_dir)
114
+ end
115
+ superseded.map(&:session)
116
+ end
117
+
118
+ # The live peer sessions of +peer+ (+project+'s only when given), oldest
119
+ # first; a dead one (its pid gone, or its socket) is removed.
120
+ # @return [Array<PeerHere>]
121
+ def here(peer, project: nil, state_dir: nil)
122
+ dir = peer_dir(peer, state_dir: state_dir)
123
+ return [] unless real_dir?(dir)
124
+
125
+ entries = Dir.children(dir).filter_map do |name|
126
+ session = name.delete_suffix(".json")
127
+ next unless name.end_with?(".json") && peer_session?(session)
128
+
129
+ entry = read_entry(File.join(dir, name), peer, session)
130
+ next unless entry
131
+
132
+ next entry if live?(entry)
133
+
134
+ FileUtils.rm_f(File.join(dir, name))
135
+ nil
136
+ end
137
+ entries = entries.select { |entry| entry.project == project } if project
138
+ entries.sort_by { |entry| [entry.at, entry.session] }
139
+ rescue PeerMailbox::Invalid, SystemCallError
140
+ []
141
+ end
142
+
143
+ # +peer+'s live entry for +session+, or nil.
144
+ def find(peer, session, state_dir: nil)
145
+ here(peer, state_dir: state_dir).find { |entry| entry.session == session }
146
+ end
147
+
148
+ # Its pid alive and its address a socket that exists (a crashed Claude
149
+ # leaves its socket file). A socket named <n>.sock (Claude Code's, by
150
+ # its pid) must be +pid+'s: a forged entry with a real Claude's pid and
151
+ # its own socket would borrow that Claude's window title and Show.
152
+ def live?(entry)
153
+ return false unless entry.pid.positive? && File.socket?(entry.address)
154
+ return false if (named = File.basename(entry.address)[/\A(\d+)\.sock\z/, 1]) && Integer(named, 10) != entry.pid
155
+
156
+ Process.kill(0, entry.pid)
157
+ true
158
+ rescue Errno::EPERM
159
+ true
160
+ rescue Errno::ESRCH, RangeError
161
+ false
162
+ end
163
+
164
+ # Session +session+ waits for +peer+ (written whole; again: a new wait).
165
+ # @return [PeerWaiting]
166
+ def wait!(peer, session:, project:, state_dir: nil, now: Time.now)
167
+ SessionPaths.check_id!(session)
168
+ dir = writable_dir(peer, WAITING, state_dir: state_dir)
169
+ mark = PeerWaiting.new(session: session, project: project, at: now.utc.iso8601)
170
+ AtomicFile.write(File.join(dir, "#{session}.json"), "#{JSON.generate(mark.to_h)}\n")
171
+ mark
172
+ end
173
+
174
+ # Session +session+'s mark for +peer+, stale or not; nil without one.
175
+ # @return [PeerWaiting, nil]
176
+ def waiting(peer, session, state_dir: nil)
177
+ return nil unless SessionPaths.valid_id?(session.to_s)
178
+
179
+ read_mark(File.join(peer_dir(peer, state_dir: state_dir), WAITING, "#{session}.json"), session)
180
+ rescue PeerMailbox::Invalid
181
+ nil
182
+ end
183
+
184
+ # The fresh marks of +project+ for +peer+ (a stale or claimed one isn't
185
+ # one, nor an archived session's: stale on read; none is removed),
186
+ # oldest first.
187
+ # @return [Array<PeerWaiting>]
188
+ def marks(peer, project:, state_dir: nil, now: Time.now)
189
+ sessions = state_dir || SessionPaths.default_state_dir
190
+ all_marks(peer, state_dir: state_dir).select { |mark| mark.project == project && !mark.stale?(now) }
191
+ .reject { |mark| ArchiveStore.archived?(SessionPaths.session_dir(mark.session, state_dir: sessions)) }
192
+ .sort_by { |mark| [mark.at, mark.session] }
193
+ end
194
+
195
+ # Session +session+'s marks, stale ones too: [[peer, PeerWaiting]], by peer.
196
+ def session_marks(session, state_dir: nil)
197
+ peers(state_dir: state_dir).filter_map do |peer|
198
+ mark = waiting(peer, session, state_dir: state_dir)
199
+ [peer, mark] if mark
200
+ end
201
+ end
202
+
203
+ # Takes session +session+'s fresh mark for +peer+ (an atomic rename), so
204
+ # one pairing pairs against it. A claim that lost (no mark, a stale one,
205
+ # another took it) is nil. #release puts it back; a pairing that paired
206
+ # ends it (#stop_waiting).
207
+ # @return [Claim, nil]
208
+ def claim(peer, session, state_dir: nil, now: Time.now)
209
+ mark = waiting(peer, session, state_dir: state_dir)
210
+ return nil if mark.nil? || mark.stale?(now)
211
+
212
+ path = File.join(peer_dir(peer, state_dir: state_dir), WAITING, "#{session}.json")
213
+ claimed = "#{path}#{CLAIMED}#{SecureRandom.hex(4)}"
214
+ File.rename(path, claimed)
215
+ Claim.new(path: path, claimed: claimed)
216
+ rescue Errno::ENOENT, PeerMailbox::Invalid
217
+ nil
218
+ end
219
+
220
+ # Whether a pairing holds session +session+'s mark for +peer+ now (a
221
+ # claim taken, its pair not done): while it does, the mark is only its
222
+ # claimed file, so #waiting and #marks don't see it. A claimed leftover
223
+ # past its 10 minutes (a crash) isn't held.
224
+ def claimed?(peer, session, state_dir: nil, now: Time.now)
225
+ return false unless SessionPaths.valid_id?(session.to_s)
226
+
227
+ dir = File.join(peer_dir(peer, state_dir: state_dir), WAITING)
228
+ return false unless real_dir?(dir)
229
+
230
+ prefix = "#{session}.json#{CLAIMED}"
231
+ Dir.children(dir).any? do |name|
232
+ next false unless name.start_with?(prefix)
233
+
234
+ mark = read_mark(File.join(dir, name), session)
235
+ mark && !mark.stale?(now)
236
+ end
237
+ rescue PeerMailbox::Invalid, SystemCallError
238
+ false
239
+ end
240
+
241
+ # A claim whose pairing didn't pair: the mark back, unless a new one
242
+ # took its place.
243
+ def release(claim)
244
+ return unless claim
245
+ return File.delete(claim.claimed) if File.exist?(claim.path)
246
+
247
+ File.rename(claim.claimed, claim.path)
248
+ rescue Errno::ENOENT
249
+ nil
250
+ end
251
+
252
+ # Ends session +session+'s wait for +peer+: its mark and any claimed
253
+ # leftover (a crash between a claim and its pair).
254
+ # @return [Boolean] whether a mark was there
255
+ def stop_waiting(peer, session, state_dir: nil)
256
+ return false unless SessionPaths.valid_id?(session.to_s)
257
+
258
+ dir = File.join(peer_dir(peer, state_dir: state_dir), WAITING)
259
+ return false unless real_dir?(dir)
260
+
261
+ name = "#{session}.json"
262
+ found = Dir.children(dir).select { |entry| entry == name || entry.start_with?("#{name}#{CLAIMED}") }
263
+ found.each { |entry| FileUtils.rm_f(File.join(dir, entry)) }
264
+ found.include?(name)
265
+ rescue PeerMailbox::Invalid, SystemCallError
266
+ false
267
+ end
268
+
269
+ # Removes session +session+'s wait for +peer+ only when it is +mark+
270
+ # (the one a caller wrote: a /<peer> start whose tab didn't open), never
271
+ # a newer wait nor a claimed file an announce holds.
272
+ # @return [Boolean] whether it was removed
273
+ def drop_wait(peer, session, mark, state_dir: nil)
274
+ return false unless mark && waiting(peer, session, state_dir: state_dir) == mark
275
+
276
+ File.delete(File.join(peer_dir(peer, state_dir: state_dir), WAITING, "#{session}.json"))
277
+ true
278
+ rescue Errno::ENOENT, PeerMailbox::Invalid
279
+ false
280
+ end
281
+
282
+ # The pairing of chi session +chi+ with +peer+'s session +peer_session+:
283
+ # one empty file, never rewritten (a resume's refresh lists them).
284
+ def paired!(peer, peer_session, chi, state_dir: nil)
285
+ return unless peer_session?(peer_session) && SessionPaths.valid_id?(chi.to_s)
286
+
287
+ dir = writable_dir(peer, PAIRED, peer_session, state_dir: state_dir)
288
+ FileUtils.touch(File.join(dir, chi))
289
+ end
290
+
291
+ # The chi sessions +peer+'s session +peer_session+ paired, by name.
292
+ # @return [Array<String>]
293
+ def paired_sessions(peer, peer_session, state_dir: nil)
294
+ return [] unless peer_session?(peer_session)
295
+
296
+ dir = File.join(peer_dir(peer, state_dir: state_dir), PAIRED, peer_session)
297
+ return [] unless real_dir?(File.dirname(dir)) && real_dir?(dir)
298
+
299
+ Dir.children(dir).select { |name| SessionPaths.valid_id?(name) }.sort
300
+ rescue PeerMailbox::Invalid, SystemCallError
301
+ []
302
+ end
303
+
304
+ # The one file of +peer_session+'s pairing of +chi+ (a refresh that found
305
+ # it no longer paired).
306
+ def drop_paired(peer, peer_session, chi, state_dir: nil)
307
+ return unless peer_session?(peer_session) && SessionPaths.valid_id?(chi.to_s)
308
+
309
+ dir = File.join(peer_dir(peer, state_dir: state_dir), PAIRED, peer_session)
310
+ FileUtils.rm_f(File.join(dir, chi))
311
+ rmdir_if_empty(dir)
312
+ end
313
+
314
+ # Chi session +chi+'s pairing files for +peer+, whichever peer session
315
+ # made them (an unpair, a delete).
316
+ # @return [Array<String>] the paths removed
317
+ def unpaired!(peer, chi, state_dir: nil)
318
+ return [] unless SessionPaths.valid_id?(chi.to_s)
319
+
320
+ dir = File.join(peer_dir(peer, state_dir: state_dir), PAIRED)
321
+ return [] unless real_dir?(dir)
322
+
323
+ Dir.children(dir).filter_map do |peer_session|
324
+ path = File.join(dir, peer_session, chi)
325
+ next unless peer_session?(peer_session) && (File.exist?(path) || File.symlink?(path))
326
+
327
+ FileUtils.rm_f(path)
328
+ rmdir_if_empty(File.dirname(path))
329
+ path
330
+ end
331
+ rescue PeerMailbox::Invalid, SystemCallError
332
+ []
333
+ end
334
+
335
+ # A peer session's pairing folder once its last pairing ended (rmdir: a
336
+ # pairing written there meanwhile keeps it, never rm_rf).
337
+ def rmdir_if_empty(dir)
338
+ Dir.rmdir(dir)
339
+ rescue SystemCallError
340
+ nil
341
+ end
342
+
343
+ # A superseded session's pairing files, moved to +to+.
344
+ def move_paired(peer, from:, to:, state_dir: nil)
345
+ paired_sessions(peer, from, state_dir: state_dir).each do |chi|
346
+ paired!(peer, to, chi, state_dir: state_dir)
347
+ end
348
+ FileUtils.rm_rf(File.join(peer_dir(peer, state_dir: state_dir), PAIRED, from)) if peer_session?(from)
349
+ end
350
+
351
+ # A deleted chi session's marks and pairing files, every peer's.
352
+ # @return [Array<String>] what was removed
353
+ def remove_session(session, state_dir: nil)
354
+ peers(state_dir: state_dir).flat_map do |peer|
355
+ removed = stop_waiting(peer, session, state_dir: state_dir) ? [File.join(peer_dir(peer, state_dir: state_dir), WAITING, "#{session}.json")] : []
356
+ removed + unpaired!(peer, session, state_dir: state_dir)
357
+ end
358
+ end
359
+
360
+ # A continue's carry (SessionContinue :peers): each mark of +from+ moves
361
+ # to +to+, keeping when it started, so the new link shows it, pairs on
362
+ # it, cancels it and times it out.
363
+ # @return [Array<String>] the peers whose mark moved
364
+ def carry(from:, to:, state_dir: nil)
365
+ session_marks(from, state_dir: state_dir).filter_map do |peer, mark|
366
+ dir = writable_dir(peer, WAITING, state_dir: state_dir)
367
+ moved = mark.with(session: to)
368
+ AtomicFile.write(File.join(dir, "#{to}.json"), "#{JSON.generate(moved.to_h)}\n")
369
+ FileUtils.rm_f(File.join(dir, "#{from}.json"))
370
+ peer
371
+ end
372
+ end
373
+
374
+ # The peers with a folder here, sorted.
375
+ def peers(state_dir: nil)
376
+ dir = root(state_dir: state_dir)
377
+ return [] unless real_dir?(dir)
378
+
379
+ Dir.children(dir).select { |name| PeerMailbox.valid_name?(name) && real_dir?(File.join(dir, name)) }.sort
380
+ rescue SystemCallError
381
+ []
382
+ end
383
+
384
+ # Every readable mark of +peer+ (stale ones too).
385
+ def all_marks(peer, state_dir: nil)
386
+ dir = File.join(peer_dir(peer, state_dir: state_dir), WAITING)
387
+ return [] unless real_dir?(dir)
388
+
389
+ Dir.children(dir).filter_map do |name|
390
+ session = name.delete_suffix(".json")
391
+ next unless name.end_with?(".json") && SessionPaths.valid_id?(session)
392
+
393
+ read_mark(File.join(dir, name), session)
394
+ end
395
+ rescue PeerMailbox::Invalid, SystemCallError
396
+ []
397
+ end
398
+
399
+ def read_entry(path, peer, session)
400
+ entry = PeerHere.from_h(read_json(path))
401
+ entry if entry && entry.peer == peer && entry.session == session
402
+ end
403
+
404
+ def read_mark(path, session)
405
+ mark = PeerWaiting.from_h(read_json(path))
406
+ mark if mark&.session == session
407
+ end
408
+
409
+ # A regular file's JSON (no link followed, at most FILE_MAX_BYTES), else nil.
410
+ def read_json(path)
411
+ stat = File.lstat(path)
412
+ return nil unless stat.file? && stat.size <= FILE_MAX_BYTES
413
+
414
+ JSON.parse(File.open(path, File::RDONLY | File::NOFOLLOW) { |io| io.read(FILE_MAX_BYTES + 1) }.to_s)
415
+ rescue SystemCallError, IOError, JSON::ParserError, EncodingError
416
+ nil
417
+ end
418
+
419
+ # .here/<peer>/<parts…> made, refusing a link anywhere on the way.
420
+ # @raise [PeerMailbox::Invalid]
421
+ def writable_dir(peer, *parts, state_dir: nil)
422
+ dir = peer_dir(peer, state_dir: state_dir)
423
+ paths = [root(state_dir: state_dir), dir]
424
+ parts.each { |part| paths << File.join(paths.last, part) }
425
+ paths.each do |path|
426
+ raise PeerMailbox::Invalid, "#{path} is a link; chi doesn't follow links there" if File.symlink?(path)
427
+ end
428
+ FileUtils.mkdir_p(paths.last)
429
+ paths.last
430
+ end
431
+
432
+ def real_dir?(path) = PeerMailbox.real_dir?(path)
433
+ end
434
+ end
@@ -14,7 +14,11 @@ module Samagotchi
14
14
  # worker alone (on its loop thread); read by the CLI (chi peer say's
15
15
  # line, ls) and chi web. A peer's own folder (PeerMailbox) holds none of
16
16
  # it, so nothing a peer writes moves chi's counters.
17
- # {"peers": {"<peer>": {"box": "a1b2c3", "taken": 12, "receipts": [Receipt…]}}}
17
+ # {"peers": {"<peer>": {"box": "a1b2c3", "taken": 12, "receipts": [Receipt…]}}, "peer_wakes": 2}
18
+ # +peer_wakes+: the peer wake turns in a row since the last interactive
19
+ # input (WorkerWakes#peer_in_a_row), so the peer.turns budget outlives a
20
+ # worker; absent is 0 (an older chi's file, and an older worker's write
21
+ # drops it: a reset).
18
22
  class PeerReceipts
19
23
  FILE = "peer_receipts.json"
20
24
  # The receipt's states: woke (its wake turn ran), held (it asked; a
@@ -61,17 +65,22 @@ module Samagotchi
61
65
  def receipt(serial) = receipts.reverse_each.find { |item| item.serial == serial }
62
66
  end
63
67
 
64
- # The whole file: Peer by name.
65
- Book = Data.define(:peers) do
68
+ # The whole file: Peer by name, and the peer wake turns in a row.
69
+ Book = Data.define(:peers, :peer_wakes) do
70
+ def initialize(peers:, peer_wakes: 0) = super
71
+
66
72
  def self.empty = new(peers: {})
67
73
 
68
74
  def peer(name) = peers[name.to_s] || Peer.empty
69
75
 
70
- def to_h = { "peers" => peers.transform_values(&:to_h) }
76
+ def to_h = { "peers" => peers.transform_values(&:to_h), "peer_wakes" => (peer_wakes if peer_wakes.positive?) }.compact
71
77
 
72
78
  def self.from_h(data)
73
- peers = data.is_a?(Hash) && data["peers"].is_a?(Hash) ? data["peers"] : {}
74
- new(peers: peers.select { |name, _| name.is_a?(String) }.transform_values { |value| Peer.from_h(value) })
79
+ data = {} unless data.is_a?(Hash)
80
+ peers = data["peers"].is_a?(Hash) ? data["peers"] : {}
81
+ wakes = data["peer_wakes"].is_a?(Integer) && data["peer_wakes"].positive? ? data["peer_wakes"] : 0
82
+ new(peers: peers.select { |name, _| name.is_a?(String) }.transform_values { |value| Peer.from_h(value) },
83
+ peer_wakes: wakes)
75
84
  end
76
85
  end
77
86
 
@@ -96,6 +105,24 @@ module Samagotchi
96
105
  # @return [Peer]
97
106
  def peer(name) = @book.peer(name)
98
107
 
108
+ # The peer wake turns in a row a worker saved (0: none).
109
+ # @return [Integer]
110
+ def peer_wakes = @book.peer_wakes
111
+
112
+ # Saves the peer wake turns in a row (WorkerWakes' on_peer_count);
113
+ # written only when it changed.
114
+ def peer_wakes=(count)
115
+ count = [count.to_i, 0].max
116
+ return if count == @book.peer_wakes
117
+
118
+ previous = @book
119
+ @book = @book.with(peer_wakes: count)
120
+ write
121
+ rescue SystemCallError, IOError
122
+ @book = previous
123
+ raise
124
+ end
125
+
99
126
  # The session's box for +name+'s note ids, minted (6 random hex) and
100
127
  # written at once with its first message, so a crash before the
101
128
  # receipts can't mint another (the ids must survive to dedupe).
@@ -1,8 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "chi_invocation"
3
4
  require_relative "peer_mailbox"
4
5
  require_relative "peer_receipts"
5
6
  require_relative "session_chain/successor"
7
+ require_relative "session_paths"
6
8
  require_relative "session_transition"
7
9
 
8
10
  module Samagotchi
@@ -26,24 +28,30 @@ module Samagotchi
26
28
  # without one. +earlier+: [[serial, reason]…] of the peer's other held
27
29
  # messages. +turns+: the wakes in a row that a held receipt's reason
28
30
  # names (peer turns or max wakes), as configured where the say ran.
29
- PeerSay = Data.define(:status, :serial, :wake, :receipt, :earlier, :next_id, :turns, :in_flight) do
31
+ # +forwarded_to+: the link it went to when the id said to was continued
32
+ # (the chain's live link, which has the pairing), nil when it went there.
33
+ PeerSay = Data.define(:status, :serial, :wake, :receipt, :earlier, :next_id, :turns, :in_flight, :forwarded_to) do
30
34
  def initialize(status:, serial: nil, wake: nil, receipt: nil, earlier: [], next_id: nil, turns: nil,
31
- in_flight: false) = super
35
+ in_flight: false, forwarded_to: nil) = super
32
36
 
33
37
  def received? = status == :received
34
38
 
35
- # The line for +peer+ (its name): "#12 received · woke chi".
36
- def line(peer)
39
+ # The line for +peer+ (its name): "#12 received · woke chi". +id+: the
40
+ # session said to, and +via+ how its commands are spelled where the
41
+ # line is drawn: a stopped session's line names its chi --resume.
42
+ def line(peer, id: nil, via: ChiInvocation::HERE)
37
43
  return PeerSay.refusal(status, peer, next_id, in_flight: in_flight) unless received?
38
44
 
39
- parts = ["##{serial} received", tail(peer)]
45
+ parts = ["##{serial} received", tail(peer, forwarded_to || id, via)]
40
46
  parts << "also held: #{PeerSay.held_list(earlier)}" unless earlier.empty?
47
+ parts << "session continued as #{forwarded_to[0, 8]}: answer there" if forwarded_to
41
48
  parts.join(" · ")
42
49
  end
43
50
 
44
51
  def to_h
45
52
  { "status" => status.to_s, "serial" => serial, "wake" => wake&.to_s, "receipt" => receipt&.to_h,
46
- "earlier" => earlier, "next_id" => next_id, "turns" => turns, "in_flight" => (true if in_flight) }.compact
53
+ "earlier" => earlier, "next_id" => next_id, "turns" => turns, "in_flight" => (true if in_flight),
54
+ "forwarded_to" => forwarded_to }.compact
47
55
  end
48
56
 
49
57
  # The JSON a chi web answered (#to_h); nil for another shape.
@@ -56,15 +64,18 @@ module Samagotchi
56
64
  wake: (data["wake"].to_sym if PeerSay::WAKES.include?(data["wake"].to_s)),
57
65
  receipt: PeerReceipts::Receipt.from_h(data["receipt"]), earlier: earlier,
58
66
  next_id: data["next_id"]&.to_s, turns: (data["turns"] if data["turns"].is_a?(Integer)),
59
- in_flight: data["in_flight"] == true)
67
+ in_flight: data["in_flight"] == true, forwarded_to: PeerSay.id_or_nil(data["forwarded_to"]))
60
68
  end
61
69
 
70
+ # A session id a chi web named, else nil.
71
+ def self.id_or_nil(value) = value.is_a?(String) && SessionPaths.valid_id?(value) ? value : nil
72
+
62
73
  # The words of a refused say, nothing written.
63
74
  def self.refusal(status, peer, next_id, in_flight: false)
64
75
  case status
65
76
  when :gone then "no such session"
66
77
  when :deleting then "this session is being deleted"
67
- when :continued then PeerSay.continued(next_id, in_flight, "say it there")
78
+ when :continued then PeerSay.continued(next_id, in_flight, "say it there", "say it again")
68
79
  when :busy then SessionTransition::Busy.new(nil).message
69
80
  when :not_paired then "not paired: run the pair script"
70
81
  when :old_worker then "this session's chi is older than chi peer: restart the session (chi sessions restart)"
@@ -74,10 +85,11 @@ module Samagotchi
74
85
  end
75
86
 
76
87
  # A continued link's refusal (SessionChain::Continued, "this session"),
77
- # then what to do: +what+ there, once the new link is saved when its
78
- # continue still runs.
79
- def self.continued(next_id, in_flight, what)
80
- "#{SessionChain::Continued.new(nil, next_id, in_flight: in_flight).message}: #{what}#{" in a moment" if in_flight}"
88
+ # then what to do: +what+ there, or, while its continue still runs,
89
+ # +again+ in a moment (the same command: once the new link is saved, a
90
+ # say or pair of this id goes there).
91
+ def self.continued(next_id, in_flight, what, again)
92
+ "#{SessionChain::Continued.new(nil, next_id, in_flight: in_flight).message}: #{in_flight ? "#{again} in a moment" : what}"
81
93
  end
82
94
 
83
95
  # "#10, #11 (paused)", a run of one reason at a time.
@@ -89,7 +101,8 @@ module Samagotchi
89
101
 
90
102
  private
91
103
 
92
- def tail(peer)
104
+ def tail(peer, id, via)
105
+ return "#{PeerSay::AT_ONCE.fetch(wake)} (#{via.resume(id[0, 8])})" if wake == :stopped && id
93
106
  return PeerSay::AT_ONCE.fetch(wake) if wake
94
107
  return "no answer from chi yet" unless receipt
95
108
 
@@ -126,19 +139,28 @@ module Samagotchi
126
139
 
127
140
  # What chi peer pair did: :paired (+link+), or a refusal (nothing
128
141
  # written): :continued (+next_id+, +in_flight+ as PeerSay's), :busy,
129
- # :old_worker (a live worker without the peer mail).
130
- PeerPaired = Data.define(:status, :link, :next_id, :in_flight) do
131
- def initialize(status:, link: nil, next_id: nil, in_flight: false) = super
142
+ # :old_worker (a live worker without the peer mail). +forwarded_to+ as
143
+ # PeerSay's: the chain's live link it paired, when the id was continued.
144
+ PeerPaired = Data.define(:status, :link, :next_id, :in_flight, :forwarded_to) do
145
+ def initialize(status:, link: nil, next_id: nil, in_flight: false, forwarded_to: nil) = super
132
146
 
133
147
  def refusal
134
148
  case status
135
- when :continued then PeerSay.continued(next_id, in_flight, "pair with it")
149
+ when :continued then PeerSay.continued(next_id, in_flight, "pair with it", "pair again")
136
150
  when :busy then SessionTransition::Busy.new(nil).message
137
151
  when :old_worker then PeerSay.refusal(:old_worker, nil, nil)
138
152
  end
139
153
  end
140
154
  end
141
155
 
156
+ # What chi peer unpair did: whether there was a pairing (+unpaired+),
157
+ # whether a wait for the peer ended (+waited+: /claude pair's mark,
158
+ # PeerPresence) and, when the id was continued, the chain's live link it
159
+ # ended (+forwarded_to+).
160
+ PeerUnpaired = Data.define(:unpaired, :forwarded_to, :waited) do
161
+ def initialize(unpaired:, forwarded_to: nil, waited: false) = super
162
+ end
163
+
142
164
  PeerSay::STATUSES = %w[received gone deleting continued busy not_paired old_worker full].freeze
143
165
  PeerSay::WAKES = %w[running starting stopped archived owned start_failed no_turn not_running deleting].freeze
144
166
  # The setting a peer_turns hold names (WorkerWakes::PEER_TURNS_KEY: the
@@ -148,7 +170,9 @@ module Samagotchi
148
170
  PeerSay::AT_ONCE = {
149
171
  running: "chi is in a turn: it reads this when the turn ends",
150
172
  starting: "chi is starting",
151
- stopped: "chi is stopped: it reads this at its next start",
173
+ # Only its owner's message starts it again (a peer's never does): the
174
+ # line adds its chi --resume when it knows the session.
175
+ stopped: "chi is stopped: it reads this when its user starts it",
152
176
  archived: "this session is archived: it reads this if you reopen it",
153
177
  owned: "a one-turn chi run has this session: it reads this at its next start",
154
178
  start_failed: "chi's worker isn't running and couldn't be started from here: it reads this at its next start",
@@ -164,13 +188,14 @@ module Samagotchi
164
188
  "queued" => "a message is queued ahead of it",
165
189
  "exit" => "chi is exiting",
166
190
  "leaving" => "chi's worker is leaving",
167
- "before_turn" => "a turn is starting"
191
+ "before_turn" => "a turn is starting",
192
+ "cold" => "chi's cache is cold"
168
193
  }.freeze
169
194
  # And until when it waits.
170
195
  PeerSay::HELD_UNTIL = {
171
196
  "off" => "waits for the user's next message", "paused" => "waits for the user's next message",
172
197
  "continue" => "waits for the user's next message", "max_wakes" => "waits for the user's next message",
173
- "peer_turns" => "waits for the user's next message",
198
+ "peer_turns" => "waits for the user's next message", "cold" => "waits for the user's next message",
174
199
  "queued" => "chi reads it in its next turn", "before_turn" => "chi reads it in that turn",
175
200
  "exit" => "it reads this at its next start", "leaving" => "it reads this at its next start"
176
201
  }.freeze
@@ -178,6 +203,6 @@ module Samagotchi
178
203
  PeerSay::SHORT_WORDS = {
179
204
  "off" => "off", "paused" => "paused", "continue" => "continue offer", "max_wakes" => "max wakes",
180
205
  "peer_turns" => "peer turns", "queued" => "queued", "exit" => "exit", "leaving" => "leaving",
181
- "before_turn" => "before a turn"
206
+ "before_turn" => "before a turn", "cold" => "cold"
182
207
  }.freeze
183
208
  end