samagotchi 0.186.0 → 0.188.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 (153) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +4 -0
  4. data/docs/architecture.md +8 -4
  5. data/docs/bundles.md +124 -120
  6. data/docs/cli.md +26 -5
  7. data/docs/configuration.md +4 -4
  8. data/docs/context.md +18 -162
  9. data/docs/guardrails.md +3 -1
  10. data/docs/hooks.md +2 -1
  11. data/docs/internals/attached-context.md +19 -37
  12. data/docs/internals/bridge.md +1 -0
  13. data/docs/internals/engine.md +2 -2
  14. data/docs/internals/inline-widgets.md +18 -0
  15. data/docs/internals/llm-context-forget.md +5 -6
  16. data/docs/internals/objectives.md +1 -0
  17. data/docs/internals/pages.md +175 -0
  18. data/docs/internals/peers.md +149 -0
  19. data/docs/internals/remote-sessions.md +7 -4
  20. data/docs/internals/web-frontend.md +65 -40
  21. data/docs/internals/web-push.md +1 -1
  22. data/docs/memory.md +8 -1
  23. data/docs/pages.md +151 -0
  24. data/docs/peers.md +141 -0
  25. data/docs/plugins.md +52 -27
  26. data/docs/sessions.md +8 -4
  27. data/docs/sub-agent.md +5 -5
  28. data/lib/samagotchi/bridge.rb +3 -3
  29. data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
  30. data/lib/samagotchi/bundle_command/check.rb +1 -1
  31. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
  32. data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
  33. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
  34. data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
  35. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
  36. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
  37. data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
  38. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
  39. data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
  40. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
  41. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  42. data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
  43. data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
  44. data/lib/samagotchi/bundles/system/manifest.yml +5 -2
  45. data/lib/samagotchi/bundles/system/self_map.md +5 -1
  46. data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
  47. data/lib/samagotchi/client_id.rb +15 -1
  48. data/lib/samagotchi/config.rb +8 -7
  49. data/lib/samagotchi/context_absorber.rb +23 -277
  50. data/lib/samagotchi/context_sources.rb +17 -69
  51. data/lib/samagotchi/engine/messages.rb +12 -1
  52. data/lib/samagotchi/engine/plugins.rb +1 -1
  53. data/lib/samagotchi/engine.rb +7 -6
  54. data/lib/samagotchi/engine_peers.rb +0 -3
  55. data/lib/samagotchi/guardrail_wiring.rb +2 -0
  56. data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
  57. data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
  58. data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
  59. data/lib/samagotchi/inline_widgets.rb +73 -0
  60. data/lib/samagotchi/log_line.rb +1 -1
  61. data/lib/samagotchi/note_move.rb +3 -1
  62. data/lib/samagotchi/page_command.rb +243 -0
  63. data/lib/samagotchi/pages/builder.rb +186 -0
  64. data/lib/samagotchi/pages/launch.rb +193 -0
  65. data/lib/samagotchi/pages/runner.rb +154 -0
  66. data/lib/samagotchi/pages/store.rb +152 -0
  67. data/lib/samagotchi/pages.rb +119 -0
  68. data/lib/samagotchi/peer_command.rb +192 -0
  69. data/lib/samagotchi/peer_continue.rb +99 -0
  70. data/lib/samagotchi/peer_exchanges.rb +3 -3
  71. data/lib/samagotchi/peer_mailbox.rb +360 -0
  72. data/lib/samagotchi/peer_note.rb +208 -0
  73. data/lib/samagotchi/peer_receipts.rb +247 -0
  74. data/lib/samagotchi/peer_registry.rb +44 -0
  75. data/lib/samagotchi/peer_roster.rb +79 -0
  76. data/lib/samagotchi/peer_say.rb +168 -0
  77. data/lib/samagotchi/plugin/api.rb +29 -21
  78. data/lib/samagotchi/plugin/context.rb +7 -0
  79. data/lib/samagotchi/plugin/loader.rb +3 -3
  80. data/lib/samagotchi/plugin/peer.rb +175 -64
  81. data/lib/samagotchi/plugin/peers.rb +70 -0
  82. data/lib/samagotchi/run_options.rb +3 -1
  83. data/lib/samagotchi/schedule_command.rb +10 -3
  84. data/lib/samagotchi/schedule_display.rb +32 -0
  85. data/lib/samagotchi/session_access/contract.rb +19 -2
  86. data/lib/samagotchi/session_access/local.rb +132 -14
  87. data/lib/samagotchi/session_access/remote.rb +4 -2
  88. data/lib/samagotchi/session_access/remote_peers.rb +75 -0
  89. data/lib/samagotchi/session_continue.rb +12 -0
  90. data/lib/samagotchi/session_inbox_delivery.rb +5 -2
  91. data/lib/samagotchi/session_manager/delivery.rb +5 -3
  92. data/lib/samagotchi/session_manager/removal.rb +2 -0
  93. data/lib/samagotchi/session_manager/spawn.rb +2 -1
  94. data/lib/samagotchi/session_manager.rb +1 -0
  95. data/lib/samagotchi/session_stores.rb +17 -0
  96. data/lib/samagotchi/steer.rb +1 -1
  97. data/lib/samagotchi/system_prompt.rb +1 -1
  98. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  99. data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
  100. data/lib/samagotchi/testing/boundary.rb +4 -13
  101. data/lib/samagotchi/testing/bundle.rb +40 -5
  102. data/lib/samagotchi/testing/install.rb +4 -4
  103. data/lib/samagotchi/testing/recording_api.rb +2 -1
  104. data/lib/samagotchi/tools/context_read.rb +0 -14
  105. data/lib/samagotchi/tools/list_schedules.rb +8 -3
  106. data/lib/samagotchi/version.rb +1 -1
  107. data/lib/samagotchi/web/app.rb +7 -18
  108. data/lib/samagotchi/web/message_display.rb +4 -2
  109. data/lib/samagotchi/web/page_routes.rb +116 -0
  110. data/lib/samagotchi/web/peer_routes.rb +133 -0
  111. data/lib/samagotchi/web/public/app.js +35 -95
  112. data/lib/samagotchi/web/public/bubbles.js +2 -2
  113. data/lib/samagotchi/web/public/cards_place.js +20 -1
  114. data/lib/samagotchi/web/public/context_chips.js +45 -46
  115. data/lib/samagotchi/web/public/history_reveal.js +4 -1
  116. data/lib/samagotchi/web/public/history_shape.js +3 -2
  117. data/lib/samagotchi/web/public/index.html +16 -0
  118. data/lib/samagotchi/web/public/notify.js +1 -1
  119. data/lib/samagotchi/web/public/page_blocks.js +58 -0
  120. data/lib/samagotchi/web/public/page_links.js +33 -0
  121. data/lib/samagotchi/web/public/page_model.js +68 -0
  122. data/lib/samagotchi/web/public/page_route.js +24 -0
  123. data/lib/samagotchi/web/public/page_table.js +74 -0
  124. data/lib/samagotchi/web/public/page_table_model.js +76 -0
  125. data/lib/samagotchi/web/public/page_view.js +219 -0
  126. data/lib/samagotchi/web/public/pages.css +77 -0
  127. data/lib/samagotchi/web/public/pages_group.js +65 -0
  128. data/lib/samagotchi/web/public/peer_chip.js +60 -74
  129. data/lib/samagotchi/web/public/peer_data.js +13 -11
  130. data/lib/samagotchi/web/public/peer_links.js +12 -7
  131. data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
  132. data/lib/samagotchi/web/public/peer_note.js +7 -3
  133. data/lib/samagotchi/web/public/peer_text.js +4 -4
  134. data/lib/samagotchi/web/public/quiet_notes.js +199 -0
  135. data/lib/samagotchi/web/public/revise_stack.js +4 -3
  136. data/lib/samagotchi/web/public/session_view.js +2 -2
  137. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  138. data/lib/samagotchi/web/public/turn_block.js +7 -3
  139. data/lib/samagotchi/web/public/turn_events.js +6 -0
  140. data/lib/samagotchi/web/public/views.js +161 -0
  141. data/lib/samagotchi/web/push/attention.rb +3 -2
  142. data/lib/samagotchi/web/session_access_routes.rb +3 -20
  143. data/lib/samagotchi/web/viewer.rb +1 -1
  144. data/lib/samagotchi/worker/leave.rb +3 -0
  145. data/lib/samagotchi/worker/mail.rb +73 -0
  146. data/lib/samagotchi/worker/startup.rb +3 -0
  147. data/lib/samagotchi/worker/wake_turns.rb +20 -5
  148. data/lib/samagotchi/worker.rb +12 -6
  149. data/lib/samagotchi/worker_inbound/mail.rb +214 -0
  150. data/lib/samagotchi/worker_inbound.rb +43 -46
  151. data/lib/samagotchi/worker_wakes.rb +26 -21
  152. metadata +39 -2
  153. data/lib/samagotchi/peer_sources.rb +0 -58
