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
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+ require_relative "../config"
5
+
6
+ module Samagotchi
7
+ class Schedules
8
+ # What a reader is told of the store without changing it: the tick
9
+ # warning (`chi schedule list`, `add`) and #listing (Pages::Runtime's
10
+ # one read).
11
+ module ListingPart
12
+ # The warning `chi schedule` prints when nothing ticks (auto_tick off and
13
+ # no tick in two intervals), nil when something does.
14
+ def tick_warning(now: @clock.call) = tick_warning_for(read.attributes[:last_tick_at], now)
15
+
16
+ # Every schedule as the file holds it now, for a reader that shows them
17
+ # (Pages::Runtime#schedules): one strict read, no lock, no write, and no
18
+ # notice claimed (#claim_disabled_notices is chi web's). +entries+ the
19
+ # readable ones, the earliest due first (as #entries with
20
+ # include_disabled); +unreadable_ids+ the id of each entry that doesn't
21
+ # read (nil for one with none); +warning+ #tick_warning's text, from the
22
+ # same read.
23
+ Listing = Data.define(:entries, :unreadable_ids, :warning)
24
+
25
+ # @return [Listing]
26
+ # @raise [Corrupt] schedules.json isn't readable JSON (#entries reads it
27
+ # as no schedules)
28
+ def listing(now: @clock.call)
29
+ file = read(strict: true)
30
+ entries = file.entries.grep(Entry).sort_by { |entry| [entry.next_due.to_s, entry.id] }
31
+ unreadable = file.entries.grep_v(Entry).map { |record| record.raw.is_a?(Hash) ? record.raw["id"]&.to_s : nil }
32
+ Listing.new(entries: entries, unreadable_ids: unreadable, warning: tick_warning_for(file.attributes[:last_tick_at], now))
33
+ end
34
+
35
+ private
36
+
37
+ # #tick_warning's rule, given the file's last_tick_at.
38
+ def tick_warning_for(last_tick_at, now)
39
+ return if Config.get("schedule.auto_tick")
40
+
41
+ stale_after = self.class.tick_interval_minutes * 120
42
+ return if last_tick_at && now - Time.iso8601(last_tick_at.to_s) <= stale_after
43
+
44
+ "Warning: no schedule tick in the last #{stale_after / 60} minutes; set schedule.auto_tick: true or " \
45
+ "run `chi schedule tick` from cron."
46
+ rescue ArgumentError
47
+ "Warning: no schedule tick in the last #{self.class.tick_interval_minutes * 2} minutes; " \
48
+ "set schedule.auto_tick: true or run `chi schedule tick` from cron."
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,116 @@
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
+ # @return [Array<Hash>] {id:, title:, kind:, count:, reason:, session_id:, at:}
29
+ # @raise [Corrupt] the file stopped being readable JSON
30
+ def claim_disabled_notices(now: @clock.call)
31
+ return [] unless read.entries.any? { |entry| entry.is_a?(Entry) && entry.disabled_notice }
32
+
33
+ claimed = []
34
+ FileUtils.mkdir_p(@store_dir)
35
+ File.open(lock_path, File::RDWR | File::CREAT, 0o600) do |lock|
36
+ return [] unless lock.flock(File::LOCK_EX | File::LOCK_NB)
37
+
38
+ file = read(strict: true)
39
+ links = nil
40
+ cleared = false
41
+ file.entries.each_with_index do |entry, position|
42
+ next unless entry.is_a?(Entry) && entry.disabled_notice
43
+
44
+ notice = entry.disabled_notice
45
+ file.entries[position] = entry.with(disabled_notice: nil)
46
+ cleared = true
47
+ next if entry.enabled || notice_stale?(notice, now)
48
+
49
+ links ||= links_now
50
+ claimed << { id: entry.id, title: entry.title, kind: notice[:kind], count: notice[:count],
51
+ reason: notice[:reason], session_id: target_of(entry, links).first || entry.head,
52
+ at: notice[:at] }
53
+ end
54
+ write(file: file) if cleared
55
+ end
56
+ claimed
57
+ end
58
+
59
+ private
60
+
61
+ # The skips and failures that turned off a recurring entry that was on when
62
+ # the pass began (+before+), as the file has it now: one diff covers every
63
+ # path that records one. A `date` one-off is spent, not disabled; an entry
64
+ # off within budget is an owner's `chi schedule disable`. The same rule
65
+ # (#budget_turned_off?) sets the entry's disabled notice; this cannot read
66
+ # that notice back, since a chi web may have claimed it by now.
67
+ def mark_disabled(outcomes, before, links: nil)
68
+ status_by_id = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }
69
+ .to_h { |outcome| [outcome.id, outcome.status] }
70
+ on = before.select { |entry| status_by_id.key?(entry.id) }.to_h { |entry| [entry.id, entry] }
71
+ return outcomes if on.empty?
72
+
73
+ off = read.entries.grep(Entry).select do |entry|
74
+ on.key?(entry.id) && budget_turned_off?(on[entry.id], entry, status_by_id[entry.id])
75
+ end
76
+ links ||= links_now unless off.empty?
77
+ off.each do |entry|
78
+ index = outcomes.rindex { |outcome| outcome.id == entry.id && %w[skipped failed].include?(outcome.status) }
79
+ session_id = target_of(entry, links).first || entry.head
80
+ outcomes[index] = outcomes[index].with(disabled: true, entry: entry, session_id: session_id)
81
+ end
82
+ outcomes
83
+ end
84
+
85
+ # "This skip or failure turned the entry off by its budget": +before+ was a
86
+ # recurring entry that was on, +after+ is off with the +status+'s counter
87
+ # at its budget. A `date` one-off is spent, not disabled; an entry off
88
+ # within budget is an owner's disable. #skipped / #failed set the
89
+ # disabled notice on it, #mark_disabled the CLI's `(disabled)`.
90
+ def budget_turned_off?(before, after, status)
91
+ return false unless before.enabled && before.recurrence[:kind] != "date" && !after.enabled
92
+
93
+ case status
94
+ when "skipped" then after.skips >= after.max_skips
95
+ when "failed" then after.failures >= after.max_failures
96
+ else false
97
+ end
98
+ end
99
+
100
+ # The notice a chi web pushes for a budget turn-off (#claim_disabled_notices),
101
+ # when this +status+ call turned +before+ off; +after+ unchanged otherwise.
102
+ def with_disabled_notice(before, after, status, reason, now)
103
+ return after unless budget_turned_off?(before, after, status)
104
+
105
+ count = status == "skipped" ? after.skips : after.failures
106
+ after.with(disabled_notice: { kind: status, count: count, reason: reason, at: now.utc.iso8601 })
107
+ end
108
+
109
+ def notice_stale?(notice, now)
110
+ Time.iso8601(notice[:at].to_s) + NOTICE_MAX_AGE < now
111
+ rescue ArgumentError
112
+ true
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,103 @@
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
+ private
46
+
47
+ def protecting(session_id, list)
48
+ links = links_now
49
+ list.find { |entry| target_of(entry, links).first == session_id }
50
+ end
51
+
52
+ # The enabled entries, the earliest due first (as #entries), from a
53
+ # strict read of its own: no log line (the caller logs the refusal
54
+ # once), a `schedules` member that isn't a list, a file chi can't open
55
+ # (permissions, a directory) and one entry that doesn't read are all
56
+ # Unreadable. A missing file holds nothing.
57
+ # @raise [SessionProtection::Unreadable]
58
+ def protection_entries
59
+ return [] unless File.exist?(path)
60
+
61
+ raw = JSON.parse(File.read(path))
62
+ if raw.is_a?(Hash) && raw.key?("schedules") && !raw["schedules"].is_a?(Array)
63
+ raise StateFormat::InvalidDocument, "schedules must be a list"
64
+ end
65
+
66
+ records = FORMAT.read(raw, collection: "schedules").entries
67
+ bad = records.find { |record| !record.readable? }
68
+ raise unreadable_entry(bad) if bad
69
+
70
+ records.map { |record| Entry.from_record(record) }.select(&:enabled).sort_by { |entry| [entry.next_due.to_s, entry.id] }
71
+ rescue JSON::ParserError, StateFormat::InvalidDocument, SystemCallError => e
72
+ raise SessionProtection::Unreadable.new(FILE, e.message)
73
+ end
74
+
75
+ # One entry that doesn't read: named by its id when it has one, so
76
+ # chi schedule cancel can drop it (#cancel_unreadable).
77
+ def unreadable_entry(record)
78
+ id = record.raw.is_a?(Hash) ? record.raw["id"] : nil
79
+ lacks = "lacks #{record.missing.join(", ")}"
80
+ return SessionProtection::Unreadable.new(FILE, lacks, entry: id) if id.is_a?(String) && !id.empty?
81
+
82
+ SessionProtection::Unreadable.new(FILE, "a schedule without an id #{lacks}")
83
+ end
84
+
85
+ # chi schedule cancel ID of a record #read keeps but can't read (#entries
86
+ # and #lookup never see it): removed by its exact id, under the lock,
87
+ # the way out of an Unreadable hold. nil when there is none.
88
+ def cancel_unreadable(id)
89
+ unreadable = ->(record) { !record.is_a?(Entry) && record.raw.is_a?(Hash) && record.raw["id"] == id }
90
+ # The lenient read first: a store that isn't JSON has no such record
91
+ # and stays as it is (no strict read, no rewrite).
92
+ return nil unless read.entries.any?(&unreadable)
93
+
94
+ removed = nil
95
+ write_under_lock do |file|
96
+ removed = file.entries.find(&unreadable)
97
+ file.entries.delete(removed) if removed
98
+ end
99
+ removed
100
+ end
101
+ end
102
+ end
103
+ 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