samagotchi 0.188.0 → 0.190.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 (112) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -1
  3. data/docs/architecture.md +9 -4
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +15 -0
  6. data/docs/cli.md +38 -9
  7. data/docs/configuration.md +1 -0
  8. data/docs/guardrails.md +22 -9
  9. data/docs/internals/attached-context.md +4 -1
  10. data/docs/internals/bundles.md +3 -3
  11. data/docs/internals/engine.md +18 -2
  12. data/docs/internals/pages.md +65 -18
  13. data/docs/internals/session-lifecycle.md +19 -6
  14. data/docs/internals/web-frontend.md +3 -3
  15. data/docs/internals/web-push.md +11 -5
  16. data/docs/pages.md +69 -15
  17. data/docs/peers.md +3 -0
  18. data/docs/plugins.md +25 -1
  19. data/docs/releasing.md +1 -1
  20. data/docs/scheduling.md +168 -11
  21. data/docs/sessions.md +4 -4
  22. data/docs/sub-agent.md +1 -1
  23. data/docs/testing.md +1 -1
  24. data/lib/samagotchi/bundle_manifest.rb +34 -5
  25. data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +15 -0
  26. data/lib/samagotchi/bundles/guardrails/manifest.yml +2 -2
  27. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  28. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +169 -0
  29. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  30. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  31. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  32. data/lib/samagotchi/config.rb +2 -0
  33. data/lib/samagotchi/context_fetch.rb +9 -3
  34. data/lib/samagotchi/engine/models.rb +6 -4
  35. data/lib/samagotchi/engine/turn_end.rb +20 -2
  36. data/lib/samagotchi/engine.rb +5 -1
  37. data/lib/samagotchi/failure_line.rb +43 -0
  38. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  39. data/lib/samagotchi/guardrails/chi_dirs.rb +20 -5
  40. data/lib/samagotchi/guardrails/parent_approvals.rb +1 -1
  41. data/lib/samagotchi/guardrails/protected_paths.rb +8 -4
  42. data/lib/samagotchi/guardrails/shell_paths.rb +16 -2
  43. data/lib/samagotchi/guardrails/targets.rb +1 -1
  44. data/lib/samagotchi/guardrails/verdict.rb +5 -3
  45. data/lib/samagotchi/image_store.rb +4 -0
  46. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  47. data/lib/samagotchi/last_turn.rb +2 -1
  48. data/lib/samagotchi/llm/utf8_scrub.rb +26 -0
  49. data/lib/samagotchi/llm_context_view.rb +6 -0
  50. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  51. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  52. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  53. data/lib/samagotchi/model_profile.rb +4 -1
  54. data/lib/samagotchi/page_command.rb +9 -6
  55. data/lib/samagotchi/pages/bundled.rb +83 -0
  56. data/lib/samagotchi/pages/launch.rb +14 -2
  57. data/lib/samagotchi/pages/runner.rb +7 -2
  58. data/lib/samagotchi/pages/runtime.rb +84 -0
  59. data/lib/samagotchi/pages/store.rb +18 -5
  60. data/lib/samagotchi/pages.rb +47 -3
  61. data/lib/samagotchi/peer_continue.rb +14 -8
  62. data/lib/samagotchi/reply_wait.rb +1 -1
  63. data/lib/samagotchi/run_options.rb +1 -1
  64. data/lib/samagotchi/schedule_command.rb +175 -39
  65. data/lib/samagotchi/schedule_display.rb +85 -0
  66. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  67. data/lib/samagotchi/schedules/condition_part.rb +312 -0
  68. data/lib/samagotchi/schedules/edit_part.rb +144 -0
  69. data/lib/samagotchi/schedules/history_part.rb +51 -0
  70. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  71. data/lib/samagotchi/schedules/notices_part.rb +122 -0
  72. data/lib/samagotchi/schedules/protection_part.rb +113 -0
  73. data/lib/samagotchi/schedules/prune_part.rb +79 -0
  74. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  75. data/lib/samagotchi/schedules.rb +188 -409
  76. data/lib/samagotchi/session_access/local.rb +9 -1
  77. data/lib/samagotchi/session_access/remote.rb +2 -1
  78. data/lib/samagotchi/session_chain/delete.rb +7 -5
  79. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  80. data/lib/samagotchi/session_lifecycle.rb +3 -2
  81. data/lib/samagotchi/session_manager/removal.rb +16 -9
  82. data/lib/samagotchi/session_protection.rb +99 -0
  83. data/lib/samagotchi/session_retention.rb +21 -6
  84. data/lib/samagotchi/sessions_command.rb +4 -0
  85. data/lib/samagotchi/system_one/self_protect.rb +4 -2
  86. data/lib/samagotchi/testing/boundary.rb +13 -0
  87. data/lib/samagotchi/tools/cancel_schedule.rb +32 -4
  88. data/lib/samagotchi/tools/execute.rb +5 -1
  89. data/lib/samagotchi/tools/list_schedules.rb +1 -0
  90. data/lib/samagotchi/tools/task_runtime.rb +6 -0
  91. data/lib/samagotchi/turn_endings.rb +14 -2
  92. data/lib/samagotchi/turn_flow.rb +2 -1
  93. data/lib/samagotchi/turn_outcome.rb +41 -0
  94. data/lib/samagotchi/version.rb +1 -1
  95. data/lib/samagotchi/web/page_routes.rb +13 -8
  96. data/lib/samagotchi/web/public/app.js +12 -18
  97. data/lib/samagotchi/web/public/index.html +11 -2
  98. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  99. data/lib/samagotchi/web/public/page_links.js +1 -1
  100. data/lib/samagotchi/web/public/page_view.js +8 -5
  101. data/lib/samagotchi/web/public/pages.css +9 -2
  102. data/lib/samagotchi/web/public/pages_group.js +21 -19
  103. data/lib/samagotchi/web/public/pages_list.js +73 -0
  104. data/lib/samagotchi/web/public/pages_model.js +54 -0
  105. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  106. data/lib/samagotchi/web/public/stream_handlers.js +8 -0
  107. data/lib/samagotchi/web/public/views.js +77 -23
  108. data/lib/samagotchi/web/push/notifier.rb +4 -3
  109. data/lib/samagotchi/web/server.rb +3 -1
  110. data/lib/samagotchi/web/session_hub.rb +75 -19
  111. data/lib/samagotchi/worker.rb +6 -4
  112. metadata +20 -1