@@ -15,6 +15,10 @@ require_relative "../context_candidates"
15
15
  require_relative "../worker_inbound"
16
16
  require_relative "../context_sources"
17
17
  require_relative "../peer_exchanges"
18
+ require_relative "../peer_mailbox"
19
+ require_relative "../peer_receipts"
20
+ require_relative "../peer_roster"
21
+ require_relative "../peer_say"
18
22
  require_relative "../archive_store"
19
23
  require_relative "../session_chain"
20
24
  require_relative "../send_command/busy"
@@ -383,13 +387,7 @@ module Samagotchi
383
387
  record = lambda do
384
388
  attached.location.locked(name) do
385
389
  before = attached.location.snapshot(name).revision
386
- written = attached.location.record_text(name, fetched)
387
- peer, leg = ContextSources.peer_leg(name)
388
- if !target.project? && attached.location.session? && attached.source.scope == "session" &&
389
- leg == "outbox" && before != written.revision
390
- record_peer_answer(target.session_id, peer, written)
391
- end
392
- [before, written]
390
+ [before, attached.location.record_text(name, fetched)]
393
391
  end
394
392
  end
395
393
  unless !target.project? && attached.location.session? && attached.source.scope == "session"
@@ -538,8 +536,135 @@ module Samagotchi
538
536
  raise BadRequest.new(e.message, code: "invalid_participant")
539
537
  end
540
538
 
