samagotchi 0.187.0 → 0.189.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 (184) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +96 -1
  3. data/bin/chi +2 -0
  4. data/docs/architecture.md +13 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +139 -120
  7. data/docs/cli.md +46 -8
  8. data/docs/configuration.md +4 -4
  9. data/docs/context.md +18 -162
  10. data/docs/guardrails.md +6 -3
  11. data/docs/hooks.md +2 -1
  12. data/docs/internals/attached-context.md +19 -37
  13. data/docs/internals/bridge.md +1 -0
  14. data/docs/internals/bundles.md +3 -3
  15. data/docs/internals/engine.md +2 -2
  16. data/docs/internals/llm-context-forget.md +5 -6
  17. data/docs/internals/objectives.md +1 -0
  18. data/docs/internals/pages.md +71 -21
  19. data/docs/internals/peers.md +149 -0
  20. data/docs/internals/remote-sessions.md +7 -4
  21. data/docs/internals/session-lifecycle.md +19 -6
  22. data/docs/internals/web-frontend.md +63 -39
  23. data/docs/internals/web-push.md +12 -6
  24. data/docs/memory.md +1 -1
  25. data/docs/pages.md +70 -16
  26. data/docs/peers.md +144 -0
  27. data/docs/plugins.md +77 -28
  28. data/docs/releasing.md +1 -1
  29. data/docs/scheduling.md +71 -8
  30. data/docs/sessions.md +12 -8
  31. data/docs/sub-agent.md +5 -5
  32. data/docs/testing.md +1 -1
  33. data/lib/samagotchi/bridge.rb +3 -3
  34. data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
  35. data/lib/samagotchi/bundle_command/check.rb +1 -1
  36. data/lib/samagotchi/bundle_manifest.rb +34 -5
  37. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
  38. data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
  39. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
  40. data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
  41. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
  42. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
  43. data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
  44. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
  45. data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
  46. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
  47. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  49. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +159 -0
  50. data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
  51. data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
  52. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  53. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  54. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  55. data/lib/samagotchi/client_id.rb +15 -1
  56. data/lib/samagotchi/config.rb +8 -7
  57. data/lib/samagotchi/context_absorber.rb +23 -277
  58. data/lib/samagotchi/context_sources.rb +17 -69
  59. data/lib/samagotchi/engine/messages.rb +12 -1
  60. data/lib/samagotchi/engine/plugins.rb +1 -1
  61. data/lib/samagotchi/engine.rb +7 -6
  62. data/lib/samagotchi/engine_peers.rb +0 -3
  63. data/lib/samagotchi/guardrail_wiring.rb +2 -0
  64. data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
  65. data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
  66. data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
  67. data/lib/samagotchi/inline_widgets.rb +11 -3
  68. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  69. data/lib/samagotchi/log_line.rb +1 -1
  70. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  71. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  72. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  73. data/lib/samagotchi/note_move.rb +3 -1
  74. data/lib/samagotchi/page_command.rb +25 -13
  75. data/lib/samagotchi/pages/builder.rb +7 -8
  76. data/lib/samagotchi/pages/bundled.rb +83 -0
  77. data/lib/samagotchi/pages/launch.rb +22 -4
  78. data/lib/samagotchi/pages/runner.rb +7 -2
  79. data/lib/samagotchi/pages/runtime.rb +83 -0
  80. data/lib/samagotchi/pages/store.rb +29 -7
  81. data/lib/samagotchi/pages.rb +47 -3
  82. data/lib/samagotchi/peer_command.rb +192 -0
  83. data/lib/samagotchi/peer_continue.rb +105 -0
  84. data/lib/samagotchi/peer_exchanges.rb +3 -3
  85. data/lib/samagotchi/peer_mailbox.rb +360 -0
  86. data/lib/samagotchi/peer_note.rb +208 -0
  87. data/lib/samagotchi/peer_receipts.rb +247 -0
  88. data/lib/samagotchi/peer_registry.rb +44 -0
  89. data/lib/samagotchi/peer_roster.rb +79 -0
  90. data/lib/samagotchi/peer_say.rb +168 -0
  91. data/lib/samagotchi/plugin/api.rb +29 -21
  92. data/lib/samagotchi/plugin/context.rb +7 -0
  93. data/lib/samagotchi/plugin/loader.rb +3 -3
  94. data/lib/samagotchi/plugin/peer.rb +175 -64
  95. data/lib/samagotchi/plugin/peers.rb +70 -0
  96. data/lib/samagotchi/run_options.rb +3 -2
  97. data/lib/samagotchi/schedule_command.rb +88 -39
  98. data/lib/samagotchi/schedule_display.rb +101 -0
  99. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  100. data/lib/samagotchi/schedules/edit_part.rb +120 -0
  101. data/lib/samagotchi/schedules/history_part.rb +51 -0
  102. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  103. data/lib/samagotchi/schedules/notices_part.rb +116 -0
  104. data/lib/samagotchi/schedules/protection_part.rb +103 -0
  105. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  106. data/lib/samagotchi/schedules.rb +134 -330
  107. data/lib/samagotchi/session_access/contract.rb +18 -1
  108. data/lib/samagotchi/session_access/local.rb +140 -14
  109. data/lib/samagotchi/session_access/remote.rb +6 -3
  110. data/lib/samagotchi/session_access/remote_peers.rb +75 -0
  111. data/lib/samagotchi/session_chain/delete.rb +7 -5
  112. data/lib/samagotchi/session_continue.rb +12 -0
  113. data/lib/samagotchi/session_inbox_delivery.rb +5 -2
  114. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  115. data/lib/samagotchi/session_lifecycle.rb +3 -2
  116. data/lib/samagotchi/session_manager/delivery.rb +5 -3
  117. data/lib/samagotchi/session_manager/removal.rb +18 -9
  118. data/lib/samagotchi/session_manager/spawn.rb +2 -1
  119. data/lib/samagotchi/session_manager.rb +1 -0
  120. data/lib/samagotchi/session_protection.rb +99 -0
  121. data/lib/samagotchi/session_retention.rb +21 -6
  122. data/lib/samagotchi/session_stores.rb +17 -0
  123. data/lib/samagotchi/sessions_command.rb +4 -0
  124. data/lib/samagotchi/steer.rb +1 -1
  125. data/lib/samagotchi/system_prompt.rb +1 -1
  126. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  127. data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
  128. data/lib/samagotchi/testing/boundary.rb +17 -13
  129. data/lib/samagotchi/testing/bundle.rb +40 -5
  130. data/lib/samagotchi/testing/install.rb +4 -4
  131. data/lib/samagotchi/testing/recording_api.rb +2 -1
  132. data/lib/samagotchi/tools/cancel_schedule.rb +5 -2
  133. data/lib/samagotchi/tools/context_read.rb +0 -14
  134. data/lib/samagotchi/tools/list_schedules.rb +8 -3
  135. data/lib/samagotchi/turn_outcome.rb +41 -0
  136. data/lib/samagotchi/version.rb +1 -1
  137. data/lib/samagotchi/web/app.rb +2 -13
  138. data/lib/samagotchi/web/message_display.rb +4 -2
  139. data/lib/samagotchi/web/page_routes.rb +13 -8
  140. data/lib/samagotchi/web/peer_routes.rb +133 -0
  141. data/lib/samagotchi/web/public/app.js +23 -29
  142. data/lib/samagotchi/web/public/bubbles.js +2 -2
  143. data/lib/samagotchi/web/public/cards_place.js +20 -1
  144. data/lib/samagotchi/web/public/context_chips.js +45 -46
  145. data/lib/samagotchi/web/public/history_reveal.js +4 -1
  146. data/lib/samagotchi/web/public/history_shape.js +3 -2
  147. data/lib/samagotchi/web/public/index.html +24 -2
  148. data/lib/samagotchi/web/public/notify.js +1 -1
  149. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  150. data/lib/samagotchi/web/public/page_links.js +1 -1
  151. data/lib/samagotchi/web/public/page_view.js +10 -6
  152. data/lib/samagotchi/web/public/pages.css +9 -2
  153. data/lib/samagotchi/web/public/pages_group.js +21 -19
  154. data/lib/samagotchi/web/public/pages_list.js +73 -0
  155. data/lib/samagotchi/web/public/pages_model.js +54 -0
  156. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  157. data/lib/samagotchi/web/public/peer_chip.js +60 -74
  158. data/lib/samagotchi/web/public/peer_data.js +13 -11
  159. data/lib/samagotchi/web/public/peer_links.js +12 -7
  160. data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
  161. data/lib/samagotchi/web/public/peer_note.js +7 -3
  162. data/lib/samagotchi/web/public/peer_text.js +4 -4
  163. data/lib/samagotchi/web/public/quiet_notes.js +199 -0
  164. data/lib/samagotchi/web/public/revise_stack.js +4 -3
  165. data/lib/samagotchi/web/public/session_view.js +2 -2
  166. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  167. data/lib/samagotchi/web/public/turn_block.js +7 -3
  168. data/lib/samagotchi/web/public/turn_events.js +6 -0
  169. data/lib/samagotchi/web/public/views.js +77 -23
  170. data/lib/samagotchi/web/push/attention.rb +3 -2
  171. data/lib/samagotchi/web/push/notifier.rb +4 -3
  172. data/lib/samagotchi/web/server.rb +3 -1
  173. data/lib/samagotchi/web/session_access_routes.rb +3 -20
  174. data/lib/samagotchi/web/session_hub.rb +64 -19
  175. data/lib/samagotchi/worker/leave.rb +3 -0
  176. data/lib/samagotchi/worker/mail.rb +73 -0
  177. data/lib/samagotchi/worker/startup.rb +3 -0
  178. data/lib/samagotchi/worker/wake_turns.rb +20 -5
  179. data/lib/samagotchi/worker.rb +12 -6
  180. data/lib/samagotchi/worker_inbound/mail.rb +214 -0
  181. data/lib/samagotchi/worker_inbound.rb +43 -46
  182. data/lib/samagotchi/worker_wakes.rb +26 -21
  183. metadata +35 -2
  184. data/lib/samagotchi/peer_sources.rb +0 -58
