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
@@ -6,6 +6,7 @@ require "time"
6
6
  require_relative "cli/command"
7
7
  require_relative "cli/exit"
8
8
  require_relative "cli/flags"
9
+ require_relative "schedule_display"
9
10
  require_relative "schedules"
10
11
  require_relative "session"
11
12
 
@@ -19,11 +20,15 @@ module Samagotchi
19
20
  include CLI::Command
20
21
 
21
22
  USAGE = <<~TEXT
22
- Usage: chi schedule <add|list|show|tick|run-now|enable|disable|cancel> [flags]
23
+ Usage: chi schedule <add|edit|list|show|tick|run-now|enable|disable|cancel> [flags]
23
24
 
24
25
  add --session ID (--continues ID) (-m|--message|--prompt TEXT) [--title TEXT]
25
26
  one of: --every 30m | --weekday 1 --time 09:00 | --date 2026-11-20T09:00
26
27
  [--mode chain|same] [--catch-up once|none] [--keep-links N] [--max-failures N] [--max-skips N]
28
+ edit ID [--title TEXT] [-m|--prompt TEXT] [one recurrence, whole, as add's]
29
+ [--catch-up once|none] [--keep-links N] [--max-failures N] [--max-skips N]
30
+ only the flags given change; the session and mode stay (cancel and add for those);
31
+ a spent --date one-off stays disabled (enable it)
27
32
  list [--all] [--format text|json]
28
33
  show ID
29
34
  tick [--dry-run] [--format text|json]
@@ -40,26 +45,35 @@ module Samagotchi
40
45
  (default 12) or max_failures failures (default 3) the schedule is disabled.
41
46
  TEXT
42
47
 
43
- SUBCOMMANDS = %w[add list show tick run-now enable disable cancel].freeze
48
+ SUBCOMMANDS = %w[add edit list show tick run-now enable disable cancel].freeze
44
49
 
45
50
  # A usage error names the subcommand it was given (CLI::Command's
46
51
  # usage_error builds its line from this).
47
52
  def command_name = SUBCOMMANDS.include?(@argv.first.to_s) ? "chi schedule #{@argv.first}" : "chi schedule"
48
53
 
54
+ # The flags that set a schedule's fields (add's, and the ones edit changes).
55
+ FIELD_FLAGS = lambda do |f|
56
+ f.value "-m", "--message", "--prompt", key: :prompt
57
+ f.value "--title"
58
+ f.value "--every"
59
+ f.value "--weekday"
60
+ f.value "--time"
61
+ f.value "--date"
62
+ f.value "--catch-up"
63
+ f.value "--keep-links"
64
+ f.value "--max-failures"
65
+ f.value "--max-skips"
66
+ end
67
+
49
68
  FLAGS = {
50
69
  "add" => CLI::Flags.new(args: true) do |f|
51
70
  f.value "--session", "--continues", key: :target
52
- f.value "-m", "--message", "--prompt", key: :prompt
53
- f.value "--title"
54
- f.value "--every"
55
- f.value "--weekday"
56
- f.value "--time"
57
- f.value "--date"
58
71
  f.value "--mode"
59
- f.value "--catch-up"
60
- f.value "--keep-links"
61
- f.value "--max-failures"
62
- f.value "--max-skips"
72
+ FIELD_FLAGS.call(f)
73
+ end,
74
+ "edit" => CLI::Flags.new(args: true) do |f|
75
+ FIELD_FLAGS.call(f)
76
+ f.refuse "--session", "--continues", "--mode", "edit can't change the session or mode: cancel it and add a new one"
63
77
  end,
64
78
  "list" => CLI::Flags.new(args: false) do |f|
65
79
  f.switch "--all", key: :include_disabled
@@ -103,6 +117,7 @@ module Samagotchi
103
117
 
104
118
  case sub
105
119
  when "add" then add
120
+ when "edit" then edit
106
121
  when "list" then list
107
122
  when "show" then show
108
123
  when "tick" then tick
@@ -141,6 +156,28 @@ module Samagotchi
141
156
  CLI::Exit::OK
142
157
  end
143
158
 
159
+ # Only the flags given change; a recurrence is given whole (--time alone
160
+ # is refused as add refuses it).
161
+ def edit
162
+ id = @args.first
163
+ return usage_error("edit needs a schedule id") if id.to_s.strip.empty?
164
+
165
+ recurrence = if %i[every weekday time date].any? { |key| @opts.key?(key) }
166
+ Schedules.recurrence(every: @opts[:every], weekday: @opts[:weekday], time: @opts[:time], date: @opts[:date])
167
+ end
168
+ entry = @schedules.edit(id, title: @opts[:title], prompt: @opts[:prompt], recurrence: recurrence,
169
+ catch_up: @opts[:catch_up], keep_links: @opts[:keep_links],
170
+ max_failures: @opts[:max_failures], max_skips: @opts[:max_skips])
171
+ return failed("no schedule #{id}") if entry.nil?
172
+
173
+ @stdout.puts(entry_line(entry))
174
+ CLI::Exit::OK
175
+ rescue Schedules::EditPart::InFlight => e
176
+ failed(e.message)
177
+ rescue Schedules::Usage => e
178
+ usage_error(e.message)
179
+ end
180
+
144
181
  def list
145
182
  refused = format_refusal(@opts[:format])
146
183
  return refused if refused
@@ -156,7 +193,8 @@ module Samagotchi
156
193
  print_tick_warning
157
194
  return CLI::Exit::OK
158
195
  end
159
- entries.each { |entry| @stdout.puts(entry_line(entry)) }
196
+ name_width = ScheduleDisplay.name_width(entries)
197
+ entries.each { |entry| @stdout.puts(entry_line(entry, name_width: name_width)) }
160
198
  print_tick_warning
161
199
  CLI::Exit::OK
162
200
  end
@@ -175,11 +213,24 @@ module Samagotchi
175
213
  @stdout.puts(" skips: #{entry.skips} of #{entry.max_skips} failures: #{entry.failures} of #{entry.max_failures}")
176
214
  @stdout.puts(" keep_links: #{entry.keep_links} enabled: #{entry.enabled}")
177
215
  @stdout.puts(" prompt: #{entry.prompt}")
216
+ print_history(entry)
178
217
  CLI::Exit::OK
179
218
  rescue Schedules::Usage => e
180
219
  usage_error(e.message)
181
220
  end
182
221
 
222
+ # The last outcomes (Schedules::HistoryPart), newest first: when, what,
223
+ # why, and the session it acted on.
224
+ def print_history(entry)
225
+ return @stdout.puts(" history: -") if entry.history.empty?
226
+
227
+ @stdout.puts(" history (newest first):")
228
+ entry.history.reverse_each do |row|
229
+ line = [clock(row[:at]), row[:status], row[:detail], row[:session_id]&.slice(0, 8)].compact.reject { |part| part.to_s.empty? }
230
+ @stdout.puts(" #{line.join(" ")}")
231
+ end
232
+ end
233
+
183
234
  def tick
184
235
  refused = format_refusal(@opts[:format])
185
236
  return refused if refused
@@ -243,39 +294,37 @@ module Samagotchi
243
294
  iso.to_s
244
295
  end
245
296
 
246
- def entry_line(entry)
297
+ # One `list` row: id, name, mode, recurrence, next due, target head, and the
298
+ # notes (skips, why it is disabled, the last result). +name_width+ is the
299
+ # widest name among the rows printed; without it the name column is just
300
+ # the name. "disabled after N" only when that budget is spent: a one-off
301
+ # whose firing failed (ScheduleDisplay.off_reason "failures") reads
302
+ # " disabled" here.
303
+ def entry_line(entry, name_width: nil)
247
304
  note = ""
248
- note += " skips #{entry.skips} of #{entry.max_skips} (#{skip_window(entry)})" if entry.skips.positive?
249
- unless entry.enabled
250
- note += if entry.last_result == "disabled"
251
- " disabled"
252
- elsif entry.skips >= entry.max_skips
253
- " disabled after #{entry.skips} #{entry.skips == 1 ? "skip" : "skips"}"
254
- elsif entry.failures >= entry.max_failures
255
- " disabled after #{entry.failures} #{entry.failures == 1 ? "failure" : "failures"}"
256
- else
257
- " disabled"
258
- end
259
- end
305
+ note += " skips #{entry.skips} of #{entry.max_skips} (#{ScheduleDisplay.skip_window(entry)})" if entry.skips.positive?
306
+ note += off_note(entry) unless entry.enabled
260
307
  note += " last: #{entry.last_result}" if entry.last_result
261
- "#{entry.id} #{entry.mode} #{entry.recurrence_words} #{clock(entry.next_due)} #{entry.head[0, 8]}#{note}"
308
+ "#{entry.id} #{ScheduleDisplay.name(entry, width: name_width)} #{entry.mode} #{entry.recurrence_words} " \
309
+ "#{clock(entry.next_due)} #{entry.head[0, 8]}#{note}"
262
310
  end
263
311
 
264
- # A skip budget as a time window: 3 of 12 at a 5 minute tick is about 1 hour
265
- # of patience, which is what the count really measures.
266
- def skip_window(entry)
267
- minutes = entry.max_skips * Schedules.tick_interval_minutes
268
- hours = minutes / 60.0
269
- hours >= 1 ? "≈#{(hours * 10).round / 10} h at a #{Schedules.tick_interval_minutes} min tick" : "≈#{minutes} min"
270
- end
312
+ def off_note(entry)
313
+ case ScheduleDisplay.off_reason(entry)
314
+ when "skips"
315
+ return " disabled" unless entry.skips >= entry.max_skips
316
+
317
+ " disabled after #{entry.skips} #{entry.skips == 1 ? "skip" : "skips"}"
318
+ when "failures"
319
+ return " disabled" unless entry.failures >= entry.max_failures
271
320
 
272
- def entry_line_json(entry)
273
- entry.to_h.transform_keys(&:to_s).merge(
274
- "recurrence_words" => entry.recurrence_words,
275
- "skip_window" => skip_window(entry)
276
- )
321
+ " disabled after #{entry.failures} #{entry.failures == 1 ? "failure" : "failures"}"
322
+ else " disabled"
323
+ end
277
324
  end
278
325
 
326
+ def entry_line_json(entry) = ScheduleDisplay.json(entry)
327
+
279
328
  def print_tick_warning(stream = @stdout)
280
329
  warning = @schedules.tick_warning
281
330
  stream.puts(warning) if warning
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "schedules"
4
+
5
+ module Samagotchi
6
+ # What a schedule is called when it is listed: `chi schedule list` and the
7
+ # `list_schedules` tool both use this, so a schedule reads the same in the
8
+ # terminal and to the model. The name is its title when it has one; a schedule
9
+ # made without a title is named by the start of its prompt, in quotes, cut at
10
+ # PROMPT_CHARS with "…" where the cut falls. The name is display only: the
11
+ # entry keeps its title as given (nil when there is none) and its whole prompt.
12
+ module ScheduleDisplay
13
+ # How much of a titleless prompt the name shows.
14
+ PROMPT_CHARS = 30
15
+
16
+ # @param entry [Schedules::Entry]
17
+ # @param width [Integer, nil] pad to this width — the widest name among the
18
+ # rows being printed — so the columns after the name line up; without it
19
+ # the name is just the name.
20
+ def self.name(entry, width: nil)
21
+ given = entry.title.to_s.strip
22
+ if given.empty?
23
+ words = entry.prompt.to_s.gsub(/\s+/, " ").strip
24
+ given = words.length > PROMPT_CHARS ? "\"#{words[0, PROMPT_CHARS]}…\"" : "\"#{words}\""
25
+ end
26
+ width ? given.ljust(width) : given
27
+ end
28
+
29
+ # The width of the name column for these entries.
30
+ def self.name_width(entries)
31
+ entries.map { |entry| name(entry) }.map(&:length).max
32
+ end
33
+
34
+ # The history statuses that are outcomes of a firing (HistoryPart): the
35
+ # owner's enabled/disabled and an edit's rows say nothing of how a
36
+ # one-off ended.
37
+ OUTCOMES = %w[fired failed missed skipped].freeze
38
+
39
+ # "firing" while a firing is under way (a tick holds it, or its turn is
40
+ # pending: a one-off is already off then, see Schedules#advance), "on"
41
+ # when enabled, else "off".
42
+ # @param entry [Schedules::Entry]
43
+ def self.state(entry)
44
+ return "firing" if entry.firing_since || entry.pending_session_id
45
+
46
+ entry.enabled ? "on" : "off"
47
+ end
48
+
49
+ # Why an off schedule is off, nil when it isn't (state on or firing):
50
+ # "owner" turned off by `chi schedule disable` (its last result)
51
+ # "skips" its skip budget ran out (max_skips)
52
+ # "failures" its failure budget ran out (max_failures), or a one-off
53
+ # whose firing failed
54
+ # "done" a one-off that fired
55
+ # "missed" a one-off whose moment passed unseen
56
+ # "off" none of these (an older file's spent one-off)
57
+ # A one-off's reason is its last outcome row in the history (OUTCOMES),
58
+ # never `enabled: false` alone: firing, failing and missing all turn a
59
+ # one-off off.
60
+ def self.off_reason(entry)
61
+ return nil unless state(entry) == "off"
62
+ return "owner" if entry.last_result == "disabled"
63
+ return "skips" if entry.skips >= entry.max_skips
64
+ return "failures" if entry.failures >= entry.max_failures
65
+ return "off" unless entry.recurrence[:kind] == "date"
66
+
67
+ case entry.history.reverse.find { |row| OUTCOMES.include?(row[:status]) }&.dig(:status)
68
+ when "fired" then "done"
69
+ when "failed" then "failures"
70
+ when "missed" then "missed"
71
+ when "skipped" then "skips"
72
+ else "off"
73
+ end
74
+ end
75
+
76
+ # A skip budget as a time window: 3 of 12 at a 5 minute tick is about 1
77
+ # hour of patience, which is what the count really measures.
78
+ def self.skip_window(entry)
79
+ tick = Schedules.tick_interval_minutes
80
+ minutes = entry.max_skips * tick
81
+ hours = minutes / 60.0
82
+ hours >= 1 ? "≈#{(hours * 10).round / 10} h at a #{tick} min tick" : "≈#{minutes} min"
83
+ end
84
+
85
+ # One entry as `chi schedule list --format json` prints it (and
86
+ # Pages::Runtime reads it): every stored field with its extra keys, then
87
+ # what a reader needs and would otherwise compute: recurrence_words,
88
+ # skip_window, name, state, off_reason. Those come last, so an extra key
89
+ # of the same name (a newer chi's) never shadows them.
90
+ # @return [Hash{String => Object}]
91
+ def self.json(entry)
92
+ entry.to_h.transform_keys(&:to_s).merge(
93
+ "recurrence_words" => entry.recurrence_words,
94
+ "skip_window" => skip_window(entry),
95
+ "name" => name(entry),
96
+ "state" => state(entry),
97
+ "off_reason" => off_reason(entry)
98
+ )
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,146 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../continue_offer"
4
+ require_relative "../log"
5
+ require_relative "../session"
6
+ require_relative "../session_inbox"
7
+ require_relative "../session_lifecycle"
8
+ require_relative "../session_manager"
9
+ require_relative "../session_row"
10
+ require_relative "../worker_link"
11
+ require_relative "../worker_presence"
12
+
13
+ module Samagotchi
14
+ class Schedules
15
+ # The busy check (docs/scheduling.md, "The busy check"): whether a
16
+ # schedule may act on its target now, or the skip and its words.
17
+ module BusyPart
18
+ # Seconds a tick waits for a live worker's GET /activity.
19
+ ACTIVITY_TIMEOUT = 2.0
20
+ # The skip words of each busy cell (SessionLifecycle::ALLOWED's
21
+ # sched_chain / sched_same) but :go and :worker_newer (WorkerLink::Skew's
22
+ # own words, #busy_words). spec/schedules_spec.rb checks every cell the
23
+ # table holds has words; one it misses still skips (#busy_words), so a
24
+ # table edit never aborts a tick.
25
+ BUSY_WORDS = {
26
+ deleting: SessionManager::DeliverResult::DELETING["detail"],
27
+ stopped: SessionManager::DeliverResult::STOPPED["detail"],
28
+ worker_busy: "its worker is starting or leaving"
29
+ }.freeze
30
+
31
+ private
32
+
33
+ # Two paths (FR7). The state's answer comes from the lifecycle table
34
+ # (#busy_cell: SessionLifecycle::ALLOWED, plus two op-local overrides);
35
+ # then a live worker is asked through its Bridge (#live_busy_reason)
36
+ # and with no worker the files say what the tick can know
37
+ # (#file_busy_reason). A session being deleted is a skip first, then
38
+ # one its owner stopped, in both modes: a schedule restarts nothing the
39
+ # owner stopped (deliver_turn would refuse a same-mode firing too,
40
+ # SessionManager::DeliverResult::STOPPED, in the same words).
41
+ def busy_reason(entry, links, target)
42
+ dir = Session.session_dir(target, state_dir: @state_dir)
43
+ owner = SessionManager.session_owner(target, state_dir: @state_dir)
44
+ presence = WorkerPresence.read(target, state_dir: @state_dir, owner: owner, link: :look)
45
+ # exists: true: #target_of resolved the target already, and a delete
46
+ # mid-way (its JSON gone, the deleting lock held) must read deleting,
47
+ # not absent. No extra read: SessionLifecycle.read would add a
48
+ # ContinueIntent read this check doesn't use.
49
+ state = SessionLifecycle::Reading.derive(presence.with(exists: true)).state
50
+ cell = busy_cell(entry, presence, state)
51
+ return [:skip, busy_words(cell, presence.link)] unless cell == :go
52
+ return live_busy_reason(entry, links, target, presence.link) if state == :live
53
+
54
+ file_busy_reason(links.session(target), dir)
55
+ end
56
+
57
+ # The table's cell for this mode in +state+, then the two facts the
58
+ # state doesn't hold, read in today's order (spec/session_lifecycle/
59
+ # matrix_spec.rb's KNOWN_DIFFERENCES name both):
60
+ # - the stop marker before the owner (F1, chain and same; an unknown
61
+ # owner's stop too): stopped under any lock but a deleter's;
62
+ # - F1b: chain mode's starting check with no one-turn-run check: a
63
+ # fresh starting marker without a worker's lock is worker_busy (a
64
+ # worker being started for it holds no lock yet: a chain firing would
65
+ # archive it from under that worker; a queued turn is fine).
66
+ def busy_cell(entry, presence, state)
67
+ chain = entry.mode == CHAIN
68
+ cell = SessionLifecycle.allowed(chain ? :sched_chain : :sched_same, state)
69
+ return :stopped if presence.stop_marked? && cell != :deleting
70
+ return :worker_busy if chain && cell == :go && presence.starting? && !presence.worker_owned?
71
+
72
+ cell
73
+ end
74
+
75
+ # A newer worker's Bridge cannot be asked (:worker_newer); updating chi
76
+ # or restarting chi web fixes it, and max_skips still bounds a stuck
77
+ # schedule. A worker that has not published its Bridge yet, or is
78
+ # closing it (:worker_busy): nothing can be read from it, and firing
79
+ # now would race with it.
80
+ def busy_words(cell, link)
81
+ return link.short_message if cell == :worker_newer
82
+
83
+ BUSY_WORDS.fetch(cell) { "it is not free now (#{cell})" }
84
+ end
85
+
86
+ # A live worker, asked through its Bridge.
87
+ def live_busy_reason(entry, links, target, link)
88
+ activity = ask_activity(link, target)
89
+ if activity == :old
90
+ # Its chi predates GET /activity. The file checks cannot see an open
91
+ # tab, so a chain firing would archive under someone's terminal:
92
+ # refuse with a restart, never silently degrade. Same mode only
93
+ # queues a turn, so for it the files are enough.
94
+ return [:skip, "its worker is too old to ask: chi sessions restart #{target[0, 8]}"] if entry.mode == CHAIN
95
+
96
+ return file_busy_reason(links.session(target), Session.session_dir(target, state_dir: @state_dir))
97
+ end
98
+ return [:skip, "its worker is not answering"] if activity.nil?
99
+
100
+ return [:skip, "a turn is running in it"] if activity[:turn_running]
101
+ return [:skip, "a prompt is queued for it"] if activity[:input_pending]
102
+ return [:skip, "its step-limit question waits for an answer"] if activity[:awaiting_continue]
103
+
104
+ # A chain firing archives the session and stops its worker: a
105
+ # terminal or a web tab on it would be cut off. A queued turn into
106
+ # an open session is fine, so same mode does not count streams.
107
+ return [:skip, "a terminal or a web tab is open on it"] if entry.mode == CHAIN && activity[:open_streams].to_i.positive?
108
+
109
+ # An idle live worker: free, whatever a starting marker its own
110
+ # start left (Worker#start clears it just after the lock).
111
+ nil
112
+ end
113
+
114
+ # The worker's activity snapshot, :old when it has no /activity route, or
115
+ # nil when it did not answer at all. A worker published its features when
116
+ # it started, so a sidecar without "activity" is an older chi's: asking it
117
+ # would only cost a round trip to a 404.
118
+ def ask_activity(link, session_id)
119
+ return :old unless Array(link.features).include?(WorkerLink::ACTIVITY_FEATURE)
120
+
121
+ status, body = link.client(session_id, read_timeout: ACTIVITY_TIMEOUT).get("activity")
122
+ return nil if status.nil?
123
+ return body.transform_keys(&:to_sym) if status == 200 && body.is_a?(Hash)
124
+
125
+ :old
126
+ rescue StandardError => e
127
+ Log.warn(:worker, "activity_failed", sid: session_id, error: e.class.name, msg: e.message)
128
+ nil
129
+ end
130
+
131
+ # The signals RemovalPart#archive_refusal reads, from the files alone.
132
+ def file_busy_reason(session, dir)
133
+ return nil if session.nil?
134
+
135
+ if SessionRow.running_or_starting?(saved_status: session.status, live: false, busy: false, updated_at: session.updated_at)
136
+ return [:skip, "a turn is running in it"]
137
+ end
138
+ return [:skip, "a prompt is queued for it"] unless SessionInbox.find_new_input_files(dir).empty?
139
+
140
+ return [:skip, "its step-limit question waits for an answer"] if session.waiting_question(live: false)&.dig(:kind) == ContinueOffer::KIND
141
+
142
+ nil
143
+ end
144
+ end
145
+ end
146
+ end
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ class Schedules
5
+ # `chi schedule edit` (docs/scheduling.md): change a schedule's title,
6
+ # prompt, recurrence, catch-up or budgets in place, keeping its id, its
7
+ # session and mode (cancel and add for those), its counters, `enabled`
8
+ # (a spent `date` one-off stays disabled) and the firing fields.
9
+ module EditPart
10
+ # A recurrence edit while a firing is in flight: a state, not a usage
11
+ # error (`chi schedule edit` exits 1).
12
+ class InFlight < StandardError
13
+ def initialize(msg = "a run is in progress; edit the time after it settles") = super
14
+ end
15
+
16
+ # Each argument nil keeps the field; only the fields given change.
17
+ # @param recurrence [Hash, nil] a whole one, from Schedules.recurrence
18
+ # @return [Entry, nil] the entry as edited; nil when no schedule matches
19
+ # (or it is gone by the time the lock is held)
20
+ # @raise [Usage] nothing to change, a field that is wrong, a duplicate
21
+ # in the chain
22
+ # @raise [InFlight] a recurrence edit while a firing is in flight
23
+ def edit(id_or_name, title: nil, prompt: nil, recurrence: nil, catch_up: nil, keep_links: nil, max_failures: nil,
24
+ max_skips: nil)
25
+ entry = lookup(id_or_name)
26
+ return nil if entry.nil?
27
+
28
+ changes = differing(entry, edit_changes(title: title, prompt: prompt, recurrence: recurrence, catch_up: catch_up,
29
+ keep_links: keep_links, max_failures: max_failures, max_skips: max_skips))
30
+ raise Usage, "nothing to change" if changes.empty?
31
+
32
+ # Each duplicate test only on what the edit changes: a clash in a field
33
+ # it leaves alone (a twin `enable` let in) is not of its making.
34
+ by_title = changes.key?(:title)
35
+ by_content = changes.key?(:prompt) || changes.key?(:recurrence)
36
+ if by_title || by_content
37
+ same = duplicate_in_chain(entry.anchor, prompt: changes.fetch(:prompt, entry.prompt),
38
+ title: changes.fetch(:title, entry.title),
39
+ recurrence: changes.fetch(:recurrence, entry.recurrence), except: entry.id,
40
+ by_title: by_title, by_content: by_content)
41
+ refuse_duplicate!(same, entry.mode) if same
42
+ end
43
+
44
+ result = nil
45
+ write_under_lock do |file|
46
+ position = file.entries.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
47
+ next if position.nil?
48
+
49
+ result = file.entries[position] = edited(file.entries[position], changes)
50
+ end
51
+ result
52
+ end
53
+
54
+ # The duplicate rule #add and #edit share: an enabled schedule of the
55
+ # same chain that says the same thing, the same prompt and recurrence
56
+ # or the same title. An edit passes +except+ (its own entry is no
57
+ # duplicate of itself) and turns off the test whose fields it leaves
58
+ # alone (+by_content+: the prompt and recurrence; +by_title+).
59
+ # @return [Entry, nil]
60
+ def duplicate_in_chain(session_id, prompt:, title:, recurrence:, except: nil, by_content: true, by_title: true)
61
+ given_title = title.to_s.strip
62
+ ids = chain_of(session_id)
63
+ entries.find do |entry|
64
+ next if entry.id == except
65
+ next unless ids.include?(entry.anchor) || ids.include?(entry.head)
66
+
67
+ (by_content && entry.prompt == prompt && entry.recurrence == recurrence) ||
68
+ (by_title && !given_title.empty? && entry.title.to_s.strip.casecmp?(given_title))
69
+ end
70
+ end
71
+
72
+ # @raise [Usage] naming the schedule that already says the same thing
73
+ def refuse_duplicate!(same, mode)
74
+ raise Usage, "#{same.id} already schedules this (#{same.recurrence_words}, #{mode}: #{same.prompt}); " \
75
+ "cancel it with chi schedule cancel #{same.id} to change it"
76
+ end
77
+
78
+ private
79
+
80
+ # The +changes+ whose value is not +entry+'s already (`--title ""` on
81
+ # an untitled entry changes nothing).
82
+ def differing(entry, changes) = changes.reject { |field, value| entry.public_send(field) == value }
83
+
84
+ # The fields given, checked as #add checks them.
85
+ def edit_changes(title:, prompt:, recurrence:, catch_up:, **budgets)
86
+ changes = {}
87
+ changes[:title] = title.to_s.strip.empty? ? nil : title.to_s.strip unless title.nil?
88
+ changes[:prompt] = validate_prompt!(prompt) unless prompt.nil?
89
+ changes[:recurrence] = recurrence unless recurrence.nil?
90
+ unless catch_up.nil?
91
+ changes[:catch_up] = catch_up.to_s.strip
92
+ validate_catch_up!(changes[:catch_up])
93
+ end
94
+ { keep_links: 0, max_failures: 1, max_skips: 1 }.each do |field, min|
95
+ value = int_value(budgets[field], min: min, name: field.to_s)
96
+ changes[field] = value unless value.nil?
97
+ end
98
+ changes
99
+ end
100
+
101
+ # +stored+ with +changes+, under the lock. A new recurrence's clock
102
+ # starts now, as #add's does; while a firing is in flight it is refused:
103
+ # #record would put that firing's due_was back over the new clock.
104
+ def edited(stored, changes)
105
+ # Against the entry as stored now: what another writer already set is no change.
106
+ changes = differing(stored, changes)
107
+ return stored if changes.empty?
108
+
109
+ now = @clock.call
110
+ updated = stored.with(**changes)
111
+ if changes.key?(:recurrence)
112
+ raise InFlight if stored.firing_since || stored.pending_turn_id
113
+
114
+ updated = updated.with(next_due: next_due_for(changes[:recurrence], from: now).utc.iso8601, due_was: nil)
115
+ end
116
+ with_history(updated, "edited", changes.keys.join(", "), at: now)
117
+ end
118
+ end
119
+ end
120
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ class Schedules
5
+ # The run history (docs/scheduling.md, `chi schedule show`): each entry
6
+ # keeps its last HISTORY_MAX outcomes in `history`, newest last, rows
7
+ # {at:, status:, detail:, session_id:}. One writer per status, each
8
+ # appending once per event:
9
+ # skipped, failed — #skipped / #failed (the helpers, never their
10
+ # callers), and #run_now's refusal of a disabled entry (no counters);
11
+ # a budget turn-off is that row, its detail "disabled: <reason>"
12
+ # fired — #finish_pending (a firing that settles) and #record's "fired"
13
+ # missed — #reschedule
14
+ # enabled, disabled — #change (the owner's; never a budget turn-off)
15
+ # edited — #edit, its detail the changed fields
16
+ # A pending firing writes no row: it is not an outcome yet.
17
+ module HistoryPart
18
+ HISTORY_MAX = 20
19
+ # A detail is clipped to this many characters (an exception's message
20
+ # or a turn's reason can be long): with the row's other fields (~120
21
+ # bytes) an entry's history stays under about 20 × 320 bytes, 6.4 KB.
22
+ DETAIL_MAX = 200
23
+
24
+ # The rows as JSON hands them back (string keys) or as written (symbol
25
+ # keys): symbol keys, non-rows dropped.
26
+ # @return [Array<Hash>]
27
+ def self.rows(value)
28
+ Array(value).filter_map { |row| row.transform_keys(&:to_sym) if row.is_a?(Hash) }
29
+ end
30
+
31
+ private
32
+
33
+ # A skip's or a failure's row (+before+ the call, +after+ it), and the
34
+ # disabled notice when this call turned the entry off by its budget.
35
+ # Its session: the pending firing's, else the head.
36
+ def recorded(before, after, status, reason, now)
37
+ off = budget_turned_off?(before, after, status)
38
+ noticed = with_disabled_notice(before, after, status, reason, now)
39
+ with_history(noticed, status, off ? "disabled: #{reason}" : reason, at: now,
40
+ session_id: before.pending_session_id || before.head)
41
+ end
42
+
43
+ # +entry+ with one row more, the oldest dropped past HISTORY_MAX.
44
+ def with_history(entry, status, detail, at:, session_id: nil)
45
+ clipped = detail.nil? ? nil : detail.to_s[0, DETAIL_MAX]
46
+ row = { at: at.utc.iso8601, status: status, detail: clipped, session_id: session_id }
47
+ entry.with(history: (HistoryPart.rows(entry.history) + [row]).last(HISTORY_MAX))
48
+ end
49
+ end
50
+ end
51
+ end