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
@@ -22,8 +22,15 @@ require_relative "session_inbox"
22
22
  require_relative "session_manager"
23
23
  require_relative "session_row"
24
24
  require_relative "state_format"
25
- require_relative "turn_checkpoint"
25
+ require_relative "turn_outcome"
26
26
  require_relative "worker_link"
27
+ require_relative "schedules/busy_part"
28
+ require_relative "schedules/edit_part"
29
+ require_relative "schedules/history_part"
30
+ require_relative "schedules/listing_part"
31
+ require_relative "schedules/notices_part"
32
+ require_relative "schedules/protection_part"
33
+ require_relative "schedules/recurrence"
27
34
 
28
35
  module Samagotchi
29
36
  # Durable schedules: `chi schedule` and the schedule tools. A schedule lives
@@ -50,6 +57,13 @@ module Samagotchi
50
57
  # read-modify-write, never across the action: SessionContinue.run waits up to
51
58
  # 30 s for a recap and 5 s for an archive, and an `add` must not wait on it.
52
59
  class Schedules
60
+ include BusyPart
61
+ include EditPart
62
+ include HistoryPart
63
+ include ListingPart
64
+ include NoticesPart
65
+ include ProtectionPart
66
+
53
67
  FILE = "schedules.json"
54
68
  LOCK = "schedules.lock"
55
69
  VERSION = 1
@@ -62,13 +76,14 @@ module Samagotchi
62
76
  # A schedule prompt is a chain link's first message or a turn's prompt: the
63
77
  # same limit the note inbox uses.
64
78
  PROMPT_MAX_BYTES = SessionInbox::NOTE_MAX_BYTES
65
- # Seconds a tick waits for a live worker's GET /activity.
66
- ACTIVITY_TIMEOUT = 2.0
67
79
  # A chain firing can wait 30 s for a recap and 5 s for an archive; 5 s
68
80
  # more leaves margin before an unfinished turn is called interrupted.
69
81
  FIRING_TIMEOUT = 40
70
82
  PENDING_MIN_SECONDS = 10 * 60
71
83
  PENDING_MAX_SECONDS = 6 * 60 * 60
84
+ # A disabled notice older than this is dropped, not pushed: a chi web that
85
+ # comes up a week later does not send a batch of stale notifications.
86
+ NOTICE_MAX_AGE = 24 * 60 * 60
72
87
  # Refusals that mean "not now" rather than "this schedule is broken".
73
88
  # (starting: the link's worker holds no lock yet, e.g. another ticker's
74
89
  # firing just continued the chain.)
@@ -93,13 +108,17 @@ module Samagotchi
93
108
  Entry = Data.define(:id, :title, :anchor, :head, :mode, :prompt, :recurrence, :busy, :catch_up,
94
109
  :keep_links, :max_failures, :max_skips, :next_due, :due_was, :last_fired, :last_result,
95
110
  :firing_since, :firing_token, :pending_session_id, :pending_turn_id, :failures, :skips, :enabled,
96
- :created_at, :extra) do
111
+ :created_at, :disabled_notice, :history, :extra) do
97
112
  # The recurrence comes back from JSON with string keys: every reader of
98
- # it below matches on `recurrence[:kind]`, so it is symbolised here once.
113
+ # it below matches on `recurrence[:kind]`, so it is symbolised here once
114
+ # (the disabled notice too, whose fields the claim hands on as is).
99
115
  def self.from_record(record)
100
116
  fields = record.attributes
101
117
  recurrence = fields[:recurrence]
102
118
  fields[:recurrence] = recurrence.transform_keys(&:to_sym) if recurrence.is_a?(Hash)
119
+ notice = fields[:disabled_notice]
120
+ fields[:disabled_notice] = notice.is_a?(Hash) ? notice.transform_keys(&:to_sym) : nil
121
+ fields[:history] = HistoryPart.rows(fields[:history])
103
122
  new(**fields, extra: record.extra)
104
123
  end
105
124
 
@@ -157,6 +176,12 @@ module Samagotchi
157
176
  StateFormat.added(:skips, in_version: VERSION, default: 0),
158
177
  StateFormat.added(:enabled, in_version: VERSION, default: true),
159
178
  StateFormat.added(:created_at, in_version: VERSION, default: nil),
179
+ # {kind: "skipped"|"failed", count:, reason:, at:}: this entry's budget
180
+ # turned it off and no chi web has pushed that yet
181
+ # (#claim_disabled_notices). Set by whichever ticker disabled it.
182
+ StateFormat.added(:disabled_notice, in_version: VERSION, default: nil),
183
+ # The last outcomes, newest last (HistoryPart).
184
+ StateFormat.added(:history, in_version: VERSION, default: []),
160
185
  StateFormat.extra(:extra, in_version: VERSION)
161
186
  ],
162
187
  document_members: [StateFormat.added(:last_tick_at, in_version: VERSION, default: nil)]
@@ -200,24 +225,6 @@ module Samagotchi
200
225
  include_disabled ? list : list.select(&:enabled)
201
226
  end
202
227
 