@@ -20,11 +20,16 @@ module Samagotchi
20
20
  include CLI::Command
21
21
 
22
22
  USAGE = <<~TEXT
23
- 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]
24
24
 
25
25
  add --session ID (--continues ID) (-m|--message|--prompt TEXT) [--title TEXT]
26
26
  one of: --every 30m | --weekday 1 --time 09:00 | --date 2026-11-20T09:00
27
27
  [--mode chain|same] [--catch-up once|none] [--keep-links N] [--max-failures N] [--max-skips N]
28
+ [--if CMD]
29
+ edit ID [--title TEXT] [-m|--prompt TEXT] [one recurrence, whole, as add's]
30
+ [--catch-up once|none] [--keep-links N] [--max-failures N] [--max-skips N] [--if CMD | --no-if]
31
+ only the flags given change; the session and mode stay (cancel and add for those);
32
+ a spent --date one-off stays disabled (enable it)
28
33
  list [--all] [--format text|json]
29
34
  show ID
30
35
  tick [--dry-run] [--format text|json]
@@ -39,28 +44,43 @@ module Samagotchi
39
44
  same queues it as a turn in the session itself.
40
45
  A busy target is skipped and retried at the next tick; after max_skips skips
41
46
  (default 12) or max_failures failures (default 3) the schedule is disabled.
47
+ --if CMD: the tick runs CMD in the session's folder first; exit 0 fires, 1..125
48
+ skips this occurrence quietly ("not needed"), anything else is a failure. From
49
+ your own terminal only (not inside a chi session); run-now doesn't run it.
42
50
  TEXT
43
51
 
44
- SUBCOMMANDS = %w[add list show tick run-now enable disable cancel].freeze
52
+ SUBCOMMANDS = %w[add edit list show tick run-now enable disable cancel].freeze
45
53
 
46
54
  # A usage error names the subcommand it was given (CLI::Command's
47
55
  # usage_error builds its line from this).
48
56
  def command_name = SUBCOMMANDS.include?(@argv.first.to_s) ? "chi schedule #{@argv.first}" : "chi schedule"
49
57
 
58
+ # The flags that set a schedule's fields (add's, and the ones edit changes).
59
+ FIELD_FLAGS = lambda do |f|
60
+ f.value "-m", "--message", "--prompt", key: :prompt
61
+ f.value "--title"
62
+ f.value "--every"
63
+ f.value "--weekday"
64
+ f.value "--time"
65
+ f.value "--date"
66
+ f.value "--catch-up"
67
+ f.value "--keep-links"
68
+ f.value "--max-failures"
69
+ f.value "--max-skips"
70
+ end
71
+
50
72
  FLAGS = {
51
73
  "add" => CLI::Flags.new(args: true) do |f|
52
74
  f.value "--session", "--continues", key: :target
53
- f.value "-m", "--message", "--prompt", key: :prompt
54
- f.value "--title"
55
- f.value "--every"
56
- f.value "--weekday"
57
- f.value "--time"
58
- f.value "--date"
59
75
  f.value "--mode"
60
- f.value "--catch-up"
61
- f.value "--keep-links"
62
- f.value "--max-failures"
63
- f.value "--max-skips"
76
+ FIELD_FLAGS.call(f)
77
+ f.value "--if", key: :condition
78
+ end,
79
+ "edit" => CLI::Flags.new(args: true) do |f|
80
+ FIELD_FLAGS.call(f)
81
+ f.value "--if", key: :condition
82
+ f.switch "--no-if"
83
+ f.refuse "--session", "--continues", "--mode", "edit can't change the session or mode: cancel it and add a new one"
64
84
  end,
65
85
  "list" => CLI::Flags.new(args: false) do |f|
66
86
  f.switch "--all", key: :include_disabled
@@ -78,12 +98,23 @@ module Samagotchi
78
98
  }.freeze
79
99
 
80
100
  # @param argv [Array<String>] the arguments after "schedule"
101
+ # A condition runs unattended, outside the guardrails: never set from
102
+ # inside a chi session (an agent), as chi broadcast refuses there too.
103
+ CONDITION_IN_SESSION = "a schedule's condition is set only from your own terminal (chi schedule … --if), " \
104
+ "not from inside a chi session"
105
+ # The older chis that would fire a condition entry unchecked hide it
106
+ # instead (Schedules::ConditionPart): the line add and edit print.
107
+ CONDITION_TICKERS = "every chi that ticks (chi web, cron) must be newer than 0.189.0; " \
108
+ "an older one leaves this schedule alone"
109
+
81
110
  # @param schedules [Schedules, nil] the store; default this machine's
82
- def initialize(argv, stdout: $stdout, stderr: $stderr, schedules: nil)
111
+ # @param env [Hash] SAMAGOTCHI_PARENT_SESSION set: run inside a session
112
+ def initialize(argv, stdout: $stdout, stderr: $stderr, schedules: nil, env: ENV)
83
113
  @argv = argv.dup
84
114
  @stdout = stdout
85
115
  @stderr = stderr
86
116
  @schedules = schedules || Schedules.new
117
+ @env = env
87
118
  end
88
119
 
89
120
  # @return [Integer] exit status: 0 ok, 1 a missing session or schedule,
@@ -101,9 +132,17 @@ module Samagotchi
101
132
 
102
133
  @opts = parsed.options
103
134
  @args = parsed.args
135
+ if @opts.key?(:condition) || @opts[:no_if]
136
+ unless @env["SAMAGOTCHI_PARENT_SESSION"].to_s.empty?
137
+ error_line("#{command_name}: #{CONDITION_IN_SESSION}")
138
+ return CLI::Exit::USAGE
139
+ end
140
+ return usage_error("--if and --no-if together: give one") if @opts.key?(:condition) && @opts[:no_if]
141
+ end
104
142
 
105
143
  case sub
106
144
  when "add" then add
145
+ when "edit" then edit
107
146
  when "list" then list
108
147
  when "show" then show
109
148
  when "tick" then tick
@@ -128,7 +167,8 @@ module Samagotchi
128
167
  entry = @schedules.add(target: @opts[:target], prompt: @opts[:prompt], recurrence: recurrence,
129
168
  title: @opts[:title], mode: @opts[:mode] || Schedules::CHAIN,
130
169
  catch_up: @opts[:catch_up], keep_links: @opts[:keep_links],
131
- max_failures: @opts[:max_failures], max_skips: @opts[:max_skips])
170
+ max_failures: @opts[:max_failures], max_skips: @opts[:max_skips],
171
+ condition: @opts[:condition])
132
172
  rescue Schedules::Usage => e
