samagotchi 0.193.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 (138) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +77 -1
  3. data/docs/bundle-authoring.md +1 -1
  4. data/docs/bundles.md +37 -12
  5. data/docs/cli.md +26 -10
  6. data/docs/configuration.md +71 -5
  7. data/docs/desktop.md +3 -0
  8. data/docs/guardrails.md +11 -1
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/engine.md +46 -3
  11. data/docs/internals/panes.md +66 -0
  12. data/docs/internals/peers.md +101 -5
  13. data/docs/internals/prompt-caching.md +4 -0
  14. data/docs/internals/session-lifecycle.md +9 -2
  15. data/docs/internals/web-frontend.md +16 -4
  16. data/docs/peers.md +79 -5
  17. data/docs/plugins.md +42 -4
  18. data/docs/sessions.md +15 -6
  19. data/docs/sub-agent.md +6 -4
  20. data/docs/system-one.md +4 -0
  21. data/docs/testing.md +3 -0
  22. data/lib/samagotchi/bridge/card_store.rb +1 -1
  23. data/lib/samagotchi/broadcast/triage_model.rb +17 -0
  24. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  25. data/lib/samagotchi/bundles/claude-peer/plugin.rb +24 -5
  26. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +28 -7
  27. data/lib/samagotchi/bundles/claude-peer/scripts/pair +31 -8
  28. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  29. data/lib/samagotchi/bundles/codex-peer/plugin.rb +62 -6
  30. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +23 -2
  31. data/lib/samagotchi/bundles/codex-peer/scripts/pair +28 -7
  32. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  33. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  34. data/lib/samagotchi/chi_invocation.rb +7 -0
  35. data/lib/samagotchi/client.rb +18 -0
  36. data/lib/samagotchi/codex_rollout.rb +93 -0
  37. data/lib/samagotchi/config.rb +15 -6
  38. data/lib/samagotchi/effective_model.rb +28 -2
  39. data/lib/samagotchi/engine/cards.rb +9 -4
  40. data/lib/samagotchi/engine/hooks.rb +8 -0
  41. data/lib/samagotchi/engine/models.rb +180 -7
  42. data/lib/samagotchi/engine/side_requests.rb +72 -13
  43. data/lib/samagotchi/engine/toolkit.rb +1 -1
  44. data/lib/samagotchi/engine/turn_helpers.rb +1 -1
  45. data/lib/samagotchi/engine.rb +11 -8
  46. data/lib/samagotchi/engine_snapshots.rb +16 -3
  47. data/lib/samagotchi/events.rb +1 -0
  48. data/lib/samagotchi/hooks.rb +3 -1
  49. data/lib/samagotchi/host_registry.rb +146 -16
  50. data/lib/samagotchi/idle_client.rb +13 -2
  51. data/lib/samagotchi/idle_recap.rb +33 -3
  52. data/lib/samagotchi/idle_target.rb +27 -7
  53. data/lib/samagotchi/llm/adapter_common.rb +4 -2
  54. data/lib/samagotchi/llm/anthropic_messages.rb +3 -2
  55. data/lib/samagotchi/llm/errors.rb +35 -4
  56. data/lib/samagotchi/llm/model_listing.rb +19 -0
  57. data/lib/samagotchi/llm/openai_chat.rb +3 -2
  58. data/lib/samagotchi/model_binding.rb +46 -4
  59. data/lib/samagotchi/model_catalog.rb +68 -8
  60. data/lib/samagotchi/model_profile.rb +35 -0
  61. data/lib/samagotchi/models_command.rb +8 -4
  62. data/lib/samagotchi/panes/kitty.rb +122 -0
  63. data/lib/samagotchi/panes.rb +185 -0
  64. data/lib/samagotchi/peer_announce.rb +245 -0
  65. data/lib/samagotchi/peer_command.rb +97 -11
  66. data/lib/samagotchi/peer_continue.rb +10 -0
  67. data/lib/samagotchi/peer_mailbox.rb +30 -7
  68. data/lib/samagotchi/peer_pair_here.rb +149 -0
  69. data/lib/samagotchi/peer_presence.rb +434 -0
  70. data/lib/samagotchi/peer_say.rb +17 -10
  71. data/lib/samagotchi/peer_wait_expiry.rb +47 -0
  72. data/lib/samagotchi/plugin/api.rb +12 -1
  73. data/lib/samagotchi/plugin/card.rb +68 -11
  74. data/lib/samagotchi/plugin/context.rb +20 -1
  75. data/lib/samagotchi/plugin/panes.rb +54 -0
  76. data/lib/samagotchi/plugin/peer.rb +52 -10
  77. data/lib/samagotchi/plugin/peer_pairing.rb +290 -0
  78. data/lib/samagotchi/plugin/peer_start.rb +301 -0
  79. data/lib/samagotchi/plugin/peer_start_hook.rb +207 -0
  80. data/lib/samagotchi/plugin/peers.rb +76 -3
  81. data/lib/samagotchi/recap_setup.rb +40 -3
  82. data/lib/samagotchi/self_report.rb +25 -6
  83. data/lib/samagotchi/send_command.rb +6 -6
  84. data/lib/samagotchi/served_lookup.rb +225 -0
  85. data/lib/samagotchi/served_ref.rb +41 -0
  86. data/lib/samagotchi/session_access/contract.rb +6 -0
  87. data/lib/samagotchi/session_access/local.rb +54 -6
  88. data/lib/samagotchi/session_access/remote.rb +4 -4
  89. data/lib/samagotchi/session_access/remote_peers.rb +7 -4
  90. data/lib/samagotchi/session_commands.rb +40 -8
  91. data/lib/samagotchi/session_continue.rb +6 -2
  92. data/lib/samagotchi/session_lifecycle/allowed.rb +4 -2
  93. data/lib/samagotchi/session_manager/delivery.rb +5 -0
  94. data/lib/samagotchi/session_manager/lifecycle.rb +58 -7
  95. data/lib/samagotchi/session_manager/removal.rb +3 -0
  96. data/lib/samagotchi/session_model_settings.rb +7 -3
  97. data/lib/samagotchi/session_stores.rb +9 -0
  98. data/lib/samagotchi/sessions_command.rb +16 -3
  99. data/lib/samagotchi/system_one/http_backend.rb +111 -10
  100. data/lib/samagotchi/system_prompt.rb +11 -4
  101. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -1
  102. data/lib/samagotchi/terminal_ui/formatting.rb +26 -12
  103. data/lib/samagotchi/terminal_ui/status_row.rb +20 -3
  104. data/lib/samagotchi/terminal_ui.rb +1 -1
  105. data/lib/samagotchi/testing/bundle.rb +6 -2
  106. data/lib/samagotchi/turn_endings.rb +6 -2
  107. data/lib/samagotchi/user_typed.rb +29 -0
  108. data/lib/samagotchi/version.rb +1 -1
  109. data/lib/samagotchi/web/app.rb +8 -20
  110. data/lib/samagotchi/web/participant_review.rb +1 -1
  111. data/lib/samagotchi/web/participant_view.rb +1 -1
  112. data/lib/samagotchi/web/peer_routes.rb +33 -13
  113. data/lib/samagotchi/web/public/app.js +1 -1
  114. data/lib/samagotchi/web/public/card.js +26 -10
  115. data/lib/samagotchi/web/public/context_chips.js +24 -2
  116. data/lib/samagotchi/web/public/copy.js +8 -2
  117. data/lib/samagotchi/web/public/data.js +2 -1
  118. data/lib/samagotchi/web/public/format.js +9 -1
  119. data/lib/samagotchi/web/public/index.html +18 -0
  120. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  121. data/lib/samagotchi/web/public/model_pick.js +18 -5
  122. data/lib/samagotchi/web/public/model_picker.js +1 -1
  123. data/lib/samagotchi/web/public/peer_chip.js +15 -5
  124. data/lib/samagotchi/web/public/peer_data.js +4 -2
  125. data/lib/samagotchi/web/public/peer_wait.js +36 -0
  126. data/lib/samagotchi/web/public/served_ref.js +9 -0
  127. data/lib/samagotchi/web/public/session_fields.js +1 -0
  128. data/lib/samagotchi/web/public/session_state.js +4 -0
  129. data/lib/samagotchi/web/public/stage_missing.js +23 -6
  130. data/lib/samagotchi/web/public/stream_handlers.js +16 -0
  131. data/lib/samagotchi/web/public/version_notices.js +7 -1
  132. data/lib/samagotchi/web/session_control.rb +19 -10
  133. data/lib/samagotchi/web/session_show.rb +20 -0
  134. data/lib/samagotchi/web/update_ops.rb +2 -2
  135. data/lib/samagotchi/worker/command_queue.rb +3 -0
  136. data/lib/samagotchi/worker/mail.rb +14 -1
  137. data/lib/samagotchi/worker.rb +1 -0
  138. metadata +18 -1