203
- def protected_session_ids
204
- links = links_now
205
- entries.flat_map { |entry| [entry.anchor, entry.head, target_of(entry, links).first] }.compact.uniq
206
- end
207
-
208
- def protecting(session_id)
209
- links = links_now
210
- entries.find { |entry| target_of(entry, links).first == session_id }
211
- end
212
-
213
- # The enabled schedule a delete of +session_id+ would break: one whose
214
- # target (#protecting), anchor or head it is. A head deleted would make
215
- # the schedule fall back to its anchor (an archived link) and fail.
216
- # @return [Entry, nil]
217
- def protecting_link(session_id)
218
- entries.find { |entry| entry.anchor == session_id || entry.head == session_id } || protecting(session_id)
219
- end
220
-
221
228
  # @param id_or_name [String] an id, a unique prefix of one, or a title
222
229
  # @return [Entry, nil]
223
230
  # @raise [Usage] the prefix or the title names more than one schedule
@@ -254,16 +261,8 @@ module Samagotchi
254
261
  raise Usage, "mode must be one of #{MODES.join(", ")}" unless MODES.include?(mode)
255
262
 
256
263
  given_catch_up = catch_up.nil? || catch_up.to_s.strip.empty? ? Config.get("schedule.default_catch_up") : catch_up.to_s.strip
257
- raise Usage, "catch_up must be one of #{CATCH_UP.join(", ")}" unless CATCH_UP.include?(given_catch_up)
258
-
259
- prompt = prompt.to_s
260
- raise Usage, "a schedule needs a prompt" if prompt.strip.empty?
261
- # It fires from a schedule, never a person: a shell line would be
262
- # refused at every firing (CommandIntake); a /word one is the model's text.
263
- raise Usage, CommandIntake::REFUSED if CommandIntake.shell_line?(prompt)
264
- if prompt.bytesize > PROMPT_MAX_BYTES
265
- raise Usage, "the prompt is #{prompt.bytesize} bytes; the limit is 16 KiB (#{PROMPT_MAX_BYTES} bytes)"
266
- end
264
+ validate_catch_up!(given_catch_up)
265
+ prompt = validate_prompt!(prompt)
267
266
 
268
267
  anchor = Session.resolve!(target.to_s, state_dir: @state_dir)
269
268
  if Session.load(anchor, state_dir: @state_dir).scratch
@@ -274,10 +273,7 @@ module Samagotchi
274
273
  # firing would otherwise multiply the same schedule: the chain keeps one
275
274
  # entry per thing it does, and the machine a bounded number of them.
276
275
  same = duplicate_in_chain(anchor, prompt: prompt, title: title, recurrence: recurrence)
277
- if same
278
- raise Usage, "#{same.id} already schedules this (#{same.recurrence_words}, #{mode}: #{same.prompt}); " \
279
- "cancel it with chi schedule cancel #{same.id} to change it"
280
- end
276
+ refuse_duplicate!(same, mode) if same
281
277
 
282
278
  ids = chain_of(anchor)
283
279
  in_chain = entries.count { |entry| ids.include?(entry.anchor) || ids.include?(entry.head) }
@@ -297,14 +293,15 @@ module Samagotchi
297
293
  max_skips: int_or_default(max_skips, "schedule.default_max_skips", 12, min: 1),
298
294
  next_due: next_due_for(recurrence, from: now).utc.iso8601, due_was: nil,
299
295
  last_fired: nil, last_result: nil, firing_since: nil, firing_token: nil, pending_session_id: nil,
300
- pending_turn_id: nil, failures: 0, skips: 0, enabled: true, created_at: now.utc.iso8601, extra: {}
296
+ pending_turn_id: nil, failures: 0, skips: 0, enabled: true, created_at: now.utc.iso8601,
297
+ disabled_notice: nil, history: [], extra: {}
301
298
  )
302
299
  write_under_lock { |file| file.entries << entry }
303
300
  entry
304
301
  end
305
302
 
306
303
  # @return [Entry, nil] nil when no schedule matches
307
- def cancel(id_or_name) = change(id_or_name, delete: true)
304
+ def cancel(id_or_name) = change(id_or_name, delete: true) || cancel_unreadable(id_or_name)
308
305
  def enable(id_or_name) = change(id_or_name, enabled: true)
309
306
  def disable(id_or_name) = change(id_or_name, enabled: false)
310
307
 
@@ -321,20 +318,6 @@ module Samagotchi
321
318
  entries(include_disabled: include_disabled).select { |entry| ids.include?(entry.anchor) || ids.include?(entry.head) }
322
319
  end
323
320
 
324
- # An enabled schedule of the same chain that says the same thing: the same
325
- # prompt and recurrence, or the same title.
326
- # @return [Entry, nil]
327
- def duplicate_in_chain(session_id, prompt:, title:, recurrence:)
328
- given_title = title.to_s.strip
329
- ids = chain_of(session_id)
330
- entries.find do |entry|
331
- next unless ids.include?(entry.anchor) || ids.include?(entry.head)
332
-
333
- (entry.prompt == prompt && entry.recurrence == recurrence) ||
334
- (!given_title.empty? && entry.title.to_s.strip.casecmp?(given_title))
335
- end
336
- end
337
-
338
321
  # How many enabled schedules one chain may hold, and one machine.