133
173
  return usage_error(e.message)
134
174
  rescue Session::AmbiguousId => e
@@ -137,28 +177,64 @@ module Samagotchi
137
177
  return failed("no session #{@opts[:target]}")
138
178
  end
139
179
 
140
- @stdout.puts("#{entry.id} added: #{entry.target_words} · #{entry.recurrence_words} · next #{clock(entry.next_due)}")
180
+ @stdout.puts("#{entry.id} added: #{entry.target_words} · #{entry.recurrence_words}#{condition_words(entry)} · " \
181
+ "next #{clock(entry.next_due)}")
182
+ if entry.condition
183
+ @stdout.puts(CONDITION_TICKERS)
184
+ print_gate_warning(entry)
185
+ end
141
186
  print_tick_warning
142
187
  CLI::Exit::OK
143
188
  end
144
189
 
190
+ # Only the flags given change; a recurrence is given whole (--time alone
191
+ # is refused as add refuses it).
192
+ def edit
193
+ id = @args.first
194
+ return usage_error("edit needs a schedule id") if id.to_s.strip.empty?
195
+
196
+ recurrence = if %i[every weekday time date].any? { |key| @opts.key?(key) }
197
+ Schedules.recurrence(every: @opts[:every], weekday: @opts[:weekday], time: @opts[:time], date: @opts[:date])
198
+ end
199
+ condition = @opts[:no_if] ? :none : @opts[:condition]
200
+ entry = @schedules.edit(id, title: @opts[:title], prompt: @opts[:prompt], recurrence: recurrence,
201
+ catch_up: @opts[:catch_up], keep_links: @opts[:keep_links],
202
+ max_failures: @opts[:max_failures], max_skips: @opts[:max_skips], condition: condition)
203
+ return failed("no schedule #{id}") if entry.nil?
204
+
205
+ @stdout.puts(entry_line(entry))
206
+ if @opts.key?(:condition)
207
+ @stdout.puts(CONDITION_TICKERS)
208
+ print_gate_warning(entry)
209
+ end
210
+ CLI::Exit::OK
211
+ rescue Schedules::EditPart::InFlight => e
212
+ failed(e.message)
213
+ rescue Schedules::Usage => e
214
+ usage_error(e.message)
215
+ end
216
+
145
217
  def list
