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
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "log"
4
+
5
+ module Samagotchi
6
+ # Who protects a session from a delete (docs/sessions.md, "Deleting a
7
+ # session"): the sibling of SessionStores, which says what a delete
8
+ # removes; this says what refuses it. The retention sweep keeps every
9
+ # protected id, a link's delete is refused by its first #hold and a chain's
10
+ # by its first #chain_hold (SessionManager::DeleteRefused, whose reasons
11
+ # hold the words).
12
+ #
13
+ # A protector is what a PROTECTORS entry builds for a state dir, answering
14
+ # three questions: #protected_ids (Array<String>), #hold(session_id) and
15
+ # #chain_hold(session_id) (a Hold or nil). Schedules is the one protector
16
+ # (Schedules::ProtectionPart: an enabled schedule's anchor, head and
17
+ # resolved target).
18
+ #
19
+ # Fail-closed: a protector that raises is logged and the error re-raised,
20
+ # never read as "unprotected". The sweep (SessionRetention.sweep_if_due)
21
+ # logs retention_failed and deletes nothing (an Unreadable store:
22
+ # retention_skipped, once per sweep interval); a delete raises to its
23
+ # caller, and a store that is there but doesn't read (Unreadable) is its
24
+ # refusal (DeleteRefused :protection_unreadable,
25
+ # SessionManager.refuse_protected!). A missing store protects nothing.
26
+ module SessionProtection
27
+ # +session_id+ the session held, +reason+ the DeleteRefused reason the
28
+ # holder asks for (:scheduled for a link, :chain_scheduled for a chain),
29
+ # +ref+ the holder's id for the words (the schedule id).
30
+ Hold = Data.define(:session_id, :reason, :ref)
31
+
32
+ # A protector's store is there but doesn't read (schedules.json not
33
+ # JSON, not a schedules document, a file chi can't open, or one schedule
34
+ # in it that doesn't read): who it protects is unknown, so no session is
35
+ # deleted until it is fixed. Its words, one per condition: the whole
36
+ # file, or one entry (+entry+, its id) and the way to drop that entry.
37
+ class Unreadable < StandardError
38
+ # @param file [String] the store's name, for the words
39
+ # @param error [String] why it doesn't read
40
+ # @param entry [String, nil] the id of the one entry that doesn't read
41
+ def initialize(file, error, entry: nil)
42
+ if entry
43
+ super("schedule entry #{entry} in #{file} is unreadable (#{error}): chi schedule cancel #{entry}, " \
44
+ "or fix the file, before deleting sessions")
45
+ else
46
+ super("#{file} is unreadable (#{error}): fix or remove it before deleting sessions")
47
+ end
48
+ end
49
+ end
50
+
51
+ module_function
52
+
53
+ # Deferred: schedules.rb requires session_manager, whose removal part
54
+ # requires this file.
55
+ def schedule_protector(state_dir)
56
+ require_relative "schedules"
57
+ Schedules.new(state_dir: state_dir)
58
+ end
59
+
60
+ PROTECTORS = { schedule: method(:schedule_protector) }.freeze
61
+
62
+ # @return [Array<String>] every id some protector holds (retention keeps them)
63
+ def protected_ids(state_dir:)
64
+ PROTECTORS.flat_map { |name, build| ask(name, build, state_dir, &:protected_ids) }.uniq
65
+ end
66
+
67
+ # @return [Hold, nil] the first protector's hold on a delete of +session_id+
68
+ def hold(session_id, state_dir:)
69
+ first_hold(session_id, state_dir) { |protector| protector.hold(session_id) }
70
+ end
71
+
72
+ # @return [Hold, nil] the first protector's hold on a delete of the chain
73
+ # +session_id+ belongs to
74
+ def chain_hold(session_id, state_dir:)
75
+ first_hold(session_id, state_dir) { |protector| protector.chain_hold(session_id) }
76
+ end
77
+
78
+ def first_hold(session_id, state_dir, &question)
79
+ PROTECTORS.each do |name, build|
80
+ found = ask(name, build, state_dir, sid: session_id, &question)
81
+ return found if found
82
+ end
83
+ nil
84
+ end
85
+ private_class_method :first_hold
86
+
87
+ # An Unreadable store is logged once, by the caller (retention_skipped,
88
+ # or the delete's refusal), not here.
89
+ def ask(name, build, state_dir, sid: nil)
90
+ yield build.call(state_dir)
91
+ rescue Unreadable
92
+ raise
93
+ rescue StandardError => e
94
+ Log.warn(:worker, "protector_failed", protector: name, sid: sid, error: e.class.name, msg: e.message)
95
+ raise
96
+ end
97
+ private_class_method :ask
98
+ end
99
+ end
@@ -10,6 +10,7 @@ require_relative "config"
10
10
  require_relative "log"