339
322
  def per_chain_limit = positive_config("schedule.max_per_session", 10)
340
323
  def total_limit = positive_config("schedule.max_total", 50)
@@ -376,7 +359,7 @@ module Samagotchi
376
359
  next unless entry.is_a?(Entry)
377
360
 
378
361
  if entry.firing_since && !entry.pending_turn_id && firing_expired?(entry, now)
379
- interrupted = failed(entry, "interrupted")
362
+ interrupted = failed(entry, "interrupted", now: now)
380
363
  interrupted = interrupted.with(enabled: false) if entry.recurrence[:kind] == "date"
381
364
  updated[position] = interrupted
382
365
  pending_ids << entry.id
@@ -389,7 +372,7 @@ module Samagotchi
389
372
  outcome = resolve_pending(entry, now)
390
373
  pending_ids << entry.id
391
374
  if outcome
392
- updated[position] = finish_pending(entry, outcome)
375
+ updated[position] = finish_pending(entry, outcome, now: now)
393
376
  outcomes << outcome
394
377
  if outcome.status == "fired" && entry.mode == CHAIN
395
378
  resolved_chains << entry
@@ -424,7 +407,7 @@ module Samagotchi
424
407
  if verdict
425
408
  kind, reason = verdict
426
409
  unless dry_run
427
- updated[position] = kind == :skip ? skipped(entry, reason) : failed(entry, reason)
410
+ updated[position] = kind == :skip ? skipped(entry, reason, now: now) : failed(entry, reason, now: now)
428
411
  end
429
412
  outcomes << Outcome.new(id: entry.id, title: entry.title, status: kind == :skip ? "skipped" : "failed",
430
413
  detail: reason, entry: entry)
@@ -432,13 +415,13 @@ module Samagotchi
432
415
  end
433
416
  if entry.mode == CHAIN && fired_chains[chain_key(links, entry)]
434
417
  reason = "the chain just fired; retry at the next tick"
435
- updated[position] = skipped(entry, reason) unless dry_run
418
+ updated[position] = skipped(entry, reason, now: now) unless dry_run
436
419
  outcomes << Outcome.new(id: entry.id, title: entry.title, status: "skipped", detail: reason, entry: entry)
437
420
  next
438
421
  end
439
422
  if entry.mode == CHAIN && pending_chains.include?(chain_key(links, entry))
440
423
  reason = "a schedule turn is still pending in this chain"
441
- updated[position] = skipped(entry, reason) unless dry_run
424
+ updated[position] = skipped(entry, reason, now: now) unless dry_run
442
425
  outcomes << Outcome.new(id: entry.id, title: entry.title, status: "skipped", detail: reason, entry: entry)
443
426
  next
444
427
  end
@@ -461,7 +444,7 @@ module Samagotchi
461
444
  end
462
445
 
463
446
  pending.each do |entry|
464
- outcome = fire_and_record(entry, links)
447
+ outcome = fire_and_record(entry, links, now: now)
465
448
  outcomes << outcome
466
449
  prune_after << outcome.entry if outcome.status == "fired" && entry.mode == CHAIN && entry.keep_links.positive?
467
450
  end
@@ -482,6 +465,7 @@ module Samagotchi
482
465
  return Outcome.new(id: id_or_name.to_s, status: "failed", detail: "no such schedule") if entry.nil?
483
466
 
484
467
  links = links_now
468
+ now = @clock.call
485
469
  reserved = nil
486
470
  outcome = nil
487
471
  write_under_lock do |file|
@@ -507,21 +491,21 @@ module Samagotchi
507
491
  if verdict
508
492
  kind, reason = verdict
509
493
  status = kind == :skip ? "skipped" : "failed"
510
- updated = status == "skipped" ? skipped(current, reason) : failed(current, reason) if current.enabled
511
- updated ||= current.with(last_result: reason)
494
+ updated = status == "skipped" ? skipped(current, reason, now: now) : failed(current, reason, now: now) if current.enabled
495
+ updated ||= with_history(current.with(last_result: reason), status, reason, at: now, session_id: current.head)
512
496
  file.entries[position] = updated
513
497
  outcome = Outcome.new(id: current.id, title: current.title, status: status, detail: reason, entry: updated)
514
498
  next
515
499
  end
516
500
 
517
- reserved = advance(current, @clock.call)
501
+ reserved = advance(current, now)
518
502
  file.entries[position] = reserved
519
503
  end
520
504
 
521
505
  return mark_disabled([outcome], [entry], links: links).first if outcome
522
506
  return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "no such schedule") unless reserved
523
507
 
524
- mark_disabled([fire_and_record(reserved, links)], [entry], links: links).first
508
+ mark_disabled([fire_and_record(reserved, links, now: now)], [entry], links: links).first
525
509
  end
526
510
 
527
511
  # Minutes between the hub's ticks when schedule.auto_tick is on.
@@ -530,110 +514,6 @@ module Samagotchi
530
514
  value.positive? ? value : 5
531
515
  end
532
516
 