146
218
  refused = format_refusal(@opts[:format])
147
219
  return refused if refused
148
220
 
149
221
  entries = @schedules.entries(include_disabled: @opts[:include_disabled] ? true : false)
222
+ unreadable = unreadable_line
150
223
  if @opts[:format] == "json"
151
224
  @stdout.puts(JSON.pretty_generate(entries.map { |entry| entry_line_json(entry) }))
225
+ @stderr.puts(unreadable) if unreadable
152
226
  print_tick_warning(@stderr)
153
227
  return CLI::Exit::OK
154
228
  end
155
229
  if entries.empty?
156
230
  @stdout.puts("no schedules")
231
+ @stdout.puts(unreadable) if unreadable
157
232
  print_tick_warning
158
233
  return CLI::Exit::OK
159
234
  end
160
235
  name_width = ScheduleDisplay.name_width(entries)
161
236
  entries.each { |entry| @stdout.puts(entry_line(entry, name_width: name_width)) }
237
+ @stdout.puts(unreadable) if unreadable
162
238
  print_tick_warning
163
239
  CLI::Exit::OK
164
240
  end
@@ -176,12 +252,26 @@ module Samagotchi
176
252
  @stdout.puts(" last fired: #{clock(entry.last_fired)} last result: #{entry.last_result || "-"}")