539
+ # --- peers (PeerMailbox: the peer's side; PeerReceipts: the worker's)
540
+
541
+ # Pairs +peer+ with session +id+ (link.json). Refused, nothing
542
+ # written, when the session was continued or a live worker of it
543
+ # doesn't take the peer mail (a pairing to it would look done and
544
+ # not work).
545
+ # @return [PeerPaired]
546
+ # @raise [PeerMailbox::Invalid] a bad name
547
+ # @raise [Session::NotFound] no such session
548
+ def peer_pair(id, peer, address:, from:)
549
+ PeerMailbox.check_name!(peer)
550
+ raise Session::NotFound, id unless Session.exist?(id, **dir)
551
+ if (next_id = continued_as(id))
552
+ return PeerPaired.new(status: :continued, next_id: next_id)
553
+ end
554
+ return PeerPaired.new(status: :old_worker) if old_peer_worker?(id)
555
+
556
+ PeerPaired.new(status: :paired, link: PeerMailbox.pair(id, peer, address: address, from: from, state_dir: state_dir!))
557
+ end
558
+
559
+ # Ends the pairing (link.json); the messages stay.
560
+ # @return [Boolean] whether there was one
561
+ def peer_unpair(id, peer) = PeerMailbox.unpair(id, peer, state_dir: state_dir!)
562
+
563
+ # @return [Array<PeerRoster::Peer>]
564
+ def peer_list(id) = PeerRoster.build(id, state_dir: state_dir!)
565
+
566
+ # A message from +peer+ into session +id+, as a delivery
567
+ # (SessionInbox.deliver :peer): refused before anything is written
568
+ # for a gone session, a continued one, no pairing, a live worker
569
+ # without the peer mail, UNTAKEN_MAX unread; else written inside the
570
+ # delivery's block (a session being deleted refuses first), which
571
+ # asks for a worker by the message's own +wake+ alone (no
572
+ # context.wake, no window). Then what chi did, at once when it can't
573
+ # answer yet, else the receipt within +wait+ seconds (a look every
574
+ # PeerSay::POLL_SECONDS).
575
+ # @return [PeerSay]
576
+ # @raise [PeerMailbox::Invalid] a bad name, an empty or oversized text
577
+ def peer_say(id, peer, text:, summary:, wake:, re:, wait: 0, sleeper: ->(seconds) { sleep(seconds) },
578
+ clock: -> { monotonic })
579
+ PeerMailbox.check_name!(peer)
580
+ PeerMailbox.checked_text(text)
581
+ return PeerSay.new(status: :gone) unless Session.exist?(id, **dir)
582
+ if (next_id = continued_as(id))
583
+ return PeerSay.new(status: :continued, next_id: next_id)
584
+ end
585
+ return PeerSay.new(status: :not_paired) unless PeerMailbox.link(id, peer, state_dir: state_dir!)
586
+ return PeerSay.new(status: :old_worker) if old_peer_worker?(id)
587
+
588
+ message = nil
589
+ start_failed = false
590
+ delivered = begin
591
+ SessionInbox.deliver(:peer, id, state_dir: state_dir!) do
592
+ message = PeerMailbox.post(id, peer, text: text, summary: summary, wake: wake, re: re, state_dir: state_dir!,
593
+ taken: PeerReceipts.taken(id, peer, state_dir: state_dir!))
594
+ message.wake
595
+ end
596
+ rescue PeerMailbox::Full
597
+ return PeerSay.new(status: :full)
598
+ rescue StandardError => e
599
+ raise unless message
600
+
601
+ Log.exception(:peer, "peer_say_wake_failed", e, sid: id, peer: peer)
602
+ start_failed = true
603
+ nil
604
+ end
605
+ return PeerSay.new(status: delivered.wake == :deleting ? :deleting : :gone) if delivered&.refused?
606
+
607
+ at_once = start_failed ? :start_failed : peer_at_once(id, delivered.wake)
608
+ receipt = at_once ? nil : peer_receipt_within(id, peer, message.serial, wait, sleeper, clock)
609
+ peer_said(id, peer, message.serial, at_once, receipt)
610
+ end
611
+
541
612
  private
542
613
 
614
+ # Whether +id+'s live worker doesn't take the peer mail (its Bridge
615
+ # features: a read-only look). No live worker: nil (the next one does).
616
+ def old_peer_worker?(id)
617
+ features = WorkerLink.live_features(id, state_dir: state_dir!)
618
+ features && !features.include?(PeerMailbox::FEATURE)
619
+ end
620
+
621
+ # What a say says without waiting (PeerSay::AT_ONCE), from the
622
+ # delivery's +wake+ and the session; nil when a worker sees the
623
+ # message now and the say may wait for its receipt.
624
+ def peer_at_once(id, wake)
625
+ case wake
626
+ when :stopped, :archived, :owned, :starting, :deleting then wake
627
+ when :scratch then :start_failed
628
+ when :live, :woken
629
+ session = Session.load(id, **dir)
630
+ started = Array(session.messages).any? { |m| %w[user assistant model].include?((m[:role] || m["role"]).to_s) }
631
+ return :no_turn unless started
632
+
633
+ :running if wake == :live && session.status == Session::STATUS_RUNNING
634
+ else :not_running
635
+ end
636
+ end
637
+
638
+ # The worker's receipt for +serial+, looked at until one comes or
639
+ # +wait+ seconds pass (one look for 0).
640
+ # @return [PeerReceipts::Receipt, nil]
641
+ def peer_receipt_within(id, peer, serial, wait, sleeper, clock)
642
+ deadline = clock.call + wait.to_f
643
+ loop do
644
+ receipt = PeerReceipts.receipt(id, peer, serial, state_dir: state_dir!)
645
+ return receipt if receipt
646
+
647
+ left = deadline - clock.call
648
+ return nil unless left.positive?
649
+
650
+ sleeper.call([PeerSay::POLL_SECONDS, left].min)
651
+ end
652
+ end
653
+
654
+ # The say's PeerSay: the peer's other held messages read now, and the
655
+ # turns a held reason counts, as configured here.
656
+ def peer_said(id, peer, serial, at_once, receipt)
657
+ latest = PeerReceipts.read(id, state_dir: state_dir!).peer(peer).receipts.to_h { |item| [item.serial, item] }
658
+ earlier = latest.values.select { |item| item.state == "held" && item.serial != serial }.sort_by(&:serial)
659
+ .map { |item| [item.serial, item.reason.to_s] }
660
+ wakes = WorkerWakes.new(grace: 0)
661
+ turns = case receipt&.reason
662
+ when "peer_turns" then wakes.peer_turns
663
+ when "max_wakes" then wakes.max
664
+ end
665
+ PeerSay.new(status: :received, serial: serial, wake: at_once, receipt: receipt, earlier: earlier, turns: turns)
666
+ end
667
+
543
668
  # A session source's push, as a push delivery (SessionInbox.deliver