533
- def tick_warning(now: @clock.call)
534
- return if Config.get("schedule.auto_tick")
535
-
536
- last_tick_at = read.attributes[:last_tick_at]
537
- stale_after = self.class.tick_interval_minutes * 120
538
- return if last_tick_at && now - Time.iso8601(last_tick_at.to_s) <= stale_after
539
-
540
- "Warning: no schedule tick in the last #{stale_after / 60} minutes; set schedule.auto_tick: true or " \
541
- "run `chi schedule tick` from cron."
542
- rescue ArgumentError
543
- "Warning: no schedule tick in the last #{self.class.tick_interval_minutes * 2} minutes; " \
544
- "set schedule.auto_tick: true or run `chi schedule tick` from cron."
545
- end
546
-
547
- # A recurrence from the CLI's flags or the tool's arguments. Blank strings
548
- # (what a model sends for the fields it did not use) count as absent.
549
- # @return [Hash] {kind:, ...}
550
- # @raise [Usage] none or more than one kind given, or an interval that is
551
- # not a positive amount of time
552
- def self.recurrence(every: nil, weekday: nil, time: nil, date: nil)
553
- every = nil if every.to_s.strip.empty?
554
- weekday = nil if weekday.to_s.strip.empty?
555
- time = nil if time.to_s.strip.empty?
556
- date = nil if date.to_s.strip.empty?
557
-
558
- kinds = [every, weekday, date].compact
559
- raise Usage, "a schedule needs one of every, weekday or date" if kinds.empty?
560
- raise Usage, "give one of every, weekday or date, not more" if kinds.size > 1
561
-
562
- if every
563
- raise Usage, "time is only for a weekday schedule" if time && !weekday
564
-
565
- interval = every.to_s.strip
566
- raise Usage, "every needs an interval like 30m, 2h or 1d, got #{every}" unless interval.match?(/\A\d+[smhd]?\z/)
567
-
568
- seconds = interval_seconds(interval)
569
- raise Usage, "every must be at least 1s, got #{every}" if seconds.nil? || seconds.zero?
570
-
571
- { kind: "every", interval: interval }
572
- elsif weekday
573
- raise Usage, "weekday needs time HH:MM" if time.nil?
574
-
575
- day = weekday.to_s.strip
576
- raise Usage, "weekday must be 1 (Mon) to 7 (Sun), got #{weekday}" unless day.match?(/\A[1-7]\z/)
577
-
578
- { kind: "weekday", weekday: day.to_i, time: time.to_s.strip }
579
- else
580
- { kind: "date", at: local_moment(*parse_local(date)).utc.iso8601 }
581
- end
582
- end
583
-
584
- # The length of an interval in seconds; nil for something that is not an
585
- # interval, and nil for zero so a `0m` schedule can never fire every tick.
586
- def self.interval_seconds(interval)
587
- match = interval.to_s.strip.match(/\A(\d+)(s|m|h|d)?\z/)
588
- return nil unless match
589
-
590
- seconds = { "s" => 1, "m" => 60, "h" => 3600, "d" => 86_400, nil => 60 }[match[2]] * match[1].to_i
591
- seconds.positive? ? seconds : nil
592
- end
593
-
594
- def self.parse_clock(time)
595
- match = time.to_s.strip.match(/\A(\d{1,2}):(\d{1,2})\z/)
596
- raise Usage, "time must be HH:MM, got #{time}" unless match
597
-
598
- hour = match[1].to_i
599
- minute = match[2].to_i
600
- raise Usage, "time must be HH:MM, got #{time}" unless (0..23).cover?(hour) && (0..59).cover?(minute)
601
-
602
- [hour, minute]
603
- end
604
-
605
- def self.parse_local(text)
606
- match = text.to_s.strip.match(/\A(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{1,2}):(\d{2}))?\z/)
607
- raise Usage, "date must be YYYY-MM-DD or YYYY-MM-DDTHH:MM, got #{text}" unless match
608
-
609
- year = match[1].to_i
610
- month = match[2].to_i
611
- day = match[3].to_i
612
- hour = match[4] ? match[4].to_i : 0
613
- minute = match[5] ? match[5].to_i : 0
614
- unless Date.valid_date?(year, month, day) && (0..23).cover?(hour) && (0..59).cover?(minute)
615
- raise Usage, "date must be a real date, got #{text}"
616
- end
617
-
618
- [year, month, day, hour, minute]
619
- end
620
-
621
- # A local moment that exists. When the requested minute falls in a
622
- # spring-forward gap, the first valid minute whose wall clock is at or
623
- # after it.
624
- def self.local_moment(year, month, day, hour, minute)
625
- moment = Time.local(year, month, day, hour, minute)
626
- return moment if moment.hour == hour && moment.min == minute
627
-
628
- wanted = (hour * 60) + minute
629
- day_start = Time.local(year, month, day, 0, 0)
630
- 1440.times do |step|
631
- probe = day_start + (step * 60)
632
- return probe if (probe.hour * 60) + probe.min >= wanted
633
- end
634
- moment
635
- end
636
-
637
517
  private
638
518
 
639
519
  # The chains as they are now, over one session listing (SessionChain::Links):