177
253
  @stdout.puts(" skips: #{entry.skips} of #{entry.max_skips} failures: #{entry.failures} of #{entry.max_failures}")
178
254
  @stdout.puts(" keep_links: #{entry.keep_links} enabled: #{entry.enabled}")
255
+ @stdout.puts(" if: #{condition_show(entry)}") unless entry.condition.nil?
179
256
  @stdout.puts(" prompt: #{entry.prompt}")
257
+ print_history(entry)
180
258
  CLI::Exit::OK
181
259
  rescue Schedules::Usage => e
182
260
  usage_error(e.message)
183
261
  end
184
262
 
263
+ # The last outcomes (Schedules::HistoryPart), newest first: when, what,
264
+ # why, and the session it acted on.
265
+ def print_history(entry)
266
+ return @stdout.puts(" history: -") if entry.history.empty?
267
+
268
+ @stdout.puts(" history (newest first):")
269
+ entry.history.reverse_each do |row|
270
+ line = [clock(row[:at]), row[:status], row[:detail], row[:session_id]&.slice(0, 8)].compact.reject { |part| part.to_s.empty? }
271
+ @stdout.puts(" #{line.join(" ")}")
272
+ end
273
+ end
274
+
185
275
  def tick
186
276
  refused = format_refusal(@opts[:format])
187
277
  return refused if refused
@@ -248,41 +338,87 @@ module Samagotchi
248
338
  # One `list` row: id, name, mode, recurrence, next due, target head, and the
249
339
  # notes (skips, why it is disabled, the last result). +name_width+ is the
250
340
  # widest name among the rows printed; without it the name column is just
251
- # the name.
341
+ # the name. "disabled after N" only when that budget is spent: a one-off
342
+ # whose firing failed (ScheduleDisplay.off_reason "failures") reads
343
+ # " disabled" here.
252
344
  def entry_line(entry, name_width: nil)
253
345
  note = ""
254
- note += " skips #{entry.skips} of #{entry.max_skips} (#{skip_window(entry)})" if entry.skips.positive?
255
- unless entry.enabled
256
- note += if entry.last_result == "disabled"
257
- " disabled"
258
- elsif entry.skips >= entry.max_skips
259
- " disabled after #{entry.skips} #{entry.skips == 1 ? "skip" : "skips"}"
260
- elsif entry.failures >= entry.max_failures
261
- " disabled after #{entry.failures} #{entry.failures == 1 ? "failure" : "failures"}"
262
- else
263
- " disabled"
264
- end
265
- end
346
+ note += " skips #{entry.skips} of #{entry.max_skips} (#{ScheduleDisplay.skip_window(entry)})" if entry.skips.positive?
347
+ note += off_note(entry) unless entry.enabled
348
+ note += " if: #{ScheduleDisplay.condition_words(entry, chars: ScheduleDisplay::PROMPT_CHARS)}" unless entry.condition.nil?
266
349
  note += " last: #{entry.last_result}" if entry.last_result
267
350
  "#{entry.id} #{ScheduleDisplay.name(entry, width: name_width)} #{entry.mode} #{entry.recurrence_words} " \
268
351
  "#{clock(entry.next_due)} #{entry.head[0, 8]}#{note}"
269
352
  end
270
353
 
271
- # A skip budget as a time window: 3 of 12 at a 5 minute tick is about 1 hour
272
- # of patience, which is what the count really measures.
273
- def skip_window(entry)
274
- minutes = entry.max_skips * Schedules.tick_interval_minutes
275
- hours = minutes / 60.0
276
- hours >= 1 ? "≈#{(hours * 10).round / 10} h at a #{Schedules.tick_interval_minutes} min tick" : "≈#{minutes} min"
354
+ # Schedules::ConditionPart.gate_warning for the folder CMD runs in (the
355
+ # target session's), when CMD is a script the model can edit.
356
+ def print_gate_warning(entry)
357
+ cmd = entry.condition.is_a?(Hash) ? entry.condition[:cmd] : nil
358
+ return unless cmd.is_a?(String)
359
+
360
+ folder = begin
361
+ Session.load(entry.head, state_dir: @schedules.state_dir).working_directory
362
+ rescue Session::NotFound
363
+ nil
364
+ end
365
+ warning = Schedules::ConditionPart.gate_warning(cmd, folder: folder)
366
+ @stdout.puts(warning) if warning
277
367
  end