@@ -10,7 +10,7 @@ module Samagotchi
10
10
  # "chi <cmd> runs on this machine only: run it on <remote>"). The v1 scope is the remote-sessions plan's
11
11
  # D3: send, answer, note, a session's context (add, push, ls, show, rm)
12
12
  # and sessions list/stop/restart/archive/unarchive/delete, chi share
13
- # (the shared-sessions plan's P2); the rest
13
+ # (the shared-sessions plan's P2), chi peer (peer-mailbox); the rest
14
14
  # stays local. bin/chi's subcommands that act on the machine, not on
15
15
  # sessions, are MACHINE. The run flags (chi --attach, -p, --resume: a
16
16
  # session in this terminal, a remote attach there) are RUN's.
@@ -150,6 +150,23 @@ module Samagotchi
150
150
  "mcp" => SUPPORTED,
151
151
  "mcp serve" => SUPPORTED,
152
152
 
153
+ # A peer agent's side of a session (PeerMailbox): the remote's chi
154
+ # web pairs and writes, and a say waits there (POST …/say, wait:).
155
+ "peer" => SUPPORTED,
156
+ "peer pair" => SUPPORTED,
157
+ "peer pair --address" => SUPPORTED,
158
+ "peer pair --from" => SUPPORTED,
159
+ "peer unpair" => SUPPORTED,
160
+ "peer say" => SUPPORTED,
161
+ "peer say --wake" => SUPPORTED,
162
+ "peer say --nowake" => SUPPORTED,
163
+ "peer say --summary" => SUPPORTED,
164
+ "peer say --re" => SUPPORTED,
165
+ "peer say --message" => SUPPORTED,
166
+ "peer say --wait" => SUPPORTED,
167
+ "peer ls" => SUPPORTED,
168
+ "peer ls --format" => SUPPORTED,
169
+
153
170
  "broadcast" => LOCAL_ONLY