@@ -643,7 +523,7 @@ module Samagotchi
643
523
 
644
524
  # @param strict [Boolean] a file that is not readable JSON raises rather
645
525
  # than reading as empty: a write starting from an empty list would rewrite
646
- # the file and lose every schedule on it. Listing stays lenient.
526
+ # the file and lose every schedule on it. #entries stays lenient.
647
527
  def read(strict: false)
648
528
  return FORMAT.read({}, collection: "schedules") unless File.exist?(path)
649
529
 
@@ -685,35 +565,72 @@ module Samagotchi
685
565
  end
686
566
 
687
567
  # The same resolution as #lookup — an id, a unique prefix, or a title, and
688
- # an ambiguous one raises Usage rather than taking the first match.
568
+ # an ambiguous one raises Usage rather than taking the first match. nil
569
+ # too when the entry is gone by the time the lock is held (another cancel
570
+ # landed in between): the caller says "no schedule", not "ok".
571
+ # @return [Entry, nil] the entry as changed (as removed, for a delete)
689
572
  def change(id_or_name, enabled: nil, delete: false)
690
573
  entry = lookup(id_or_name)
691
574
  return nil if entry.nil?
692
575
 
576
+ result = nil
693
577
  write_under_lock do |file|
694
578
  position = file.entries.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
695
579
  next if position.nil?
696
580
 
697
581
  if delete
582
+ result = file.entries[position]
698
583
  file.entries[position] = nil
699
584
  file.entries.compact!
700
585
  else
701
- changed = file.entries[position].with(enabled: enabled, last_result: enabled ? "enabled" : "disabled")
702
- # Enabled again with a fresh budget: its next skip must not end it at once.
703
- file.entries[position] = enabled ? changed.with(skips: 0, failures: 0) : changed
586
+ stored = file.entries[position]
587
+ word = enabled ? "enabled" : "disabled"
588
+ # The owner's row only for a change: an enable of an enabled entry adds none.
589
+ changed = stored.with(enabled: enabled, last_result: word)
590
+ changed = with_history(changed, word, nil, at: @clock.call) unless stored.enabled == enabled
591
+ # Enabled again with a fresh budget: its next skip must not end it at
592
+ # once, and the turn-off it was disabled by is no news any more.
593
+ result = file.entries[position] = enabled ? changed.with(skips: 0, failures: 0, disabled_notice: nil) : changed
704
594
  end
705
595
  end
706
- entry
596
+ result
707
597
  end
708
598
 
709
- # +name+ is what the caller's flag is called, so a bad value says which one.
710
- def int_or_default(value, key, fallback, min:, name: key.split(".").last)
711
- unless value.nil? || value.to_s.strip.empty?
712
- raise Usage, "#{name} must be a number, got #{value.inspect}" unless value.to_s.strip.match?(/\A-?\d+\z/)
599
+ # The checks a schedule's fields pass, for #add and #edit.
600
+ # @raise [Usage]
601
+ def validate_catch_up!(value)
602
+ raise Usage, "catch_up must be one of #{CATCH_UP.join(", ")}" unless CATCH_UP.include?(value)
603
+ end
713
604
 
714
- return [value.to_i, min].max
605
+ # @return [String] the prompt
606
+ # @raise [Usage]
607
+ def validate_prompt!(prompt)
608
+ prompt = prompt.to_s
609
+ raise Usage, "a schedule needs a prompt" if prompt.strip.empty?
610
+ # It fires from a schedule, never a person: a shell line would be
611
+ # refused at every firing (CommandIntake); a /word one is the model's text.
612
+ raise Usage, CommandIntake::REFUSED if CommandIntake.shell_line?(prompt)
613
+ if prompt.bytesize > PROMPT_MAX_BYTES
614
+ raise Usage, "the prompt is #{prompt.bytesize} bytes; the limit is 16 KiB (#{PROMPT_MAX_BYTES} bytes)"
715
615
  end
716
616
 
617
+ prompt
618
+ end
619
+
620
+ # A whole number given for +name+, at least +min+; nil when none was given.
621
+ # @raise [Usage] not a number
622
+ def int_value(value, min:, name:)
623
+ return nil if value.nil? || value.to_s.strip.empty?
624
+ raise Usage, "#{name} must be a number, got #{value.inspect}" unless value.to_s.strip.match?(/\A-?\d+\z/)
625
+
626
+ [value.to_i, min].max
627
+ end
628
+
629
+ # +name+ is what the caller's flag is called, so a bad value says which one.
630
+ def int_or_default(value, key, fallback, min:, name: key.split(".").last)
631
+ given = int_value(value, min: min, name: name)
632
+ return given unless given.nil?
633
+
717
634
  configured = Config.get(key)
718
635
  configured.to_s.strip.match?(/\A-?\d+\z/) ? [configured.to_i, min].max : fallback
719
636
  end
@@ -774,11 +691,12 @@ module Samagotchi
774
691
  # is disabled — `late?` never sends a one-off here, but a spent `date` entry
775
692
  # arriving from an older file is still spent.
776
693
  def reschedule(entry, now)
694
+ missed = with_history(entry, "missed", "past its time", at: now, session_id: entry.head)
777
695
  if entry.recurrence[:kind] == "date"
