samagotchi 0.188.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 (77) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +42 -1
  3. data/docs/architecture.md +5 -3
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +15 -0
  6. data/docs/cli.md +23 -5
  7. data/docs/guardrails.md +3 -2
  8. data/docs/internals/bundles.md +3 -3
  9. data/docs/internals/pages.md +65 -18
  10. data/docs/internals/session-lifecycle.md +19 -6
  11. data/docs/internals/web-frontend.md +3 -3
  12. data/docs/internals/web-push.md +11 -5
  13. data/docs/pages.md +68 -15
  14. data/docs/peers.md +3 -0
  15. data/docs/plugins.md +25 -1
  16. data/docs/releasing.md +1 -1
  17. data/docs/scheduling.md +71 -8
  18. data/docs/sessions.md +4 -4
  19. data/docs/testing.md +1 -1
  20. data/lib/samagotchi/bundle_manifest.rb +34 -5
  21. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  22. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +159 -0
  23. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  24. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  25. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  26. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  27. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  28. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  29. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  30. data/lib/samagotchi/page_command.rb +9 -6
  31. data/lib/samagotchi/pages/bundled.rb +83 -0
  32. data/lib/samagotchi/pages/launch.rb +14 -2
  33. data/lib/samagotchi/pages/runner.rb +7 -2
  34. data/lib/samagotchi/pages/runtime.rb +83 -0
  35. data/lib/samagotchi/pages/store.rb +18 -5
  36. data/lib/samagotchi/pages.rb +47 -3
  37. data/lib/samagotchi/peer_continue.rb +14 -8
  38. data/lib/samagotchi/run_options.rb +1 -1
  39. data/lib/samagotchi/schedule_command.rb +79 -37
  40. data/lib/samagotchi/schedule_display.rb +69 -0
  41. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  42. data/lib/samagotchi/schedules/edit_part.rb +120 -0
  43. data/lib/samagotchi/schedules/history_part.rb +51 -0
  44. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  45. data/lib/samagotchi/schedules/notices_part.rb +116 -0
  46. data/lib/samagotchi/schedules/protection_part.rb +103 -0
  47. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  48. data/lib/samagotchi/schedules.rb +134 -330
  49. data/lib/samagotchi/session_access/local.rb +9 -1
  50. data/lib/samagotchi/session_access/remote.rb +2 -1
  51. data/lib/samagotchi/session_chain/delete.rb +7 -5
  52. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  53. data/lib/samagotchi/session_lifecycle.rb +3 -2
  54. data/lib/samagotchi/session_manager/removal.rb +16 -9
  55. data/lib/samagotchi/session_protection.rb +99 -0
  56. data/lib/samagotchi/session_retention.rb +21 -6
  57. data/lib/samagotchi/sessions_command.rb +4 -0
  58. data/lib/samagotchi/testing/boundary.rb +13 -0
  59. data/lib/samagotchi/tools/cancel_schedule.rb +5 -2
  60. data/lib/samagotchi/turn_outcome.rb +41 -0
  61. data/lib/samagotchi/version.rb +1 -1
  62. data/lib/samagotchi/web/page_routes.rb +13 -8
  63. data/lib/samagotchi/web/public/app.js +12 -18
  64. data/lib/samagotchi/web/public/index.html +11 -2
  65. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  66. data/lib/samagotchi/web/public/page_links.js +1 -1
  67. data/lib/samagotchi/web/public/page_view.js +8 -5
  68. data/lib/samagotchi/web/public/pages.css +9 -2
  69. data/lib/samagotchi/web/public/pages_group.js +21 -19
  70. data/lib/samagotchi/web/public/pages_list.js +73 -0
  71. data/lib/samagotchi/web/public/pages_model.js +54 -0
  72. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  73. data/lib/samagotchi/web/public/views.js +77 -23
  74. data/lib/samagotchi/web/push/notifier.rb +4 -3
  75. data/lib/samagotchi/web/server.rb +3 -1
  76. data/lib/samagotchi/web/session_hub.rb +64 -19
  77. metadata +17 -1
@@ -4,6 +4,7 @@ require "yaml"
4
4
  require "digest"
5
5
  require "fileutils"
6
6
  require_relative "context_providers"
7
+ require_relative "pages"
7
8
  require_relative "version"
8
9
 
9
10
  module Samagotchi
@@ -50,6 +51,9 @@ module Samagotchi
50
51
  # block_renderers: # optional — a fence's language → the scripts/
51
52
  # - lang: mermaid # files chi web's page loads to draw it
52
53
  # load: [lib.js, draw.js] # (BlockRenderers); each one a scripts: key
54
+ # pages: [schedules.rb] # optional — page scripts (docs/pages.md), each a
55
+ # # scripts: key named NAME.rb: the page NAME
56
+ # # (Pages::Bundled)
53
57
  # session_settings: [cap] # optional — the settings a session may set
54
58
  # # (chi --set cost-cap.cap=3), read by the
55
59
  # # plugin from ctx.settings at call time;
@@ -109,7 +113,7 @@ module Samagotchi
109
113
  # here is one this chi ignores: #unknown_keys, which `chi bundle check`
110
114
  # and the Installer say.
