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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +76 -1
- data/docs/architecture.md +9 -4
- data/docs/bundle-authoring.md +1 -1
- data/docs/bundles.md +15 -0
- data/docs/cli.md +38 -9
- data/docs/configuration.md +1 -0
- data/docs/guardrails.md +22 -9
- data/docs/internals/attached-context.md +4 -1
- data/docs/internals/bundles.md +3 -3
- data/docs/internals/engine.md +18 -2
- data/docs/internals/pages.md +65 -18
- data/docs/internals/session-lifecycle.md +19 -6
- data/docs/internals/web-frontend.md +3 -3
- data/docs/internals/web-push.md +11 -5
- data/docs/pages.md +69 -15
- data/docs/peers.md +3 -0
- data/docs/plugins.md +25 -1
- data/docs/releasing.md +1 -1
- data/docs/scheduling.md +168 -11
- data/docs/sessions.md +4 -4
- data/docs/sub-agent.md +1 -1
- data/docs/testing.md +1 -1
- data/lib/samagotchi/bundle_manifest.rb +34 -5
- data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +15 -0
- data/lib/samagotchi/bundles/guardrails/manifest.yml +2 -2
- data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
- data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +169 -0
- data/lib/samagotchi/bundles/system/manifest.yml +3 -3
- data/lib/samagotchi/bundles/system/self_map.md +2 -2
- data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
- data/lib/samagotchi/config.rb +2 -0
- data/lib/samagotchi/context_fetch.rb +9 -3
- data/lib/samagotchi/engine/models.rb +6 -4
- data/lib/samagotchi/engine/turn_end.rb +20 -2
- data/lib/samagotchi/engine.rb +5 -1
- data/lib/samagotchi/failure_line.rb +43 -0
- data/lib/samagotchi/guardrail_wiring.rb +3 -1
- data/lib/samagotchi/guardrails/chi_dirs.rb +20 -5
- data/lib/samagotchi/guardrails/parent_approvals.rb +1 -1
- data/lib/samagotchi/guardrails/protected_paths.rb +8 -4
- data/lib/samagotchi/guardrails/shell_paths.rb +16 -2
- data/lib/samagotchi/guardrails/targets.rb +1 -1
- data/lib/samagotchi/guardrails/verdict.rb +5 -3
- data/lib/samagotchi/image_store.rb +4 -0
- data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
- data/lib/samagotchi/last_turn.rb +2 -1
- data/lib/samagotchi/llm/utf8_scrub.rb +26 -0
- data/lib/samagotchi/llm_context_view.rb +6 -0
- data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
- data/lib/samagotchi/memory_bundle/builder.rb +1 -0
- data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
- data/lib/samagotchi/model_profile.rb +4 -1
- data/lib/samagotchi/page_command.rb +9 -6
- data/lib/samagotchi/pages/bundled.rb +83 -0
- data/lib/samagotchi/pages/launch.rb +14 -2
- data/lib/samagotchi/pages/runner.rb +7 -2
- data/lib/samagotchi/pages/runtime.rb +84 -0
- data/lib/samagotchi/pages/store.rb +18 -5
- data/lib/samagotchi/pages.rb +47 -3
- data/lib/samagotchi/peer_continue.rb +14 -8
- data/lib/samagotchi/reply_wait.rb +1 -1
- data/lib/samagotchi/run_options.rb +1 -1
- data/lib/samagotchi/schedule_command.rb +175 -39
- data/lib/samagotchi/schedule_display.rb +85 -0
- data/lib/samagotchi/schedules/busy_part.rb +146 -0
- data/lib/samagotchi/schedules/condition_part.rb +312 -0
- data/lib/samagotchi/schedules/edit_part.rb +144 -0
- data/lib/samagotchi/schedules/history_part.rb +51 -0
- data/lib/samagotchi/schedules/listing_part.rb +52 -0
- data/lib/samagotchi/schedules/notices_part.rb +122 -0
- data/lib/samagotchi/schedules/protection_part.rb +113 -0
- data/lib/samagotchi/schedules/prune_part.rb +79 -0
- data/lib/samagotchi/schedules/recurrence.rb +103 -0
- data/lib/samagotchi/schedules.rb +188 -409
- data/lib/samagotchi/session_access/local.rb +9 -1
- data/lib/samagotchi/session_access/remote.rb +2 -1
- data/lib/samagotchi/session_chain/delete.rb +7 -5
- data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
- data/lib/samagotchi/session_lifecycle.rb +3 -2
- data/lib/samagotchi/session_manager/removal.rb +16 -9
- data/lib/samagotchi/session_protection.rb +99 -0
- data/lib/samagotchi/session_retention.rb +21 -6
- data/lib/samagotchi/sessions_command.rb +4 -0
- data/lib/samagotchi/system_one/self_protect.rb +4 -2
- data/lib/samagotchi/testing/boundary.rb +13 -0
- data/lib/samagotchi/tools/cancel_schedule.rb +32 -4
- data/lib/samagotchi/tools/execute.rb +5 -1
- data/lib/samagotchi/tools/list_schedules.rb +1 -0
- data/lib/samagotchi/tools/task_runtime.rb +6 -0
- data/lib/samagotchi/turn_endings.rb +14 -2
- data/lib/samagotchi/turn_flow.rb +2 -1
- data/lib/samagotchi/turn_outcome.rb +41 -0
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/page_routes.rb +13 -8
- data/lib/samagotchi/web/public/app.js +12 -18
- data/lib/samagotchi/web/public/index.html +11 -2
- data/lib/samagotchi/web/public/owner_claim.js +7 -5
- data/lib/samagotchi/web/public/page_links.js +1 -1
- data/lib/samagotchi/web/public/page_view.js +8 -5
- data/lib/samagotchi/web/public/pages.css +9 -2
- data/lib/samagotchi/web/public/pages_group.js +21 -19
- data/lib/samagotchi/web/public/pages_list.js +73 -0
- data/lib/samagotchi/web/public/pages_model.js +54 -0
- data/lib/samagotchi/web/public/pages_wiring.js +66 -0
- data/lib/samagotchi/web/public/stream_handlers.js +8 -0
- data/lib/samagotchi/web/public/views.js +77 -23
- data/lib/samagotchi/web/push/notifier.rb +4 -3
- data/lib/samagotchi/web/server.rb +3 -1
- data/lib/samagotchi/web/session_hub.rb +75 -19
- data/lib/samagotchi/worker.rb +6 -4
- metadata +20 -1
data/lib/samagotchi/schedules.rb
CHANGED
|
@@ -22,8 +22,17 @@ 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 "
|
|
25
|
+
require_relative "turn_outcome"
|
|
26
26
|
require_relative "worker_link"
|
|
27
|
+
require_relative "schedules/busy_part"
|
|
28
|
+
require_relative "schedules/condition_part"
|
|
29
|
+
require_relative "schedules/edit_part"
|
|
30
|
+
require_relative "schedules/history_part"
|
|
31
|
+
require_relative "schedules/listing_part"
|
|
32
|
+
require_relative "schedules/notices_part"
|
|
33
|
+
require_relative "schedules/protection_part"
|
|
34
|
+
require_relative "schedules/prune_part"
|
|
35
|
+
require_relative "schedules/recurrence"
|
|
27
36
|
|
|
28
37
|
module Samagotchi
|
|
29
38
|
# Durable schedules: `chi schedule` and the schedule tools. A schedule lives
|
|
@@ -50,6 +59,15 @@ module Samagotchi
|
|
|
50
59
|
# read-modify-write, never across the action: SessionContinue.run waits up to
|
|
51
60
|
# 30 s for a recap and 5 s for an archive, and an `add` must not wait on it.
|
|
52
61
|
class Schedules
|
|
62
|
+
include BusyPart
|
|
63
|
+
include ConditionPart
|
|
64
|
+
include EditPart
|
|
65
|
+
include HistoryPart
|
|
66
|
+
include ListingPart
|
|
67
|
+
include NoticesPart
|
|
68
|
+
include ProtectionPart
|
|
69
|
+
include PrunePart
|
|
70
|
+
|
|
53
71
|
FILE = "schedules.json"
|
|
54
72
|
LOCK = "schedules.lock"
|
|
55
73
|
VERSION = 1
|
|
@@ -62,13 +80,14 @@ module Samagotchi
|
|
|
62
80
|
# A schedule prompt is a chain link's first message or a turn's prompt: the
|
|
63
81
|
# same limit the note inbox uses.
|
|
64
82
|
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
83
|
# A chain firing can wait 30 s for a recap and 5 s for an archive; 5 s
|
|
68
84
|
# more leaves margin before an unfinished turn is called interrupted.
|
|
69
85
|
FIRING_TIMEOUT = 40
|
|
70
86
|
PENDING_MIN_SECONDS = 10 * 60
|
|
71
87
|
PENDING_MAX_SECONDS = 6 * 60 * 60
|
|
88
|
+
# A disabled notice older than this is dropped, not pushed: a chi web that
|
|
89
|
+
# comes up a week later does not send a batch of stale notifications.
|
|
90
|
+
NOTICE_MAX_AGE = 24 * 60 * 60
|
|
72
91
|
# Refusals that mean "not now" rather than "this schedule is broken".
|
|
73
92
|
# (starting: the link's worker holds no lock yet, e.g. another ticker's
|
|
74
93
|
# firing just continued the chain.)
|
|
@@ -89,18 +108,24 @@ module Samagotchi
|
|
|
89
108
|
# the session a same-mode turn was queued into. That is what makes
|
|
90
109
|
# keep_links pruning provably safe: everything deleted is behind it.
|
|
91
110
|
# `due_was` is the occurrence the last tick attempted: a skip or a failure
|
|
92
|
-
# puts the clock back to it.
|
|
111
|
+
# puts the clock back to it. `condition` is the owner's `--if CMD`
|
|
112
|
+
# (ConditionPart), nil for none.
|
|
93
113
|
Entry = Data.define(:id, :title, :anchor, :head, :mode, :prompt, :recurrence, :busy, :catch_up,
|
|
94
114
|
:keep_links, :max_failures, :max_skips, :next_due, :due_was, :last_fired, :last_result,
|
|
95
115
|
:firing_since, :firing_token, :pending_session_id, :pending_turn_id, :failures, :skips, :enabled,
|
|
96
|
-
:created_at, :extra) do
|
|
116
|
+
:created_at, :disabled_notice, :history, :condition, :extra) do
|
|
97
117
|
# 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
|
|
118
|
+
# it below matches on `recurrence[:kind]`, so it is symbolised here once
|
|
119
|
+
# (the disabled notice too, whose fields the claim hands on as is; the
|
|
120
|
+
# condition and its hidden next_due: ConditionPart.stored).
|
|
99
121
|
def self.from_record(record)
|
|
100
122
|
fields = record.attributes
|
|
101
123
|
recurrence = fields[:recurrence]
|
|
102
124
|
fields[:recurrence] = recurrence.transform_keys(&:to_sym) if recurrence.is_a?(Hash)
|
|
103
|
-
|
|
125
|
+
notice = fields[:disabled_notice]
|
|
126
|
+
fields[:disabled_notice] = notice.is_a?(Hash) ? notice.transform_keys(&:to_sym) : nil
|
|
127
|
+
fields[:history] = HistoryPart.rows(fields[:history])
|
|
128
|
+
new(**ConditionPart.stored(fields, record.extra))
|
|
104
129
|
end
|
|
105
130
|
|
|
106
131
|
def to_h
|
|
@@ -157,13 +182,22 @@ module Samagotchi
|
|
|
157
182
|
StateFormat.added(:skips, in_version: VERSION, default: 0),
|
|
158
183
|
StateFormat.added(:enabled, in_version: VERSION, default: true),
|
|
159
184
|
StateFormat.added(:created_at, in_version: VERSION, default: nil),
|
|
185
|
+
# {kind: "skipped"|"failed", count:, reason:, at:}: this entry's budget
|
|
186
|
+
# turned it off and no chi web has pushed that yet
|
|
187
|
+
# (#claim_disabled_notices). Set by whichever ticker disabled it.
|
|
188
|
+
StateFormat.added(:disabled_notice, in_version: VERSION, default: nil),
|
|
189
|
+
# The last outcomes, newest last (HistoryPart).
|
|
190
|
+
StateFormat.added(:history, in_version: VERSION, default: []),
|
|
191
|
+
# {cmd:, by: "cli", set_at:}: the owner's `--if CMD` (ConditionPart).
|
|
192
|
+
StateFormat.added(:condition, in_version: VERSION, default: nil),
|
|
160
193
|
StateFormat.extra(:extra, in_version: VERSION)
|
|
161
194
|
],
|
|
162
195
|
document_members: [StateFormat.added(:last_tick_at, in_version: VERSION, default: nil)]
|
|
163
196
|
)
|
|
164
197
|
|
|
165
|
-
# What one entry did in a tick: "fired", "skipped", "missed", "failed"
|
|
166
|
-
# "
|
|
198
|
+
# What one entry did in a tick: "fired", "skipped", "missed", "failed",
|
|
199
|
+
# "not-needed" (its condition said no: ConditionPart) or "dry" (a
|
|
200
|
+
# --dry-run's "would fire"). +detail+ is the reason. +disabled+:
|
|
167
201
|
# this skip or failure used up a recurring entry's budget (#mark_disabled).
|
|
168
202
|
Outcome = Data.define(:id, :title, :status, :detail, :entry, :disabled, :session_id) do
|
|
169
203
|
def initialize(id:, status:, title: nil, detail: nil, entry: nil, disabled: false, session_id: nil) = super
|
|
@@ -180,12 +214,17 @@ module Samagotchi
|
|
|
180
214
|
# its lock sit in the state root above it (docs/scheduling.md), so the
|
|
181
215
|
# session listing never mistakes it for a session
|
|
182
216
|
# @param clock [#call] "now", as a Time
|
|
183
|
-
|
|
217
|
+
# @param condition_runner [#call] runs a condition's CMD (ConditionPart::DEFAULT_RUNNER)
|
|
218
|
+
# @param monotonic [#call] seconds, for the time the condition pre-pass took
|
|
219
|
+
def initialize(state_dir: nil, clock: -> { Time.now }, condition_runner: ConditionPart::DEFAULT_RUNNER,
|
|
220
|
+
monotonic: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
|
|
184
221
|
@state_dir = state_dir || Session.default_state_dir
|
|
185
222
|
# ~/.local/state/samagotchi for the default sessions dir; expand_path
|
|
186
223
|
# first so a trailing slash does not make the parent the sessions dir.
|
|
187
224
|
@store_dir = File.dirname(File.expand_path(@state_dir))
|
|
188
225
|
@clock = clock
|
|
226
|
+
@condition_runner = condition_runner
|
|
227
|
+
@monotonic = monotonic
|
|
189
228
|
end
|
|
190
229
|
|
|
191
230
|
attr_reader :state_dir, :store_dir
|
|
@@ -200,24 +239,6 @@ module Samagotchi
|
|
|
200
239
|
include_disabled ? list : list.select(&:enabled)
|
|
201
240
|
end
|
|
202
241
|
|
|
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
242
|
# @param id_or_name [String] an id, a unique prefix of one, or a title
|
|
222
243
|
# @return [Entry, nil]
|
|
223
244
|
# @raise [Usage] the prefix or the title names more than one schedule
|
|
@@ -248,22 +269,18 @@ module Samagotchi
|
|
|
248
269
|
# @return [Entry]
|
|
249
270
|
# @raise [Usage] the add is wrong
|
|
250
271
|
# @raise [Session::NotFound, Session::AmbiguousId] no such session
|
|
272
|
+
# +condition+ is the owner's `--if CMD` (ConditionPart): the CLI's only,
|
|
273
|
+
# never a tool's.
|
|
251
274
|
def add(target:, prompt:, recurrence:, title: nil, mode: CHAIN, catch_up: nil, keep_links: nil,
|
|
252
|
-
max_failures: nil, max_skips: nil)
|
|
275
|
+
max_failures: nil, max_skips: nil, condition: nil)
|
|
253
276
|
raise Usage, "a schedule needs a session to run against" if target.to_s.strip.empty?
|
|
254
277
|
raise Usage, "mode must be one of #{MODES.join(", ")}" unless MODES.include?(mode)
|
|
255
278
|
|
|
256
|
-
|
|
257
|
-
raise Usage, "catch_up must be one of #{CATCH_UP.join(", ")}" unless CATCH_UP.include?(given_catch_up)
|
|
279
|
+
condition = condition.nil? ? nil : condition_for(condition, recurrence)
|
|
258
280
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
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
|
|
281
|
+
given_catch_up = catch_up.nil? || catch_up.to_s.strip.empty? ? Config.get("schedule.default_catch_up") : catch_up.to_s.strip
|
|
282
|
+
validate_catch_up!(given_catch_up)
|
|
283
|
+
prompt = validate_prompt!(prompt)
|
|
267
284
|
|
|
268
285
|
anchor = Session.resolve!(target.to_s, state_dir: @state_dir)
|
|
269
286
|
if Session.load(anchor, state_dir: @state_dir).scratch
|
|
@@ -274,10 +291,7 @@ module Samagotchi
|
|
|
274
291
|
# firing would otherwise multiply the same schedule: the chain keeps one
|
|
275
292
|
# entry per thing it does, and the machine a bounded number of them.
|
|
276
293
|
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
|
|
294
|
+
refuse_duplicate!(same, mode) if same
|
|
281
295
|
|
|
282
296
|
ids = chain_of(anchor)
|
|
283
297
|
in_chain = entries.count { |entry| ids.include?(entry.anchor) || ids.include?(entry.head) }
|
|
@@ -297,14 +311,15 @@ module Samagotchi
|
|
|
297
311
|
max_skips: int_or_default(max_skips, "schedule.default_max_skips", 12, min: 1),
|
|
298
312
|
next_due: next_due_for(recurrence, from: now).utc.iso8601, due_was: nil,
|
|
299
313
|
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,
|
|
314
|
+
pending_turn_id: nil, failures: 0, skips: 0, enabled: true, created_at: now.utc.iso8601,
|
|
315
|
+
disabled_notice: nil, history: [], condition: condition, extra: {}
|
|
301
316
|
)
|
|
302
317
|
write_under_lock { |file| file.entries << entry }
|
|
303
318
|
entry
|
|
304
319
|
end
|
|
305
320
|
|
|
306
321
|
# @return [Entry, nil] nil when no schedule matches
|
|
307
|
-
def cancel(id_or_name) = change(id_or_name, delete: true)
|
|
322
|
+
def cancel(id_or_name) = change(id_or_name, delete: true) || cancel_unreadable(id_or_name)
|
|
308
323
|
def enable(id_or_name) = change(id_or_name, enabled: true)
|
|
309
324
|
def disable(id_or_name) = change(id_or_name, enabled: false)
|
|
310
325
|
|
|
@@ -321,30 +336,25 @@ module Samagotchi
|
|
|
321
336
|
entries(include_disabled: include_disabled).select { |entry| ids.include?(entry.anchor) || ids.include?(entry.head) }
|
|
322
337
|
end
|
|
323
338
|
|
|
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
339
|
# How many enabled schedules one chain may hold, and one machine.
|
|
339
340
|
def per_chain_limit = positive_config("schedule.max_per_session", 10)
|
|
340
341
|
def total_limit = positive_config("schedule.max_total", 50)
|
|
341
342
|
|
|
342
343
|
# One pass over the file: the entries due now, each checked for busy, then
|
|
343
|
-
# advanced and (outside the lock) fired.
|
|
344
|
-
#
|
|
344
|
+
# advanced and (outside the lock) fired. The due conditions run first,
|
|
345
|
+
# before the lock (ConditionPart); `now` moves on by the time they took.
|
|
346
|
+
# @param dry_run [Boolean] report what would fire, change nothing (no CMD runs)
|
|
345
347
|
# @param now [Time] "now"
|
|
348
|
+
# @param cancelled [#call] true: stop the conditions (chi web stopping)
|
|
346
349
|
# @return [Tick]
|
|
347
|
-
def tick(dry_run: false, now: @clock.call)
|
|
350
|
+
def tick(dry_run: false, now: @clock.call, cancelled: -> { false })
|
|
351
|
+
unless dry_run
|
|
352
|
+
started_at = @monotonic.call
|
|
353
|
+
conditions = condition_results(now, cancelled)
|
|
354
|
+
now += @monotonic.call - started_at if conditions
|
|
355
|
+
# chi web stopping: no firing now, which its stop would cut short.
|
|
356
|
+
return Tick.new(locked: false, outcomes: []) if cancelled.call
|
|
357
|
+
end
|
|
348
358
|
outcomes = []
|
|
349
359
|
pending = []
|
|
350
360
|
prune_after = []
|
|
@@ -376,7 +386,7 @@ module Samagotchi
|
|
|
376
386
|
next unless entry.is_a?(Entry)
|
|
377
387
|
|
|
378
388
|
if entry.firing_since && !entry.pending_turn_id && firing_expired?(entry, now)
|
|
379
|
-
interrupted = failed(entry, "interrupted")
|
|
389
|
+
interrupted = failed(entry, "interrupted", now: now)
|
|
380
390
|
interrupted = interrupted.with(enabled: false) if entry.recurrence[:kind] == "date"
|
|
381
391
|
updated[position] = interrupted
|
|
382
392
|
pending_ids << entry.id
|
|
@@ -389,7 +399,7 @@ module Samagotchi
|
|
|
389
399
|
outcome = resolve_pending(entry, now)
|
|
390
400
|
pending_ids << entry.id
|
|
391
401
|
if outcome
|
|
392
|
-
updated[position] = finish_pending(entry, outcome)
|
|
402
|
+
updated[position] = finish_pending(entry, outcome, now: now)
|
|
393
403
|
outcomes << outcome
|
|
394
404
|
if outcome.status == "fired" && entry.mode == CHAIN
|
|
395
405
|
resolved_chains << entry
|
|
@@ -420,11 +430,17 @@ module Samagotchi
|
|
|
420
430
|
pending_chains = in_flight.select { |entry| entry.mode == CHAIN }.map { |entry| chain_key(links, entry) }
|
|
421
431
|
due.each do |entry|
|
|
422
432
|
position = updated.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
|
|
433
|
+
gated = condition_gate(entry, links, conditions, now) unless dry_run
|
|
434
|
+
if gated
|
|
435
|
+
updated[position], outcome = gated
|
|
436
|
+
outcomes << outcome if outcome
|
|
437
|
+
next
|
|
438
|
+
end
|
|
423
439
|
verdict = check(entry, links)
|
|
424
440
|
if verdict
|
|
425
441
|
kind, reason = verdict
|
|
426
442
|
unless dry_run
|
|
427
|
-
updated[position] = kind == :skip ? skipped(entry, reason) : failed(entry, reason)
|
|
443
|
+
updated[position] = kind == :skip ? skipped(entry, reason, now: now) : failed(entry, reason, now: now)
|
|
428
444
|
end
|
|
429
445
|
outcomes << Outcome.new(id: entry.id, title: entry.title, status: kind == :skip ? "skipped" : "failed",
|
|
430
446
|
detail: reason, entry: entry)
|
|
@@ -432,19 +448,20 @@ module Samagotchi
|
|
|
432
448
|
end
|
|
433
449
|
if entry.mode == CHAIN && fired_chains[chain_key(links, entry)]
|
|
434
450
|
reason = "the chain just fired; retry at the next tick"
|
|
435
|
-
updated[position] = skipped(entry, reason) unless dry_run
|
|
451
|
+
updated[position] = skipped(entry, reason, now: now) unless dry_run
|
|
436
452
|
outcomes << Outcome.new(id: entry.id, title: entry.title, status: "skipped", detail: reason, entry: entry)
|
|
437
453
|
next
|
|
438
454
|
end
|
|
439
455
|
if entry.mode == CHAIN && pending_chains.include?(chain_key(links, entry))
|
|
440
456
|
reason = "a schedule turn is still pending in this chain"
|
|
441
|
-
updated[position] = skipped(entry, reason) unless dry_run
|
|
457
|
+
updated[position] = skipped(entry, reason, now: now) unless dry_run
|
|
442
458
|
outcomes << Outcome.new(id: entry.id, title: entry.title, status: "skipped", detail: reason, entry: entry)
|
|
443
459
|
next
|
|
444
460
|
end
|
|
445
461
|
if dry_run
|
|
446
462
|
fired_chains[chain_key(links, entry)] = true if entry.mode == CHAIN
|
|
447
|
-
|
|
463
|
+
detail = entry.condition.nil? ? entry.recurrence_words : "#{entry.recurrence_words} · if #{condition_cmd(entry)} (not run)"
|
|
464
|
+
outcomes << Outcome.new(id: entry.id, title: entry.title, status: "dry", detail: detail, entry: entry)
|
|
448
465
|
next
|
|
449
466
|
end
|
|
450
467
|
if entry.catch_up == "none" && late?(entry, now)
|
|
@@ -461,7 +478,7 @@ module Samagotchi
|
|
|
461
478
|
end
|
|
462
479
|
|
|
463
480
|
pending.each do |entry|
|
|
464
|
-
outcome = fire_and_record(entry, links)
|
|
481
|
+
outcome = fire_and_record(entry, links, now: now)
|
|
465
482
|
outcomes << outcome
|
|
466
483
|
prune_after << outcome.entry if outcome.status == "fired" && entry.mode == CHAIN && entry.keep_links.positive?
|
|
467
484
|
end
|
|
@@ -482,6 +499,7 @@ module Samagotchi
|
|
|
482
499
|
return Outcome.new(id: id_or_name.to_s, status: "failed", detail: "no such schedule") if entry.nil?
|
|
483
500
|
|
|
484
501
|
links = links_now
|
|
502
|
+
now = @clock.call
|
|
485
503
|
reserved = nil
|
|
486
504
|
outcome = nil
|
|
487
505
|
write_under_lock do |file|
|
|
@@ -507,21 +525,21 @@ module Samagotchi
|
|
|
507
525
|
if verdict
|
|
508
526
|
kind, reason = verdict
|
|
509
527
|
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)
|
|
528
|
+
updated = status == "skipped" ? skipped(current, reason, now: now) : failed(current, reason, now: now) if current.enabled
|
|
529
|
+
updated ||= with_history(current.with(last_result: reason), status, reason, at: now, session_id: current.head)
|
|
512
530
|
file.entries[position] = updated
|
|
513
531
|
outcome = Outcome.new(id: current.id, title: current.title, status: status, detail: reason, entry: updated)
|
|
514
532
|
next
|
|
515
533
|
end
|
|
516
534
|
|
|
517
|
-
reserved = advance(current,
|
|
535
|
+
reserved = advance(current, now)
|
|
518
536
|
file.entries[position] = reserved
|
|
519
537
|
end
|
|
520
538
|
|
|
521
539
|
return mark_disabled([outcome], [entry], links: links).first if outcome
|
|
522
540
|
return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "no such schedule") unless reserved
|
|
523
541
|
|
|
524
|
-
mark_disabled([fire_and_record(reserved, links)], [entry], links: links).first
|
|
542
|
+
mark_disabled([fire_and_record(reserved, links, now: now)], [entry], links: links).first
|
|
525
543
|
end
|
|
526
544
|
|
|
527
545
|
# Minutes between the hub's ticks when schedule.auto_tick is on.
|
|
@@ -530,110 +548,6 @@ module Samagotchi
|
|
|
530
548
|
value.positive? ? value : 5
|
|
531
549
|
end
|
|
532
550
|
|
|
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
551
|
private
|
|
638
552
|
|
|
639
553
|
# The chains as they are now, over one session listing (SessionChain::Links):
|
|
@@ -643,8 +557,9 @@ module Samagotchi
|
|
|
643
557
|
|
|
644
558
|
# @param strict [Boolean] a file that is not readable JSON raises rather
|
|
645
559
|
# than reading as empty: a write starting from an empty list would rewrite
|
|
646
|
-
# the file and lose every schedule on it.
|
|
647
|
-
|
|
560
|
+
# the file and lose every schedule on it. #entries stays lenient.
|
|
561
|
+
# @param quiet [Boolean] no log lines (the tick's condition pre-pass: its main pass logs them)
|
|
562
|
+
def read(strict: false, quiet: false)
|
|
648
563
|
return FORMAT.read({}, collection: "schedules") unless File.exist?(path)
|
|
649
564
|
|
|
650
565
|
file = FORMAT.read(JSON.parse(File.read(path)), collection: "schedules")
|
|
@@ -652,14 +567,15 @@ module Samagotchi
|
|
|
652
567
|
if record.readable?
|
|
653
568
|
Entry.from_record(record)
|
|
654
569
|
else
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
570
|
+
unless quiet
|
|
571
|
+
Log.warn(:worker, "schedule_entry_unreadable", id: record.raw.is_a?(Hash) ? record.raw["id"] : nil,
|
|
572
|
+
missing: record.missing.map(&:to_s))
|
|
573
|
+
end
|
|
658
574
|
record
|
|
659
575
|
end
|
|
660
576
|
end)
|
|
661
577
|
rescue JSON::ParserError, StateFormat::InvalidDocument => e
|
|
662
|
-
Log.warn(:worker, "store_unreadable", error: e.class.name, msg: e.message)
|
|
578
|
+
Log.warn(:worker, "store_unreadable", error: e.class.name, msg: e.message) unless quiet
|
|
663
579
|
raise Corrupt, "#{path} is not readable JSON (#{e.message}): fix or remove it before changing schedules" if strict
|
|
664
580
|
|
|
665
581
|
FORMAT.read({}, collection: "schedules")
|
|
@@ -668,7 +584,9 @@ module Samagotchi
|
|
|
668
584
|
def write(file:)
|
|
669
585
|
FileUtils.mkdir_p(@store_dir)
|
|
670
586
|
FileUtils.mkdir_p(@state_dir)
|
|
671
|
-
|
|
587
|
+
# A copy (callers keep file.entries); ConditionPart#hide_next_due.
|
|
588
|
+
stored = file.with(entries: file.entries.map { |entry| entry.is_a?(Entry) ? hide_next_due(entry) : entry })
|
|
589
|
+
body = FORMAT.write(stored, collection: "schedules", updated_at: Time.now.utc.iso8601)
|
|
672
590
|
AtomicFile.write(path, "#{JSON.pretty_generate(body)}\n")
|
|
673
591
|
end
|
|
674
592
|
|
|
@@ -685,35 +603,72 @@ module Samagotchi
|
|
|
685
603
|
end
|
|
686
604
|
|
|
687
605
|
# 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.
|
|
606
|
+
# an ambiguous one raises Usage rather than taking the first match. nil
|
|
607
|
+
# too when the entry is gone by the time the lock is held (another cancel
|
|
608
|
+
# landed in between): the caller says "no schedule", not "ok".
|
|
609
|
+
# @return [Entry, nil] the entry as changed (as removed, for a delete)
|
|
689
610
|
def change(id_or_name, enabled: nil, delete: false)
|
|
690
611
|
entry = lookup(id_or_name)
|
|
691
612
|
return nil if entry.nil?
|
|
692
613
|
|
|
614
|
+
result = nil
|
|
693
615
|
write_under_lock do |file|
|
|
694
616
|
position = file.entries.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
|
|
695
617
|
next if position.nil?
|
|
696
618
|
|
|
697
619
|
if delete
|
|
620
|
+
result = file.entries[position]
|
|
698
621
|
file.entries[position] = nil
|
|
699
622
|
file.entries.compact!
|
|
700
623
|
else
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
624
|
+
stored = file.entries[position]
|
|
625
|
+
word = enabled ? "enabled" : "disabled"
|
|
626
|
+
# The owner's row only for a change: an enable of an enabled entry adds none.
|
|
627
|
+
changed = stored.with(enabled: enabled, last_result: word)
|
|
628
|
+
changed = with_history(changed, word, nil, at: @clock.call) unless stored.enabled == enabled
|
|
629
|
+
# Enabled again with a fresh budget: its next skip must not end it at
|
|
630
|
+
# once, and the turn-off it was disabled by is no news any more.
|
|
631
|
+
result = file.entries[position] = enabled ? changed.with(skips: 0, failures: 0, disabled_notice: nil) : changed
|
|
704
632
|
end
|
|
705
633
|
end
|
|
706
|
-
|
|
634
|
+
result
|
|
707
635
|
end
|
|
708
636
|
|
|
709
|
-
#
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
637
|
+
# The checks a schedule's fields pass, for #add and #edit.
|
|
638
|
+
# @raise [Usage]
|
|
639
|
+
def validate_catch_up!(value)
|
|
640
|
+
raise Usage, "catch_up must be one of #{CATCH_UP.join(", ")}" unless CATCH_UP.include?(value)
|
|
641
|
+
end
|
|
713
642
|
|
|
714
|
-
|
|
643
|
+
# @return [String] the prompt
|
|
644
|
+
# @raise [Usage]
|
|
645
|
+
def validate_prompt!(prompt)
|
|
646
|
+
prompt = prompt.to_s
|
|
647
|
+
raise Usage, "a schedule needs a prompt" if prompt.strip.empty?
|
|
648
|
+
# It fires from a schedule, never a person: a shell line would be
|
|
649
|
+
# refused at every firing (CommandIntake); a /word one is the model's text.
|
|
650
|
+
raise Usage, CommandIntake::REFUSED if CommandIntake.shell_line?(prompt)
|
|
651
|
+
if prompt.bytesize > PROMPT_MAX_BYTES
|
|
652
|
+
raise Usage, "the prompt is #{prompt.bytesize} bytes; the limit is 16 KiB (#{PROMPT_MAX_BYTES} bytes)"
|
|
715
653
|
end
|
|
716
654
|
|
|
655
|
+
prompt
|
|
656
|
+
end
|
|
657
|
+
|
|
658
|
+
# A whole number given for +name+, at least +min+; nil when none was given.
|
|
659
|
+
# @raise [Usage] not a number
|
|
660
|
+
def int_value(value, min:, name:)
|
|
661
|
+
return nil if value.nil? || value.to_s.strip.empty?
|
|
662
|
+
raise Usage, "#{name} must be a number, got #{value.inspect}" unless value.to_s.strip.match?(/\A-?\d+\z/)
|
|
663
|
+
|
|
664
|
+
[value.to_i, min].max
|
|
665
|
+
end
|
|
666
|
+
|
|
667
|
+
# +name+ is what the caller's flag is called, so a bad value says which one.
|
|
668
|
+
def int_or_default(value, key, fallback, min:, name: key.split(".").last)
|
|
669
|
+
given = int_value(value, min: min, name: name)
|
|
670
|
+
return given unless given.nil?
|
|
671
|
+
|
|
717
672
|
configured = Config.get(key)
|
|
718
673
|
configured.to_s.strip.match?(/\A-?\d+\z/) ? [configured.to_i, min].max : fallback
|
|
719
674
|
end
|
|
@@ -774,11 +729,12 @@ module Samagotchi
|
|
|
774
729
|
# is disabled — `late?` never sends a one-off here, but a spent `date` entry
|
|
775
730
|
# arriving from an older file is still spent.
|
|
776
731
|
def reschedule(entry, now)
|
|
732
|
+
missed = with_history(entry, "missed", "past its time", at: now, session_id: entry.head)
|
|
777
733
|
if entry.recurrence[:kind] == "date"
|
|
778
|
-
|
|
734
|
+
missed.with(next_due: nil, last_result: "missed", firing_since: nil, firing_token: nil, enabled: false)
|
|
779
735
|
else
|
|
780
|
-
|
|
781
|
-
|
|
736
|
+
missed.with(next_due: next_due_for(entry.recurrence, from: now).utc.iso8601, last_result: "missed",
|
|
737
|
+
firing_since: nil, firing_token: nil)
|
|
782
738
|
end
|
|
783
739
|
end
|
|
784
740
|
|
|
@@ -797,47 +753,22 @@ module Samagotchi
|
|
|
797
753
|
enabled: one_off ? false : entry.enabled)
|
|
798
754
|
end
|
|
799
755
|
|
|
800
|
-
|
|
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)
|
|
756
|
+
def skipped(entry, reason, now: @clock.call)
|
|
829
757
|
skips = entry.skips + 1
|
|
830
758
|
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
|
-
|
|
833
|
-
|
|
759
|
+
updated = entry.with(skips: skips, firing_since: nil, firing_token: nil, pending_session_id: nil, pending_turn_id: nil,
|
|
760
|
+
last_result: within_budget ? "skipped" : "disabled: #{reason}",
|
|
761
|
+
enabled: within_budget && (entry.enabled || entry.recurrence[:kind] == "date"))
|
|
762
|
+
recorded(entry, updated, "skipped", reason, now)
|
|
834
763
|
end
|
|
835
764
|
|
|
836
|
-
def failed(entry, reason)
|
|
765
|
+
def failed(entry, reason, now: @clock.call)
|
|
837
766
|
failures = entry.failures + 1
|
|
838
767
|
within_budget = failures < entry.max_failures
|
|
839
|
-
entry.with(failures: failures, firing_since: nil, firing_token: nil, pending_session_id: nil,
|
|
840
|
-
|
|
768
|
+
updated = entry.with(failures: failures, firing_since: nil, firing_token: nil, pending_session_id: nil,
|
|
769
|
+
pending_turn_id: nil, last_result: reason,
|
|
770
|
+
enabled: within_budget && (entry.enabled || entry.recurrence[:kind] == "date"))
|
|
771
|
+
recorded(entry, updated, "failed", reason, now)
|
|
841
772
|
end
|
|
842
773
|
|
|
843
774
|
def pending_detail(entry)
|
|
@@ -850,30 +781,27 @@ module Samagotchi
|
|
|
850
781
|
"waiting for turn #{entry.pending_turn_id}"
|
|
851
782
|
end
|
|
852
783
|
|
|
784
|
+
# In this order: the reply (fired), then a question this firing started
|
|
785
|
+
# and the turn has not ended before (waits, or "no outcome" once
|
|
786
|
+
# expired), then the settled turn (fired when it completed), then
|
|
787
|
+
# expiry.
|
|
853
788
|
def resolve_pending(entry, now)
|
|
854
789
|
session = Session.load(entry.pending_session_id, state_dir: @state_dir)
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
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
|
|
790
|
+
result = TurnOutcome.for(session, entry.pending_turn_id,
|
|
791
|
+
session_dir: Session.session_dir(entry.pending_session_id, state_dir: @state_dir))
|
|
792
|
+
return Outcome.new(id: entry.id, title: entry.title, status: "fired", detail: result.detail, entry: entry) if result.replied
|
|
861
793
|
|
|
862
794
|
question = session.pending_question
|
|
863
|
-
if question_started?(question, entry) && !question_after_turn?(question, turn)
|
|
795
|
+
if question_started?(question, entry) && !question_after_turn?(question, result.turn)
|
|
864
796
|
return nil unless pending_expired?(entry, now)
|
|
865
797
|
|
|
866
798
|
return Outcome.new(id: entry.id, title: entry.title, status: "failed",
|
|
867
799
|
detail: "no outcome", entry: entry)
|
|
868
800
|
end
|
|
869
801
|
|
|
870
|
-
if turn
|
|
871
|
-
return Outcome.new(id: entry.id, title: entry.title, status: "fired"
|
|
872
|
-
|
|
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)
|
|
802
|
+
if result.turn
|
|
803
|
+
return Outcome.new(id: entry.id, title: entry.title, status: result.completed? ? "fired" : "failed",
|
|
804
|
+
detail: result.detail, entry: entry)
|
|
877
805
|
end
|
|
878
806
|
|
|
879
807
|
return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "no outcome", entry: entry) if
|
|
@@ -928,12 +856,13 @@ module Samagotchi
|
|
|
928
856
|
PENDING_MAX_SECONDS
|
|
929
857
|
end
|
|
930
858
|
|
|
931
|
-
def finish_pending(entry, outcome)
|
|
859
|
+
def finish_pending(entry, outcome, now: @clock.call)
|
|
932
860
|
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
|
-
|
|
861
|
+
settled = entry.with(firing_since: nil, firing_token: nil, due_was: nil, pending_session_id: nil, pending_turn_id: nil,
|
|
862
|
+
last_result: outcome.detail, failures: 0, skips: 0)
|
|
863
|
+
with_history(settled, "fired", outcome.detail, at: now, session_id: entry.pending_session_id)
|
|
935
864
|
else
|
|
936
|
-
updated = failed(entry, outcome.detail).with(due_was: nil)
|
|
865
|
+
updated = failed(entry, outcome.detail, now: now).with(due_was: nil)
|
|
937
866
|
entry.recurrence[:kind] == "date" ? updated.with(enabled: false) : updated
|
|
938
867
|
end
|
|
939
868
|
end
|
|
@@ -998,103 +927,15 @@ module Samagotchi
|
|
|
998
927
|
target ? links.root(target) : "unresolved:#{entry.id}"
|
|
999
928
|
end
|
|
1000
929
|
|
|
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
930
|
# A firing whose target no longer resolves (#target_of: gone, archived,
|
|
1090
931
|
# or being continued since the tick's check): what #check would say.
|
|
1091
932
|
def unresolved(entry, reason, kind)
|
|
1092
933
|
Outcome.new(id: entry.id, title: entry.title, status: kind == :skip ? "skipped" : "failed", detail: reason, entry: entry)
|
|
1093
934
|
end
|
|
1094
935
|
|
|
1095
|
-
def fire_and_record(entry, links)
|
|
936
|
+
def fire_and_record(entry, links, now: @clock.call)
|
|
1096
937
|
outcome = fire(entry, links)
|
|
1097
|
-
record(entry, outcome)
|
|
938
|
+
record(entry, outcome, now: now)
|
|
1098
939
|
outcome
|
|
1099
940
|
end
|
|
1100
941
|
|
|
@@ -1200,7 +1041,7 @@ module Samagotchi
|
|
|
1200
1041
|
# scheduled occurrence, so there is no occurrence to put the clock back to.
|
|
1201
1042
|
# The result goes back under the lock before any pruning, so a prune that
|
|
1202
1043
|
# raises midway cannot lose the new head.
|
|
1203
|
-
def record(entry, outcome)
|
|
1044
|
+
def record(entry, outcome, now: @clock.call)
|
|
1204
1045
|
write_under_lock do |file|
|
|
1205
1046
|
position = file.entries.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
|
|
1206
1047
|
stored = position && file.entries[position]
|
|
@@ -1220,13 +1061,14 @@ module Samagotchi
|
|
|
1220
1061
|
# skips spread over months do not kill a healthy schedule.
|
|
1221
1062
|
# A `date` schedule is a one-off: `advance` already left it
|
|
1222
1063
|
# 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,
|
|
1224
|
-
|
|
1225
|
-
|
|
1064
|
+
fired = stored.with(head: outcome.entry.head, last_result: outcome.detail, firing_since: nil,
|
|
1065
|
+
firing_token: nil, pending_session_id: nil, pending_turn_id: nil,
|
|
1066
|
+
failures: 0, skips: 0, last_fired: @clock.call.utc.iso8601)
|
|
1067
|
+
with_history(fired, "fired", outcome.detail, at: now, session_id: outcome.entry.head)
|
|
1226
1068
|
when "skipped"
|
|
1227
|
-
skipped(stored, outcome.detail).with(firing_since: nil)
|
|
1069
|
+
skipped(stored, outcome.detail, now: now).with(firing_since: nil)
|
|
1228
1070
|
else
|
|
1229
|
-
failed(stored, outcome.detail)
|
|
1071
|
+
failed(stored, outcome.detail, now: now)
|
|
1230
1072
|
end
|
|
1231
1073
|
|
|
1232
1074
|
# A skip or a failure is "not now", not "late": the occurrence the tick
|
|
@@ -1236,68 +1078,5 @@ module Samagotchi
|
|
|
1236
1078
|
file.entries[position] = updated
|
|
1237
1079
|
end
|
|
1238
1080
|
end
|
|
1239
|
-
|
|
1240
|
-
# The links behind the kept window, with the delegates that hung under
|
|
1241
|
-
# them: archiving a link archives its descendants, and archived sessions
|
|
1242
|
-
# are outside the retention sweep, so the delegate pile is the bulk of the
|
|
1243
|
-
# archived count. Oldest link first, and within a link its children first
|
|
1244
|
-
# (deepest first) and the link last. The walk stops at a link that is not
|
|
1245
|
-
# archived, one whose subtree has a live worker, or one with a descendant
|
|
1246
|
-
# still unarchived: nothing is deleted in that case, and the next firing
|
|
1247
|
-
# retries (a schedule failure it is not). The anchor is never pruned:
|
|
1248
|
-
# `last:<anchor>` must keep resolving, and it is the id the user remembers.
|
|
1249
|
-
def prune(entry, links)
|
|
1250
|
-
chain = []
|
|
1251
|
-
id = entry.head
|
|
1252
|
-
seen = []
|
|
1253
|
-
while id && !seen.include?(id)
|
|
1254
|
-
seen << id
|
|
1255
|
-
chain << id
|
|
1256
|
-
# The walk stops at the anchor: the links before it are the user's own
|
|
1257
|
-
# history, made before this schedule existed, and the anchor itself is
|
|
1258
|
-
# the id `last:<anchor>` and the user remember.
|
|
1259
|
-
break if id == entry.anchor
|
|
1260
|
-
|
|
1261
|
-
# The link a firing just made is not in the tick's listing; every
|
|
1262
|
-
# older one is.
|
|
1263
|
-
session = links.session(id) || (File.exist?(Session.session_file(id, state_dir: @state_dir)) ? Session.load(id, state_dir: @state_dir) : nil)
|
|
1264
|
-
id = session&.continues
|
|
1265
|
-
end
|
|
1266
|
-
older = chain[entry.keep_links..] || []
|
|
1267
|
-
return if older.empty?
|
|
1268
|
-
|
|
1269
|
-
older.reverse_each do |link|
|
|
1270
|
-
next if link == entry.anchor
|
|
1271
|
-
break unless ArchiveStore.archived?(Session.session_dir(link, state_dir: @state_dir))
|
|
1272
|
-
|
|
1273
|
-
tree = SessionManager.delete_tree_ids(link, @state_dir)
|
|
1274
|
-
descendants = tree[0...-1]
|
|
1275
|
-
# The whole subtree must be ready: a live worker anywhere in it, or a
|
|
1276
|
-
# link's descendant that is not archived, stops the walk here rather
|
|
1277
|
-
# than half-deleting a tree.
|
|
1278
|
-
owned = tree.select { |sid| SessionManager.session_owner(sid, state_dir: @state_dir) }
|
|
1279
|
-
unless owned.empty?
|
|
1280
|
-
Log.warn(:worker, "prune_waiting", sid: link, id: entry.id, owned: owned.map { |sid| sid[0, 8] })
|
|
1281
|
-
break
|
|
1282
|
-
end
|
|
1283
|
-
|
|
1284
|
-
open = descendants.reject { |sid| ArchiveStore.archived?(Session.session_dir(sid, state_dir: @state_dir)) }
|
|
1285
|
-
unless open.empty?
|
|
1286
|
-
Log.warn(:worker, "prune_open_children", sid: link, id: entry.id, open: open.map { |sid| sid[0, 8] })
|
|
1287
|
-
break
|
|
1288
|
-
end
|
|
1289
|
-
|
|
1290
|
-
# Children first (deepest first), the link last: if a delete is
|
|
1291
|
-
# refused partway, nothing above it has gone, so the next firing
|
|
1292
|
-
# retries the same set instead of leaving children under a link that
|
|
1293
|
-
# is already deleted.
|
|
1294
|
-
SessionManager.delete_ids(tree, state_dir: @state_dir)
|
|
1295
|
-
Log.info(:worker, "pruned_link", sid: link, id: entry.id, links: descendants.size + 1)
|
|
1296
|
-
end
|
|
1297
|
-
rescue SessionManager::DeleteRefused => e
|
|
1298
|
-
Log.warn(:worker, "prune_stopped", sid: e.session_id, id: entry.id, msg: e.message)
|
|
1299
|
-
rescue Session::NotFound => e
|
|
1300
|
-
Log.warn(:worker, "prune_missing", id: entry.id, msg: e.message)
|
|
1301
|
-
end
|
|
1302
1081
|
end
|
|
1303
1082
|
end
|