778
- entry.with(next_due: nil, last_result: "missed", firing_since: nil, firing_token: nil, enabled: false)
696
+ missed.with(next_due: nil, last_result: "missed", firing_since: nil, firing_token: nil, enabled: false)
779
697
  else
780
- entry.with(next_due: next_due_for(entry.recurrence, from: now).utc.iso8601, last_result: "missed",
781
- firing_since: nil, firing_token: nil)
698
+ missed.with(next_due: next_due_for(entry.recurrence, from: now).utc.iso8601, last_result: "missed",
699
+ firing_since: nil, firing_token: nil)
782
700
  end
783
701
  end
784
702
 
@@ -797,47 +715,22 @@ module Samagotchi
797
715
  enabled: one_off ? false : entry.enabled)
798
716
  end
799
717
 
800
- # The skips and failures that turned off a recurring entry that was on when
801
- # the pass began (+before+), as the file has it now: one diff covers every
802
- # path that records one. A `date` one-off is spent, not disabled; an entry
803
- # off within budget is an owner's `chi schedule disable`.
804
- def mark_disabled(outcomes, before, links: nil)
805
- ended = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }.map(&:id)
806
- status_by_id = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }
807
- .to_h { |outcome| [outcome.id, outcome.status] }
808
- on = before.select { |entry| entry.enabled && entry.recurrence[:kind] != "date" && ended.include?(entry.id) }.map(&:id)
809
- return outcomes if on.empty?
810
-
811
- off = read.entries.grep(Entry).select do |entry|
812
- budget_reached = case status_by_id[entry.id]
813
- when "skipped" then entry.skips >= entry.max_skips
814
- when "failed" then entry.failures >= entry.max_failures
815
- else false
816
- end
817
- on.include?(entry.id) && !entry.enabled && budget_reached
818
- end
819
- links ||= links_now unless off.empty?
820
- off.each do |entry|
821
- index = outcomes.rindex { |outcome| outcome.id == entry.id && %w[skipped failed].include?(outcome.status) }
822
- session_id = target_of(entry, links).first || entry.head
823
- outcomes[index] = outcomes[index].with(disabled: true, entry: entry, session_id: session_id)
824
- end
825
- outcomes
826
- end
827
-
828
- def skipped(entry, reason)
718
+ def skipped(entry, reason, now: @clock.call)
829
719
  skips = entry.skips + 1
830
720
  within_budget = skips < entry.max_skips
831
- entry.with(skips: skips, firing_since: nil, firing_token: nil, pending_session_id: nil, pending_turn_id: nil,
832
- last_result: within_budget ? "skipped" : "disabled: #{reason}",
833
- enabled: within_budget && (entry.enabled || entry.recurrence[:kind] == "date"))
721
+ updated = entry.with(skips: skips, firing_since: nil, firing_token: nil, pending_session_id: nil, pending_turn_id: nil,
722
+ last_result: within_budget ? "skipped" : "disabled: #{reason}",
723
+ enabled: within_budget && (entry.enabled || entry.recurrence[:kind] == "date"))
724
+ recorded(entry, updated, "skipped", reason, now)
834
725
  end
835
726
 
836
- def failed(entry, reason)
727
+ def failed(entry, reason, now: @clock.call)
837
728
  failures = entry.failures + 1
838
729
  within_budget = failures < entry.max_failures
839
- entry.with(failures: failures, firing_since: nil, firing_token: nil, pending_session_id: nil, pending_turn_id: nil,
840
- last_result: reason, enabled: within_budget && (entry.enabled || entry.recurrence[:kind] == "date"))
730
+ updated = entry.with(failures: failures, firing_since: nil, firing_token: nil, pending_session_id: nil,
731
+ pending_turn_id: nil, last_result: reason,
732
+ enabled: within_budget && (entry.enabled || entry.recurrence[:kind] == "date"))
733
+ recorded(entry, updated, "failed", reason, now)
841
734
  end
842
735
 
843
736
  def pending_detail(entry)
@@ -850,30 +743,27 @@ module Samagotchi
850
743
  "waiting for turn #{entry.pending_turn_id}"
851
744
  end
852
745
 
746
+ # In this order: the reply (fired), then a question this firing started
747
+ # and the turn has not ended before (waits, or "no outcome" once
748
+ # expired), then the settled turn (fired when it completed), then
749
+ # expiry.
853
750
  def resolve_pending(entry, now)
854
751
  session = Session.load(entry.pending_session_id, state_dir: @state_dir)
855
- turn = session.last_turn if session.last_turn&.enqueued_id == entry.pending_turn_id
856
- turn ||= TurnCheckpoint.settled_turn(Session.session_dir(entry.pending_session_id, state_dir: @state_dir),
857
- entry.pending_turn_id)
858
- if SessionInbox.reply_for(Session.session_dir(entry.pending_session_id, state_dir: @state_dir), entry.pending_turn_id)
859
- return Outcome.new(id: entry.id, title: entry.title, status: "fired", detail: "turn completed", entry: entry)
860
- end
752
+ result = TurnOutcome.for(session, entry.pending_turn_id,
753
+ session_dir: Session.session_dir(entry.pending_session_id, state_dir: @state_dir))
754
+ return Outcome.new(id: entry.id, title: entry.title, status: "fired", detail: result.detail, entry: entry) if result.replied
861
755
 