11
11
  require_relative "model_profile"
12
12
  require_relative "session_manager"
13
+ require_relative "session_protection"
13
14
  require_relative "system_one/runs"
14
15
 
15
16
  module Samagotchi
@@ -143,9 +144,15 @@ module Samagotchi
143
144
  age = Time.now - File.mtime(marker)
144
145
  return if age < interval
145
146
  end
146
- result = prune(state_dir: sd)
147
+ result = begin
148
+ prune(state_dir: sd)
149
+ rescue SessionProtection::Unreadable => e
150
+ skipped_round(sd, e)
151
+ end
147
152
  sweep_runs(sd)
148
153
  FileUtils.touch(marker)
154
+ return nil if result.nil?
155
+
149
156
  if result[:deleted].any?
150
157
  stops = result[:tasks_stopped].to_i
151
158
  suffix = stops.positive? ? "; stopped #{stops} background tasks" : ""
@@ -157,6 +164,16 @@ module Samagotchi
157
164
  nil
158
165
  end
159
166
 
167
+ # A protector's store doesn't read: no session is deleted this round,
168
+ # logged once (the next try is at the next interval, the marker touched
169
+ # as for a sweep that ran); the parts that ask no protector still run
170
+ # (the skeleton-only dirs here, the saved runs after).
171
+ private_class_method def self.skipped_round(state_dir, error)
172
+ Log.warn(:worker, "retention_skipped", msg: error.message)
173
+ prune_orphan_dirs(state_dir, dry_run: false) if SessionManager.discard_empty?
174
+ nil
175
+ end
176
+
160
177
  # System 1's saved runs last as long as sessions, by day file. Never a
161
178
  # reason the session sweep fails.
162
179
  private_class_method def self.sweep_runs(state_dir)
@@ -214,9 +231,7 @@ module Samagotchi
214
231
  def self.apply(state_dir: Session.default_state_dir, days: DEFAULT_RETENTION_DAYS, max_count: DEFAULT_MAX_COUNT,
215
232
  keep_status: DEFAULT_KEEP_STATUS, dry_run: false, test_only: false, alive_check: nil,
216
233
  empty_check: nil, any_age: false, now: Time.now)
217
- require_relative "schedules"
218
- schedules = Schedules.new(state_dir: state_dir)
219
- scheduled_targets = schedules.protected_session_ids
234
+ protected_ids = SessionProtection.protected_ids(state_dir: state_dir)
220
235
  keep_status = Array(keep_status).map(&:to_s)
221
236
  # Fetch all sessions sorted newest-first for count logic
222
237
  all = Session.list(state_dir: state_dir, sort: "updated_at", order: "desc")
@@ -243,7 +258,7 @@ module Samagotchi
243
258
  next
244
259
  end
245
260
 
246
- if scheduled_targets.include?(session.id)
261
+ if protected_ids.include?(session.id)
247
262
  kept << session.id
248
263
  next
249
264
  end
@@ -318,7 +333,7 @@ module Samagotchi
318
333
  # once, at the start): resumed or taken by a worker since, it stays.
319
334
  elsif held?(session.id, state_dir, alive_check)
320
335
  kept << session.id
321
- elsif scheduled_targets.include?(session.id)
336
+ elsif protected_ids.include?(session.id)
322
337
  kept << session.id
323
338
  else
324
339
  policy = SessionManager::RunningTasks::Policy.stop(by: "retention")
@@ -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,
@@ -4,6 +4,7 @@ require "json"
4
4
  require_relative "session"
5
5
  require_relative "session_row"
6
6
  require_relative "session_manager"