154
171
  }.freeze
155
172
 
@@ -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,143 @@ 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
+ link = PeerMailbox.pair(id, peer, address: address, from: from, state_dir: state_dir!)
557
+ location = ContextSources.session_location(id, state_dir: state_dir!)
558
+ # These are exactly the bundles' LEGACY_INBOX and LEGACY_OUTBOX names.
559
+ ["#{peer}-inbox", "#{peer}-outbox"].each do |name|
560
+ location.remove(name)
561
+ rescue SystemCallError
562
+ nil
563
+ end
564
+ PeerPaired.new(status: :paired, link: link)
565
+ end
566
+
567
+ # Ends the pairing (link.json); the messages stay.
568
+ # @return [Boolean] whether there was one
569
+ def peer_unpair(id, peer) = PeerMailbox.unpair(id, peer, state_dir: state_dir!)
570
+
571
+ # @return [Array<PeerRoster::Peer>]
572
+ def peer_list(id) = PeerRoster.build(id, state_dir: state_dir!)
573
+
574
+ # A message from +peer+ into session +id+, as a delivery
575
+ # (SessionInbox.deliver :peer): refused before anything is written
576
+ # for a gone session, a continued one, no pairing, a live worker
577
+ # without the peer mail, UNTAKEN_MAX unread; else written inside the
578
+ # delivery's block (a session being deleted refuses first), which
579
+ # asks for a worker by the message's own +wake+ alone (no
580
+ # context.wake, no window). Then what chi did, at once when it can't
581
+ # answer yet, else the receipt within +wait+ seconds (a look every
582
+ # PeerSay::POLL_SECONDS).
583
+ # @return [PeerSay]
584
+ # @raise [PeerMailbox::Invalid] a bad name, an empty or oversized text
585
+ def peer_say(id, peer, text:, summary:, wake:, re:, wait: 0, sleeper: ->(seconds) { sleep(seconds) },
586
+ clock: -> { monotonic })
587
+ PeerMailbox.check_name!(peer)
588
+ PeerMailbox.checked_text(text)
589
+ return PeerSay.new(status: :gone) unless Session.exist?(id, **dir)
590
+ if (next_id = continued_as(id))
591
+ return PeerSay.new(status: :continued, next_id: next_id)
592
+ end
593
+ return PeerSay.new(status: :not_paired) unless PeerMailbox.link(id, peer, state_dir: state_dir!)
594
+ return PeerSay.new(status: :old_worker) if old_peer_worker?(id)
595
+
596
+ message = nil
597
+ start_failed = false
598
+ delivered = begin
599
+ SessionInbox.deliver(:peer, id, state_dir: state_dir!) do
600
+ message = PeerMailbox.post(id, peer, text: text, summary: summary, wake: wake, re: re, state_dir: state_dir!,
601
+ taken: PeerReceipts.taken(id, peer, state_dir: state_dir!))
602
+ message.wake
603
+ end
604
+ rescue PeerMailbox::Full
605
+ return PeerSay.new(status: :full)
606
+ rescue StandardError => e
607
+ raise unless message
608
+
609
+ Log.exception(:peer, "peer_say_wake_failed", e, sid: id, peer: peer)
610
+ start_failed = true
611
+ nil
612
+ end
613
+ return PeerSay.new(status: delivered.wake == :deleting ? :deleting : :gone) if delivered&.refused?
614
+
615
+ at_once = start_failed ? :start_failed : peer_at_once(id, delivered.wake)
616
+ receipt = at_once ? nil : peer_receipt_within(id, peer, message.serial, wait, sleeper, clock)
617
+ peer_said(id, peer, message.serial, at_once, receipt)
618
+ end
619
+
541
620
  private