278
368
 
279
- def entry_line_json(entry)
280
- entry.to_h.transform_keys(&:to_s).merge(
281
- "recurrence_words" => entry.recurrence_words,
282
- "skip_window" => skip_window(entry)
283
- )
369
+ # " · if CMD" for add's line, "" without a condition.
370
+ def condition_words(entry) = entry.condition.nil? ? "" : " · if #{ScheduleDisplay.condition_words(entry)}"
371
+
372
+ # show's: the command, who set it and when, and what holds for it.
373
+ def condition_show(entry)
374
+ condition = entry.condition
375
+ return ScheduleDisplay.condition_words(entry) unless condition.is_a?(Hash) && condition[:cmd].is_a?(String)
376
+
377
+ by = condition[:by] == Schedules::ConditionPart::CONDITION_BY ? "the CLI" : condition[:by].inspect
378
+ "#{condition[:cmd]} (set from #{by} #{clock(condition[:set_at])}; timeout #{@schedules.condition_timeout_seconds} s; " \
379
+ "run-now skips it)"
284
380
  end
285
381
 
382
+ def off_note(entry)
383
+ case ScheduleDisplay.off_reason(entry)
384
+ when "skips"
385
+ return " disabled" unless entry.skips >= entry.max_skips
386
+
387
+ " disabled after #{entry.skips} #{entry.skips == 1 ? "skip" : "skips"}"
388
+ when "failures"
389
+ return " disabled" unless entry.failures >= entry.max_failures
390
+
391
+ " disabled after #{entry.failures} #{entry.failures == 1 ? "failure" : "failures"}"
392
+ else " disabled"
393
+ end
394
+ end
395
+
396
+ def entry_line_json(entry) = ScheduleDisplay.json(entry)
397
+
398
+ # The entries of schedules.json that don't read, which list leaves out:
399
+ # one line naming them and the way out (Schedules#cancel takes one by its
400
+ # id, #cancel_unreadable), nil when there are none. A file that isn't
401
+ # JSON lists as no schedules, as before.
402
+ UNREADABLE_IDS_SHOWN = 5
403
+
404
+ def unreadable_line
405
+ ids = @schedules.listing.unreadable_ids
406
+ named = ids.compact
407
+ nameless = ids.size - named.size
408
+ parts = []
409
+ unless named.empty?
410
+ shown = named.first(UNREADABLE_IDS_SHOWN).join(", ")
411
+ shown += ", …" if named.size > UNREADABLE_IDS_SHOWN
412
+ parts << "#{plural(named.size, "schedule")} can't be read (#{shown}): chi schedule cancel ID removes one"
413
+ end
414
+ parts << "#{plural(nameless, "schedule")} with no id can't be read: fix or remove it in schedules.json" if nameless.positive?
415
+ parts.empty? ? nil : parts.join("; ")
416
+ rescue Schedules::Corrupt
417
+ nil
418
+ end
419
+
420
+ def plural(count, word) = "#{count} #{word}#{"s" unless count == 1}"
421
+
286
422
  def print_tick_warning(stream = @stdout)
287
423
  warning = @schedules.tick_warning
288
424
  stream.puts(warning) if warning
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "schedules"
4
+
3
5
  module Samagotchi
4
6
  # What a schedule is called when it is listed: `chi schedule list` and the
5
7
  # `list_schedules` tool both use this, so a schedule reads the same in the
@@ -24,9 +26,92 @@ module Samagotchi
24
26
  width ? given.ljust(width) : given
25
27
  end
26
28
 