862
756
  question = session.pending_question
863
- if question_started?(question, entry) && !question_after_turn?(question, turn)
757
+ if question_started?(question, entry) && !question_after_turn?(question, result.turn)
864
758
  return nil unless pending_expired?(entry, now)
865
759
 
866
760
  return Outcome.new(id: entry.id, title: entry.title, status: "failed",
867
761
  detail: "no outcome", entry: entry)
868
762
  end
869
763
 
870
- if turn
871
- return Outcome.new(id: entry.id, title: entry.title, status: "fired", detail: "turn completed", entry: entry) if
872
- turn.outcome == "completed"
873
-
874
- reason = [turn.outcome, turn.error_kind, turn.cancel_reason, turn.stopped_by].compact.join(": ")
875
- return Outcome.new(id: entry.id, title: entry.title, status: "failed",
876
- detail: "turn #{reason.empty? ? "did not complete" : reason}", entry: entry)
764
+ if result.turn
765
+ return Outcome.new(id: entry.id, title: entry.title, status: result.completed? ? "fired" : "failed",
766
+ detail: result.detail, entry: entry)
877
767
  end
878
768
 
879
769
  return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "no outcome", entry: entry) if
@@ -928,12 +818,13 @@ module Samagotchi
928
818
  PENDING_MAX_SECONDS
929
819
  end
930
820
 
931
- def finish_pending(entry, outcome)
821
+ def finish_pending(entry, outcome, now: @clock.call)
932
822
  if outcome.status == "fired"
933
- entry.with(firing_since: nil, firing_token: nil, due_was: nil, pending_session_id: nil, pending_turn_id: nil,
934
- last_result: outcome.detail, failures: 0, skips: 0)
823
+ settled = entry.with(firing_since: nil, firing_token: nil, due_was: nil, pending_session_id: nil, pending_turn_id: nil,
824
+ last_result: outcome.detail, failures: 0, skips: 0)
825
+ with_history(settled, "fired", outcome.detail, at: now, session_id: entry.pending_session_id)
935
826
  else
936
- updated = failed(entry, outcome.detail).with(due_was: nil)
827
+ updated = failed(entry, outcome.detail, now: now).with(due_was: nil)
937
828
  entry.recurrence[:kind] == "date" ? updated.with(enabled: false) : updated
938
829
  end
939
830
  end
@@ -998,103 +889,15 @@ module Samagotchi
998
889
  target ? links.root(target) : "unresolved:#{entry.id}"
999
890
  end
1000
891
 