7
+ require_relative "session_protection"
7
8
  require_relative "session_retention"
8
9
  require_relative "project_scope"
9
10
  require_relative "analytics_file"
@@ -364,6 +365,9 @@ module Samagotchi
364
365
  @stdout.puts "\nRun without --dry-run to delete."
365
366
  end
366
367
  0
368
+ rescue Samagotchi::SessionProtection::Unreadable => e
369
+ @stderr.puts e.message
370
+ 1
367
371
  end
368
372
  end
369
373
  end
@@ -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",
@@ -124,6 +115,19 @@ module Samagotchi
124
115
  "Samagotchi::ProjectEnv.respond_to?" => "checks the worker has ProjectEnv.spawn_env (an older chi doesn't)",
125
116
  "Samagotchi::ProjectEnv.spawn_env" => "starts a server in the session's project env: needs a ctx tools-env API"
126
117
  },
118
+ # The kit has no page runner: the page's spec runs it through chi's own (Pages::Launch).
119
+ "schedules" => {
120
+ 'require "samagotchi/memory_bundle/installer"' => "spec: installs the bundle as chi does (the page is listed from the record)",
121
+ "Samagotchi::MemoryBundle::Installer.new" => "spec: installs the bundle as chi does",
122
+ 'require "samagotchi/pages"' => "spec: for Pages",
123
+ 'require "samagotchi/pages/launch"' => "spec: for Pages::Launch",
124
+ "Samagotchi::Pages::Launch.run" => "spec: a run as chi web's Refresh starts it: a kit page runner could replace it",
125
+ "Samagotchi::Pages::Store" => "spec: the page as listed and stored",
126
+ "Samagotchi::Pages.scripts_dir" => "spec: the owner's pages folder stays unmade",
127
+ "Samagotchi::Pages::MAX_OUTPUT_BYTES" => "spec: the output cap the page stays under",
128
+ "Samagotchi::Pages::MAX_TEXT_BYTES" => "spec: the text block cap the off and unreadable texts stay under",
129
+ "Samagotchi::Paths.state_dir" => "spec: where the fixture schedules.json goes"
130
+ },
127
131
  "slow-commands" => {
128
132
  'require "samagotchi/guardrails/shell_lex"' => "for ShellLex",
129
133
  "Samagotchi::Guardrails::ShellLex" => "splits a command into its parts: needs a stable shell-parsing helper",
@@ -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 ||= [])
@@ -25,8 +25,10 @@ module Samagotchi
25
25
  entry = schedules.lookup(name)
26
26
  return "No schedule named #{name}." if entry.nil?
27
27
 
28
+ # nil: gone since the lookup (another cancel in between).
28
29
  if want_all || peers&.session_id.nil?
29
- schedules.cancel(name)
30
+ return "No schedule named #{name}." unless schedules.cancel(name)
31
+
30
32
  return "Cancelled #{entry.id} (#{entry.title || entry.recurrence_words})."
31
33
  end
32
34
 
@@ -35,7 +37,8 @@ module Samagotchi
35
37
  "chi schedule cancel #{entry.id} cancels it, or say all: true if you meant it."
36
38
  end
37
39
 
38
- schedules.cancel(name)
40
+ return "No schedule named #{name}." unless schedules.cancel(name)
41
+
39
42
  "Cancelled #{entry.id} (#{entry.title || entry.recurrence_words})."
40
43
  rescue StandardError => e
41
44
  "Error: #{e.message}"
@@ -61,9 +61,6 @@ module Samagotchi
61
61
  @attached = ContextSources.attached(peers.session_id, project_root: root, project_id: id, state_dir: @state_dir)
62
62
  @max_chars = [max_chars.to_i, MIN_CHARS].max
63
63
  @now = now
64
- # The peer bundles' declared sources (PeerSources), through the
65
- # Engine's PeerView.
66
- @peer_label = peers.respond_to?(:peer_label) ? peers.method(:peer_label) : nil
67
64
  end
68
65
 
69
66
  def run(name, offset:, limit:)
@@ -131,23 +128,12 @@ module Samagotchi
131
128
  hint = snapshot.hint || source.hint