@@ -16,6 +16,7 @@ module Samagotchi
16
16
  # worker did with each message, is PeerReceipts, in the session's own
17
17
  # folder).
18
18
  # <session id>/<peer>/link.json PeerLink: the pairing (chi peer pair)
19
+ # .here/ PeerPresence: who is here, who waits (not a session id)
19
20
  # <session id>/<peer>/in/<serial>.json PeerMessage: one message (chi peer say)
20
21
  # <session id>/<peer>/lock the say's, while it picks a serial and writes
21
22
  # No head file: the next serial is max(the newest file, taken) + 1, and
@@ -56,16 +57,29 @@ module Samagotchi
56
57
  class Full < Invalid; end
57
58
 
58
59
  # A pairing: the +peer+'s name, the +address+ chi's sends go to (nil:
59
- # answers only), when it was made and by whom (+from+, free text).
60
- PeerLink = Data.define(:peer, :address, :paired_at, :from) do
61
- def to_h = { "peer" => peer, "address" => address, "paired_at" => paired_at, "from" => from }
60
+ # answers only), when it was made and by whom (+from+, free text), and
61
+ # the peer's own session id when the pairing knows it (+peer_session+:
62
+ # Claude Code's session id, stable across a resume; PeerPresence). An
63
+ # older chi drops +peer_session+ on its continue and its re-pair.
64
+ PeerLink = Data.define(:peer, :address, :paired_at, :from, :peer_session) do
65
+ def initialize(peer:, address:, paired_at:, from:, peer_session: nil) = super
66
+
67
+ # Its address an inbox socket path that is no socket now (that Claude
68
+ # ended). A thread id (Codex) or no address (answers only) never is.
69
+ def socket_gone? = PeerMailbox.socket_gone?(address)
70
+
71
+ def to_h
72
+ base = { "peer" => peer, "address" => address, "paired_at" => paired_at, "from" => from }
73
+ peer_session ? base.merge("peer_session" => peer_session) : base
74
+ end
62
75
 