544
669
  # :push): the text recorded, then a wake when it asks one (a change
545
670
  # with wake, context.wake on, the source not woken lately) as the
@@ -564,13 +689,6 @@ module Samagotchi
564
689
  ContextPush.new(status: :pushed, before: before, revision: written.revision, wake: asked ? delivered&.wake : nil)
565
690
  end
566
691
 
567
- def record_peer_answer(session_id, peer, snapshot)
568
- PeerExchanges.append(session_id, { t: "answer", peer: peer, re: snapshot.re, summary: snapshot.summary,
569
- serial: snapshot.serial, wake: snapshot.wake }, state_dir: state_dir!)
570
- rescue SystemCallError, IOError, JSON::GeneratorError => e
571
- Log.exception(:context, "peer_exchange_not_saved", e, sid: session_id, source: "#{peer}-outbox")
572
- end
573
-
574
692
  def context_wake_allowed?(location, name)
575
693
  return false if Config.get("context.wake") == false
576
694
 
@@ -16,6 +16,7 @@ require_relative "../guardrails/parent_policy"
16
16
  require_relative "../model_profile"
17
17
  require_relative "../grants"
18
18
  require_relative "http_transport"
19
+ require_relative "remote_peers"
19
20
  require_relative "../chi_invocation"
20
21
  require_relative "../client_id"
21
22
  require_relative "../delivery"
@@ -35,6 +36,8 @@ module Samagotchi
35
36
  # the remote. Waits and prefixes run on the server (plan D2); a wait
36
37
  # here asks again until it ends or the caller's own timeout passes.
37
38
  class Remote
39
+ include RemotePeers
40
+
38
41
  # The longest a wait route waits (Web::SessionAccessRoutes::
39
42
  # WAIT_MAX_SECONDS): each request asks for at most this.
40
43
  WAIT_SLICE = 30.0
@@ -605,8 +608,7 @@ module Samagotchi
605
608
  def context_push(target, name, fetched)
606
609
  ContextSources.check_name!(name)
607
610
  reply = request(:post, "#{session_path(target.session_id)}/context/#{name}/push",
608
- body: { text: fetched.text, summary: fetched.summary, wake: fetched.wake, hint: fetched.hint,
609
- re: fetched.re })
611
+ body: { text: fetched.text, summary: fetched.summary, wake: fetched.wake, hint: fetched.hint })
610
612
  case reply.status
611
613
  when 200
612
614
  # An older chi web's answer names no wake: the line is as it was.
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../session_access"
4
+ require_relative "../peer_mailbox"
5
+ require_relative "../peer_roster"
6
+ require_relative "../peer_say"
7
+
8
+ module Samagotchi
9
+ module SessionAccess
10
+ # SessionAccess::Remote's chi peer: chi web's …/peers routes, the twins
11
+ # of Local#peer_pair, #peer_unpair, #peer_list and #peer_say. Uses the
12
+ # Remote's request, session_path, raise_refusal and entry.
13
+ module RemotePeers
14
+ # How long a say's request may take beyond its wait: the server
15
+ # starts a worker first.
16
+ PEER_SAY_SLACK = 30
17
+
18
+ # @return [PeerPaired]
19
+ def peer_pair(id, peer, address:, from:)
20
+ PeerMailbox.check_name!(peer)
21
+ reply = peer_request(:post, "#{session_path(id)}/peers/#{peer}/pair", body: { address: address, from: from })
22
+ case reply.status
23
+ when 200
24
+ link = PeerMailbox::PeerLink.from_h(reply.json["link"]) or raise RemoteFailed, "#{@entry.label}: no link in its answer"
25
+ PeerPaired.new(status: :paired, link: link)
26
+ when 409
27
+ status = %w[continued old_worker].find { |known| known == reply.json["status"] } or raise_refusal(reply)
28
+ PeerPaired.new(status: status.to_sym, next_id: reply.json["next_id"]&.to_s)
29
+ else raise_refusal(reply)
30
+ end
31
+ end
32
+
33
+ # @return [Boolean] whether there was a pairing
34
+ def peer_unpair(id, peer)
35
+ PeerMailbox.check_name!(peer)
36
+ reply = peer_request(:delete, "#{session_path(id)}/peers/#{peer}")
37
+ raise_refusal(reply) unless reply.status == 200
38
+
39
+ reply.json["unpaired"] == true
40
+ end
41
+
42
+ # @return [Array<PeerRoster::Peer>]
43
+ def peer_list(id)
44
+ reply = peer_request(:get, "#{session_path(id)}/peers")
45
+ raise_refusal(reply) unless reply.status == 200
46
+
47
+ Array(reply.json["peers"]).filter_map { |row| PeerRoster::Peer.from_h(row) }
48
+ end
49
+
50
+ # The say, and its wait, on the remote's chi web (POST …/say, wait:):
51
+ # its PeerSay, so the line is the remote's.
52
+ # @return [PeerSay]
53
+ def peer_say(id, peer, text:, summary:, wake:, re:, wait: 0, **)
54
+ PeerMailbox.check_name!(peer)
55
+ reply = peer_request(:post, "#{session_path(id)}/peers/#{peer}/say",
56
+ body: { text: text, summary: summary, wake: wake, re: re, wait: wait },
57
+ read_timeout: wait.to_f + PEER_SAY_SLACK)
58
+ return PeerSay.new(status: :gone) if reply.status == 404 && reply.error == "not_found"
59
+ raise BadRequest.new(reply.json["detail"].to_s, code: reply.error) if reply.status == 400
60
+
61
+ said = PeerSay.from_h(reply.json) if [200, 409].include?(reply.status)
62
+ said || raise_refusal(reply)
63
+ end
64
+
65
+ private
66
+
67
+ # A …/peers request; an older chi web (no such route) says it has no chi peer.
68
+ def peer_request(method, path, **)
69
+ request(method, path, **)
70
+ rescue RemoteTooOld
71
+ raise RemoteTooOld, "chi web on #{@entry.name} is older: it has no chi peer (update chi there: chi update)"
72
+ end
73
+ end
74
+ end
75
+ end
@@ -13,6 +13,7 @@ require_relative "child_move"
13
13
  require_relative "starting_marker"