111
115
  KEYS = %w[name version scope description files hooks trust_level plugin requires_chi requires_chi_next needs
112
- scripts context_providers block_renderers includes session_settings settings].freeze
116
+ scripts context_providers block_renderers pages includes session_settings settings].freeze
113
117
 
114
118
  # The first chi release that reads each manifest key or shape (from git:
115
119
  # the first tag whose manifest.rb reads it), for `chi bundle check`'s
@@ -132,13 +136,14 @@ module Samagotchi
132
136
  "settings" => "0.143.0",
133
137
  "block_renderers" => "0.151.0",
134
138
  "plugin.required" => "0.157.0",
135
- "plugin.parts" => "0.183.0"
139
+ "plugin.parts" => "0.183.0",
140
+ "pages" => "0.189.0"
136
141
  }.freeze
137
142
 
138
143
  # files: name → "sha256:<hex>" (both forms); file_descriptions: name →
139
144
  # the description a mapping gave, for the files that have one.
140
145
  attr_reader :name, :version, :scope, :description, :files, :file_descriptions, :trust_level, :plugin, :requires_chi, :needs, :includes,
141
- :scripts, :context_providers, :block_renderers, :session_settings, :session_setting_types, :settings, :setting_types, :unknown_keys
146
+ :scripts, :context_providers, :block_renderers, :pages, :session_settings, :session_setting_types, :settings, :setting_types, :unknown_keys
142
147
 
143
148
  def initialize(path:)
144
149
  @path = path
@@ -169,6 +174,7 @@ module Samagotchi
169
174
  @scripts = parse_scripts(raw["scripts"])
170
175
  @context_providers = parse_context_providers(raw["context_providers"])
171
176
  @block_renderers = parse_block_renderers(raw["block_renderers"])
177
+ @pages = parse_pages(raw["pages"])
172
178
  @includes = parse_includes(raw["includes"])
173
179
  @session_settings = self.class.parse_session_settings(raw["session_settings"])
174
180
  @session_setting_types = self.class.parse_session_setting_types(raw["session_settings"])
@@ -200,7 +206,7 @@ module Samagotchi
200
206
  # that key, which reads as empty with its message in the problems:
201
207
  # name, version (never checked: identity is the record's), scope;
202
208
  # files and their descriptions, scripts, plugin (hooks: is ignored,
203
- # HooksRetired); needs, context_providers; block_renderers
209
+ # HooksRetired); needs, context_providers; block_renderers and pages
204
210
  # (against +fallback_scripts+ when scripts: failed); includes (after
205
211
  # what its check reads); session_settings with its types, settings
206
212
  # with theirs (one raw value each, so one problem); requires_chi,
@@ -304,6 +310,7 @@ module Samagotchi
304
310
  found["scripts"] = SINCE["scripts"] unless @scripts.empty?
305
311
  found["context_providers"] = SINCE["context_providers"] unless @context_providers.empty?
306
312
  found["block_renderers"] = SINCE["block_renderers"] unless @block_renderers.empty?
313
+ found["pages"] = SINCE["pages"] if !@pages.empty? && SINCE.key?("pages")
307
314
  found["plugin.required"] = SINCE["plugin.required"] if @plugin&.dig(:required) && SINCE.key?("plugin.required")
308
315
  found["plugin.parts"] = SINCE["plugin.parts"] if @plugin&.dig(:parts) && SINCE.key?("plugin.parts")
309
316
  found["session_settings"] = SINCE["session_settings"] unless @session_settings.empty?
@@ -318,7 +325,7 @@ module Samagotchi
318
325
  # +file_descriptions+ (name → text) writes those files as mappings.
319
326
  def self.write(dir:, name:, version:, files:, scope: nil, description: "", trust_level: nil,
320
327
  plugin: nil, requires_chi: nil, needs: nil, scripts: {}, context_providers: [], block_renderers: [], file_descriptions: {},
321
- session_settings: [], session_setting_types: {}, settings: nil, setting_types: {})
328
+ session_settings: [], session_setting_types: {}, settings: nil, setting_types: {}, pages: [])
322
329
  FileUtils.mkdir_p(dir)