29
+ # An entry's condition as it is listed: its command (cut at +chars+ with
30
+ # "…" when given), or what a condition that doesn't read is. nil without
31
+ # one.
32
+ def self.condition_words(entry, chars: nil)
33
+ condition = entry.condition
34
+ return nil if condition.nil?
35
+
36
+ cmd = condition.is_a?(Hash) ? condition[:cmd] : nil
37
+ return "(doesn't read: the tick fails it)" unless cmd.is_a?(String)
38
+
39
+ chars && cmd.length > chars ? "#{cmd[0, chars]}…" : cmd
40
+ end
41
+
27
42
  # The width of the name column for these entries.
28
43
  def self.name_width(entries)
29
44
  entries.map { |entry| name(entry) }.map(&:length).max
30
45
  end
46
+
47
+ # The history statuses that are outcomes of a firing (HistoryPart): the
48
+ # owner's enabled/disabled and an edit's rows say nothing of how a
49
+ # one-off ended.
50
+ OUTCOMES = %w[fired failed missed skipped].freeze
51
+
52
+ # "firing" while a firing is under way (a tick holds it, or its turn is
53
+ # pending: a one-off is already off then, see Schedules#advance), "on"
54
+ # when enabled, else "off".
55
+ # @param entry [Schedules::Entry]
56
+ def self.state(entry)
57
+ return "firing" if entry.firing_since || entry.pending_session_id
58
+
59
+ entry.enabled ? "on" : "off"
60
+ end
61
+
62
+ # Why an off schedule is off, nil when it isn't (state on or firing):
63
+ # "owner" turned off by `chi schedule disable` (its last result)
64
+ # "skips" its skip budget ran out (max_skips)
65
+ # "failures" its failure budget ran out (max_failures), or a one-off
66
+ # whose firing failed
67
+ # "done" a one-off that fired
68
+ # "missed" a one-off whose moment passed unseen
69
+ # "off" none of these (an older file's spent one-off)
70
+ # A one-off's reason is its last outcome row in the history (OUTCOMES),
71
+ # never `enabled: false` alone: firing, failing and missing all turn a
72
+ # one-off off.
73
+ def self.off_reason(entry)
74
+ return nil unless state(entry) == "off"
75
+ return "owner" if entry.last_result == "disabled"
76
+ return "skips" if entry.skips >= entry.max_skips
77
+ return "failures" if entry.failures >= entry.max_failures
78
+ return "off" unless entry.recurrence[:kind] == "date"
79
+
80
+ case entry.history.reverse.find { |row| OUTCOMES.include?(row[:status]) }&.dig(:status)
81
+ when "fired" then "done"
82
+ when "failed" then "failures"
83
+ when "missed" then "missed"
84
+ when "skipped" then "skips"
85
+ else "off"
86
+ end
87
+ end
88
+
89
+ # A skip budget as a time window: 3 of 12 at a 5 minute tick is about 1
90
+ # hour of patience, which is what the count really measures.
91
+ def self.skip_window(entry)
92
+ tick = Schedules.tick_interval_minutes
93
+ minutes = entry.max_skips * tick
94
+ hours = minutes / 60.0
95
+ hours >= 1 ? "≈#{(hours * 10).round / 10} h at a #{tick} min tick" : "≈#{minutes} min"
96
+ end
97
+
98
+ # One entry as `chi schedule list --format json` prints it (and
99
+ # Pages::Runtime reads it): every stored field with its extra keys (the
100
+ # real next_due: the file's hidden one is Schedules#write's), the
101
+ # condition with string keys, then what a reader needs and would
102
+ # otherwise compute: recurrence_words, skip_window, name, state,
103
+ # off_reason. Those come last, so an extra key of the same name (a newer
104
+ # chi's) never shadows them.
105
+ # @return [Hash{String => Object}]
106
+ def self.json(entry)
107
+ condition = entry.condition.is_a?(Hash) ? entry.condition.transform_keys(&:to_s) : entry.condition
108
+ entry.to_h.transform_keys(&:to_s).merge("condition" => condition).merge(
109
+ "recurrence_words" => entry.recurrence_words,
110
+ "skip_window" => skip_window(entry),
111
+ "name" => name(entry),
112
+ "state" => state(entry),
113
+ "off_reason" => off_reason(entry)
114
+ )
115
+ end
31
116
  end
32
117
  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