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
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "shellwords"
|
|
4
|
+
require "time"
|
|
5
|
+
require_relative "../config"
|
|
6
|
+
require_relative "../git_env"
|
|
7
|
+
require_relative "../log"
|
|
8
|
+
require_relative "../session"
|
|
9
|
+
require_relative "../spawn_env"
|
|
10
|
+
|
|
11
|
+
module Samagotchi
|
|
12
|
+
class Schedules
|
|
13
|
+
# A schedule's condition (docs/scheduling.md, "Conditions (--if)"): the
|
|
14
|
+
# owner's `chi schedule add|edit --if CMD`, stored as
|
|
15
|
+
# {cmd:, by: "cli", set_at:}. Only the CLI sets one: no tool declares it,
|
|
16
|
+
# and the guardrails keep the model's shell and file tools from setting
|
|
17
|
+
# it (the chi-schedule-if rule, schedules.json a protected path).
|
|
18
|
+
#
|
|
19
|
+
# An older chi (0.189.0 and before) doesn't know the member and would
|
|
20
|
+
# fire the entry whatever CMD says. So an entry with a condition is
|
|
21
|
+
# stored with `next_due: null` and the real moment under
|
|
22
|
+
# CONDITION_NEXT_DUE (#hide_next_due, on every #write; Entry.from_record
|
|
23
|
+
# reads it back): an older chi's due? can't parse null, so it never
|
|
24
|
+
# fires it, while the entry stays readable and enabled (it still
|
|
25
|
+
# protects its sessions from retention, and an older list shows it).
|
|
26
|
+
#
|
|
27
|
+
# The tick (#condition_results, then #condition_gate in its main pass):
|
|
28
|
+
# before it takes the lock, it runs each due entry's CMD once, in turn,
|
|
29
|
+
# in the target session's folder (`sh -c`, its own process group, stdin
|
|
30
|
+
# closed, ContextFetch.run_command), with the scrubbed spawn env and
|
|
31
|
+
# SAMAGOTCHI_SCHEDULE_ID/_TITLE/_SESSION, for at most
|
|
32
|
+
# schedule.condition_timeout_seconds. Exit 0 lets the entry go on to the
|
|
33
|
+
# busy check and the firing; 1..125 is "not needed": the clock moves to
|
|
34
|
+
# the next occurrence and nothing else changes (no counter, no history
|
|
35
|
+
# row, the chain's one firing unused); anything else (126, 127, a
|
|
36
|
+
# signal, a timeout, more than 1 MiB printed, no folder, a condition set
|
|
37
|
+
# by anyone but the CLI) is a failure, counted as any other. Under the
|
|
38
|
+
# lock a result counts only when the entry still has the same condition
|
|
39
|
+
# and next_due (another ticker, an edit or a run-now since: it is left
|
|
40
|
+
# alone and the next tick runs CMD again).
|
|
41
|
+
module ConditionPart
|
|
42
|
+
# The member that holds a condition entry's real next_due in the file.
|
|
43
|
+
CONDITION_NEXT_DUE = "condition_next_due"
|
|
44
|
+
# Who set a condition: the owner, from the CLI. Any other value fails
|
|
45
|
+
# closed (the tick records a failure and never runs it).
|
|
46
|
+
CONDITION_BY = "cli"
|
|
47
|
+
CONDITION_MAX_BYTES = 1024
|
|
48
|
+
CONDITION_TIMEOUT = 30
|
|
49
|
+
CONDITION_TIMEOUT_MAX = 300
|
|
50
|
+
# A result's detail (last_result, the tick's outcome, the log) keeps
|
|
51
|
+
# this many characters of one line.
|
|
52
|
+
CONDITION_DETAIL_CHARS = 120
|
|
53
|
+
|
|
54
|
+
# What one run of an entry's condition said: +kind+ :pass, :not_needed
|
|
55
|
+
# or :error, for the +condition+, +next_due+ and +failures+ it ran for
|
|
56
|
+
# (a result counts only while the entry still has all three: a failure
|
|
57
|
+
# keeps next_due, so another ticker's counted error moves +failures+).
|
|
58
|
+
ConditionResult = Data.define(:id, :condition, :next_due, :failures, :kind, :detail)
|
|
59
|
+
|
|
60
|
+
# The command that runs a condition: ContextFetch.run_command's
|
|
61
|
+
# signature, its Run back.
|
|
62
|
+
DEFAULT_RUNNER = lambda do |cmd, **options|
|
|
63
|
+
require_relative "../context_fetch"
|
|
64
|
+
ContextFetch.run_command(cmd, **options)
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Entry.from_record's fields with +extra+: the condition symbolised (kept
|
|
68
|
+
# as it is when it isn't a Hash: any condition but nil gates the entry,
|
|
69
|
+
# and one that doesn't read fails, never fires), and next_due from
|
|
70
|
+
# CONDITION_NEXT_DUE unless the stored next_due holds one (an older
|
|
71
|
+
# chi's run-now or edit wrote it since).
|
|
72
|
+
# @return [Hash] the fields, extra: included
|
|
73
|
+
def self.stored(fields, extra)
|
|
74
|
+
condition = fields[:condition]
|
|
75
|
+
fields[:condition] = condition.transform_keys(&:to_sym) if condition.is_a?(Hash)
|
|
76
|
+
extra = extra.dup
|
|
77
|
+
hidden = extra.delete(CONDITION_NEXT_DUE)
|
|
78
|
+
fields[:next_due] = hidden if fields[:next_due].nil? && hidden.is_a?(String)
|
|
79
|
+
fields.merge(extra: extra)
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# The warning `add` / `edit --if` print when CMD's first word is a
|
|
83
|
+
# script the model can edit (review M4): a relative path (it resolves
|
|
84
|
+
# in the session's folder, where CMD runs), or one inside the target
|
|
85
|
+
# session's folder or any git work tree. nil for a command on PATH or
|
|
86
|
+
# a script outside every project. A warning, not a refusal: chi's
|
|
87
|
+
# guardrails are an accident guard.
|
|
88
|
+
GATE_IN_REACH = "warning: the model can edit this script; keep a gate outside your projects " \
|
|
89
|
+
"(an absolute path, e.g. under ~/.local/bin)"
|
|
90
|
+
|
|
91
|
+
# @param cmd [String] @param folder [String, nil] the target session's
|
|
92
|
+
# @return [String, nil] GATE_IN_REACH or nil
|
|
93
|
+
def self.gate_warning(cmd, folder:)
|
|
94
|
+
word = first_word(cmd)
|
|
95
|
+
return nil if word.nil? || !word.include?("/")
|
|
96
|
+
|
|
97
|
+
expanded = word.sub(%r{\A(~|\$HOME|\$\{HOME\})(?=/)}) { Dir.home }
|
|
98
|
+
return GATE_IN_REACH unless expanded.start_with?("/")
|
|
99
|
+
|
|
100
|
+
path = File.expand_path(expanded)
|
|
101
|
+
inside = folder && !folder.to_s.empty? && (path == File.expand_path(folder) || path.start_with?(File.join(File.expand_path(folder), "")))
|
|
102
|
+
inside || in_work_tree?(path) ? GATE_IN_REACH : nil
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# CMD's first word, past VAR=value assignments; nil when it doesn't split.
|
|
106
|
+
def self.first_word(cmd)
|
|
107
|
+
Shellwords.split(cmd.to_s).find { |word| !word.match?(/\A[A-Za-z_][A-Za-z0-9_]*=/) }
|
|
108
|
+
rescue ArgumentError
|
|
109
|
+
nil
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def self.in_work_tree?(path)
|
|
113
|
+
dir = File.directory?(path) ? path : File.dirname(path)
|
|
114
|
+
dir = File.dirname(dir) until File.directory?(dir) || dir == "/"
|
|
115
|
+
out = IO.popen(GitEnv::UNSET, ["git", "-C", dir, "rev-parse", "--is-inside-work-tree"], err: File::NULL, &:read)
|
|
116
|
+
out.to_s.strip == "true"
|
|
117
|
+
rescue SystemCallError
|
|
118
|
+
false
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# How long a condition may run (schedule.condition_timeout_seconds,
|
|
122
|
+
# 1..CONDITION_TIMEOUT_MAX), for `chi schedule show` too.
|
|
123
|
+
def condition_timeout_seconds
|
|
124
|
+
value = Config.get("schedule.condition_timeout_seconds").to_i
|
|
125
|
+
value.positive? ? value.clamp(1, CONDITION_TIMEOUT_MAX) : CONDITION_TIMEOUT
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
private
|
|
129
|
+
|
|
130
|
+
# The condition +cmd+ stores as, checked: one line, not blank, at most
|
|
131
|
+
# CONDITION_MAX_BYTES. A `date` one-off takes none: it fires once, and a
|
|
132
|
+
# "not needed" would have no next time to move to.
|
|
133
|
+
# @return [Hash] {cmd:, by:, set_at:}
|
|
134
|
+
# @raise [Usage]
|
|
135
|
+
def condition_for(cmd, recurrence)
|
|
136
|
+
cmd = cmd.to_s
|
|
137
|
+
raise Usage, "--if needs a command" if cmd.strip.empty?
|
|
138
|
+
raise Usage, "--if takes one line: no newline, carriage return or NUL" if cmd.match?(/[\n\r\0]/)
|
|
139
|
+
if cmd.bytesize > CONDITION_MAX_BYTES
|
|
140
|
+
raise Usage, "the --if command is #{cmd.bytesize} bytes; the limit is #{CONDITION_MAX_BYTES}"
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
refuse_dated_condition!(recurrence)
|
|
144
|
+
{ cmd: cmd, by: CONDITION_BY, set_at: @clock.call.utc.iso8601 }
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# @raise [Usage] a `date` one-off with a condition
|
|
148
|
+
def refuse_dated_condition!(recurrence)
|
|
149
|
+
return unless recurrence.is_a?(Hash) && recurrence[:kind] == "date"
|
|
150
|
+
|
|
151
|
+
raise Usage, "a --date one-off can't have --if: it fires once (use --every or --weekday)"
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# The pre-pass: each enabled entry with a condition that is due now
|
|
155
|
+
# (lock-free read; the main pass applies the rest of the rules), its
|
|
156
|
+
# CMD run once, in turn, until +cancelled+. nil when there is none.
|
|
157
|
+
# @return [Hash{String => ConditionResult}, nil]
|
|
158
|
+
def condition_results(now, cancelled)
|
|
159
|
+
candidates = read(quiet: true).entries.grep(Entry).select { |entry| entry.enabled && !entry.condition.nil? && entry.due?(now) }
|
|
160
|
+
return nil if candidates.empty?
|
|
161
|
+
|
|
162
|
+
links = links_now
|
|
163
|
+
results = {}
|
|
164
|
+
candidates.sort_by { |entry| [entry.next_due.to_s, entry.id] }.each do |entry|
|
|
165
|
+
break if cancelled.call
|
|
166
|
+
|
|
167
|
+
result = evaluate_condition(entry, links, cancelled)
|
|
168
|
+
results[entry.id] = result if result
|
|
169
|
+
end
|
|
170
|
+
results
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# One entry's condition run; nil when it didn't run to an answer (its
|
|
174
|
+
# target doesn't resolve: the main pass's check says why; or the run
|
|
175
|
+
# was cancelled).
|
|
176
|
+
def evaluate_condition(entry, links, cancelled)
|
|
177
|
+
cmd = condition_cmd(entry)
|
|
178
|
+
by = entry.condition.is_a?(Hash) ? entry.condition[:by] : nil
|
|
179
|
+
return condition_result(entry, :error, "it doesn't read (no command)") if cmd.nil?
|
|
180
|
+
unless by == CONDITION_BY
|
|
181
|
+
return condition_result(entry, :error, "set by #{by.to_s.empty? ? "no one" : by}: this chi runs only one set with chi schedule")
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# A one-off takes none (#refuse_dated_condition!), but an older chi's
|
|
185
|
+
# `edit --date` can make one: a not needed would leave it due at the
|
|
186
|
+
# same moment forever. A failure instead, so its budget ends it.
|
|
187
|
+
return condition_result(entry, :error, "conditions don't apply to a one-off (--date)") if entry.recurrence[:kind] == "date"
|
|
188
|
+
|
|
189
|
+
target, = target_of(entry, links)
|
|
190
|
+
return nil if target.nil?
|
|
191
|
+
|
|
192
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
193
|
+
run = @condition_runner.call(cmd, cwd: condition_cwd(target), env: condition_env(entry, target),
|
|
194
|
+
timeout: condition_timeout_seconds, cancelled: cancelled)
|
|
195
|
+
return nil if run.cancelled
|
|
196
|
+
|
|
197
|
+
kind, detail = condition_verdict(run)
|
|
198
|
+
Log.info(:worker, "schedule_condition", id: entry.id, result: kind, detail: detail,
|
|
199
|
+
ms: ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round)
|
|
200
|
+
condition_result(entry, kind, detail)
|
|
201
|
+
rescue StandardError => e
|
|
202
|
+
# A run that blows up (a spawn refusing its env, a session file that
|
|
203
|
+
# doesn't load) is this entry's failure, never the whole tick's: the
|
|
204
|
+
# entry stays due, and an abort here would stop every schedule.
|
|
205
|
+
Log.warn(:worker, "schedule_condition_failed", id: entry.id, error: e.class.name, msg: e.message)
|
|
206
|
+
condition_result(entry, :error, "couldn't run it: #{e.class}: #{e.message}")
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
def condition_result(entry, kind, detail)
|
|
210
|
+
ConditionResult.new(id: entry.id, condition: entry.condition, next_due: entry.next_due, failures: entry.failures,
|
|
211
|
+
kind: kind, detail: condition_line(detail))
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
# [kind, detail] for a Run: by how it ended first (Run#status is nil
|
|
215
|
+
# unless it ended on its own within the cap), then by its exit code.
|
|
216
|
+
def condition_verdict(run)
|
|
217
|
+
code = run.status&.exitstatus
|
|
218
|
+
return [:error, run.error || "it didn't run"] if code.nil?
|
|
219
|
+
return [:pass, "exit 0"] if code.zero?
|
|
220
|
+
|
|
221
|
+
said = first_line(run.output) || last_line(run.stderr)
|
|
222
|
+
return [:not_needed, ["exit #{code}", said].compact.join(": ")] if (1..125).cover?(code)
|
|
223
|
+
|
|
224
|
+
[:error, run.error || "exit #{code}"]
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# The main pass's say on an entry with a condition, under the lock,
|
|
228
|
+
# once its target resolves (the check reports one that doesn't). nil:
|
|
229
|
+
# it passed, on to the busy check and the firing. Else [entry as
|
|
230
|
+
# updated, Outcome or nil]: catch_up none a whole cycle late (missed,
|
|
231
|
+
# CMD unasked), no fresh result (left as it is, no outcome: the next
|
|
232
|
+
# tick runs CMD again), a failure, or not needed.
|
|
233
|
+
# @return [Array(Entry, Outcome|nil), nil]
|
|
234
|
+
def condition_gate(entry, links, results, now)
|
|
235
|
+
return nil if entry.condition.nil?
|
|
236
|
+
|
|
237
|
+
target, = target_of(entry, links)
|
|
238
|
+
return nil if target.nil?
|
|
239
|
+
|
|
240
|
+
if entry.catch_up == "none" && late?(entry, now)
|
|
241
|
+
return [reschedule(entry, now), Outcome.new(id: entry.id, title: entry.title, status: "missed", detail: "past its time",
|
|
242
|
+
entry: entry)]
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
result = results&.fetch(entry.id, nil)
|
|
246
|
+
unless result && result.condition == entry.condition && result.next_due == entry.next_due &&
|
|
247
|
+
result.failures == entry.failures
|
|
248
|
+
Log.info(:worker, "schedule_condition_unchecked", id: entry.id)
|
|
249
|
+
return [entry, nil]
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
case result.kind
|
|
253
|
+
when :pass then nil
|
|
254
|
+
when :not_needed
|
|
255
|
+
updated = not_needed(entry, result, now)
|
|
256
|
+
[updated, Outcome.new(id: entry.id, title: entry.title, status: "not-needed", detail: result.detail, entry: updated)]
|
|
257
|
+
else
|
|
258
|
+
reason = "condition: #{result.detail}"
|
|
259
|
+
[failed(entry, reason, now: now), Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: reason, entry: entry)]
|
|
260
|
+
end
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
# Not needed this time: the clock moves to the next occurrence, as
|
|
264
|
+
# if it had fired; no counter, no history row, no firing field changes.
|
|
265
|
+
def not_needed(entry, result, now)
|
|
266
|
+
entry.with(next_due: next_due_for(entry.recurrence, from: now).utc.iso8601, last_result: "not needed: #{result.detail}")
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
# The target session's folder (nil: run_command says it is gone).
|
|
270
|
+
def condition_cwd(target)
|
|
271
|
+
Session.load(target, state_dir: @state_dir).working_directory
|
|
272
|
+
rescue Session::NotFound
|
|
273
|
+
nil
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
# The scrubbed spawn env and the schedule's own keys; never the
|
|
277
|
+
# ticker's SAMAGOTCHI_PARENT_SESSION (CMD is no agent's).
|
|
278
|
+
def condition_env(entry, target)
|
|
279
|
+
SpawnEnv.sanitized_spawn_env.merge("SAMAGOTCHI_SCHEDULE_ID" => entry.id, "SAMAGOTCHI_SCHEDULE_TITLE" => entry.title.to_s,
|
|
280
|
+
"SAMAGOTCHI_SCHEDULE_SESSION" => target, "SAMAGOTCHI_PARENT_SESSION" => nil)
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
def first_line(text) = text_lines(text).first
|
|
284
|
+
def last_line(text) = text_lines(text).last
|
|
285
|
+
|
|
286
|
+
def text_lines(text)
|
|
287
|
+
text.to_s.dup.force_encoding(Encoding::UTF_8).scrub.lines.map(&:strip).reject(&:empty?)
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
# One line of valid UTF-8, no control characters, cut.
|
|
291
|
+
def condition_line(text)
|
|
292
|
+
line = text.to_s.dup.force_encoding(Encoding::UTF_8).scrub.gsub(/[[:cntrl:]]+/, " ").strip
|
|
293
|
+
line.length > CONDITION_DETAIL_CHARS ? "#{line[0, CONDITION_DETAIL_CHARS - 1]}…" : line
|
|
294
|
+
end
|
|
295
|
+
|
|
296
|
+
# The command of +entry+'s condition, nil when it has none or one that
|
|
297
|
+
# isn't {cmd: String}.
|
|
298
|
+
def condition_cmd(entry)
|
|
299
|
+
condition = entry.condition
|
|
300
|
+
condition.is_a?(Hash) && condition[:cmd].is_a?(String) ? condition[:cmd] : nil
|
|
301
|
+
end
|
|
302
|
+
|
|
303
|
+
# +entry+ as the file stores it: one with a condition and a next_due
|
|
304
|
+
# keeps that next_due under CONDITION_NEXT_DUE, and null in next_due.
|
|
305
|
+
def hide_next_due(entry)
|
|
306
|
+
return entry if entry.condition.nil? || entry.next_due.nil?
|
|
307
|
+
|
|
308
|
+
entry.with(next_due: nil, extra: entry.extra.merge(CONDITION_NEXT_DUE => entry.next_due))
|
|
309
|
+
end
|
|
310
|
+
end
|
|
311
|
+
end
|
|
312
|
+
end
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Samagotchi
|
|
4
|
+
class Schedules
|
|
5
|
+
# `chi schedule edit` (docs/scheduling.md): change a schedule's title,
|
|
6
|
+
# prompt, recurrence, catch-up or budgets in place, keeping its id, its
|
|
7
|
+
# session and mode (cancel and add for those), its counters, `enabled`
|
|
8
|
+
# (a spent `date` one-off stays disabled) and the firing fields.
|
|
9
|
+
module EditPart
|
|
10
|
+
# A recurrence edit while a firing is in flight: a state, not a usage
|
|
11
|
+
# error (`chi schedule edit` exits 1).
|
|
12
|
+
class InFlight < StandardError
|
|
13
|
+
def initialize(msg = "a run is in progress; edit the time after it settles") = super
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Each argument nil keeps the field; only the fields given change.
|
|
17
|
+
# @param recurrence [Hash, nil] a whole one, from Schedules.recurrence
|
|
18
|
+
# @param condition [String, :none, nil] the owner's `--if CMD`, :none
|
|
19
|
+
# to drop it (`--no-if`); the CLI's only, never a tool's
|
|
20
|
+
# @return [Entry, nil] the entry as edited; nil when no schedule matches
|
|
21
|
+
# (or it is gone by the time the lock is held)
|
|
22
|
+
# @raise [Usage] nothing to change, a field that is wrong, a duplicate
|
|
23
|
+
# in the chain
|
|
24
|
+
# @raise [InFlight] a recurrence edit while a firing is in flight
|
|
25
|
+
def edit(id_or_name, title: nil, prompt: nil, recurrence: nil, catch_up: nil, keep_links: nil, max_failures: nil,
|
|
26
|
+
max_skips: nil, condition: nil)
|
|
27
|
+
entry = lookup(id_or_name)
|
|
28
|
+
return nil if entry.nil?
|
|
29
|
+
|
|
30
|
+
changes = differing(entry, edit_changes(title: title, prompt: prompt, recurrence: recurrence, catch_up: catch_up,
|
|
31
|
+
keep_links: keep_links, max_failures: max_failures, max_skips: max_skips))
|
|
32
|
+
changes.merge!(condition_change(entry, condition, changes.fetch(:recurrence, entry.recurrence)))
|
|
33
|
+
# A condition kept, on a recurrence edited to a one-off.
|
|
34
|
+
refuse_dated_condition!(changes[:recurrence]) if changes.key?(:recurrence) && changes.fetch(:condition, entry.condition)
|
|
35
|
+
raise Usage, "nothing to change" if changes.empty?
|
|
36
|
+
|
|
37
|
+
# Each duplicate test only on what the edit changes: a clash in a field
|
|
38
|
+
# it leaves alone (a twin `enable` let in) is not of its making.
|
|
39
|
+
by_title = changes.key?(:title)
|
|
40
|
+
by_content = changes.key?(:prompt) || changes.key?(:recurrence)
|
|
41
|
+
if by_title || by_content
|
|
42
|
+
same = duplicate_in_chain(entry.anchor, prompt: changes.fetch(:prompt, entry.prompt),
|
|
43
|
+
title: changes.fetch(:title, entry.title),
|
|
44
|
+
recurrence: changes.fetch(:recurrence, entry.recurrence), except: entry.id,
|
|
45
|
+
by_title: by_title, by_content: by_content)
|
|
46
|
+
refuse_duplicate!(same, entry.mode) if same
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
result = nil
|
|
50
|
+
write_under_lock do |file|
|
|
51
|
+
position = file.entries.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
|
|
52
|
+
next if position.nil?
|
|
53
|
+
|
|
54
|
+
result = file.entries[position] = edited(file.entries[position], changes)
|
|
55
|
+
end
|
|
56
|
+
result
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# The duplicate rule #add and #edit share: an enabled schedule of the
|
|
60
|
+
# same chain that says the same thing, the same prompt and recurrence
|
|
61
|
+
# or the same title. An edit passes +except+ (its own entry is no
|
|
62
|
+
# duplicate of itself) and turns off the test whose fields it leaves
|
|
63
|
+
# alone (+by_content+: the prompt and recurrence; +by_title+).
|
|
64
|
+
# @return [Entry, nil]
|
|
65
|
+
def duplicate_in_chain(session_id, prompt:, title:, recurrence:, except: nil, by_content: true, by_title: true)
|
|
66
|
+
given_title = title.to_s.strip
|
|
67
|
+
ids = chain_of(session_id)
|
|
68
|
+
entries.find do |entry|
|
|
69
|
+
next if entry.id == except
|
|
70
|
+
next unless ids.include?(entry.anchor) || ids.include?(entry.head)
|
|
71
|
+
|
|
72
|
+
(by_content && entry.prompt == prompt && entry.recurrence == recurrence) ||
|
|
73
|
+
(by_title && !given_title.empty? && entry.title.to_s.strip.casecmp?(given_title))
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# @raise [Usage] naming the schedule that already says the same thing
|
|
78
|
+
def refuse_duplicate!(same, mode)
|
|
79
|
+
raise Usage, "#{same.id} already schedules this (#{same.recurrence_words}, #{mode}: #{same.prompt}); " \
|
|
80
|
+
"cancel it with chi schedule cancel #{same.id} to change it"
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
private
|
|
84
|
+
|
|
85
|
+
# The +changes+ whose value is not +entry+'s already (`--title ""` on
|
|
86
|
+
# an untitled entry changes nothing). A condition is the same when its
|
|
87
|
+
# command is: a new set_at alone is no change.
|
|
88
|
+
def differing(entry, changes)
|
|
89
|
+
changes.reject do |field, value|
|
|
90
|
+
field == :condition ? same_condition?(entry.condition, value) : entry.public_send(field) == value
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def same_condition?(stored, given)
|
|
95
|
+
return stored.nil? if given.nil?
|
|
96
|
+
|
|
97
|
+
stored.is_a?(Hash) && stored[:cmd] == given[:cmd] && stored[:by] == given[:by]
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# {condition: …} when +condition+ changes it: a command checked as #add
|
|
101
|
+
# checks it, :none for none; {} for nil (kept) or the same command.
|
|
102
|
+
def condition_change(entry, condition, recurrence)
|
|
103
|
+
return {} if condition.nil?
|
|
104
|
+
|
|
105
|
+
differing(entry, condition: condition == :none ? nil : condition_for(condition, recurrence))
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# The fields given, checked as #add checks them.
|
|
109
|
+
def edit_changes(title:, prompt:, recurrence:, catch_up:, **budgets)
|
|
110
|
+
changes = {}
|
|
111
|
+
changes[:title] = title.to_s.strip.empty? ? nil : title.to_s.strip unless title.nil?
|
|
112
|
+
changes[:prompt] = validate_prompt!(prompt) unless prompt.nil?
|
|
113
|
+
changes[:recurrence] = recurrence unless recurrence.nil?
|
|
114
|
+
unless catch_up.nil?
|
|
115
|
+
changes[:catch_up] = catch_up.to_s.strip
|
|
116
|
+
validate_catch_up!(changes[:catch_up])
|
|
117
|
+
end
|
|
118
|
+
{ keep_links: 0, max_failures: 1, max_skips: 1 }.each do |field, min|
|
|
119
|
+
value = int_value(budgets[field], min: min, name: field.to_s)
|
|
120
|
+
changes[field] = value unless value.nil?
|
|
121
|
+
end
|
|
122
|
+
changes
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# +stored+ with +changes+, under the lock. A new recurrence's clock
|
|
126
|
+
# starts now, as #add's does; while a firing is in flight it is refused:
|
|
127
|
+
# #record would put that firing's due_was back over the new clock.
|
|
128
|
+
def edited(stored, changes)
|
|
129
|
+
# Against the entry as stored now: what another writer already set is no change.
|
|
130
|
+
changes = differing(stored, changes)
|
|
131
|
+
return stored if changes.empty?
|
|
132
|
+
|
|
133
|
+
now = @clock.call
|
|
134
|
+
updated = stored.with(**changes)
|
|
135
|
+
if changes.key?(:recurrence)
|
|
136
|
+
raise InFlight if stored.firing_since || stored.pending_turn_id
|
|
137
|
+
|
|
138
|
+
updated = updated.with(next_due: next_due_for(changes[:recurrence], from: now).utc.iso8601, due_was: nil)
|
|
139
|
+
end
|
|
140
|
+
with_history(updated, "edited", changes.keys.join(", "), at: now)
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
end
|
|
144
|
+
end
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Samagotchi
|
|
4
|
+
class Schedules
|
|
5
|
+
# The run history (docs/scheduling.md, `chi schedule show`): each entry
|
|
6
|
+
# keeps its last HISTORY_MAX outcomes in `history`, newest last, rows
|
|
7
|
+
# {at:, status:, detail:, session_id:}. One writer per status, each
|
|
8
|
+
# appending once per event:
|
|
9
|
+
# skipped, failed — #skipped / #failed (the helpers, never their
|
|
10
|
+
# callers), and #run_now's refusal of a disabled entry (no counters);
|
|
11
|
+
# a budget turn-off is that row, its detail "disabled: <reason>"
|
|
12
|
+
# fired — #finish_pending (a firing that settles) and #record's "fired"
|
|
13
|
+
# missed — #reschedule
|
|
14
|
+
# enabled, disabled — #change (the owner's; never a budget turn-off)
|
|
15
|
+
# edited — #edit, its detail the changed fields
|
|
16
|
+
# A pending firing writes no row: it is not an outcome yet.
|
|
17
|
+
module HistoryPart
|
|
18
|
+
HISTORY_MAX = 20
|
|
19
|
+
# A detail is clipped to this many characters (an exception's message
|
|
20
|
+
# or a turn's reason can be long): with the row's other fields (~120
|
|
21
|
+
# bytes) an entry's history stays under about 20 × 320 bytes, 6.4 KB.
|
|
22
|
+
DETAIL_MAX = 200
|
|
23
|
+
|
|
24
|
+
# The rows as JSON hands them back (string keys) or as written (symbol
|
|
25
|
+
# keys): symbol keys, non-rows dropped.
|
|
26
|
+
# @return [Array<Hash>]
|
|
27
|
+
def self.rows(value)
|
|
28
|
+
Array(value).filter_map { |row| row.transform_keys(&:to_sym) if row.is_a?(Hash) }
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
private
|
|
32
|
+
|
|
33
|
+
# A skip's or a failure's row (+before+ the call, +after+ it), and the
|
|
34
|
+
# disabled notice when this call turned the entry off by its budget.
|
|
35
|
+
# Its session: the pending firing's, else the head.
|
|
36
|
+
def recorded(before, after, status, reason, now)
|
|
37
|
+
off = budget_turned_off?(before, after, status)
|
|
38
|
+
noticed = with_disabled_notice(before, after, status, reason, now)
|
|
39
|
+
with_history(noticed, status, off ? "disabled: #{reason}" : reason, at: now,
|
|
40
|
+
session_id: before.pending_session_id || before.head)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# +entry+ with one row more, the oldest dropped past HISTORY_MAX.
|
|
44
|
+
def with_history(entry, status, detail, at:, session_id: nil)
|
|
45
|
+
clipped = detail.nil? ? nil : detail.to_s[0, DETAIL_MAX]
|
|
46
|
+
row = { at: at.utc.iso8601, status: status, detail: clipped, session_id: session_id }
|
|
47
|
+
entry.with(history: (HistoryPart.rows(entry.history) + [row]).last(HISTORY_MAX))
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
@@ -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
|