samagotchi 0.188.0 → 0.190.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -1
  3. data/docs/architecture.md +9 -4
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +15 -0
  6. data/docs/cli.md +38 -9
  7. data/docs/configuration.md +1 -0
  8. data/docs/guardrails.md +22 -9
  9. data/docs/internals/attached-context.md +4 -1
  10. data/docs/internals/bundles.md +3 -3
  11. data/docs/internals/engine.md +18 -2
  12. data/docs/internals/pages.md +65 -18
  13. data/docs/internals/session-lifecycle.md +19 -6
  14. data/docs/internals/web-frontend.md +3 -3
  15. data/docs/internals/web-push.md +11 -5
  16. data/docs/pages.md +69 -15
  17. data/docs/peers.md +3 -0
  18. data/docs/plugins.md +25 -1
  19. data/docs/releasing.md +1 -1
  20. data/docs/scheduling.md +168 -11
  21. data/docs/sessions.md +4 -4
  22. data/docs/sub-agent.md +1 -1
  23. data/docs/testing.md +1 -1
  24. data/lib/samagotchi/bundle_manifest.rb +34 -5
  25. data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +15 -0
  26. data/lib/samagotchi/bundles/guardrails/manifest.yml +2 -2
  27. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  28. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +169 -0
  29. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  30. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  31. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  32. data/lib/samagotchi/config.rb +2 -0
  33. data/lib/samagotchi/context_fetch.rb +9 -3
  34. data/lib/samagotchi/engine/models.rb +6 -4
  35. data/lib/samagotchi/engine/turn_end.rb +20 -2
  36. data/lib/samagotchi/engine.rb +5 -1
  37. data/lib/samagotchi/failure_line.rb +43 -0
  38. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  39. data/lib/samagotchi/guardrails/chi_dirs.rb +20 -5
  40. data/lib/samagotchi/guardrails/parent_approvals.rb +1 -1
  41. data/lib/samagotchi/guardrails/protected_paths.rb +8 -4
  42. data/lib/samagotchi/guardrails/shell_paths.rb +16 -2
  43. data/lib/samagotchi/guardrails/targets.rb +1 -1
  44. data/lib/samagotchi/guardrails/verdict.rb +5 -3
  45. data/lib/samagotchi/image_store.rb +4 -0
  46. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  47. data/lib/samagotchi/last_turn.rb +2 -1
  48. data/lib/samagotchi/llm/utf8_scrub.rb +26 -0
  49. data/lib/samagotchi/llm_context_view.rb +6 -0
  50. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  51. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  52. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  53. data/lib/samagotchi/model_profile.rb +4 -1
  54. data/lib/samagotchi/page_command.rb +9 -6
  55. data/lib/samagotchi/pages/bundled.rb +83 -0
  56. data/lib/samagotchi/pages/launch.rb +14 -2
  57. data/lib/samagotchi/pages/runner.rb +7 -2
  58. data/lib/samagotchi/pages/runtime.rb +84 -0
  59. data/lib/samagotchi/pages/store.rb +18 -5
  60. data/lib/samagotchi/pages.rb +47 -3
  61. data/lib/samagotchi/peer_continue.rb +14 -8
  62. data/lib/samagotchi/reply_wait.rb +1 -1
  63. data/lib/samagotchi/run_options.rb +1 -1
  64. data/lib/samagotchi/schedule_command.rb +175 -39
  65. data/lib/samagotchi/schedule_display.rb +85 -0
  66. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  67. data/lib/samagotchi/schedules/condition_part.rb +312 -0
  68. data/lib/samagotchi/schedules/edit_part.rb +144 -0
  69. data/lib/samagotchi/schedules/history_part.rb +51 -0
  70. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  71. data/lib/samagotchi/schedules/notices_part.rb +122 -0
  72. data/lib/samagotchi/schedules/protection_part.rb +113 -0
  73. data/lib/samagotchi/schedules/prune_part.rb +79 -0
  74. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  75. data/lib/samagotchi/schedules.rb +188 -409
  76. data/lib/samagotchi/session_access/local.rb +9 -1
  77. data/lib/samagotchi/session_access/remote.rb +2 -1
  78. data/lib/samagotchi/session_chain/delete.rb +7 -5
  79. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  80. data/lib/samagotchi/session_lifecycle.rb +3 -2
  81. data/lib/samagotchi/session_manager/removal.rb +16 -9
  82. data/lib/samagotchi/session_protection.rb +99 -0
  83. data/lib/samagotchi/session_retention.rb +21 -6
  84. data/lib/samagotchi/sessions_command.rb +4 -0
  85. data/lib/samagotchi/system_one/self_protect.rb +4 -2
  86. data/lib/samagotchi/testing/boundary.rb +13 -0
  87. data/lib/samagotchi/tools/cancel_schedule.rb +32 -4
  88. data/lib/samagotchi/tools/execute.rb +5 -1
  89. data/lib/samagotchi/tools/list_schedules.rb +1 -0
  90. data/lib/samagotchi/tools/task_runtime.rb +6 -0
  91. data/lib/samagotchi/turn_endings.rb +14 -2
  92. data/lib/samagotchi/turn_flow.rb +2 -1
  93. data/lib/samagotchi/turn_outcome.rb +41 -0
  94. data/lib/samagotchi/version.rb +1 -1
  95. data/lib/samagotchi/web/page_routes.rb +13 -8
  96. data/lib/samagotchi/web/public/app.js +12 -18
  97. data/lib/samagotchi/web/public/index.html +11 -2
  98. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  99. data/lib/samagotchi/web/public/page_links.js +1 -1
  100. data/lib/samagotchi/web/public/page_view.js +8 -5
  101. data/lib/samagotchi/web/public/pages.css +9 -2
  102. data/lib/samagotchi/web/public/pages_group.js +21 -19
  103. data/lib/samagotchi/web/public/pages_list.js +73 -0
  104. data/lib/samagotchi/web/public/pages_model.js +54 -0
  105. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  106. data/lib/samagotchi/web/public/stream_handlers.js +8 -0
  107. data/lib/samagotchi/web/public/views.js +77 -23
  108. data/lib/samagotchi/web/push/notifier.rb +4 -3
  109. data/lib/samagotchi/web/server.rb +3 -1
  110. data/lib/samagotchi/web/session_hub.rb +75 -19
  111. data/lib/samagotchi/worker.rb +6 -4
  112. metadata +20 -1
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "time"
5
+
6
+ module Samagotchi
7
+ class Schedules
8
+ # The disabled notice (docs/scheduling.md): a recurring schedule a ticker
9
+ # turned off by its budget carries {kind:, count:, reason:, at:} in
10
+ # `disabled_notice` until a chi web claims it and pushes it. Set by
11
+ # #skipped / #failed, whatever ran them (a cron tick, a run-now, chi
12
+ # web's own tick); claimed by SessionHub#publish_disabled.
13
+ module NoticesPart
14
+ # The disabled notices whatever ticker set them (#skipped / #failed: a
15
+ # cron `chi schedule tick`, a `run-now`, chi web's own tick), each cleared
16
+ # here and returned once, for chi web's hub to push (SessionHub
17
+ # #publish_disabled). A lock-free read first: with no notice (the usual
18
+ # case) nothing is locked or written. Then the lock, non-blocking: a tick
19
+ # can hold it for seconds through its busy checks, and the hub's scan must
20
+ # not wait; [] then, and the next pass retries. The notices are cleared
21
+ # before the hub emits them (at most once): the Notifier dedupes only
22
+ # within its own process, so two chi webs on one state dir must not both
23
+ # get the same notice; a crash between the clear and the push loses one
24
+ # push, never sends two. An entry enabled again since (an older chi's
25
+ # `enable` keeps the notice) and a notice older than NOTICE_MAX_AGE are
26
+ # cleared without being returned.
27
+ # @param now [Time]
28
+ # @param on_lock_held [#call, nil] called when there were notices but
29
+ # the lock was held (the [] then is "not now", not "none": the hub
30
+ # retries at its next scan, SessionHub#claim_disabled_if_due)
31
+ # @return [Array<Hash>] {id:, title:, kind:, count:, reason:, session_id:, at:}
32
+ # @raise [Corrupt] the file stopped being readable JSON
33
+ def claim_disabled_notices(now: @clock.call, on_lock_held: nil)
34
+ return [] unless read.entries.any? { |entry| entry.is_a?(Entry) && entry.disabled_notice }
35
+
36
+ claimed = []
37
+ FileUtils.mkdir_p(@store_dir)
38
+ File.open(lock_path, File::RDWR | File::CREAT, 0o600) do |lock|
39
+ unless lock.flock(File::LOCK_EX | File::LOCK_NB)
40
+ on_lock_held&.call
41
+ return []
42
+ end
43
+
44
+ file = read(strict: true)
45
+ links = nil
46
+ cleared = false
47
+ file.entries.each_with_index do |entry, position|
48
+ next unless entry.is_a?(Entry) && entry.disabled_notice
49
+
50
+ notice = entry.disabled_notice
51
+ file.entries[position] = entry.with(disabled_notice: nil)
52
+ cleared = true
53
+ next if entry.enabled || notice_stale?(notice, now)
54
+
55
+ links ||= links_now
56
+ claimed << { id: entry.id, title: entry.title, kind: notice[:kind], count: notice[:count],
57
+ reason: notice[:reason], session_id: target_of(entry, links).first || entry.head,
58
+ at: notice[:at] }
59
+ end
60
+ write(file: file) if cleared
61
+ end
62
+ claimed
63
+ end
64
+
65
+ private
66
+
67
+ # The skips and failures that turned off a recurring entry that was on when
68
+ # the pass began (+before+), as the file has it now: one diff covers every
69
+ # path that records one. A `date` one-off is spent, not disabled; an entry
70
+ # off within budget is an owner's `chi schedule disable`. The same rule
71
+ # (#budget_turned_off?) sets the entry's disabled notice; this cannot read
72
+ # that notice back, since a chi web may have claimed it by now.
73
+ def mark_disabled(outcomes, before, links: nil)
74
+ status_by_id = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }
75
+ .to_h { |outcome| [outcome.id, outcome.status] }
76
+ on = before.select { |entry| status_by_id.key?(entry.id) }.to_h { |entry| [entry.id, entry] }
77
+ return outcomes if on.empty?
78
+
79
+ off = read.entries.grep(Entry).select do |entry|
80
+ on.key?(entry.id) && budget_turned_off?(on[entry.id], entry, status_by_id[entry.id])
81
+ end
82
+ links ||= links_now unless off.empty?
83
+ off.each do |entry|
84
+ index = outcomes.rindex { |outcome| outcome.id == entry.id && %w[skipped failed].include?(outcome.status) }
85
+ session_id = target_of(entry, links).first || entry.head
86
+ outcomes[index] = outcomes[index].with(disabled: true, entry: entry, session_id: session_id)
87
+ end
88
+ outcomes
89
+ end
90
+
91
+ # "This skip or failure turned the entry off by its budget": +before+ was a
92
+ # recurring entry that was on, +after+ is off with the +status+'s counter
93
+ # at its budget. A `date` one-off is spent, not disabled; an entry off
94
+ # within budget is an owner's disable. #skipped / #failed set the
95
+ # disabled notice on it, #mark_disabled the CLI's `(disabled)`.
96
+ def budget_turned_off?(before, after, status)
97
+ return false unless before.enabled && before.recurrence[:kind] != "date" && !after.enabled
98
+
99
+ case status
100
+ when "skipped" then after.skips >= after.max_skips
101
+ when "failed" then after.failures >= after.max_failures
102
+ else false
103
+ end
104
+ end
105
+
106
+ # The notice a chi web pushes for a budget turn-off (#claim_disabled_notices),
107
+ # when this +status+ call turned +before+ off; +after+ unchanged otherwise.
108
+ def with_disabled_notice(before, after, status, reason, now)
109
+ return after unless budget_turned_off?(before, after, status)
110
+
111
+ count = status == "skipped" ? after.skips : after.failures
112
+ after.with(disabled_notice: { kind: status, count: count, reason: reason, at: now.utc.iso8601 })
113
+ end
114
+
115
+ def notice_stale?(notice, now)
116
+ Time.iso8601(notice[:at].to_s) + NOTICE_MAX_AGE < now
117
+ rescue ArgumentError
118
+ true
119
+ end
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../session_protection"
5
+ require_relative "../state_format"
6
+
7
+ module Samagotchi
8
+ class Schedules
9
+ # Schedules as a SessionProtection protector: an enabled schedule holds
10
+ # its anchor, its head and its resolved target (#target_of). A disabled
11
+ # one holds nothing. The file is read strict (#protection_entries): one
12
+ # that is there but doesn't read, or holds an entry that doesn't, raises
13
+ # SessionProtection::Unreadable (the tick and the other readers keep
14
+ # their own rules; chi schedule cancel ID drops such an entry,
15
+ # #cancel_unreadable). A missing file holds nothing.
16
+ module ProtectionPart
17
+ # @return [Array<String>] the ids retention keeps
18
+ def protected_ids
19
+ links = links_now
20
+ protection_entries.flat_map { |entry| [entry.anchor, entry.head, target_of(entry, links).first] }.compact.uniq
21
+ end
22
+
23
+ # The enabled schedule a delete of +session_id+ would break: one whose
24
+ # anchor or head it is, else one whose target (#protecting) it is. A
25
+ # head deleted would make the schedule fall back to its anchor (an
26
+ # archived link) and fail.
27
+ # @return [SessionProtection::Hold, nil] reason :scheduled
28
+ def hold(session_id)
29
+ list = protection_entries
30
+ entry = list.find { |candidate| candidate.anchor == session_id || candidate.head == session_id } ||
31
+ protecting(session_id, list)
32
+ entry && SessionProtection::Hold.new(session_id: session_id, reason: :scheduled, ref: entry.id)
33
+ end
34
+
35
+ # The first enabled schedule on the chain +session_id+ belongs to (as
36
+ # #for_chain: its anchor or head a link of it), which a chain's delete
37
+ # would take.
38
+ # @return [SessionProtection::Hold, nil] reason :chain_scheduled
39
+ def chain_hold(session_id)
40
+ ids = chain_of(session_id)
41
+ entry = protection_entries.find { |candidate| ids.include?(candidate.anchor) || ids.include?(candidate.head) }
42
+ entry && SessionProtection::Hold.new(session_id: session_id, reason: :chain_scheduled, ref: entry.id)
43
+ end
44
+
45
+ # The stored fields of the record #read keeps but can't read whose id
46
+ # is exactly +id+ (lenient read: what chi schedule cancel ID drops,
47
+ # #cancel_unreadable), for a caller that must look before it cancels
48
+ # (the cancel_schedule tool's chain check). nil when there is none.
49
+ # @return [Hash, nil]
50
+ def unreadable_record(id)
51
+ record = read.entries.find { |entry| !entry.is_a?(Entry) && entry.raw.is_a?(Hash) && entry.raw["id"] == id }
52
+ record&.raw
53
+ end
54
+
55
+ private
56
+
57
+ def protecting(session_id, list)
58
+ links = links_now
59
+ list.find { |entry| target_of(entry, links).first == session_id }
60
+ end
61
+
62
+ # The enabled entries, the earliest due first (as #entries), from a
63
+ # strict read of its own: no log line (the caller logs the refusal
64
+ # once), a `schedules` member that isn't a list, a file chi can't open
65
+ # (permissions, a directory) and one entry that doesn't read are all
66
+ # Unreadable. A missing file holds nothing.
67
+ # @raise [SessionProtection::Unreadable]
68
+ def protection_entries
69
+ return [] unless File.exist?(path)
70
+
71
+ raw = JSON.parse(File.read(path))
72
+ if raw.is_a?(Hash) && raw.key?("schedules") && !raw["schedules"].is_a?(Array)
73
+ raise StateFormat::InvalidDocument, "schedules must be a list"
74
+ end
75
+
76
+ records = FORMAT.read(raw, collection: "schedules").entries
77
+ bad = records.find { |record| !record.readable? }
78
+ raise unreadable_entry(bad) if bad
79
+
80
+ records.map { |record| Entry.from_record(record) }.select(&:enabled).sort_by { |entry| [entry.next_due.to_s, entry.id] }
81
+ rescue JSON::ParserError, StateFormat::InvalidDocument, SystemCallError => e
82
+ raise SessionProtection::Unreadable.new(FILE, e.message)
83
+ end
84
+
85
+ # One entry that doesn't read: named by its id when it has one, so
86
+ # chi schedule cancel can drop it (#cancel_unreadable).
87
+ def unreadable_entry(record)
88
+ id = record.raw.is_a?(Hash) ? record.raw["id"] : nil
89
+ lacks = "lacks #{record.missing.join(", ")}"
90
+ return SessionProtection::Unreadable.new(FILE, lacks, entry: id) if id.is_a?(String) && !id.empty?
91
+
92
+ SessionProtection::Unreadable.new(FILE, "a schedule without an id #{lacks}")
93
+ end
94
+
95
+ # chi schedule cancel ID of a record #read keeps but can't read (#entries
96
+ # and #lookup never see it): removed by its exact id, under the lock,
97
+ # the way out of an Unreadable hold. nil when there is none.
98
+ def cancel_unreadable(id)
99
+ unreadable = ->(record) { !record.is_a?(Entry) && record.raw.is_a?(Hash) && record.raw["id"] == id }
100
+ # The lenient read first: a store that isn't JSON has no such record
101
+ # and stays as it is (no strict read, no rewrite).
102
+ return nil unless read.entries.any?(&unreadable)
103
+
104
+ removed = nil
105
+ write_under_lock do |file|
106
+ removed = file.entries.find(&unreadable)
107
+ file.entries.delete(removed) if removed
108
+ end
109
+ removed
110
+ end
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../archive_store"
4
+ require_relative "../log"
5
+ require_relative "../session"
6
+ require_relative "../session_manager"
7
+
8
+ module Samagotchi
9
+ class Schedules
10
+ # The chain prune after a firing (docs/scheduling.md, "Keeping the chain
11
+ # short"): the links behind a chain entry's keep_links window go.
12
+ module PrunePart
13
+ private
14
+
15
+ # The links behind the kept window, with the delegates that hung under
16
+ # them: archiving a link archives its descendants, and archived sessions
17
+ # are outside the retention sweep, so the delegate pile is the bulk of the
18
+ # archived count. Oldest link first, and within a link its children first
19
+ # (deepest first) and the link last. The walk stops at a link that is not
20
+ # archived, one whose subtree has a live worker, or one with a descendant
21
+ # still unarchived: nothing is deleted in that case, and the next firing
22
+ # retries (a schedule failure it is not). The anchor is never pruned:
23
+ # `last:<anchor>` must keep resolving, and it is the id the user remembers.
24
+ def prune(entry, links)
25
+ chain = []
26
+ id = entry.head
27
+ seen = []
28
+ while id && !seen.include?(id)
29
+ seen << id
30
+ chain << id
31
+ # The walk stops at the anchor: the links before it are the user's own
32
+ # history, made before this schedule existed, and the anchor itself is
33
+ # the id `last:<anchor>` and the user remember.
34
+ break if id == entry.anchor
35
+
36
+ # The link a firing just made is not in the tick's listing; every
37
+ # older one is.
38
+ session = links.session(id) || (File.exist?(Session.session_file(id, state_dir: @state_dir)) ? Session.load(id, state_dir: @state_dir) : nil)
39
+ id = session&.continues
40
+ end
41
+ older = chain[entry.keep_links..] || []
42
+ return if older.empty?
43
+
44
+ older.reverse_each do |link|
45
+ next if link == entry.anchor
46
+ break unless ArchiveStore.archived?(Session.session_dir(link, state_dir: @state_dir))
47
+
48
+ tree = SessionManager.delete_tree_ids(link, @state_dir)
49
+ descendants = tree[0...-1]
50
+ # The whole subtree must be ready: a live worker anywhere in it, or a
51
+ # link's descendant that is not archived, stops the walk here rather
52
+ # than half-deleting a tree.
53
+ owned = tree.select { |sid| SessionManager.session_owner(sid, state_dir: @state_dir) }
54
+ unless owned.empty?
55
+ Log.warn(:worker, "prune_waiting", sid: link, id: entry.id, owned: owned.map { |sid| sid[0, 8] })
56
+ break
57
+ end
58
+
59
+ open = descendants.reject { |sid| ArchiveStore.archived?(Session.session_dir(sid, state_dir: @state_dir)) }
60
+ unless open.empty?
61
+ Log.warn(:worker, "prune_open_children", sid: link, id: entry.id, open: open.map { |sid| sid[0, 8] })
62
+ break
63
+ end
64
+
65
+ # Children first (deepest first), the link last: if a delete is
66
+ # refused partway, nothing above it has gone, so the next firing
67
+ # retries the same set instead of leaving children under a link that
68
+ # is already deleted.
69
+ SessionManager.delete_ids(tree, state_dir: @state_dir)
70
+ Log.info(:worker, "pruned_link", sid: link, id: entry.id, links: descendants.size + 1)
71
+ end
72
+ rescue SessionManager::DeleteRefused => e
73
+ Log.warn(:worker, "prune_stopped", sid: e.session_id, id: entry.id, msg: e.message)
74
+ rescue Session::NotFound => e
75
+ Log.warn(:worker, "prune_missing", id: entry.id, msg: e.message)
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "time"
5
+
6
+ module Samagotchi
7
+ class Schedules
8
+ # The recurrence parsing (docs/scheduling.md, Recurrence): the class
9
+ # methods `chi schedule add` and the schedule tools build a
10
+ # recurrence with, and the local-clock helpers the next-due math uses.
11
+ # They raise Schedules::Usage (schedules.rb).
12
+
13
+ # A recurrence from the CLI's flags or the tool's arguments. Blank strings
14
+ # (what a model sends for the fields it did not use) count as absent.
15
+ # @return [Hash] {kind:, ...}
16
+ # @raise [Usage] none or more than one kind given, or an interval that is
17
+ # not a positive amount of time
18
+ def self.recurrence(every: nil, weekday: nil, time: nil, date: nil)
19
+ every = nil if every.to_s.strip.empty?
20
+ weekday = nil if weekday.to_s.strip.empty?
21
+ time = nil if time.to_s.strip.empty?
22
+ date = nil if date.to_s.strip.empty?
23
+
24
+ kinds = [every, weekday, date].compact
25
+ raise Usage, "a schedule needs one of every, weekday or date" if kinds.empty?
26
+ raise Usage, "give one of every, weekday or date, not more" if kinds.size > 1
27
+
28
+ if every
29
+ raise Usage, "time is only for a weekday schedule" if time && !weekday
30
+
31
+ interval = every.to_s.strip
32
+ raise Usage, "every needs an interval like 30m, 2h or 1d, got #{every}" unless interval.match?(/\A\d+[smhd]?\z/)
33
+
34
+ seconds = interval_seconds(interval)
35
+ raise Usage, "every must be at least 1s, got #{every}" if seconds.nil? || seconds.zero?
36
+
37
+ { kind: "every", interval: interval }
38
+ elsif weekday
39
+ raise Usage, "weekday needs time HH:MM" if time.nil?
40
+
41
+ day = weekday.to_s.strip
42
+ raise Usage, "weekday must be 1 (Mon) to 7 (Sun), got #{weekday}" unless day.match?(/\A[1-7]\z/)
43
+
44
+ { kind: "weekday", weekday: day.to_i, time: time.to_s.strip }
45
+ else
46
+ { kind: "date", at: local_moment(*parse_local(date)).utc.iso8601 }
47
+ end
48
+ end
49
+
50
+ # The length of an interval in seconds; nil for something that is not an
51
+ # interval, and nil for zero so a `0m` schedule can never fire every tick.
52
+ def self.interval_seconds(interval)
53
+ match = interval.to_s.strip.match(/\A(\d+)(s|m|h|d)?\z/)
54
+ return nil unless match
55
+
56
+ seconds = { "s" => 1, "m" => 60, "h" => 3600, "d" => 86_400, nil => 60 }[match[2]] * match[1].to_i
57
+ seconds.positive? ? seconds : nil
58
+ end
59
+
60
+ def self.parse_clock(time)
61
+ match = time.to_s.strip.match(/\A(\d{1,2}):(\d{1,2})\z/)
62
+ raise Usage, "time must be HH:MM, got #{time}" unless match
63
+
64
+ hour = match[1].to_i
65
+ minute = match[2].to_i
66
+ raise Usage, "time must be HH:MM, got #{time}" unless (0..23).cover?(hour) && (0..59).cover?(minute)
67
+
68
+ [hour, minute]
69
+ end
70
+
71
+ def self.parse_local(text)
72
+ match = text.to_s.strip.match(/\A(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{1,2}):(\d{2}))?\z/)
73
+ raise Usage, "date must be YYYY-MM-DD or YYYY-MM-DDTHH:MM, got #{text}" unless match
74
+
75
+ year = match[1].to_i
76
+ month = match[2].to_i
77
+ day = match[3].to_i
78
+ hour = match[4] ? match[4].to_i : 0
79
+ minute = match[5] ? match[5].to_i : 0
80
+ unless Date.valid_date?(year, month, day) && (0..23).cover?(hour) && (0..59).cover?(minute)
81
+ raise Usage, "date must be a real date, got #{text}"
82
+ end
83
+
84
+ [year, month, day, hour, minute]
85
+ end
86
+
87
+ # A local moment that exists. When the requested minute falls in a
88
+ # spring-forward gap, the first valid minute whose wall clock is at or
89
+ # after it.
90
+ def self.local_moment(year, month, day, hour, minute)
91
+ moment = Time.local(year, month, day, hour, minute)
92
+ return moment if moment.hour == hour && moment.min == minute
93
+
94
+ wanted = (hour * 60) + minute
95
+ day_start = Time.local(year, month, day, 0, 0)
96
+ 1440.times do |step|
97
+ probe = day_start + (step * 60)
98
+ return probe if (probe.hour * 60) + probe.min >= wanted
99
+ end
100
+ moment
101
+ end
102
+ end
103
+ end