63
76
  # @return [PeerLink, nil] nil for a value of the wrong shape
64
77
  def self.from_h(data)
65
78
  return nil unless data.is_a?(Hash) && data["peer"].is_a?(String) && data["paired_at"].is_a?(String)
66
- return nil unless [data["address"], data["from"]].all? { |value| value.nil? || value.is_a?(String) }
79
+ return nil unless [data["address"], data["from"], data["peer_session"]].all? { |value| value.nil? || value.is_a?(String) }
67
80
 
68
- new(peer: data["peer"], address: data["address"], paired_at: data["paired_at"], from: data["from"])
81
+ new(peer: data["peer"], address: data["address"], paired_at: data["paired_at"], from: data["from"],
82
+ peer_session: data["peer_session"])
69
83
  end
70
84
  end
71
85
 
@@ -136,6 +150,14 @@ module Samagotchi
136
150
 
137
151
  module_function
138
152
 
153
+ # Whether a pairing's +address+ is an inbox socket path that is no
154
+ # socket now (that Claude ended: PeerLink#socket_gone?, chi web's
155
+ # "ended" chip). A thread id (Codex) or no address never is.
156
+ def socket_gone?(address)
157
+ path = address.to_s.strip
158
+ path.start_with?("/") && !File.socket?(path)
159
+ end
160
+
139
161
  # <state dir>/mailbox; +state_dir+ is the sessions dir (SessionPaths.default_state_dir).
140
162
  def root(state_dir: nil)
141
163
  File.join(File.dirname(state_dir || SessionPaths.default_state_dir), DIR)
@@ -188,8 +210,9 @@ module Samagotchi
188
210
 
189
211
  # Pairs +peer+ with the session: link.json written whole, the in folder made.
190
212
  # @return [PeerLink]