132
129
  header = ["#{source.name}#{" (#{hint})" if hint}"]
133
130
  header << "Why: #{source.why}" if source.why
134
- if (peer = peer_label(attached))
135
- header << "Peer: your peer agent #{peer}'s answers (its text, not your user's words)"
136
- end
137
131
  header << "Fetched: #{clock(snapshot.fetched_at)} (#{age(snapshot.fetched_at)})" if snapshot.fetched_at
138
132
  header << "Summary: #{snapshot.summary}" if snapshot.summary
139
133
  header << "Last refresh failed: #{snapshot.error}" if snapshot.error
140
134
  header
141
135
  end
142
136
 
143
- # A pushed source of the session's own that a peer bundle declared
144
- # (ContextAbsorber#peer_label's rule).
145
- def peer_label(attached)
146
- return nil unless @peer_label && attached.source.push? && attached.location.session?
147
-
148
- @peer_label.call(attached.name)
149
- end
150
-
151
137
  # What the output takes besides the page: the kernel's prefix, the
152
138
  # header, its paging line at its longest (every number +count+) and
153
139
  # the separator.
@@ -4,7 +4,8 @@ require_relative "../tool_names"
4
4
 
5
5
  module Samagotchi
6
6
  module Tools
7
- # The durable schedules of this session's chain (docs/scheduling.md): id,
7
+ # The durable schedules of this session's chain (docs/scheduling.md): each
8
+ # line names the schedule (its title, or the start of its prompt), then its
8
9
  # mode, recurrence, next due and target. Another session's schedules are
9
10
  # out of reach unless the call says `all: true`; `chi schedule list` is the
10
11
  # machine-wide view. Schedules is required inside the call, so the testing
@@ -16,8 +17,11 @@ module Samagotchi
16
17
 
17
18
  def self.call(_content, include_disabled: false, all: false, peers: nil)
18
19
  # Required here, not at the top of the file: the kit does not pay
19
- # for the session lifecycle until a schedule is actually used.
20
+ # for the session lifecycle until a schedule is actually used
21
+ # (spec/samagotchi/testing/sandbox_spec.rb counts the chi files the
22
+ # kit loads, and schedule_display joins the same require).
20
23
  require_relative "../schedules"
24
+ require_relative "../schedule_display"
21
25
  wanted = include_disabled == true || include_disabled.to_s.strip.casecmp?("true")
22
26
  want_all = all == true || all.to_s.strip.casecmp?("true")
23
27
  schedules = Samagotchi::Schedules.new(state_dir: peers&.state_dir)
@@ -32,7 +36,8 @@ module Samagotchi
32
36
  flags = []
33
37
  flags << "skips #{entry.skips} of #{entry.max_skips}" if entry.skips.positive?
34
38
  flags << "disabled after #{entry.failures} failures" unless entry.enabled
35
- "#{entry.id} #{entry.target_words} #{entry.recurrence_words} next #{entry.next_due} #{flags.join(", ")}".rstrip
39
+ "#{entry.id} #{ScheduleDisplay.name(entry)} #{entry.target_words} #{entry.recurrence_words} " \
40
+ "next #{entry.next_due} #{flags.join(", ")}".rstrip
36
41
  end
37
42
  lines << "These are this session's chain only; `chi schedule list` shows every schedule on this machine." if scoped
38
43
  lines.join("\n")
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "session_inbox"
4
+ require_relative "turn_checkpoint"
5
+
6
+ module Samagotchi
7
+ # What a queued turn came to, from its files: whether it left a reply
8
+ # (SessionInbox.reply_for) and the turn it settled as (the session's
9
+ # last_turn when it is that turn, else TurnCheckpoint.settled_turn). A
10
+ # schedule's pending firing reads it (Schedules#resolve_pending, which
11
+ # keeps its own order around it: the reply, its question window, the turn,
12
+ # expiry).
13
+ # @!attribute replied [Boolean] a reply file names the turn
14
+ # @!attribute turn [LastTurn, nil] the settled turn, nil while it runs
15
+ TurnOutcome = Data.define(:replied, :turn) do
16
+ # @param session [Session] the session the turn was queued in
17
+ # @param turn_id [String] its enqueued id
18
+ # @param session_dir [String] that session's sidecar dir
19
+ # @return [TurnOutcome]
20
+ def self.for(session, turn_id, session_dir:)
21
+ turn = session.last_turn if session.last_turn&.enqueued_id == turn_id
22
+ turn ||= TurnCheckpoint.settled_turn(session_dir, turn_id)
23
+ new(replied: !SessionInbox.reply_for(session_dir, turn_id).nil?, turn: turn)
24
+ end
25
+
26
+ def settled? = replied || !turn.nil?
27
+
28
+ # The settled turn completed (the turn alone: a reply is #replied).
29
+ def completed? = turn&.outcome == "completed"
30
+
31
+ # The words of a settled outcome, nil before it settles.
32
+ # @return [String, nil]
33
+ def detail
34
+ return nil unless settled?
35
+ return "turn completed" if replied || completed?
36
+
37
+ reason = [turn.outcome, turn.error_kind, turn.cancel_reason, turn.stopped_by].compact.join(": ")
38
+ "turn #{reason.empty? ? "did not complete" : reason}"
39
+ end
40
+ end
41
+ end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.187.0"
4
+ VERSION = "0.189.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -339,7 +339,7 @@ module Samagotchi
339
339
  ["POST", %r{\A/api/sessions/([^/]+)/images\z}, :handle_image_upload, :participant, :session],
340
340
  ["GET", %r{\A/api/sessions/([^/]+)/images/([^/]+)\z}, :handle_image, :participant, :session],
341
341
  ["GET", %r{\A/api/sessions/([^/]+)/context\z}, :handle_context_list, :owner, :session],
342
- ["GET", %r{\A/api/sessions/([^/]+)/peers\z}, :handle_peers, :owner, :session],
342
+ *PeerRoutes::ROUTES,
343
343
  ["GET", %r{\A/api/sessions/([^/]+)/context/([^/]+)\z}, :handle_context_show, :owner, :session],
344
344
  ["POST", %r{\A/api/sessions/([^/]+)/context\z}, :handle_context_add, :owner, :session],
345
345
  ["POST", %r{\A/api/sessions/([^/]+)/context/([^/]+)/push\z}, :handle_context_push, :owner, :session],
@@ -1126,7 +1126,7 @@ module Samagotchi
1126
1126
  # delegates: chi --remote sessions delete --dry-run asks for this first.
1127
1127
  DELETE_PLAN_FEATURE = "delete_plan_all"
1128
1128
  INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
1129
- BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE, ASK_FEATURE, McpRoute::FEATURE, Delivery::AGENT_FEATURE, ReplyFor::FEATURE].freeze
1129
+ BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE, ASK_FEATURE, McpRoute::FEATURE, Delivery::AGENT_FEATURE, ReplyFor::FEATURE, PeerMailbox::FEATURE].freeze
1130
1130
 