1001
- # Two paths (FR7): a live worker is asked through its Bridge; with no
1002
- # worker the files say what the tick can know. A session being deleted
1003
- # is a skip first, then one its owner stopped, in both modes: a schedule
1004
- # restarts nothing the owner stopped (deliver_turn would refuse a same-mode
1005
- # firing too, SessionManager::DeliverResult::STOPPED, in the same words).
1006
- def busy_reason(entry, links, target)
1007
- dir = Session.session_dir(target, state_dir: @state_dir)
1008
- owner = SessionManager.session_owner(target, state_dir: @state_dir)
1009
- presence = WorkerPresence.read(target, state_dir: @state_dir, owner: owner, link: :look)
1010
- return [:skip, SessionManager::DeliverResult::DELETING["detail"]] if presence.deleting?
1011
- return [:skip, SessionManager::DeliverResult::STOPPED["detail"]] if presence.stop_marked?
1012
-
1013
- link = presence.link
1014
-
1015
- if presence.worker_owned?
1016
- # A newer worker's Bridge cannot be asked; updating chi or restarting
1017
- # chi web fixes it, and max_skips still bounds a stuck schedule.
1018
- return [:skip, link.short_message] if link.is_a?(WorkerLink::Skew)
1019
-
1020
- # A worker that has not published its Bridge yet (or is closing it):
1021
- # nothing can be read from it, and firing now would race with it.
1022
- return [:skip, "its worker is starting or leaving"] unless presence.live?
1023
-
1024
- activity = ask_activity(link, target)
1025
- if activity == :old
1026
- # Its chi predates GET /activity. The file checks cannot see an open
1027
- # tab, so a chain firing would archive under someone's terminal:
1028
- # refuse with a restart, never silently degrade. Same mode only
1029
- # queues a turn, so for it the files are enough.
1030
- return [:skip, "its worker is too old to ask: chi sessions restart #{target[0, 8]}"] if entry.mode == CHAIN
1031
-
1032
- return file_busy_reason(links.session(target), dir)
1033
- end
1034
- return [:skip, "its worker is not answering"] if activity.nil?
1035
-
1036
- return [:skip, "a turn is running in it"] if activity[:turn_running]
1037
- return [:skip, "a prompt is queued for it"] if activity[:input_pending]
1038
- return [:skip, "its step-limit question waits for an answer"] if activity[:awaiting_continue]
1039
-
1040
- # A chain firing archives the session and stops its worker: a
1041
- # terminal or a web tab on it would be cut off. A queued turn into
1042
- # an open session is fine, so same mode does not count streams.
1043
- return [:skip, "a terminal or a web tab is open on it"] if entry.mode == CHAIN && activity[:open_streams].to_i.positive?
1044
-
1045
- # An idle live worker: free, whatever a starting marker its own
1046
- # start left (Worker#start clears it just after the lock).
1047
- return nil
1048
- end
1049
- # A worker being started for it holds no lock yet (another ticker's
1050
- # firing just continued the chain to it, a resume): a chain firing
1051
- # would archive it from under that worker (its archive refuses it too).
1052
- # A queued turn is fine: the starting worker takes it.
1053
- return [:skip, "its worker is starting or leaving"] if entry.mode == CHAIN && presence.starting?
1054
-
1055
- file_busy_reason(links.session(target), dir)
1056
- end
1057
-
1058
- # The worker's activity snapshot, :old when it has no /activity route, or
1059
- # nil when it did not answer at all. A worker published its features when
1060
- # it started, so a sidecar without "activity" is an older chi's: asking it
1061
- # would only cost a round trip to a 404.
1062
- def ask_activity(link, session_id)
1063
- return :old unless Array(link.features).include?(WorkerLink::ACTIVITY_FEATURE)
1064
-
1065
- status, body = link.client(session_id, read_timeout: ACTIVITY_TIMEOUT).get("activity")
1066
- return nil if status.nil?
1067
- return body.transform_keys(&:to_sym) if status == 200 && body.is_a?(Hash)
1068
-
1069
- :old
1070
- rescue StandardError => e
1071
- Log.warn(:worker, "activity_failed", sid: session_id, error: e.class.name, msg: e.message)
1072
- nil
1073
- end
1074
-
1075
- # The signals RemovalPart#archive_refusal reads, from the files alone.
1076
- def file_busy_reason(session, dir)
1077
- return nil if session.nil?
1078
-
1079
- if SessionRow.running_or_starting?(saved_status: session.status, live: false, busy: false, updated_at: session.updated_at)
1080
- return [:skip, "a turn is running in it"]
1081
- end
1082
- return [:skip, "a prompt is queued for it"] unless SessionInbox.find_new_input_files(dir).empty?
1083
-
1084
- return [:skip, "its step-limit question waits for an answer"] if session.waiting_question(live: false)&.dig(:kind) == ContinueOffer::KIND
1085
-
1086
- nil
1087
- end
1088
-
1089
892
  # A firing whose target no longer resolves (#target_of: gone, archived,
1090
893
  # or being continued since the tick's check): what #check would say.
1091
894
  def unresolved(entry, reason, kind)
1092
895
  Outcome.new(id: entry.id, title: entry.title, status: kind == :skip ? "skipped" : "failed", detail: reason, entry: entry)
1093
896
  end
1094
897
 
1095
- def fire_and_record(entry, links)
898
+ def fire_and_record(entry, links, now: @clock.call)
1096
899
  outcome = fire(entry, links)
1097
- record(entry, outcome)
900
+ record(entry, outcome, now: now)
1098
901
  outcome
1099
902
  end
1100
903
 
@@ -1200,7 +1003,7 @@ module Samagotchi
1200
1003
  # scheduled occurrence, so there is no occurrence to put the clock back to.
1201
1004
  # The result goes back under the lock before any pruning, so a prune that
1202
1005
  # raises midway cannot lose the new head.
1203
- def record(entry, outcome)
1006
+ def record(entry, outcome, now: @clock.call)
1204
1007
  write_under_lock do |file|
1205
1008
  position = file.entries.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
1206
1009
  stored = position && file.entries[position]
@@ -1220,13 +1023,14 @@ module Samagotchi
1220
1023
  # skips spread over months do not kill a healthy schedule.
1221
1024
  # A `date` schedule is a one-off: `advance` already left it
1222
1025
  # with no next_due and disabled, and a firing keeps it so.
1223
- stored.with(head: outcome.entry.head, last_result: outcome.detail, firing_since: nil, firing_token: nil,
1224
- pending_session_id: nil, pending_turn_id: nil,
1225
- failures: 0, skips: 0, last_fired: @clock.call.utc.iso8601)
1026
+ fired = stored.with(head: outcome.entry.head, last_result: outcome.detail, firing_since: nil,
1027
+ firing_token: nil, pending_session_id: nil, pending_turn_id: nil,
1028
+ failures: 0, skips: 0, last_fired: @clock.call.utc.iso8601)
1029
+ with_history(fired, "fired", outcome.detail, at: now, session_id: outcome.entry.head)
1226
1030
  when "skipped"
1227
- skipped(stored, outcome.detail).with(firing_since: nil)
1031
+ skipped(stored, outcome.detail, now: now).with(firing_since: nil)
1228
1032
  else
1229
- failed(stored, outcome.detail)
1033
+ failed(stored, outcome.detail, now: now)
1230
1034
  end
1231
1035
 
1232
1036
  # A skip or a failure is "not now", not "late": the occurrence the tick