samagotchi 0.189.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 +35 -1
- data/docs/architecture.md +4 -1
- data/docs/cli.md +17 -6
- data/docs/configuration.md +1 -0
- data/docs/guardrails.md +20 -8
- data/docs/internals/attached-context.md +4 -1
- data/docs/internals/engine.md +18 -2
- data/docs/pages.md +3 -2
- data/docs/scheduling.md +99 -5
- data/docs/sub-agent.md +1 -1
- 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 +4 -4
- data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +13 -3
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- 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/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/model_profile.rb +4 -1
- data/lib/samagotchi/pages/runtime.rb +4 -3
- data/lib/samagotchi/reply_wait.rb +1 -1
- data/lib/samagotchi/schedule_command.rb +99 -5
- data/lib/samagotchi/schedule_display.rb +21 -5
- data/lib/samagotchi/schedules/condition_part.rb +312 -0
- data/lib/samagotchi/schedules/edit_part.rb +27 -3
- data/lib/samagotchi/schedules/notices_part.rb +8 -2
- data/lib/samagotchi/schedules/protection_part.rb +10 -0
- data/lib/samagotchi/schedules/prune_part.rb +79 -0
- data/lib/samagotchi/schedules.rb +57 -82
- data/lib/samagotchi/system_one/self_protect.rb +4 -2
- data/lib/samagotchi/tools/cancel_schedule.rb +27 -2
- 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/version.rb +1 -1
- data/lib/samagotchi/web/public/stream_handlers.js +8 -0
- data/lib/samagotchi/web/session_hub.rb +16 -5
- data/lib/samagotchi/worker.rb +6 -4
- metadata +4 -1
|
@@ -26,6 +26,19 @@ module Samagotchi
|
|
|
26
26
|
width ? given.ljust(width) : given
|
|
27
27
|
end
|
|
28
28
|
|
|
29
|
+
# An entry's condition as it is listed: its command (cut at +chars+ with
|
|
30
|
+
# "…" when given), or what a condition that doesn't read is. nil without
|
|
31
|
+
# one.
|
|
32
|
+
def self.condition_words(entry, chars: nil)
|
|
33
|
+
condition = entry.condition
|
|
34
|
+
return nil if condition.nil?
|
|
35
|
+
|
|
36
|
+
cmd = condition.is_a?(Hash) ? condition[:cmd] : nil
|
|
37
|
+
return "(doesn't read: the tick fails it)" unless cmd.is_a?(String)
|
|
38
|
+
|
|
39
|
+
chars && cmd.length > chars ? "#{cmd[0, chars]}…" : cmd
|
|
40
|
+
end
|
|
41
|
+
|
|
29
42
|
# The width of the name column for these entries.
|
|
30
43
|
def self.name_width(entries)
|
|
31
44
|
entries.map { |entry| name(entry) }.map(&:length).max
|
|
@@ -83,13 +96,16 @@ module Samagotchi
|
|
|
83
96
|
end
|
|
84
97
|
|
|
85
98
|
# One entry as `chi schedule list --format json` prints it (and
|
|
86
|
-
# Pages::Runtime reads it): every stored field with its extra keys
|
|
87
|
-
#
|
|
88
|
-
#
|
|
89
|
-
#
|
|
99
|
+
# Pages::Runtime reads it): every stored field with its extra keys (the
|
|
100
|
+
# real next_due: the file's hidden one is Schedules#write's), the
|
|
101
|
+
# condition with string keys, then what a reader needs and would
|
|
102
|
+
# otherwise compute: recurrence_words, skip_window, name, state,
|
|
103
|
+
# off_reason. Those come last, so an extra key of the same name (a newer
|
|
104
|
+
# chi's) never shadows them.
|
|
90
105
|
# @return [Hash{String => Object}]
|
|
91
106
|
def self.json(entry)
|
|
92
|
-
entry.
|
|
107
|
+
condition = entry.condition.is_a?(Hash) ? entry.condition.transform_keys(&:to_s) : entry.condition
|
|
108
|
+
entry.to_h.transform_keys(&:to_s).merge("condition" => condition).merge(
|
|
93
109
|
"recurrence_words" => entry.recurrence_words,
|
|
94
110
|
"skip_window" => skip_window(entry),
|
|
95
111
|
"name" => name(entry),
|
|
@@ -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
|
|
@@ -15,18 +15,23 @@ module Samagotchi
|
|
|
15
15
|
|
|
16
16
|
# Each argument nil keeps the field; only the fields given change.
|
|
17
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
|
|
18
20
|
# @return [Entry, nil] the entry as edited; nil when no schedule matches
|
|
19
21
|
# (or it is gone by the time the lock is held)
|
|
20
22
|
# @raise [Usage] nothing to change, a field that is wrong, a duplicate
|
|
21
23
|
# in the chain
|
|
22
24
|
# @raise [InFlight] a recurrence edit while a firing is in flight
|
|
23
25
|
def edit(id_or_name, title: nil, prompt: nil, recurrence: nil, catch_up: nil, keep_links: nil, max_failures: nil,
|
|
24
|
-
max_skips: nil)
|
|
26
|
+
max_skips: nil, condition: nil)
|
|
25
27
|
entry = lookup(id_or_name)
|
|
26
28
|
return nil if entry.nil?
|
|
27
29
|
|
|
28
30
|
changes = differing(entry, edit_changes(title: title, prompt: prompt, recurrence: recurrence, catch_up: catch_up,
|
|
29
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)
|
|
30
35
|
raise Usage, "nothing to change" if changes.empty?
|
|
31
36
|
|
|
32
37
|
# Each duplicate test only on what the edit changes: a clash in a field
|
|
@@ -78,8 +83,27 @@ module Samagotchi
|
|
|
78
83
|
private
|
|
79
84
|
|
|
80
85
|
# The +changes+ whose value is not +entry+'s already (`--title ""` on
|
|
81
|
-
# an untitled entry changes nothing).
|
|
82
|
-
|
|
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
|
|
83
107
|
|
|
84
108
|
# The fields given, checked as #add checks them.
|
|
85
109
|
def edit_changes(title:, prompt:, recurrence:, catch_up:, **budgets)
|
|
@@ -25,15 +25,21 @@ module Samagotchi
|
|
|
25
25
|
# `enable` keeps the notice) and a notice older than NOTICE_MAX_AGE are
|
|
26
26
|
# cleared without being returned.
|
|
27
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)
|
|
28
31
|
# @return [Array<Hash>] {id:, title:, kind:, count:, reason:, session_id:, at:}
|
|
29
32
|
# @raise [Corrupt] the file stopped being readable JSON
|
|
30
|
-
def claim_disabled_notices(now: @clock.call)
|
|
33
|
+
def claim_disabled_notices(now: @clock.call, on_lock_held: nil)
|
|
31
34
|
return [] unless read.entries.any? { |entry| entry.is_a?(Entry) && entry.disabled_notice }
|
|
32
35
|
|
|
33
36
|
claimed = []
|
|
34
37
|
FileUtils.mkdir_p(@store_dir)
|
|
35
38
|
File.open(lock_path, File::RDWR | File::CREAT, 0o600) do |lock|
|
|
36
|
-
|
|
39
|
+
unless lock.flock(File::LOCK_EX | File::LOCK_NB)
|
|
40
|
+
on_lock_held&.call
|
|
41
|
+
return []
|
|
42
|
+
end
|
|
37
43
|
|
|
38
44
|
file = read(strict: true)
|
|
39
45
|
links = nil
|
|
@@ -42,6 +42,16 @@ module Samagotchi
|
|
|
42
42
|
entry && SessionProtection::Hold.new(session_id: session_id, reason: :chain_scheduled, ref: entry.id)
|
|
43
43
|
end
|
|
44
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
|
+
|
|
45
55
|
private
|
|
46
56
|
|
|
47
57
|
def protecting(session_id, list)
|
|
@@ -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
|