323
330
  manifest = {
324
331
  "name" => name,
@@ -344,6 +351,7 @@ module Samagotchi
344
351
  manifest["scripts"] = scripts.transform_keys(&:to_s) unless scripts.empty?
345
352
  manifest["context_providers"] = context_providers.map(&:to_h) unless context_providers.empty?
346
353
  manifest["block_renderers"] = block_renderers.map(&:to_h) unless block_renderers.empty?
354
+ manifest["pages"] = pages.map(&:to_s) unless pages.empty?
347
355
  manifest["session_settings"] = session_settings_entry(session_settings, session_setting_types) unless Array(session_settings).empty?
348
356
  manifest["settings"] = session_settings_entry(settings, setting_types) unless settings.nil?
349
357
  File.write(File.join(dir, "manifest.yml"), YAML.dump(manifest))
@@ -452,6 +460,7 @@ module Samagotchi
452
460
  @context_providers = tolerate(problems, "context_providers", []) { parse_context_providers(raw["context_providers"]) }
453
461
  script_names = problems.key?("scripts") ? fallback_scripts.map(&:to_s) : @scripts.keys
454
462
  @block_renderers = tolerate(problems, "block_renderers", []) { parse_block_renderers(raw["block_renderers"], script_names) }
463
+ @pages = tolerate(problems, "pages", []) { parse_pages(raw["pages"], script_names) }
455
464
  @includes = tolerate(problems, "includes", []) { parse_includes(raw["includes"]) }
456
465
  @session_settings, @session_setting_types = tolerate(problems, "session_settings", [[], {}]) do
457
466
  [self.class.parse_session_settings(raw["session_settings"]), self.class.parse_session_setting_types(raw["session_settings"])]
@@ -650,6 +659,26 @@ module Samagotchi
650
659
  raise ValidationError, e.message
651
660
  end
652
661
 
662
+ # pages: → the page scripts in order, each a scripts: key; [] when absent.
663
+ # @param script_names [Array<String>] the scripts: keys
664
+ # @raise [ValidationError]
665
+ def parse_pages(raw, script_names = @scripts.keys)
666
+ return [] if raw.nil?
667
+ raise ValidationError, "pages: must be a list of script names in scripts/ (NAME.rb)" unless raw.is_a?(Array)
668
+
669
+ raw.each do |file|
670
+ unless file.is_a?(String) && file.end_with?(".rb") && Pages.valid_name?(file.delete_suffix(".rb"))
671
+ raise ValidationError, "pages: #{file.inspect} isn't a page script (NAME.rb, NAME lowercase letters, digits " \
672
+ "and hyphens, at most 40)"
673
+ end
674
+ raise ValidationError, "pages: #{file} isn't under scripts:" unless script_names.include?(file)
675
+ end
676
+ twice = raw.tally.select { |_file, count| count > 1 }.keys
677
+ raise ValidationError, "pages: #{twice.join(", ")} listed more than once" unless twice.empty?
678
+
679
+ raw
680
+ end
681
+
653
682
  # includes: → the names in order, duplicates dropped; [] when absent.
654
683
  # A meta ships nothing of its own, so files, hooks or a plugin next
655
684
  # to it is a ValidationError.
@@ -0,0 +1,11 @@
1
+ ---
2
+ name: schedules
3
+ version: 0.1.0
4
+ scope: system
5
+ description: "A Schedules page in chi web (#/p/schedules, chi page run schedules): every durable schedule, why one is off and how to turn it on, and the recent runs; read-only"
6
+ trust_level: reviewed
7
+ # pages: and runtime.schedules are new in the next chi (release:bump sets the floor)
8
+ requires_chi: ">= 0.189.0"
9
+ scripts:
10
+ schedules.rb: sha256:95d3623bd112a88b49975b45a32d16781eb069eeebb7e5c4bf62ad82ac949ec3
11
+ pages: [schedules.rb]
@@ -0,0 +1,159 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The Schedules page (#/p/schedules), from the schedules bundle
4
+ # (docs/scheduling.md): every durable schedule, why one is off, and the
5
+ # recent runs. Read-only: chi changes a schedule when asked, or
6
+ # `chi schedule enable ID` and the rest do. To make it your own, copy this
7
+ # file to ~/.config/samagotchi/pages/schedules.rb (chi page list --format
8
+ # json gives its path as script) and change it: yours replaces this one.
9
+
10
+ require "time"
11
+
12
+ # The text reads as plain text too (chi web's Markdown is off by default): no
13
+ # headings or bold, only `code` around a command.
14
+
15
+ # How many rows each table shows; the rest are counted, not drawn.
16
+ SCHEDULE_ROWS = 100
17
+ RUN_ROWS = 50
18
+ # How many lines the "Turned off" and "Can't be read" texts show, and how
19
+ # much of a name or a reason a line keeps: a text block holds at most 16 KB,
20
+ # and schedule.max_total can be raised.
21
+ TEXT_LINES = 20
22
+ NAME_CHARS = 60
23
+ REASON_CHARS = 80
24
+
25
+ def cut(text, chars) = text.size > chars ? "#{text[0, chars - 1]}…" : text
26
+
27
+ # The first TEXT_LINES of +lines+, and a line counting the rest.
28
+ def capped(lines, rest_hint)
29
+ return lines if lines.size <= TEXT_LINES
30
+
31
+ lines.first(TEXT_LINES) + ["- and #{lines.size - TEXT_LINES} more: #{rest_hint}"]
32
+ end
33
+
34
+ # A time as the page shows it, in this machine's zone; nil for none.
35
+ def clock(iso)
36
+ return nil if iso.nil? || iso.to_s.empty?
37
+
38
+ Time.iso8601(iso.to_s).localtime.strftime("%Y-%m-%d %H:%M")
39
+ rescue ArgumentError
40
+ iso.to_s
41
+ end
42
+
43
+ def plural(count, word) = "#{count} #{word}#{"s" unless count == 1}"
44
+
45
+ # A failure that turned it off before its budget ran out: a one-off's.
46
+ def failed_once?(schedule) = schedule.failures < schedule.max_failures
47
+
48
+ # The State column: on, firing, or off with why (off_reason).
49
+ def state_words(schedule)
50
+ case schedule.off_reason
51
+ when nil then schedule.state
52
+ when "owner" then "off: you"
53
+ when "skips" then "off: #{plural(schedule.skips, "skip")}"
54
+ when "failures" then failed_once?(schedule) ? "off: failed" : "off: #{plural(schedule.failures, "failure")}"
55
+ when "done" then "done"
56
+ when "missed" then "missed"
57
+ else "off"
58
+ end
59
+ end
60
+
61
+ # Why an off schedule is off, in a sentence's words.
62
+ def why_off(schedule)
63
+ case schedule.off_reason
64
+ when "owner" then "turned off by you"
65
+ when "skips" then "skipped #{plural(schedule.skips, "time")} (#{schedule.skip_window})"
66
+ when "failures" then failed_once?(schedule) ? "one-off, failed" : "failed #{plural(schedule.failures, "time")}"
67
+ when "done" then "one-off, done"
68
+ when "missed" then "one-off, missed"
69
+ else "off"
70
+ end
71
+ end
72
+
73
+ # What the last skip or failure said (a budget's last row reads "disabled: …").
74
+ def last_reason(schedule)
75
+ row = schedule.history.reverse.find { |run| %w[skipped failed].include?(run.status) }
76
+ row&.detail.to_s.delete_prefix("disabled: ")
77
+ end
78
+
79
+ def off_line(schedule)
80
+ line = "- #{cut(schedule.name.to_s, NAME_CHARS)} — #{why_off(schedule)}"
81
+ reason = %w[skips failures].include?(schedule.off_reason) ? cut(last_reason(schedule), REASON_CHARS) : ""
82
+ line += ": #{reason}" unless reason.empty?
83
+ line + " · #{turn_on(schedule)}"
84
+ end
85
+
86
+ # How to turn it on again. Enable alone brings back only a schedule with a
87
+ # next time: a spent one-off (fired, failed, missed) has none, and enabled it
88
+ # would read "on" and never fire. It gets a new moment first (edit keeps it
89
+ # off), then enable.
90
+ def turn_on(schedule)
91
+ return "`chi schedule enable #{schedule.id}`" if schedule.next_due
92
+
93
+ "to run it again: `chi schedule edit #{schedule.id} --date YYYY-MM-DDTHH:MM`, then `chi schedule enable #{schedule.id}`"
94
+ end
95
+
96
+ def unreadable_lines(ids)
97
+ lines = ids.compact.map do |id|
98
+ # An id too long to show can't be given to cancel either.
99
+ next "- schedule #{cut(id, NAME_CHARS)} can't be read: fix or remove it in schedules.json" if id.size > NAME_CHARS
100
+
101
+ "- schedule #{id} can't be read: `chi schedule cancel #{id}` removes it"
102
+ end
103
+ lines = capped(lines, "`chi schedule list` names none of them; schedules.json has them")
104
+ nameless = ids.count(nil)
105
+ lines << "- #{plural(nameless, "schedule")} with no id can't be read: fix or remove it in schedules.json" if nameless.positive?
106
+ lines
107
+ end
108
+
109
+ page "Schedules" do |ui|
110
+ list = runtime.schedules
111
+ if list.entries.empty? && list.unreadable_ids.empty?
112
+ ui.text "No schedules yet. Ask chi (\"check the CI every morning at 9\") or run " \
113
+ "`chi schedule add --session ID --every 1d -m \"…\"`; see docs/scheduling.md."
114
+ next
115
+ end
116
+
117
+ counts = list.entries.map(&:state).tally
118
+ states = %w[on firing off].filter_map { |state| "#{counts[state]} #{state}" if counts[state] }
119
+ summary = "#{plural(list.entries.size, "schedule")}#{": #{states.join(", ")}" unless states.empty?}. Refresh to update."
120
+ ui.text [summary, list.warning].compact.join("\n\n")
121
+
122
+ off = list.entries.select { |schedule| schedule.state == "off" }
123
+ ui.text "Turned off:\n\n#{capped(off.map { |schedule| off_line(schedule) }, "`chi schedule list --all`").join("\n")}" unless off.empty?
124
+ ui.text "Can't be read:\n\n#{unreadable_lines(list.unreadable_ids).join("\n")}" unless list.unreadable_ids.empty?
125
+
126
+ next if list.entries.empty?
127
+
128
+ # On (and firing) first by next due (a firing one-off has none: last of them), then off.
129
+ by_next = ->(schedule) { [schedule.next_due ? 0 : 1, schedule.next_due.to_s, schedule.id.to_s] }
130
+ ordered = list.entries.reject { |schedule| schedule.state == "off" }.sort_by(&by_next) + off
131
+ rows = ordered.first(SCHEDULE_ROWS).map do |schedule|
132
+ { "name" => schedule.name, "state" => state_words(schedule), "when" => schedule.recurrence_words,
133
+ "next" => clock(schedule.next_due), "last_run" => clock(schedule.last_fired), "last_result" => schedule.last_result,
134
+ "skips" => "#{schedule.skips}/#{schedule.max_skips}", "failures" => "#{schedule.failures}/#{schedule.max_failures}",
135
+ "mode" => schedule.mode, "id" => schedule.id.to_s[0, 8] }
136
+ end
137
+ more = ordered.size - rows.size
138
+ ui.text "Schedules#{"\n\nThe first #{SCHEDULE_ROWS}; #{more} more in `chi schedule list --all`." if more.positive?}"
139
+ ui.table rows, columns: { "name" => "Name", "state" => "State", "when" => "When", "next" => "Next", "last_run" => "Last run",
140
+ "last_result" => "Last result", "skips" => "Skips", "failures" => "Failures", "mode" => "Mode",
141
+ "id" => "ID" },
142
+ key: %w[state next]
143
+
144
+ runs = list.entries.flat_map { |schedule| schedule.history.map { |run| [schedule, run] } }
145
+ .sort_by { |_schedule, run| run.at.to_s }.reverse
146
+ if runs.empty?
147
+ ui.text "Recent runs\n\nNo runs recorded yet."
148
+ next
149
+ end
150
+
151
+ shown = runs.first(RUN_ROWS)
152
+ ui.text "Recent runs#{"\n\nThe last #{RUN_ROWS} of #{runs.size}; `chi schedule show ID` has each one's." if runs.size > RUN_ROWS}"
153
+ ui.table shown.map { |schedule, run|
154
+ { "when" => clock(run.at), "schedule" => schedule.name, "what" => run.status, "why" => run.detail,
155
+ "session" => run.session_id&.slice(0, 8) }
156
+ },
157
+ columns: { "when" => "When", "schedule" => "Schedule", "what" => "What", "why" => "Why", "session" => "Session" },
158
+ key: %w[schedule what]
159
+ end
@@ -1,14 +1,14 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.188.0
3
+ version: 0.189.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
7
7
  identity.md: sha256:29c2f7df9f6c5acbc5ec17000a4490741e55e426af15ca0d81c8706edd9bd027
8
- self_map.md: sha256:c46fefc568b9b57c907ecc04f34b181dcc92d1cbcc40ef878a66b3973d79792f
8
+ self_map.md: sha256:5c5b4414f91daa74b436fde4afc77200d3629327f5b465fac40181ebcda7cc01
9
9
  config_modification_protocol.md: sha256:03fdf3ea3138449bc73f73eaa5604cc5d702777c20499ec13ca32b7696e6d37f
10
10
  memory_guide.md: sha256:272443ff8292631b28239cb8431d6e8dd19aa23fc53d05e1a10c11696a0a5d8d
11
11
  delegated.md: sha256:a0d6ddcd4a8be06526d964898611775fd251cfd9d145a9d16afaccaa503597bd
12
12
  skill_pages.md:
13
- sha256: sha256:be6071ce6195ffb3c8340cb458fd5d181f9ef86c87bda44b840f7bf066648478
13
+ sha256: sha256:e5a19c6eae13698f3fa475dd3068368f3cc81c36b1fc6bc4aa6fc9fa2bdc5683
14
14
  description: "Make, change or remove a page in chi web (a table, text or a walk the user reopens at #/p/NAME): write the script, chi page run, check, link"
@@ -71,8 +71,8 @@
71
71
  `docs/bundle-authoring.md` in my source dir first.
72
72
 
73
73
  - Pages: `chi page run|list|rm` runs, lists and removes pages, Ruby scripts in the `pages/` folder beside the
74
- config file whose stored result chi web shows at `#/p/NAME`; how I make one is the `skill_pages` memory
75
- (`docs/pages.md`).
74
+ config file (or a bundle's, as the schedules bundle's) whose stored result chi web shows at `#/p/NAME`; how I make
75
+ one is the `skill_pages` memory (`docs/pages.md`).
76
76
 
77
77
  An MCP host or a script can drive me: `docs/mcp-server.md`, `docs/thin-clients.md`.
78
78
 
@@ -20,8 +20,8 @@ question at hand: that stays in your answer.
20
20
  5. On `error: line N: …` fix that line with edit and run again. The last good result stays meanwhile, so a
21
21
  bad edit never blanks the page.
22
22
  6. Answer in one or two lines: what the page shows, the link [Title](#/p/NAME) as a plain Markdown link, and
23
- that Refresh on the page runs it again. Always add that it is in All sessions, under Pages: Markdown is off by
24
- default, and then the link is plain text. Never put the link in backticks: a code span can't be clicked.
23
+ that Refresh on the page runs it again. Always add that it is under the `pages` pill in chi web's top bar:
24
+ Markdown is off by default, and then the link is plain text. Never put the link in backticks: a code span can't be clicked.
25
25
  7. To change a page: edit the script, run it again (steps 3-4). To remove one: `chi page rm NAME`.
26
26
 
27
27
  ## Never
@@ -77,8 +77,13 @@ What trips a script:
77
77
  fine for a few dozen; group in Ruby). Its `turn_records` are only the newest turn's: for anything per turn
78
78
  or per day, read every turn from `<sessions dir>/ID/analytics.json` (`turn_records`: `completed_at`,
79
79
  `model_ref`, `cost` as reported, `cost_estimate` from the configured price; either may be missing). `chi self`
80
- names the sessions dir. Schedules: `chi schedule list --all --format json`. `json` is loaded; `require`
81
- anything else.
80
+ names the sessions dir. `json` is loaded; `require` anything else.
81
+ - Schedules: `runtime.schedules` in the script reads them in chi itself (no command): each has `id`, `name`,
82
+ `state` (on, firing, off), `off_reason`, `next_due`, `last_fired`, `last_result`, `skips`, `failures` and
83
+ `history` (runs: `at`, `status`, `detail`, `session_id`), the keys of `chi schedule list --all --format json`;
84
+ `ui.table runtime.schedules.rows, columns: …` takes them as rows, and `.warning` says when nothing ticks.
85
+ For a ready page: `chi bundle install schedules`. To make it your own, copy its script (`chi page list
86
+ --format json` names it as `script`) to `<the pages folder>/schedules.rb` and change that.
82
87
  - Check that a command worked (`status.success?`, `$?.success?`) and `raise` with a plain message when it
83
88
  didn't: the page then says why.
84
89
 
@@ -43,6 +43,9 @@ module Samagotchi
43
43
  # script_names the scripts/ files it lists
44
44
  # context_providers Array<ContextProviders::Provider>
45
45
  # block_renderers Array<BlockRenderers::Renderer>
46
+ # pages the page scripts (pages:, Pages::Bundled): the
47
+ # kept manifest's only, [] from the record (a
48
+ # key a later manifest gains is never mirrored)
46
49
  # session_settings, session_setting_types, settings, setting_types
47
50
  # as Manifest reads them (settings nil when
48
51
  # the manifest said nothing of them)
@@ -62,7 +65,7 @@ module Samagotchi
62
65
  # the first chi that read it), {} from the record
63
66
  # origin :kept or :record
64
67
  class Manifest < Data.define(:name, :version, :requires_chi, :trust_level, :description, :needs,
65
- :script_names, :context_providers, :block_renderers, :session_settings,
68
+ :script_names, :context_providers, :block_renderers, :pages, :session_settings,
66
69
  :session_setting_types, :settings, :setting_types, :file_descriptions,
67
70
  :plugin_required, :plugin_parts, :includes, :unknown_keys, :floor_keys, :problems,
68
71
  :origin)
@@ -135,6 +138,7 @@ module Samagotchi
135
138
  script_names: pick.call("scripts", kept.scripts.keys, mirrored.script_names),
136
139
  context_providers: pick.call("context_providers", kept.context_providers, mirrored.context_providers),
137
140
  block_renderers: pick.call("block_renderers", kept.block_renderers, mirrored.block_renderers),
141
+ pages: pick.call("pages", kept.pages, mirrored.pages),
138
142
  session_settings: session.session_settings, session_setting_types: session.session_setting_types,
139
143
  settings: settings.settings, setting_types: settings.setting_types,
140
144
  file_descriptions: pick.call("files", kept.file_descriptions, mirrored.file_descriptions),
@@ -160,6 +164,7 @@ module Samagotchi
160
164
  script_names: bundle.scripts.keys,
161
165
  context_providers: parsed(problems, "context_providers", []) { ContextProviders.parse_list(raw["context_providers"]) },
162
166
  block_renderers: parsed(problems, "block_renderers", []) { BlockRenderers.parse_list(raw["block_renderers"]) },
167
+ pages: [],
163
168
  session_settings: list(raw["session_settings"]) || [],
164
169
  session_setting_types: types(raw["session_setting_types"]),
165
170
  settings: list(raw["settings"]),
@@ -218,6 +223,8 @@ module Samagotchi
218
223
  def context_providers? = !context_providers.empty?
219
224
 
220
225
  def block_renderers? = !block_renderers.empty?
226
+
227
+ def pages? = !pages.empty?
221
228
  end
222
229
  end
223
230
  end
@@ -317,9 +317,10 @@ module Samagotchi
317
317
  end
318
318
  end
319
319
 
320
- # A file only a block renderer's load names: the page loads it, nothing runs it.
320
+ # A file only a block renderer's load or pages: names: a page loads
321
+ # it (the browser's, or a page runner's Ruby), nothing execs it.
321
322
  def page_only?(file)
322
- @manifest.block_renderers.any? { |renderer| renderer.load.include?(file) } &&
323
+ (@manifest.block_renderers.any? { |renderer| renderer.load.include?(file) } || @manifest.pages.include?(file)) &&
323
324
  @manifest.context_providers.none? { |provider| provider.cmd.include?(file) }
324
325
  end
325
326
 
@@ -228,6 +228,7 @@ module Samagotchi
228
228
  scripts: parts.scripts.transform_values { |src| InstalledBundles::FileDigest.sha256(src) },
229
229
  context_providers: parts.context_providers,
230
230
  block_renderers: parts.block_renderers,
231
+ pages: manifest&.pages || [],
231
232
  file_descriptions: manifest ? manifest.file_descriptions.slice(*files_map.keys) : {},
232
233
  session_settings: manifest&.session_settings || [],
233
234
  session_setting_types: manifest&.session_setting_types || {},
@@ -49,7 +49,7 @@ module Samagotchi
49
49
  plugin: plugin(bundle, provenance, dir),
50
50
  scripts: copies(bundle.scripts, provenance.scripts_dir, File.join(dir, "scripts")),
51
51
  requires_chi: manifest.requires_chi, needs: manifest.needs,
52
- context_providers: manifest.context_providers, block_renderers: manifest.block_renderers,
52
+ context_providers: manifest.context_providers, block_renderers: manifest.block_renderers, pages: manifest.pages,
53
53
  session_settings: manifest.session_settings, session_setting_types: manifest.session_setting_types,
54
54
  settings: manifest.settings, setting_types: manifest.setting_types
55
55
  )
@@ -23,13 +23,14 @@ module Samagotchi
23
23
  def self.usage(pages_dir: Paths.tilde(Pages.scripts_dir))
24
24
  <<~TEXT
25
25
  Usage: chi page <run|list|rm> [options]
26
- run NAME [--format text|json] run #{pages_dir}/NAME.rb in a process of its own (in the
26
+ run NAME [--format text|json] run #{pages_dir}/NAME.rb (else an installed bundle's page NAME) in a process of its own (in the
27
27
  pages folder, cut at #{Pages::TIMEOUT_SECONDS} s with what it started), store what it built and print a summary of
28
28
  each block (json: the stored page). A failed run keeps the last good result. Exit 1 when the
29
29
  script raised, was stopped or broke a limit, when there is no such page or it is already running.
30
30
  list [--format text|json] every page: its title, when it last ran or failed (and on which line),
31
- (never ran), and "changed" when the script changed since the result was made
32
- rm NAME remove a page: its script and its stored result
31
+ (never ran), "changed" when the script changed since the result was made, and the bundle a page
32
+ comes with (json: bundle, and script: the path of the script it runs)
33
+ rm NAME remove a page: its script and its stored result (a bundle's page stays: uninstall the bundle)
33
34
  TEXT
34
35
  end
35
36
 
@@ -72,7 +73,7 @@ module Samagotchi
72
73
  send(:"run_#{@sub}", parsed.options, parsed.args)
73
74
  rescue Pages::BadName => e
74
75
  usage_error(e.message)
75
- rescue Pages::Missing, Pages::Busy => e
76
+ rescue Pages::Missing, Pages::Busy, Pages::FromBundle => e
76
77
  error_line("#{command_name}: #{e.message}")
77
78
  CLI::Exit::FAILED
78
79
  rescue Interrupt
@@ -188,7 +189,8 @@ module Samagotchi
188
189
  pages = Pages::Store.list
189
190
  if format == "json"
190
191
  @stdout.puts(JSON.generate(pages.map do |page|
191
- page.to_json_hash.except("blocks").merge("state" => page.state.to_s, "changed" => page.changed?)
192
+ page.to_json_hash.except("blocks").merge("state" => page.state.to_s, "changed" => page.changed?,
193
+ "bundle" => page.bundle, "script" => page.script)
192
194
  end))
193
195
  elsif pages.empty?
194
196
  @stdout.puts("no pages (a page is a script at #{Paths.tilde(Pages.scripts_dir)}/NAME.rb)")
@@ -202,7 +204,8 @@ module Samagotchi
202
204
  table = pages.map do |page|
203
205
  # A control character (a newline, a tab) in a title would break the row.
204
206
  title = page.state == :never_ran ? "(never ran)" : page.title.to_s.gsub(/[[:cntrl:]]+/, " ")
205
- [page.name, title, [status(page), ("changed" if page.changed?)].compact.join(", ")]
207
+ notes = [status(page), ("changed" if page.changed?), ("#{page.bundle} bundle" if page.bundle)]
208
+ [page.name, title, notes.compact.reject(&:empty?).join(", ")]
206
209
  end
207
210
  widths = table.transpose.map { |column| column.map(&:length).max }
208
211
  table.each do |row|
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require_relative "../pages"
5
+ require_relative "../installed_bundles"
6
+ require_relative "../log"
7
+
8
+ module Samagotchi
9
+ module Pages
10
+ # The pages installed bundles ship: a manifest's pages: names scripts/
11
+ # files, each NAME.rb the page NAME (docs/pages.md, "Pages from a
12
+ # bundle"). Read from the install records (InstalledBundles), so chi web
13
+ # answers without loading a plugin. The first bundle by name wins a page
14
+ # name; a bundle chi won't use (its record doesn't read, or it needs a
15
+ # newer chi) ships none. The user's own NAME.rb shadows a bundle's page
16
+ # (Pages.script_path), which is how a page is made one's own: copy the
17
+ # bundle's script there and change it.
18
+ #
19
+ # Loaded only when no NAME.rb of the user's is there (Pages autoloads
20
+ # it): installed_bundles.rb reaches the config, which a user's page run
21
+ # never loads.
22
+ module Bundled
23
+ # One bundle page: its name, the bundle, the scripts/ file and its
24
+ # installed path.
25
+ Page = Data.define(:name, :bundle, :file, :path) do
26
+ # Why chi won't run it (its file is missing, unrecorded, or not as
27
+ # installed: InstalledBundles::Dir#file_refusal's words), nil when it may.
28
+ # @return [String, nil]
29
+ def refusal
30
+ recorded = InstalledBundles.standing(bundle)&.record&.scripts&.fetch(file, nil)
31
+ InstalledBundles::Dir.new(name: bundle).file_refusal(:scripts, file, recorded)&.text
32
+ end
33
+ end
34
+
35
+ # What .unread has logged in this process: [bundle, why] pairs.
36
+ WARNED = Set.new
37
+ WARNED_LOCK = Mutex.new
38
+
39
+ module_function
40
+
41
+ # @return [Array<Page>] by name
42
+ def all
43
+ taken = {}
44
+ InstalledBundles.standings do |standing|
45
+ next unless standing.usable?
46
+
47
+ unread(standing.name, standing.record)
48
+ scripts_dir = InstalledBundles::Dir.new(name: standing.name).scripts_dir
49
+ standing.record.manifest.pages.each do |file|
50
+ name = file.delete_suffix(".rb")
51
+ taken[name] ||= Page.new(name: name, bundle: standing.name, file: file, path: File.join(scripts_dir, file))
52
+ end
53
+ end
54
+ taken.values.sort_by(&:name)
55
+ end
56
+
57
+ # @return [Page, nil]
58
+ def find(name) = all.find { |page| page.name == name }
59
+
60
+ # pages: is read from the kept manifest.yml only (never mirrored in the
61
+ # record): a kept file that is edited, stale or missing, or a pages:
62
+ # that doesn't parse, ships no page. Said once per process per bundle
63
+ # and why, when the kept file (as far as it reads) names pages.
64
+ def unread(bundle, record)
65
+ manifest = record.manifest
66
+ why = manifest.problems["pages"] || (manifest.standing && names_pages?(record.kept_manifest_path) && manifest.standing.to_s)
67
+ return unless why && WARNED_LOCK.synchronize { WARNED.add?([bundle, why]) }
68
+
69
+ Log.warn(:web, "bundle_pages_unread", bundle: bundle, why: why,
70
+ msg: "its kept manifest.yml isn't as installed: reinstall the bundle for its pages")
71
+ end
72
+
73
+ def names_pages?(path)
74
+ path && File.file?(path) && YAML.safe_load_file(path).then { |raw| raw.is_a?(Hash) && raw.key?("pages") }
75
+ rescue StandardError # degrade-ok: a kept file that does not read names no pages (the standing already says why)
76
+ false
77
+ end
78
+
79
+ # Forget what was logged (specs).
80
+ def reset_warnings! = WARNED_LOCK.synchronize { WARNED.clear }
81
+ end
82
+ end
83
+ end
@@ -54,21 +54,31 @@ module Samagotchi
54
54
  # @return [Result]
55
55
  def run(name, timeout: TIMEOUT_SECONDS, cancelled: nil)
56
56
  Pages.check_name!(name)
57
- raise Missing, name unless File.file?(Pages.script_path(name))
57
+ raise Missing, name unless Pages.exists?(name)
58
58
 
59
59
  Store.locked(name) do |lock|
60
60
  # Again under the lock: a `chi page rm` between the check above and
61
61
  # the lock removed the page, so this run writes nothing (not even
62
62
  # the lock file it just made).
63
- unless File.file?(Pages.script_path(name))
63
+ unless Pages.exists?(name)
64
64
  FileUtils.rm_f(Store.lock_path(name))
65
65
  raise Missing, name
66
66
  end
67
+ refusal = Pages.bundled(name)&.refusal
68
+ next refused(name, refusal) if refusal
67
69
 
68
70
  launch(name, timeout, lock, cancelled)
69
71
  end
70
72
  end
71
73
 
74
+ # A bundle page whose script isn't as installed runs nothing: the run
75
+ # fails with the refusal's words (Bundled::Page#refusal), the last good
76
+ # result kept, as any failed run.
77
+ def refused(name, refusal)
78
+ Store.record_failure(name, message: refusal, line: nil, script_sha: Store.script_sha(name))
79
+ Result.new(ok: false, page: Store.read(name), stdout: "", stderr: "", seconds: 0.0)
80
+ end
81
+
72
82
  # The runner's argv: the name, the timeout (for its cut's words) and
73
83
  # its own deadline in seconds.
74
84
  def command(name, timeout)
@@ -101,6 +111,8 @@ module Samagotchi
101
111
 
102
112
  def launch(name, timeout, lock, cancelled)
103
113
  before = Store.file_id(name)
114
+ # A bundle's page runs there too: the folder may not exist yet.
115
+ FileUtils.mkdir_p(Pages.scripts_dir)
104
116
  started = monotonic
105
117
  out_r, out_w = IO.pipe
106
118
  err_r, err_w = IO.pipe
@@ -16,12 +16,14 @@ module Samagotchi
16
16
  # and from chi web.
17
17
  #
18
18
  # The script is loaded with a fresh module as its wrap (Kernel#load), which
19
- # gives it `page` and keeps its own methods off Object. What the run built,
19
+ # gives it `page` and `runtime` and keeps its own methods off Object. What the run built,
20
20
  # or what it raised, goes to the output file (Store), never to stdout: a
21
21
  # `puts` in a script is the script's own. A TERM (Launch's cut) is not
22
22
  # rescued: the launcher records the cut itself.
23
23
  module Runner
24
- # The script's `page "Title" do |ui| … end`, once per run.
24
+ # The script's `page "Title" do |ui| … end`, once per run, and its
25
+ # `runtime` (Pages::Runtime, made on first use: a page that never asks
26
+ # loads none of it).
25
27
  class Collector
26
28
  attr_reader :builder
27
29
 
@@ -31,9 +33,12 @@ module Samagotchi
31
33
  define_method(:page) do |title, &block|
32
34
  collector.page(title, &block)
33
35
  end
36
+ define_method(:runtime) { collector.runtime }
34
37
  end
35
38
  end
36
39
 
40
+ def runtime = @runtime ||= Runtime.new
41
+
37
42
  def page(title)
38
43
  raise Refused, "a page script calls page once" if @builder
39
44