542
621
 
622
+ # Whether +id+'s live worker doesn't take the peer mail (its Bridge
623
+ # features: a read-only look). No live worker: nil (the next one does).
624
+ def old_peer_worker?(id)
625
+ features = WorkerLink.live_features(id, state_dir: state_dir!)
626
+ features && !features.include?(PeerMailbox::FEATURE)
627
+ end
628
+
629
+ # What a say says without waiting (PeerSay::AT_ONCE), from the
630
+ # delivery's +wake+ and the session; nil when a worker sees the
631
+ # message now and the say may wait for its receipt.
632
+ def peer_at_once(id, wake)
633
+ case wake
634
+ when :stopped, :archived, :owned, :starting, :deleting then wake
635
+ when :scratch then :start_failed
636
+ when :live, :woken
637
+ session = Session.load(id, **dir)
638
+ started = Array(session.messages).any? { |m| %w[user assistant model].include?((m[:role] || m["role"]).to_s) }
639
+ return :no_turn unless started
640
+
641
+ :running if wake == :live && session.status == Session::STATUS_RUNNING
642
+ else :not_running
643
+ end
644
+ end
645
+
646
+ # The worker's receipt for +serial+, looked at until one comes or
647
+ # +wait+ seconds pass (one look for 0).
648
+ # @return [PeerReceipts::Receipt, nil]
649
+ def peer_receipt_within(id, peer, serial, wait, sleeper, clock)
650
+ deadline = clock.call + wait.to_f
651
+ loop do
652
+ receipt = PeerReceipts.receipt(id, peer, serial, state_dir: state_dir!)
653
+ return receipt if receipt
654
+
655
+ left = deadline - clock.call
656
+ return nil unless left.positive?
657
+
658
+ sleeper.call([PeerSay::POLL_SECONDS, left].min)
659
+ end
660
+ end
661
+
662
+ # The say's PeerSay: the peer's other held messages read now, and the
663
+ # turns a held reason counts, as configured here.
664
+ def peer_said(id, peer, serial, at_once, receipt)
665
+ latest = PeerReceipts.read(id, state_dir: state_dir!).peer(peer).receipts.to_h { |item| [item.serial, item] }
666
+ earlier = latest.values.select { |item| item.state == "held" && item.serial != serial }.sort_by(&:serial)
667
+ .map { |item| [item.serial, item.reason.to_s] }
668
+ wakes = WorkerWakes.new(grace: 0)
669
+ turns = case receipt&.reason
670
+ when "peer_turns" then wakes.peer_turns
671
+ when "max_wakes" then wakes.max
672
+ end
673
+ PeerSay.new(status: :received, serial: serial, wake: at_once, receipt: receipt, earlier: earlier, turns: turns)
674
+ end
675
+
543
676
  # A session source's push, as a push delivery (SessionInbox.deliver