14
14
  require_relative "context_move"
15
15
  require_relative "note_move"
16
+ require_relative "peer_continue"
16
17
  require_relative "archive_store"
17
18
  require_relative "continue_intent"
18
19
  require_relative "continued_from"
@@ -116,6 +117,12 @@ module Samagotchi
116
117
  # written into the link only (NoteMove::CONTINUE_SOURCES: never given
117
118
  # back), which goes with its delete.
118
119
  CarryStep.new(name: :objectives, store: :session_files, carry: :carry_objectives, undo: {}, files: []),
120
+ # The peers' messages it hadn't read, as one note (PeerContinue): the
121
+ # pairing and the mailbox stay with the previous link (its store rows
122
+ # say so), the peer pairs again. No undo: a note written into the link
123
+ # only, which is excluded from NoteMove's give-back and goes with its
124
+ # delete; the previous link's mailbox and receipts are only read.
125
+ CarryStep.new(name: :peers, store: :session_files, carry: :carry_peers, undo: {}, files: []),
119
126
  # Its waiting notes last: the carry above read a pending /objectives
120
127
  # edit from them first. They keep their names, so they still sort
121
128
  # ahead of the link's own notes. A note sent to the previous link
@@ -345,6 +352,11 @@ module Samagotchi
345
352
  Objectives.carry(ctx.previous, to: ctx.to, state_dir: ctx.state_dir)
346
353
  end
347
354
 
355
+ # @return [Integer] how many peer messages the link's note holds
356
+ private_class_method def self.carry_peers(ctx)
357
+ PeerContinue.carry(from: ctx.previous.id, to: ctx.to, state_dir: ctx.state_dir)
358
+ end
359
+
348
360
  # @return [Array<String>] the names of the notes moved to the link
349
361
  private_class_method def self.carry_notes(ctx)
350
362
  NoteMove.move(from: ctx.previous.id, to: ctx.to, state_dir: ctx.state_dir)
@@ -69,7 +69,7 @@ module Samagotchi
69
69
  # What a delivery of one kind may do to a session's worker: one frozen
70
70
  # row per kind (ROWS), decided on WorkerPresence's predicates alone, in
71
71
  # one order for every kind (#decide).
72
- # @!attribute kind [Symbol] :send, :note, :push, :ring, :fresh_verdict,
72
+ # @!attribute kind [Symbol] :send, :note, :push, :peer, :ring, :fresh_verdict,
73
73
  # :leave (WorkerBoot's respawn, not a delivery), or a turn delivery's
74
74
  # unattended sender (deliver_turn, #for_sender): :schedule, :plugin,
75
75
  # :delegate, :participant, :automatic
@@ -158,6 +158,9 @@ module Samagotchi
158
158
  refuse_tui: true, refuse_scratch: true),
159
159
  push: WakePolicy.new(kind: :push, resolves: :pinned, starts: true, unstops: false, starts_archived: false,
160
160
  refuse_tui: false, refuse_scratch: false),
161
+ # A peer agent's message (chi peer say, PeerMailbox.post): a push's row.
162
+ peer: WakePolicy.new(kind: :peer, resolves: :pinned, starts: true, unstops: false, starts_archived: false,
163
+ refuse_tui: false, refuse_scratch: false),
161
164
  ring: WakePolicy.new(kind: :ring, resolves: :reader, starts: true, unstops: false, starts_archived: false,
162
165
  refuse_tui: false, refuse_scratch: false),