1131
1131
  # The models a new session can start on, spelled as chi spells them
1132
1132
  # elsewhere: bare for the default host (what default.model holds), and
@@ -1595,22 +1595,11 @@ module Samagotchi
1595
1595
  why: source.why, hint: snapshot.hint || source.hint, summary: snapshot.summary, error: snapshot.error,
1596
1596
  fetched_at: snapshot.fetched_at, has_text: snapshot.text?, muted: own.muted?(source.name),
1597
1597
  unread: snapshot.text? && subs[source.name]&.read != snapshot.revision }
1598
- row.merge!(context_peer(attached))
1599
1598
  return row unless full
1600
1599
 
1601
1600
  row.merge(source: source.to_h, snapshot: snapshot.to_h.except("text", :text), shadowed: attached.shadowed)
1602
1601
  end
1603
1602
 
1604
- # A pushed session source named <peer>-inbox / -outbox: the pairing's
1605
- # peer ("claude"), its leg and label, by name (docs/context.md, Peer
1606
- # sources); {} for any other.
1607
- def context_peer(attached)
1608
- return {} unless attached.source.push? && attached.location.session?
1609
-
1610
- peer, leg = ContextSources.peer_leg(attached.name)
1611
- peer ? { peer: peer, leg: leg, label: ContextSources.peer_label(peer) } : {}
1612
- end
1613
-
1614
1603
  def handle_stream(req, id)
1615
1604
  # Validate session exists
1616
1605
  begin