544
677
  # :push): the text recorded, then a wake when it asks one (a change
545
678
  # with wake, context.wake on, the source not woken lately) as the
@@ -564,13 +697,6 @@ module Samagotchi
564
697
  ContextPush.new(status: :pushed, before: before, revision: written.revision, wake: asked ? delivered&.wake : nil)
565
698
  end
566
699
 
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
700
  def context_wake_allowed?(location, name)
575
701
  return false if Config.get("context.wake") == false
576
702
 
@@ -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.
@@ -838,7 +840,8 @@ module Samagotchi
838
840
  raise SessionManager::ScratchSession, sid if json["scratch"] == true
839
841
 
840
842
  raise SessionManager::OwnedByTUI, sid
841
- when "worker_running", "still_stopping", "scheduled", "continuing", "delegate_unmovable", "chain_scheduled"
843
+ when "worker_running", "still_stopping", "scheduled", "continuing", "delegate_unmovable", "chain_scheduled",
844
+ "protection_unreadable"
842
845
  raise SessionManager::DeleteRefused.new(sid, reason || error.to_sym, message: message, ids: ids_of(json["ids"]),
843
846
  schedule_id: json["schedule_id"])
844
847
  when "tasks_running" then raise tasks_refusal(json, sid)
@@ -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
@@ -10,6 +10,7 @@ require_relative "../continued_from"
10
10
  require_relative "../note_move"
11
11
  require_relative "../owner_lock"
12
12
  require_relative "../session"
13
+ require_relative "../session_protection"
13
14
  require_relative "../starting_marker"
14
15
  require_relative "../worker_presence"
15
16
 
@@ -18,7 +19,6 @@ module Samagotchi
18
19
  # (a require cycle otherwise), and session_continue requires session_manager.