163
166
  fresh_verdict: WakePolicy.new(kind: :fresh_verdict, resolves: :pinned, starts: false, unstops: false,
@@ -241,7 +244,7 @@ module Samagotchi
241
244
  # SessionInbox.deliver and SessionInbox.wake.
242
245
  module Dispatch
243
246
  # What a start each kind makes is logged as (SessionManager.start_for_inbox).
244
- START_EVENTS = { ring: :delegate_woke_parent, push: :context_woke_session }.freeze
247
+ START_EVENTS = { ring: :delegate_woke_parent, push: :context_woke_session, peer: :peer_woke_session }.freeze
245
248
 
246
249
  module_function
247
250
 
@@ -52,14 +52,16 @@ module Samagotchi
52
52
  def detail = ack["detail"]
53
53
 
54
54
  # How a delivery that did not go in reads, as one line: the word for it
55
- # (refused: a worker older than queueing would steer the running turn,
55
+ # (refused: a worker older than queueing or without a requested feature,
56
56
  # or a remote refused it as chi send refuses it here; failed: it simply
57
57
  # did not get in) and its reason. chi send prints it, and the delegate
58
58
  # tool's follow-up says it after "Error: session <id8>".
59
59
  # @return [String]
60
60
  def refusal_text
61
- refused = error == Delivery::QUEUE_UNAVAILABLE["error"] || continued? || wake_refused? || deleting? ||
62
- DeliverResult::REMOTE_REFUSALS.include?(error)
61
+ refused = error == Delivery::QUEUE_UNAVAILABLE["error"] ||
62
+ error == Delivery::ASK_UNAVAILABLE["error"] ||
63
+ error == Delivery::PAIR_UNAVAILABLE["error"] ||
64
+ continued? || wake_refused? || deleting? || DeliverResult::REMOTE_REFUSALS.include?(error)
63
65
  "#{refused ? "refused" : "failed"}: #{detail || "could not queue it"}"
64
66
  end
65
67
 
@@ -422,6 +422,8 @@ module Samagotchi
422
422
  PluginSessionState.remove(id)
423
423
  when :context_sources
424
424
  removed.concat(ContextSources.remove_session(id, state_dir: state_dir))
425
+ when :peer_mailbox
426
+ removed.concat(PeerMailbox.remove_session(id, state_dir: state_dir))
425
427
  when :participants
426
428
  Participants.end_sessions([id], by: "delete", state_dir: state_dir)
427
429
  when :system_one_runs
@@ -213,7 +213,8 @@ module Samagotchi
213
213
  # (SessionInbox.deliver): resume_session, which keeps its own checks
214
214
  # (a claim on the starting marker: of starts racing, one spawns),
215
215
  # logged as +event+.
216
- # @param event [Symbol] :delegate_woke_parent (a ring) or :context_woke_session (a push)
216
+ # @param event [Symbol] :delegate_woke_parent (a ring), :context_woke_session (a push) or
217
+ # :peer_woke_session (a peer's say)
217
218
  # @return [Symbol] :woken (this start spawned it), :starting (another
218
219
  # start won the claim, or is pending), :live (a worker took it since)
219
220
  # or :owned (a one-turn chi run or its terminal's scratch session did)
@@ -56,6 +56,7 @@ require_relative "continue_offer"
56
56
  require_relative "image_store"
57
57
  require_relative "plugin_session_state"
58
58
  require_relative "context_sources"
59
+ require_relative "peer_mailbox"
59
60
  require_relative "context_candidates_log"
60
61
  require_relative "session_chain"
61
62
  require_relative "child_move"
@@ -3,6 +3,7 @@
3
3
  module Samagotchi
4
4
  # The files that hold state for a session, including stores outside its
5
5
  # sidecar directory. `corpus_dir` is relative to the compatibility corpus.
6
+ # A `file` ending in "/" is a folder of files (PeerMailbox's in/).
6
7
  # A Symbol in `continue` names the carry step; a String explains why it stays.
7
8
  module SessionStores
8
9
  Store = Data.define(:file, :owner, :removal, :cross_version, :continue, :corpus_dir, :corpus_exception) do
@@ -17,6 +18,12 @@ module Samagotchi
17
18
 
18
19
  SIDE_CAR = "sessions/compat-session"
19
20
  CONTEXT = "context/sessions/compat-session"
21
+ MAILBOX = "mailbox/compat-session/claude"
22
+ # A continue leaves the mailbox with the previous link (the peer pairs
23
+ # again with the next one, owner 2026-11-24); its :peers step only reads
24
+ # it, for the one note.
25
+ MAILBOX_STAYS = "the mailbox stays with the previous link (its unread messages reach the next one as one note, " \
26
+ "SessionContinue :peers); a say there is refused with the next id"
20
27
 
21
28
  STORES = [
22
29
  Store.new(file: "archived", owner: "ArchiveStore", removal: :session_files, cross_version: true,
@@ -60,6 +67,16 @@ module Samagotchi
60
67
  Store.new(file: "peer_exchanges.jsonl", owner: "PeerExchanges", removal: :session_files, cross_version: true,
61
68
  continue: "exchanges stay with the previous link; the new pairing starts empty", corpus_dir: nil,
62
69
  corpus_exception: "older readers do not read peer exchange metadata"),
70
+ # A peer's side of the session (PeerMailbox): <state>/mailbox/<id>/<peer>/.
71
+ Store.new(file: "link.json", owner: "PeerMailbox", removal: :peer_mailbox, cross_version: true,
72
+ continue: MAILBOX_STAYS, corpus_dir: MAILBOX),
73
+ Store.new(file: "in/", owner: "PeerMailbox", removal: :peer_mailbox, cross_version: true,
74
+ continue: MAILBOX_STAYS, corpus_dir: MAILBOX),
75
+ Store.new(file: "lock", owner: "PeerMailbox", removal: :peer_mailbox, cross_version: false,
76
+ continue: "a lock is not session data", corpus_dir: nil),
77
+ # What the worker did with each peer message (PeerReceipts).
78
+ Store.new(file: "peer_receipts.json", owner: "PeerReceipts", removal: :session_files, cross_version: true,
79
+ continue: MAILBOX_STAYS, corpus_dir: SIDE_CAR),
63
80
  Store.new(file: "owner.lock", owner: "OwnerLock", removal: :session_files, cross_version: false,
64
81
  continue: "the owner lock is not session data", corpus_dir: SIDE_CAR),
65
82
  Store.new(file: "reminders.json", owner: "ReminderCarry", removal: :session_files, cross_version: true,
@@ -360,7 +360,7 @@ module Samagotchi
360
360
  # A line of a participant's text that opens like one of chi's own
361
361
  # headers or frames (another participant's review header, a steer's, an
362
362
  # automatic input's, a delegate report's, a context note's, a task's, an
363
- # objectives list's or a peer's message block (ContextAbsorber.peer_block)),
363
+ # objectives list's or a peer's message block (PeerNote.block)),
364
364
  # in any case, after any spaces, format characters or markdown leads
365
365
  # (.forged_frames).
366
366
  FORGED_OPENINGS = ["Review contribution", "Steer", "Automatic input", "Delegate report", "CONTEXT NOTE",
@@ -445,7 +445,7 @@ module Samagotchi
445
445
 
446
446
  Memory convention:
447
447
  Project scope: one folder per project (a git repository, shared by its worktrees and subdirectories, or a folder marked by `chi project init` and its subfolders; its path is on the "Project memories folder" line below)
448
- System scope: ~/.config/samagotchi/memories/ (cross-project)
448
+ System scope: #{Paths.tilde(Tools::MemoryRead.memories_dir("system"))}/ (cross-project)
449
449
  memory_read accepts optional scope (project|system).
450
450
  memory_write requires explicit scope and entry name.
451
451
  For a small change to an existing memory, `edit` its file (<scope dir>/<name>.md)
@@ -738,7 +738,7 @@ module Samagotchi
738
738
  def origin_of(value) = TurnOrigin.of(value)
739
739
  def reminder_origin?(origin) = origin.client_id.to_s.start_with?(ClientId::SYSTEM_PREFIX)
740
740
  def report_origin?(origin) = origin.source == "delegate_report"
741
- def context_origin?(origin) = origin.source == "context"
741
+ def context_origin?(origin) = %w[context peer].include?(origin.source)
742
742
  def task_origin?(origin) = origin.source == "task"
743
743
  # A turn with no prompt: "(continuing)"; a context wake's or a task
744
744
  # finish wake's label alone.
@@ -232,7 +232,8 @@ module Samagotchi
232
232
 
233
233
  # Who sent a line, by its client_id: its row's label (the whole id or
234
234
  # its longest prefix), a turn an attached context source started
235
- # (context:<name>) as "context <name> changed", a finished background
235
+ # (context:<name>) as "context <name> changed", a peer's message's
236
+ # (peer:<name>) as "peer <name>", a finished background
236
237
  # task's (task:<id>) as "task <id8> finished", AUTOMATIC_LABEL for an
237
238
  # id chi doesn't know; +fallback+ for none (the user's own) and for a
238
239
  # row labelled as none (ClientId::FIRST_PROMPT, CARD_ANSWER).
@@ -251,6 +252,8 @@ module Samagotchi
251
252
  return "schedule"
252
253
  when "agent"
253
254
  return "agent #{ClientId.agent_name(id)}"
255
+ when "peer"
256
+ return "peer #{ClientId.peer_name(id)}"
254
257
  when "session"
255
258
  return "session #{ClientId.session_name(id)}"
256
259
  end
@@ -57,16 +57,10 @@ module Samagotchi
57
57
  ALLOWED_REQUIRES = (ALLOWED.map(&:file) + %w[samagotchi/testing/rspec samagotchi/testing/minitest]).uniq.freeze
58
58
 
59
59
  SESSION = "a saved session (context sources are keyed by its id): needs a kit helper that saves one"
60
- SOURCES = "the session's context sources (the peer's inbox / outbox): needs a kit helper that attaches one"
61
60
  REF_LIMITS = "a ref's kinds and limits (event[:refs] checks them too): could be stable constants"
62
- # The peers' specs pair a session through its context sources.
63
- PEER_SPEC = {
64
- 'require "samagotchi/context_sources"' => "spec: #{SOURCES}",
65
- "Samagotchi::Session.new_session" => "spec: #{SESSION}",
66
- "Samagotchi::ContextSources.session_location" => "spec: #{SOURCES}",
67
- "Samagotchi::ContextSources::Source.new" => "spec: #{SOURCES}",
68
- "Samagotchi::ContextSources::Fetched.new" => "spec: an outbox answer as the context poller records it"
69
- }.freeze
61
+ # The peers' specs pair through the kit (Bundle#pair_peer, #peer_says);
62
+ # a saved session is still theirs to make.
63
+ PEER_SPEC = { "Samagotchi::Session.new_session" => "spec: #{SESSION}" }.freeze
70
64
 
71
65
  # bundle => {reference => why}: what each shipped bundle reaches
72
66
  # beyond ALLOWED today, its specs' (why "spec: …") included.
@@ -76,10 +70,7 @@ module Samagotchi
76
70
  "Samagotchi::Guardrails::GitInfo.new" => "the work tree's top for the AGENTS.md chain (ctx.repo_root covers the top only)"
77
71
  },
78
72
  # Both bundles' goldens live in claude-peer's spec/.
79
- "claude-peer" => PEER_SPEC.merge(
80
- "Samagotchi::ContextSources.move" => "spec: a continue leaving the pairing behind, as SessionContinue " \
81
- "moves it: needs a kit helper that continues a session"
82
- ),
73
+ "claude-peer" => PEER_SPEC,
83
74
  "codex-peer" => PEER_SPEC,
84
75
  "coordinator" => {
85
76
  "Samagotchi::MemoryPaths.scope_dir" => "where the coordinator's memories live: needs a ctx memory-path API",
@@ -9,7 +9,6 @@ require_relative "../commands/registry"
9
9
  require_relative "../session_commands"
10
10
  require_relative "../tools/builtins"
11
11
  require_relative "../tools/tool_index"
12
- require_relative "../peer_sources"
13
12
  require_relative "../toolkit"
14
13
  require_relative "../guardrails/gate"
15
14
  require_relative "../turn_context"
@@ -93,16 +92,19 @@ module Samagotchi
93
92
  def shipped(name, **) = load(File.join(SHIPPED_DIR, name.to_s), **)
94
93
 
95
94
  # Registries as an Engine's start: chi's built-in commands and
96
- # tools, empty services, toolkits, tool index and peer sources;
95
+ # tools, empty services, toolkits, tool index and peer registry;
97
96
  # +fields+ set the rest (hooks:, context_for:, init: ...) or replace
98
97
  # these. Bundle#build_registries and Install's load both start here.
99
98
  # @api private
100
99
  # @return [Plugin::Registries]
101
100
  def registries(**fields)
101
+ # Here, not at the kit's load: the kit stays under its file budget
102
+ # (spec/samagotchi/testing/sandbox_spec.rb).
103
+ require_relative "../peer_registry"
102
104
  Plugin::Registries.new(
103
105
  commands: SessionCommandCatalog.register_builtins(Commands::Registry.new), tools: Tools::Builtins.registry,
104
106
  services: Plugin::Services.new, stage_tools: ->(*) {}, toolkits: [], tool_index: Tools::ToolIndex.new,
105
- peer_sources: PeerSources.new, prompt_sections: Plugin::PromptSections.new,
107
+ peer_registry: PeerRegistry.new, prompt_sections: Plugin::PromptSections.new,
106
108
  judgments: SystemOne::Judgments.new, **fields
107
109
  )
108
110
  end
@@ -339,8 +341,8 @@ module Samagotchi
339
341
  def toolkits = @registries.toolkits
340
342
  # @return [Tools::ToolIndex]
341
343
  def tool_index = @registries.tool_index
342
- # @return [PeerSources]
343
- def peer_sources = @registries.peer_sources
344
+ # @return [PeerRegistry] the peers it declared (chi.peer)
345
+ def peer_registry = @registries.peer_registry
344
346
 
345
347
  # The prompt sections as chi's next prompt build runs them, for the
346
348
  # session now (its id: a failure keeps that session's last good text).
@@ -435,6 +437,39 @@ module Samagotchi
435
437
  self
436
438
  end
437
439
 
440
+ # ── A peer's side (PeerMailbox, as `chi peer` writes it) ──────────
441
+
442
+ # Pair peer +name+ with the session (+session_id+, default the
443
+ # session now), as `chi peer pair NAME ID --address ADDR` does:
444
+ # ctx.peers.link reads it. +address+ nil: answers only.
445
+ # @return [PeerMailbox::PeerLink]
446
+ def pair_peer(name, address:, from: nil, session_id: nil)
447
+ require_relative "../peer_mailbox"
448
+ PeerMailbox.pair(session_id || peer_session_id, name.to_s, address: address, from: from,
449
+ state_dir: peer_state_dir)
450
+ end
451
+
452
+ # End the pairing, as `chi peer unpair` does (the messages stay).
453
+ def unpair_peer(name, session_id: nil)
454
+ require_relative "../peer_mailbox"
455
+ PeerMailbox.unpair(session_id || peer_session_id, name.to_s, state_dir: peer_state_dir)
456
+ end
457
+
458
+ # A message from peer +name+ in the session's mailbox, as `chi peer
459
+ # say` writes it (no worker takes it here): ctx.peers.message reads it.
460
+ # @return [PeerMailbox::PeerMessage]
461
+ def peer_says(name, text, summary: nil, wake: true, re: nil, session_id: nil)
462
+ require_relative "../peer_mailbox"
463
+ PeerMailbox.post(session_id || peer_session_id, name.to_s, text: text, summary: summary, wake: wake, re: re,
464
+ state_dir: peer_state_dir)
465
+ end
466
+
467
+ def peer_session_id = @recorder[:session_id] || raise(ArgumentError, "the session has no id: set(session_id: …)")
468
+ private :peer_session_id
469
+
470
+ def peer_state_dir = @recorder[:state_dir] || Session.default_state_dir
471
+ private :peer_state_dir
472
+
438
473
  def newest_sign_in
439
474
  sign_ins.last or raise ArgumentError, "no ctx.sign_in was started"
440
475
  end
@@ -30,9 +30,9 @@ module Samagotchi
30
30
  end
31
31
 
32
32
  # What a bundle registered (#registered): commands, tools (names),
33
- # hooks per event, inits (labels), toolkits, tool sources and peer
34
- # sources (names).
35
- Registered = Data.define(:commands, :tools, :hooks, :inits, :toolkits, :tool_sources, :peer_sources, :prompt_sections)
33
+ # hooks per event, inits (labels), toolkits, tool sources and peers
34
+ # (names, chi.peer).
35
+ Registered = Data.define(:commands, :tools, :hooks, :inits, :toolkits, :tool_sources, :peers, :prompt_sections)
36
36
  # A command: its mid_turn policy and its selection-bar labels (chi.annotation).
37
37
  Command = Data.define(:name, :mid_turn, :labels)
38
38
  # A hook on an event: the bundle, the hook (the plugin's label) and its priority.
@@ -99,7 +99,7 @@ module Samagotchi
99
99
  inits: inits.map { |init| init[:label] },
100
100
  toolkits: Array(registries.toolkits).map(&:name),
101
101
  tool_sources: registries.tool_index.sources.map(&:label),
102
- peer_sources: registries.peer_sources.names,
102
+ peers: registries.peer_registry&.names || [],
103
103
  prompt_sections: registries.prompt_sections.names(name)
104
104
  )
105
105
  end
@@ -11,7 +11,8 @@ module Samagotchi
11
11
  # The real Plugin::Api, also recording each declaration in order
12
12
  # (#declarations), for a spec of what #register declares as written.
13
13
  class RecordingApi < Plugin::Api
14
- DECLARATIONS = %i[command annotation tool on service init toolkit tool_source peer_source prompt_section judgment].freeze
14
+ DECLARATIONS = %i[command annotation tool on service init toolkit tool_source peer prompt_section
15
+ judgment].freeze
15
16
 
16
17
  # @return [Array<Declaration>]
17
18
  def declarations = (@declarations ||= [])