191
- def pair(session_id, peer, address:, from:, state_dir: nil, now: Time.now)
192
- link = PeerLink.new(peer: peer, address: address&.to_s, paired_at: now.utc.iso8601, from: from&.to_s)
213
+ def pair(session_id, peer, address:, from:, peer_session: nil, state_dir: nil, now: Time.now)
214
+ link = PeerLink.new(peer: peer, address: address&.to_s, paired_at: now.utc.iso8601, from: from&.to_s,
215
+ peer_session: peer_session&.to_s)
193
216
  write_link(session_id, link, state_dir: state_dir)
194
217
  end
195
218
 
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "memory_paths"
4
+ require_relative "peer_announce"
5
+ require_relative "peer_mailbox"
6
+ require_relative "peer_presence"
7
+ require_relative "session_chain"
8
+
9
+ module Samagotchi
10
+ # `chi peer pair NAME --here`: the pair script with no id ("pair with
11
+ # chi"). Which session: the one fresh mark of this folder's project
12
+ # (claimed first); else, of the sessions of that project a worker runs
13
+ # now (by MemoryPaths.project_key, so a worktree's session counts: not
14
+ # `sessions list --cwd`, a path-prefix filter), the one already paired
15
+ # with this peer (by its peer session, or by this address: a Codex its
16
+ # start hook paired, whose older script passes no --peer-session), the
17
+ # pairing kept as it is (+same+), else the only one; else none, with the
18
+ # candidates. Also the path of a Claude started before its start hook.
19
+ class PeerPairHere
20
+ # What it found: +id+ to pair (and the +claim+ taken on its mark), or a
21
+ # +refusal+ (its lines: the first one the reason, then the candidates);
22
+ # +gone+: the pairing on +id+'s chain whose peer is gone, which this
23
+ # pairing replaces; +same+: the pairing (a PeerLink) of +id+, a live
24
+ # session, with this peer already, which wins.
25
+ Found = Data.define(:id, :claim, :refusal, :gone, :same) do
26
+ def initialize(id:, claim:, refusal:, gone: nil, same: nil) = super
27
+ end
28
+ # A pairing whose peer is gone (PeerLink#socket_gone?): +link+, on the
29
+ # chain's live link +head+.
30
+ Gone = Data.define(:head, :link)
31
+
32
+ # @param access [SessionAccess::Local]
33
+ def initialize(peer, access:, state_dir:, cwd: Dir.pwd, now: -> { Time.now })
34
+ @peer = peer
35
+ @access = access
36
+ @state_dir = state_dir
37
+ @cwd = cwd
38
+ @now = now
39
+ end
40
+
41
+ # +peer_session+ and +address+ are this peer's: a session paired with
42
+ # another live peer is refused (owner: never replaced silently; a pair
43
+ # with its id still replaces), the same one pairs again, and one whose
44
+ # peer is gone (its socket missing, as /claude pair ends it) is
45
+ # replaced, named in +gone+.
46
+ # @return [Found]
47
+ def resolve(peer_session: nil, address: nil)
48
+ found = pick(peer_session: peer_session, address: address)
49
+ return found if found.refusal || found.same
50
+
51
+ head, link = other_pairing(found.id, peer_session, address)
52
+ return found unless link
53
+ return found.with(gone: Gone.new(head: head, link: link)) if link.socket_gone?
54
+
55
+ PeerPresence.release(found.claim)
56
+ refused("chi #{found.id[0, 8]} is paired with another #{PeerMailbox.label(@peer)} already; /#{@peer} unpair there first", [])
57
+ end
58
+
59
+ # The peer session pairing from +address+: the one given, else the
60
+ # PeerHere listed at that address.
61
+ def peer_session(given, address)
62
+ return given if given
63
+ return nil if address.nil?
64
+
65
+ PeerPresence.here(@peer, state_dir: @state_dir).find { |entry| entry.address == address }&.session
66
+ end
67
+
68
+ private
69
+
70
+ # The one fresh mark (claimed), else the live session of the project
71
+ # already paired with this peer, else the one live session; a mark
72
+ # another pairing holds now (hidden from #marks while claimed) is
73
+ # refused, never passed over for the live one. A stopped session's
74
+ # pairing never wins (a resumed Codex keeps its thread for days).
75
+ def pick(peer_session:, address:)
76
+ project = MemoryPaths.project_key(@cwd)
77
+ marks = PeerPresence.marks(@peer, project: project, state_dir: @state_dir, now: @now.call)
78
+ if marks.size == 1
79
+ claim = PeerPresence.claim(@peer, marks.first.session, state_dir: @state_dir, now: @now.call)
80
+ return claim ? Found.new(id: marks.first.session, claim: claim, refusal: nil) : pairing_now(marks.first.session)
81
+ elsif marks.size > 1
82
+ return refused("#{marks.size} chi sessions wait for #{PeerMailbox.label(@peer)} in this project: pair with one's id",
83
+ marks.map { |mark| " #{mark.session[0, 8]} waiting #{PeerAnnounce.title_of(mark.session, state_dir: @state_dir)}".rstrip })
84
+ end
85
+ paired = paired_here(project, peer_session, address) and return paired
86
+
87
+ found = live(project)
88
+ found.id && PeerPresence.claimed?(@peer, found.id, state_dir: @state_dir, now: @now.call) ? pairing_now(found.id) : found
89
+ rescue MemoryPaths::ProjectIdConflict, ArgumentError => e
90
+ refused("can't tell this folder's project (#{e.message}): pair with an id", [])
91
+ end
92
+
93
+ def pairing_now(id)
94
+ refused("a #{PeerMailbox.label(@peer)} is pairing with chi #{id[0, 8]} now: try again, or pair with its id", [])
95
+ end
96
+
97
+ # [head, link]: the chain's live link of +id+ and its pairing with
98
+ # another peer, or [head, nil]: none, or this peer's own (this address:
99
+ # the same socket is the same Claude, a /clear's new session id too;
100
+ # else, when both are named, this peer session: a resume's new socket).
101
+ def other_pairing(id, peer_session, address)
102
+ head = SessionChain::Links.new(state_dir: @state_dir).first_live(id) || id
103
+ link = PeerMailbox.link(head, @peer, state_dir: @state_dir) or return [head, nil]
104
+ return [head, nil] if !address.to_s.empty? && link.address.to_s == address.to_s
105
+ return [head, nil] if link.peer_session && peer_session && link.peer_session == peer_session
106
+
107
+ [head, link]
108
+ end
109
+
110
+ # Found with +same+: the live session of +project+ whose pairing with
111
+ # this peer is this +peer_session+'s or at this +address+; nil: none.
112
+ def paired_here(project, peer_session, address)
113
+ project_rows(project).each do |row|
114
+ link = PeerMailbox.link(row.id, @peer, state_dir: @state_dir) or next
115
+ next unless (peer_session && link.peer_session == peer_session) || (!address.to_s.empty? && link.address.to_s == address.to_s)
116
+
117
+ return Found.new(id: row.id, claim: nil, refusal: nil, same: link)
118
+ end
119
+ nil
120
+ end
121
+
122
+ # The live sessions of +project+ (read once).
123
+ def project_rows(project)
124
+ @project_rows ||= begin
125
+ cache = {}
126
+ @access.summaries(live: true, include_tests: true).select do |row|
127
+ cache.fetch(row.cwd) { cache[row.cwd] = key_of(row.cwd) } == project
128
+ end
129
+ end
130
+ end
131
+
132
+ def live(project)
133
+ rows = project_rows(project)
134
+ return Found.new(id: rows.first.id, claim: nil, refusal: nil) if rows.size == 1
135
+ return refused("no live chi session in this project: start one, or pair with an id", []) if rows.empty?
136
+
137
+ refused("#{rows.size} live chi sessions in this project: pair with one's id",
138
+ rows.map { |row| " #{row.id[0, 8]} #{row.status} #{PeerAnnounce.title_line(row.title.to_s.empty? ? row.desc : row.title)}" })
139
+ end
140
+
141
+ def key_of(cwd)
142
+ cwd.to_s.empty? ? nil : MemoryPaths.project_key(cwd)
143
+ rescue StandardError # degrade-ok: a row whose folder has no project is no candidate
144
+ nil
145
+ end
146
+
147
+ def refused(reason, candidates) = Found.new(id: nil, claim: nil, refusal: [reason, *candidates])
148
+ end
149
+ end
@@ -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