19
20
  autoload :SessionManager, File.expand_path("../session_manager", __dir__)
20
21
  autoload :SessionContinue, File.expand_path("../session_continue", __dir__)
21
- autoload :Schedules, File.expand_path("../schedules", __dir__)
22
22
 
23
23
  module SessionChain
24
24
  # A user's delete of a session (the CLI, the web, the TUI's /exit
@@ -145,7 +145,7 @@ module Samagotchi
145
145
  # task the link or such a delegate started that still runs.
146
146
  # @raise [SessionManager::DeleteRefused, SessionManager::OwnedByTUI]
147
147
  def check_link!(plan, state_dir, running_tasks: SessionManager::RunningTasks::Policy::IGNORE)
148
- SessionManager.refuse_scheduled!(plan.id, state_dir)
148
+ SessionManager.refuse_protected!(plan.id, state_dir)
149
149
  refuse_unmovable!(plan.id, plan.moved, state_dir)
150
150
  precheck!(plan.delegates.delete, state_dir)
151
151
  SessionManager::RunningTasks.check!([*plan.delegates.delete, plan.id], state_dir: state_dir,
@@ -218,8 +218,11 @@ module Samagotchi
218
218
  def precheck!(ids, state_dir)
219
219
  ids.each do |sid|
220
220
  begin
221
- SessionManager.refuse_scheduled!(sid, state_dir)
221
+ SessionManager.refuse_protected!(sid, state_dir)
222
222
  rescue SessionManager::DeleteRefused => e
223
+ # Only a schedule names the delegate; any other refusal keeps its words.
224
+ raise unless e.reason == :scheduled
225
+
223
226
  raise SessionManager::DeleteRefused.new(
224
227
  sid, :scheduled, schedule_id: e.schedule_id,
225
228
  message: "its delegate #{sid[0, 8]} is the target of an enabled schedule; " \
@@ -356,8 +359,7 @@ module Samagotchi
356
359
  # a background task any of them started that still runs.
357
360
  # @raise [SessionManager::DeleteRefused, SessionManager::OwnedByTUI]
358
361
  def check_chain!(plan, state_dir, stop:, running_tasks: SessionManager::RunningTasks::Policy::IGNORE)
359
- schedule = Schedules.new(state_dir: state_dir).for_chain(plan.id).first
360
- raise SessionManager::DeleteRefused.new(plan.id, :chain_scheduled, schedule_id: schedule.id) if schedule
362
+ SessionManager.refuse_protected!(plan.id, state_dir, chain: true)
361
363
 
362
364
  plan.links.each do |link|
363
365
  presence = WorkerPresence.read(link, state_dir: state_dir, owner: SessionManager.session_owner(link, state_dir: state_dir))
@@ -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
 
@@ -25,7 +25,8 @@ module Samagotchi
25
25
  # or offer, not SIGSTOPped, features restart and activity, an idle worker
26
26
  # with no streams). For schedules, worker_busy is "its worker is starting
27
27
  # or leaving", deleting is DeliverResult::DELETING's detail, and
28
- # worker_newer is WorkerLink::Skew#short_message. Resume's live is "a
28
+ # worker_newer is WorkerLink::Skew#short_message (Schedules::BusyPart's
29
+ # BUSY_WORDS; Schedules#busy_cell reads these two columns). Resume's live is "a
29
30
  # worker holds it"; restart's fallback is its unresponsive-worker path,
30
31
  # its stop_marked a stop marked and its deleting a deleter holds the lock
31
32
  # (it reads this table: restart_session's precheck); attach's gone_* are
@@ -12,8 +12,9 @@ module Samagotchi
12
12
  # stored: see docs/internals/session-lifecycle.md (Derived states).
13
13
  #
14
14
  # A read only: it writes, clears and unlinks nothing (the marker writers
15
- # are pinned in spec/session_lifecycle_writers_spec.rb). One decider
16
- # reads it (restart_session's precheck, ALLOWED[:restart]); ALLOWED is what
15
+ # are pinned in spec/session_lifecycle_writers_spec.rb). Two deciders
16
+ # read it (restart_session's precheck, ALLOWED[:restart]; a schedule's busy
17
+ # check, Schedules#busy_cell, ALLOWED[:sched_chain] / [:sched_same]); ALLOWED is what
17
18
  # each operation does in each state, pinned against the deciders by
18
19
  # spec/session_lifecycle/matrix_spec.rb.
19
20
  module SessionLifecycle
@@ -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
 
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../session_protection"
3
4
  require_relative "../session_stores"
4
5
  require_relative "running_tasks"
5
6
 
@@ -14,7 +15,9 @@ module Samagotchi
14
15
  # the previous one a delete would bring back), :delegate_unmovable (a
15
16
  # delegate the deleted link's continue moved can't go back: +ids+,
16
17
  # +detail+ says why), :chain_scheduled (a schedule is on the chain a
17
- # chain delete would take: +schedule_id+), :plan_changed (the plan no
18
+ # chain delete would take: +schedule_id+), :protection_unreadable (a
19
+ # SessionProtection protector's store doesn't read: its own words),
20
+ # :plan_changed (the plan no
18
21
  # longer matches the digest the caller confirmed), :tasks_running
19
22
  # (background tasks it or a session the delete takes started still run:
20
23
  # +tasks+, a RunningTasks::Listing; +worker_stopped+ when a worker was
@@ -327,7 +330,7 @@ module Samagotchi
327
330
  sd = state_dir
328
331
  path = Session.session_file(id, state_dir: sd)
329
332
  dir = Session.session_dir(id, state_dir: sd)
330
- refuse_scheduled!(id, sd) unless allow_scheduled
333
+ refuse_protected!(id, sd) unless allow_scheduled
331
334
  RunningTasks.check!([id], state_dir: sd, policy: running_tasks) do |listing|
332
335
  DeleteRefused.new(id, :tasks_running, tasks: listing)
333
336
  end
@@ -391,13 +394,17 @@ module Samagotchi
391
394
  # @return [Array<String>]
392
395
  def delete_tree_ids(id, state_dir) = [*descendant_ids(id, state_dir).reverse, id]
393
396
 
394
- # DeleteRefused :scheduled when an enabled schedule's target, anchor
395
- # or head is +id+: deleting a head would make the schedule fall back to
396
- # an archived link and lose the links after it.
397
- def refuse_scheduled!(id, state_dir)
398
- require_relative "../schedules"
399
- schedule = Schedules.new(state_dir: state_dir).protecting_link(id)
400
- raise DeleteRefused.new(id, :scheduled, schedule_id: schedule.id) if schedule
397
+ # DeleteRefused with the reason a SessionProtection protector holds +id+
398
+ # for (:scheduled: an enabled schedule's target, anchor or head;
399
+ # deleting a head would make the schedule fall back to an archived link
400
+ # and lose the links after it), or with +chain+ the chain +id+ is in
401
+ # (:chain_scheduled). A protector's store that doesn't read refuses it
402
+ # too (:protection_unreadable, its words); any other raise raises here.
403
+ def refuse_protected!(id, state_dir, chain: false)
404
+ hold = chain ? SessionProtection.chain_hold(id, state_dir: state_dir) : SessionProtection.hold(id, state_dir: state_dir)
405
+ raise DeleteRefused.new(id, hold.reason, schedule_id: hold.ref) if hold
406
+ rescue SessionProtection::Unreadable => e
407
+ raise DeleteRefused.new(id, :protection_unreadable, message: e.message)
401
408
  end
402
409
 
403
410
  # Remove every store with state scoped to +id+. The file and sidecar
@@ -422,6 +429,8 @@ module Samagotchi
422
429
  PluginSessionState.remove(id)
423
430
  when :context_sources
424
431
  removed.concat(ContextSources.remove_session(id, state_dir: state_dir))
432
+ when :peer_mailbox
433
+ removed.concat(PeerMailbox.remove_session(id, state_dir: state_dir))
425
434
  when :participants
426
435
  Participants.end_sessions([id], by: "delete", state_dir: state_dir)
427
436
  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"