samagotchi 0.186.0 → 0.188.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 (153) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +4 -0
  4. data/docs/architecture.md +8 -4
  5. data/docs/bundles.md +124 -120
  6. data/docs/cli.md +26 -5
  7. data/docs/configuration.md +4 -4
  8. data/docs/context.md +18 -162
  9. data/docs/guardrails.md +3 -1
  10. data/docs/hooks.md +2 -1
  11. data/docs/internals/attached-context.md +19 -37
  12. data/docs/internals/bridge.md +1 -0
  13. data/docs/internals/engine.md +2 -2
  14. data/docs/internals/inline-widgets.md +18 -0
  15. data/docs/internals/llm-context-forget.md +5 -6
  16. data/docs/internals/objectives.md +1 -0
  17. data/docs/internals/pages.md +175 -0
  18. data/docs/internals/peers.md +149 -0
  19. data/docs/internals/remote-sessions.md +7 -4
  20. data/docs/internals/web-frontend.md +65 -40
  21. data/docs/internals/web-push.md +1 -1
  22. data/docs/memory.md +8 -1
  23. data/docs/pages.md +151 -0
  24. data/docs/peers.md +141 -0
  25. data/docs/plugins.md +52 -27
  26. data/docs/sessions.md +8 -4
  27. data/docs/sub-agent.md +5 -5
  28. data/lib/samagotchi/bridge.rb +3 -3
  29. data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
  30. data/lib/samagotchi/bundle_command/check.rb +1 -1
  31. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
  32. data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
  33. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
  34. data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
  35. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
  36. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
  37. data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
  38. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
  39. data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
  40. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
  41. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  42. data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
  43. data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
  44. data/lib/samagotchi/bundles/system/manifest.yml +5 -2
  45. data/lib/samagotchi/bundles/system/self_map.md +5 -1
  46. data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
  47. data/lib/samagotchi/client_id.rb +15 -1
  48. data/lib/samagotchi/config.rb +8 -7
  49. data/lib/samagotchi/context_absorber.rb +23 -277
  50. data/lib/samagotchi/context_sources.rb +17 -69
  51. data/lib/samagotchi/engine/messages.rb +12 -1
  52. data/lib/samagotchi/engine/plugins.rb +1 -1
  53. data/lib/samagotchi/engine.rb +7 -6
  54. data/lib/samagotchi/engine_peers.rb +0 -3
  55. data/lib/samagotchi/guardrail_wiring.rb +2 -0
  56. data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
  57. data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
  58. data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
  59. data/lib/samagotchi/inline_widgets.rb +73 -0
  60. data/lib/samagotchi/log_line.rb +1 -1
  61. data/lib/samagotchi/note_move.rb +3 -1
  62. data/lib/samagotchi/page_command.rb +243 -0
  63. data/lib/samagotchi/pages/builder.rb +186 -0
  64. data/lib/samagotchi/pages/launch.rb +193 -0
  65. data/lib/samagotchi/pages/runner.rb +154 -0
  66. data/lib/samagotchi/pages/store.rb +152 -0
  67. data/lib/samagotchi/pages.rb +119 -0
  68. data/lib/samagotchi/peer_command.rb +192 -0
  69. data/lib/samagotchi/peer_continue.rb +99 -0
  70. data/lib/samagotchi/peer_exchanges.rb +3 -3
  71. data/lib/samagotchi/peer_mailbox.rb +360 -0
  72. data/lib/samagotchi/peer_note.rb +208 -0
  73. data/lib/samagotchi/peer_receipts.rb +247 -0
  74. data/lib/samagotchi/peer_registry.rb +44 -0
  75. data/lib/samagotchi/peer_roster.rb +79 -0
  76. data/lib/samagotchi/peer_say.rb +168 -0
  77. data/lib/samagotchi/plugin/api.rb +29 -21
  78. data/lib/samagotchi/plugin/context.rb +7 -0
  79. data/lib/samagotchi/plugin/loader.rb +3 -3
  80. data/lib/samagotchi/plugin/peer.rb +175 -64
  81. data/lib/samagotchi/plugin/peers.rb +70 -0
  82. data/lib/samagotchi/run_options.rb +3 -1
  83. data/lib/samagotchi/schedule_command.rb +10 -3
  84. data/lib/samagotchi/schedule_display.rb +32 -0
  85. data/lib/samagotchi/session_access/contract.rb +19 -2
  86. data/lib/samagotchi/session_access/local.rb +132 -14
  87. data/lib/samagotchi/session_access/remote.rb +4 -2
  88. data/lib/samagotchi/session_access/remote_peers.rb +75 -0
  89. data/lib/samagotchi/session_continue.rb +12 -0
  90. data/lib/samagotchi/session_inbox_delivery.rb +5 -2
  91. data/lib/samagotchi/session_manager/delivery.rb +5 -3
  92. data/lib/samagotchi/session_manager/removal.rb +2 -0
  93. data/lib/samagotchi/session_manager/spawn.rb +2 -1
  94. data/lib/samagotchi/session_manager.rb +1 -0
  95. data/lib/samagotchi/session_stores.rb +17 -0
  96. data/lib/samagotchi/steer.rb +1 -1
  97. data/lib/samagotchi/system_prompt.rb +1 -1
  98. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  99. data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
  100. data/lib/samagotchi/testing/boundary.rb +4 -13
  101. data/lib/samagotchi/testing/bundle.rb +40 -5
  102. data/lib/samagotchi/testing/install.rb +4 -4
  103. data/lib/samagotchi/testing/recording_api.rb +2 -1
  104. data/lib/samagotchi/tools/context_read.rb +0 -14
  105. data/lib/samagotchi/tools/list_schedules.rb +8 -3
  106. data/lib/samagotchi/version.rb +1 -1
  107. data/lib/samagotchi/web/app.rb +7 -18
  108. data/lib/samagotchi/web/message_display.rb +4 -2
  109. data/lib/samagotchi/web/page_routes.rb +116 -0
  110. data/lib/samagotchi/web/peer_routes.rb +133 -0
  111. data/lib/samagotchi/web/public/app.js +35 -95
  112. data/lib/samagotchi/web/public/bubbles.js +2 -2
  113. data/lib/samagotchi/web/public/cards_place.js +20 -1
  114. data/lib/samagotchi/web/public/context_chips.js +45 -46
  115. data/lib/samagotchi/web/public/history_reveal.js +4 -1
  116. data/lib/samagotchi/web/public/history_shape.js +3 -2
  117. data/lib/samagotchi/web/public/index.html +16 -0
  118. data/lib/samagotchi/web/public/notify.js +1 -1
  119. data/lib/samagotchi/web/public/page_blocks.js +58 -0
  120. data/lib/samagotchi/web/public/page_links.js +33 -0
  121. data/lib/samagotchi/web/public/page_model.js +68 -0
  122. data/lib/samagotchi/web/public/page_route.js +24 -0
  123. data/lib/samagotchi/web/public/page_table.js +74 -0
  124. data/lib/samagotchi/web/public/page_table_model.js +76 -0
  125. data/lib/samagotchi/web/public/page_view.js +219 -0
  126. data/lib/samagotchi/web/public/pages.css +77 -0
  127. data/lib/samagotchi/web/public/pages_group.js +65 -0
  128. data/lib/samagotchi/web/public/peer_chip.js +60 -74
  129. data/lib/samagotchi/web/public/peer_data.js +13 -11
  130. data/lib/samagotchi/web/public/peer_links.js +12 -7
  131. data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
  132. data/lib/samagotchi/web/public/peer_note.js +7 -3
  133. data/lib/samagotchi/web/public/peer_text.js +4 -4
  134. data/lib/samagotchi/web/public/quiet_notes.js +199 -0
  135. data/lib/samagotchi/web/public/revise_stack.js +4 -3
  136. data/lib/samagotchi/web/public/session_view.js +2 -2
  137. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  138. data/lib/samagotchi/web/public/turn_block.js +7 -3
  139. data/lib/samagotchi/web/public/turn_events.js +6 -0
  140. data/lib/samagotchi/web/public/views.js +161 -0
  141. data/lib/samagotchi/web/push/attention.rb +3 -2
  142. data/lib/samagotchi/web/session_access_routes.rb +3 -20
  143. data/lib/samagotchi/web/viewer.rb +1 -1
  144. data/lib/samagotchi/worker/leave.rb +3 -0
  145. data/lib/samagotchi/worker/mail.rb +73 -0
  146. data/lib/samagotchi/worker/startup.rb +3 -0
  147. data/lib/samagotchi/worker/wake_turns.rb +20 -5
  148. data/lib/samagotchi/worker.rb +12 -6
  149. data/lib/samagotchi/worker_inbound/mail.rb +214 -0
  150. data/lib/samagotchi/worker_inbound.rb +43 -46
  151. data/lib/samagotchi/worker_wakes.rb +26 -21
  152. metadata +39 -2
  153. data/lib/samagotchi/peer_sources.rb +0 -58
@@ -269,6 +269,7 @@ module Samagotchi
269
269
  @protected ||= begin
270
270
  require_relative "installed_bundles"
271
271
  require_relative "context_sources"
272
+ require_relative "peer_mailbox"
272
273
  require_relative "chi_home"
273
274
  require_relative "chi_shim"
274
275
  require_relative "paths"
@@ -278,6 +279,7 @@ module Samagotchi
278
279
  config_path: Samagotchi::ConfigFile.global_path,
279
280
  hooks_dir: Hooks::Loader.hooks_dir,
280
281
  context_dir: ContextSources.root,
282
+ mailbox_dir: PeerMailbox.root,
281
283
  runs_dir: File.join(File.dirname(@approvals.path, 2), "system_one"),
282
284
  home_path: ChiHome.path,
283
285
  shim_path: ChiShim.path,
@@ -13,7 +13,7 @@ module Samagotchi
13
13
  # (read each call). Each surface keeps its set:
14
14
  # .protected the config dir, the hooks dir, the approval store's
15
15
  # dir, the installed bundles' dir, attached context,
16
- # System 1's saved runs: an ask only the user may answer
16
+ # the peer mailbox, System 1's saved runs: an ask only the user may answer
17
17
  # (ParentApprovals.chi_files?)
18
18
  # .touches .protected and the session repo's git hooks dir: a
19
19
  # rule's touches: chi_dirs (Targets#touches_chi?)
@@ -28,13 +28,14 @@ module Samagotchi
28
28
  module_function
29
29
 
30
30
  # chi's config dir, the hooks dir, the approval store's dir, the
31
- # installed bundles' dir, attached context and System 1's saved runs
31
+ # installed bundles' dir, attached context, the peer mailbox (a message
32
+ # there speaks as a peer) and System 1's saved runs
32
33
  # (labels there may train a model: no agent writes them).
33
34
  def protected
34
35
  hooks = begin Hooks::Loader.hooks_dir rescue nil end
35
36
  bundles = begin MemoryPaths.bundles_dir rescue nil end
36
37
  [ConfigFile.config_dir, hooks, File.join(Paths.state_dir, "guardrails"), bundles, File.join(Paths.state_dir, "context"),
37
- File.join(Paths.state_dir, "system_one")]
38
+ File.join(Paths.state_dir, "mailbox"), File.join(Paths.state_dir, "system_one")]
38
39
  .compact.map { |dir| dir.to_s.chomp("/") }.reject(&:empty?).uniq
39
40
  end
40
41
 
@@ -32,11 +32,12 @@ module Samagotchi
32
32
  AGENT_MARKERS = ["CLAUDECODE", "AI_AGENT", "CODEX_THREAD_ID", PARENT_SESSION_ENV].freeze
33
33
  # Rules only the user may allow (Verdict::PROTECTED_RULES).
34
34
  PROTECTED_RULES = Verdict::PROTECTED_RULES
35
- # A shell command naming chi's config, hooks, guardrails or attached
36
- # context as text (broad: a parent may not allow what only looks like
37
- # one). samagotchi/context stops before a word character or a dot, so
38
- # chi's own lib/samagotchi/context_*.rb isn't one.
39
- CHI_TEXT = %r{\.config/samagotchi|samagotchi/config\.yml|samagotchi/hooks|samagotchi/guardrails|samagotchi/context(?![\w.])|memories/\.bundles}
35
+ # A shell command naming chi's config, hooks, guardrails, attached
36
+ # context or the peer mailbox as text (broad: a parent may not allow
37
+ # what only looks like one). samagotchi/context and samagotchi/mailbox
38
+ # stop before a word character or a dot, so chi's own
39
+ # lib/samagotchi/context_*.rb isn't one.
40
+ CHI_TEXT = %r{\.config/samagotchi|samagotchi/config\.yml|samagotchi/hooks|samagotchi/guardrails|samagotchi/context(?![\w.])|samagotchi/mailbox(?![\w.])|memories/\.bundles}
40
41
  # The guardrails bundle's ask before a memory removal: its paths are in
41
42
  # the config dir, yet a parent may answer it.
42
43
  MEMORY_REMOVE_RULE = "memory-remove"
@@ -14,8 +14,9 @@ module Samagotchi
14
14
  # deny: the approval store's dir, installed bundles (.bundles/:
15
15
  # hooks, rules, manifests), attached context (a source's
16
16
  # command runs later, outside the gate; chi context writes
17
- # it) and System 1's saved runs (a label there may train a
18
- # model); nothing legitimate writes there through a tool
17
+ # it), the peer mailbox (a message there speaks as a peer
18
+ # agent; chi peer writes it) and System 1's saved runs (a
19
+ # label there may train a model); nothing legitimate writes there through a tool
19
20
  # that says it writes.
20
21
  # ask (once / session): config.yml, home.json (the chi home: the
21
22
  # Ruby every chi launch boots), the chi shim (ChiShim: the
@@ -47,12 +48,13 @@ module Samagotchi
47
48
  # @param config_path [String] config.yml
48
49
  # @param hooks_dir [String] the plain hooks dir
49
50
  # @param context_dir [String, nil] <state dir>/context (ContextSources.root)
51
+ # @param mailbox_dir [String, nil] <state dir>/mailbox (PeerMailbox.root)
50
52
  # @param runs_dir [String, nil] <state dir>/system_one (SystemOne::Runs)
51
53
  # @param home_path [String, nil] home.json (ChiHome.path)
52
54
  # @param shim_path [String, nil] the chi shim (ChiShim.path)
53
55
  # @param plugins_dir [String, nil] <state dir>/plugins (the bundles' data, their secrets/ in it)
54
56
  def initialize(store_dir:, bundles_dir:, config_path:, hooks_dir:, context_dir: nil, runs_dir: nil, home_path: nil, shim_path: nil,
55
- plugins_dir: nil)
57
+ plugins_dir: nil, mailbox_dir: nil)
56
58
  @plugins_dir = plugins_dir
57
59
  # The same, spelled out: this state dir's own plugins/<x>/secrets.
58
60
  @secrets_text = plugins_dir && Regexp.union(SECRETS_TEXT, *([plugins_dir.to_s.chomp("/")] | PathResolve.reals(plugins_dir.to_s.chomp("/"))).map do |dir|
@@ -62,6 +64,7 @@ module Samagotchi
62
64
  ["guardrail-store", store_dir, "the approval store belongs to the user"],
63
65
  ["installed-bundles", bundles_dir, "installed bundles (hooks, rules, manifests) are changed by chi bundle install"],
64
66
  ["chi-context", context_dir, "attached context sources run commands; change them with chi context"],
67
+ ["chi-mailbox", mailbox_dir, "a message there speaks as a peer agent; chi peer writes the peer mailbox"],
65
68
  ["system-one-runs", runs_dir, "System 1's saved runs are chi's own record"]
66
69
  ]
67
70
  @ask = [
@@ -91,6 +91,30 @@ module Samagotchi
91
91
  Result.new(type: nil, data: nil, lenient: lenient, error: "the block nests too deep")
92
92
  end
93
93
 
94
+ # A script's data (a page's walk, Pages::Builder) through the same schema
95
+ # as a block's YAML, so the same widget draws it: one deep conversion
96
+ # (DataTree) into what Tree hands Schema, then Schema unchanged, with no
97
+ # folds and no lenient pass. A picks id that Schema#row_id mends is mended
98
+ # here too, and the result still isn't lenient: there was no source to be
99
+ # lenient with.
100
+ # @return [Result]
101
+ def check(type, data)
102
+ type = type.to_s if type.is_a?(Symbol)
103
+ raise Refused, "the data's type #{echo(type)} isn't picks or walk" unless TYPES.include?(type)
104
+
105
+ raise Refused, "the data isn't a mapping" unless data.is_a?(Hash)
106
+
107
+ tree = DataTree.convert(data)
108
+ schema = Schema.new({}.compare_by_identity)
109
+ data = type == "picks" ? schema.picks(tree) : schema.walk(tree)
110
+ Result.new(type: type, data: data, lenient: false, error: nil)
111
+ rescue Refused => e
112
+ Result.new(type: TYPES.include?(type) ? type : nil, data: nil, lenient: false, error: e.message)
113
+ rescue SystemStackError
114
+ # DataTree's depth and loop guards come first; this is the backstop.
115
+ Result.new(type: nil, data: nil, lenient: false, error: "the data nests too deep")
116
+ end
117
+
94
118
  def echo(type)
95
119
  return "(not text)" unless type.is_a?(String)
96
120
 
@@ -173,6 +197,55 @@ module Samagotchi
173
197
  end
174
198
  end
175
199
 
200
+ # A script's Hashes, Arrays and values as Tree would have read them from
201
+ # YAML: keys strings (a Symbol or a number made its text), a String kept
202
+ # (scrubbed to valid UTF-8), a Symbol or a number made its text, nil kept
203
+ # (absent). true, false and anything else are refused with the path to
204
+ # them (steps[2].does), since YAML text never reads as one here.
205
+ module DataTree
206
+ module_function
207
+
208
+ def convert(value, path = nil, depth = 1, open = {}.compare_by_identity)
209
+ raise Refused, "the data nests too deep" if depth > MAX_DEPTH || open.key?(value)
210
+
211
+ case value
212
+ when Hash, Array then nested(value, path, depth, open)
213
+ when String then text(value)
214
+ when Symbol, Integer, Float then value.to_s
215
+ when nil then nil
216
+ else raise Refused, "#{path || "the data"} must be text, not #{shown(value)}"
217
+ end
218
+ end
219
+
220
+ def text(value)
221
+ value = value.to_s
222
+ if [Encoding::BINARY, Encoding::US_ASCII].include?(value.encoding)
223
+ value.dup.force_encoding(Encoding::UTF_8).scrub
224
+ else
225
+ value.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
226
+ end
227
+ end
228
+
229
+ def nested(value, path, depth, open)
230
+ open[value] = true
231
+ if value.is_a?(Array)
232
+ value.each_with_index.map { |item, index| convert(item, "#{path || "the data"}[#{index}]", depth + 1, open) }
233
+ else
234
+ value.to_h { |key, item| [key(key, path), convert(item, path ? "#{path}.#{key}" : key.to_s, depth + 1, open)] }
235
+ end
236
+ ensure
237
+ open.delete(value)
238
+ end
239
+
240
+ def key(key, path)
241
+ return text(key) if key.is_a?(String) || key.is_a?(Symbol) || key.is_a?(Integer)
242
+
243
+ raise Refused, "#{path || "the data"} has a key that isn't text"
244
+ end
245
+
246
+ def shown(value) = [true, false].include?(value) ? value.to_s : "a #{value.class}"
247
+ end
248
+
176
249
  # Eval 0013's lenient pass: a free-text value, or a list item that isn't a
177
250
  # mapping, goes in quotes unless it is one clean scalar already, so
178
251
  # `does: Asked: ...`, `- B: keep 1 h` and `text: "x" is called` all parse.
@@ -16,7 +16,7 @@ module Samagotchi
16
16
  # (debug dumps) are indented by four spaces and belong to the record above.
17
17
  module LogLine
18
18
  LEVELS = %w[DEBUG INFO WARN ERROR].freeze
19
- TAGS = %w[turn http worker bridge web attached idle recap hooks plugins guardrails config memory model context broadcast toolkit system_one prompt].freeze
19
+ TAGS = %w[turn http worker bridge web attached idle recap hooks plugins guardrails config memory model context peer broadcast toolkit system_one prompt].freeze
20
20
  INDENT = " "
21
21
 
22
22
  Record = Struct.new(:ts, :level, :tag, :pid, :sid, :event, :fields, :payload, keyword_init: true)
@@ -7,6 +7,7 @@ require_relative "archive_store"
7
7
  require_relative "context_move"
8
8
  require_relative "log"
9
9
  require_relative "objectives"
10
+ require_relative "peer_continue"
10
11
  require_relative "session"
11
12
  require_relative "session_chain"
12
13
  require_relative "session_inbox"
@@ -27,7 +28,8 @@ module Samagotchi
27
28
  # The notes a continue writes into its new link itself (the chain note,
28
29
  # ChildMove's, the attached context's, the objectives' carry): a failed
29
30
  # continue deletes them with the link.
30
- CONTINUE_SOURCES = [SessionChain::NOTE_SOURCE, ContextMove::NOTE_SOURCE, Objectives::SOURCE].freeze
31
+ CONTINUE_SOURCES = [SessionChain::NOTE_SOURCE, ContextMove::NOTE_SOURCE, Objectives::SOURCE,
32
+ PeerContinue::NOTE_SOURCE].freeze
31
33
 
32
34
  module_function
33
35
 
@@ -0,0 +1,243 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "cli/command"
5
+ require_relative "cli/exit"
6
+ require_relative "cli/flags"
7
+ require_relative "message_time"
8
+ require_relative "pages"
9
+ require_relative "pages/store"
10
+ require_relative "pages/launch"
11
+
12
+ module Samagotchi
13
+ # `chi page`: run, list and remove pages (docs/pages.md). run goes through
14
+ # Pages::Launch, the one launch path chi web's Refresh takes too, and
15
+ # prints what a model needs to check its own work: per block a few lines,
16
+ # a table's labels, first rows and total, formatted as the page shows them.
17
+ class PageCommand
18
+ include CLI::Command
19
+
20
+ # The help, with the folder chi page reads its scripts from as the user
21
+ # sees it (~ for the home folder). Read when printed, so a config home set
22
+ # after load (XDG_CONFIG_HOME) names its own pages folder.
23
+ def self.usage(pages_dir: Paths.tilde(Pages.scripts_dir))
24
+ <<~TEXT
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
27
+ pages folder, cut at #{Pages::TIMEOUT_SECONDS} s with what it started), store what it built and print a summary of
28
+ each block (json: the stored page). A failed run keeps the last good result. Exit 1 when the
29
+ script raised, was stopped or broke a limit, when there is no such page or it is already running.
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
33
+ TEXT
34
+ end
35
+
36
+ # The help as chi loaded, for callers that want the text itself.
37
+ USAGE = usage
38
+
39
+ SUBCOMMANDS = %w[run list rm].freeze
40
+
41
+ FLAGS = {
42
+ "run" => CLI::Flags.new(help: HELP_WORDS) { |f| f.value "--format" },
43
+ "list" => CLI::Flags.new(help: HELP_WORDS) { |f| f.value "--format" },
44
+ "rm" => CLI::Flags.new(help: HELP_WORDS)
45
+ }.freeze
46
+
47
+ # How much of a run's summary each block gets.
48
+ TEXT_LINES = 3
49
+ TEXT_CHARS = 240
50
+ TABLE_ROWS = 3
51
+ STDERR_LINES = 10
52
+ BLANK = "—"
53
+
54
+ def initialize(argv, stdout: $stdout, stderr: $stderr)
55
+ @argv = argv.dup
56
+ @stdout = stdout
57
+ @stderr = stderr
58
+ end
59
+
60
+ # @return [Integer] 0 done, 1 failed (the script, no such page, busy), 2 usage
61
+ def run
62
+ @sub = @argv[0]
63
+ if @sub.nil? || HELP_WORDS.include?(@sub)
64
+ @stdout.puts(usage_text)
65
+ return CLI::Exit::OK
66
+ end
67
+ return usage_error("unknown subcommand #{@sub}") unless SUBCOMMANDS.include?(@sub)
68
+
69
+ parsed = parse_flags(FLAGS.fetch(@sub), @argv[1..])
70
+ return parsed if parsed.is_a?(Integer)
71
+
72
+ send(:"run_#{@sub}", parsed.options, parsed.args)
73
+ rescue Pages::BadName => e
74
+ usage_error(e.message)
75
+ rescue Pages::Missing, Pages::Busy => e
76
+ error_line("#{command_name}: #{e.message}")
77
+ CLI::Exit::FAILED
78
+ rescue Interrupt
79
+ CLI::Exit::INTERRUPTED
80
+ end
81
+
82
+ # The summary's form of a cell: :money as $0.0000, :count as 1.2k / 3.4M,
83
+ # nil as —, anything else as it is.
84
+ def self.cell(value, format)
85
+ return BLANK if value.nil?
86
+ return value.to_s unless value.is_a?(Numeric)
87
+
88
+ case format
89
+ when "money" then Kernel.format("$%.4f", value)
90
+ when "count" then count(value)
91
+ else value.to_s
92
+ end
93
+ end
94
+
95
+ def self.count(value)
96
+ size = value.abs
97
+ return value.to_s if size < 1000
98
+
99
+ text, unit = size < 1_000_000 ? [value / 1000.0, "k"] : [value / 1_000_000.0, "M"]
100
+ "#{Kernel.format("%.1f", text).delete_suffix(".0")}#{unit}"
101
+ end
102
+
103
+ private
104
+
105
+ def command_name = @sub && SUBCOMMANDS.include?(@sub) ? "chi page #{@sub}" : "chi page"
106
+ def usage_on_error = nil
107
+ def usage_text = self.class.usage
108
+
109
+ def one_name(args)
110
+ return usage_error("give the page's NAME") if args.empty?
111
+ return usage_error("#{@sub} takes one NAME (unexpected #{args[1]})") if args.size > 1
112
+
113
+ Pages.check_name!(args.first)
114
+ end
115
+
116
+ def run_run(options, args)
117
+ format = options[:format]
118
+ refused = format_refusal(format)
119
+ return refused if refused
120
+
121
+ name = one_name(args)
122
+ return name if name.is_a?(Integer)
123
+
124
+ result = Pages::Launch.run(name)
125
+ if format == "json"
126
+ @stdout.puts(JSON.generate(result.page.to_json_hash))
127
+ elsif result.ok?
128
+ print_summary(result)
129
+ else
130
+ print_failure(result)
131
+ end
132
+ result.ok? ? CLI::Exit::OK : CLI::Exit::FAILED
133
+ end
134
+
135
+ def print_summary(result)
136
+ page = result.page
137
+ @stdout.puts(%(page #{page.name}: #{page.title.inspect} (#{Kernel.format("%.1f", result.seconds)} s)))
138
+ page.blocks.each { |block| summary(block).each { |line| @stdout.puts(line) } }
139
+ end
140
+
141
+ def summary(block)
142
+ case block["type"]
143
+ when "text" then text_summary(block["text"].to_s)
144
+ when "table" then table_summary(block)
145
+ when "walk" then [%(- walk: #{block.dig("data", "title").to_s.inspect}, #{Array(block.dig("data", "steps")).size} steps)]
146
+ else ["- #{block["type"]}"]
147
+ end
148
+ end
149
+
150
+ def text_summary(text)
151
+ lines = text.lines.map(&:chomp)
152
+ shown = lines.first(TEXT_LINES).join("\n")
153
+ cut = lines.size > TEXT_LINES || shown.size > TEXT_CHARS
154
+ shown = shown[0, TEXT_CHARS]
155
+ first, *rest = shown.split("\n", -1)
156
+ ["- text: #{first}#{" …" if cut && rest.empty?}", *rest.each_with_index.map do |line, i|
157
+ " #{line}#{" …" if cut && i == rest.size - 1}"
158
+ end]
159
+ end
160
+
161
+ def table_summary(block)
162
+ columns = Array(block["columns"])
163
+ rows = Array(block["rows"])
164
+ dropped = block["dropped"].to_i
165
+ head = "- table, #{rows.size} rows#{" (#{dropped} dropped)" unless dropped.zero?}, columns: " \
166
+ "#{columns.map { |c| c["label"] }.join(", ")}"
167
+ line = ->(cells) { columns.each_with_index.map { |c, i| self.class.cell(cells[i], c["format"]) }.join(" | ") }
168
+ [head, *rows.first(TABLE_ROWS).map { |cells| " #{line.call(cells)}" },
169
+ *(" total: #{line.call(block["total"])}" if block["total"])]
170
+ end
171
+
172
+ def print_failure(result)
173
+ page = result.page
174
+ error = page.error
175
+ @stdout.flush
176
+ @stderr.puts("error: #{"line #{error.line}: " if error&.line}#{error&.message}")
177
+ result.stderr.lines.map(&:chomp).reject(&:empty?).last(STDERR_LINES).each { |line| @stderr.puts(" #{line}") }
178
+ @stderr.puts("the result of #{local(page.ran_at)} is kept") if page.ran_at
179
+ end
180
+
181
+ def run_list(options, args)
182
+ return usage_error("list takes no NAME (unexpected #{args.first})") unless args.empty?
183
+
184
+ format = options[:format]
185
+ refused = format_refusal(format)
186
+ return refused if refused
187
+
188
+ pages = Pages::Store.list
189
+ if format == "json"
190
+ @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
+ end))
193
+ elsif pages.empty?
194
+ @stdout.puts("no pages (a page is a script at #{Paths.tilde(Pages.scripts_dir)}/NAME.rb)")
195
+ else
196
+ print_list(pages)
197
+ end
198
+ CLI::Exit::OK
199
+ end
200
+
201
+ def print_list(pages)
202
+ table = pages.map do |page|
203
+ # A control character (a newline, a tab) in a title would break the row.
204
+ 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(", ")]
206
+ end
207
+ widths = table.transpose.map { |column| column.map(&:length).max }
208
+ table.each do |row|
209
+ @stdout.puts(row.each_with_index.map { |cell, i| i == row.size - 1 ? cell : cell.ljust(widths[i]) }.join(" ").rstrip)
210
+ end
211
+ end
212
+
213
+ def status(page)
214
+ case page.state
215
+ when :ok then "ran #{ago(page.ran_at)}"
216
+ when :failed then "failed #{ago(page.error.at)}#{" (line #{page.error.line})" if page.error.line}"
217
+ else ""
218
+ end
219
+ end
220
+
221
+ def ago(iso)
222
+ seconds = Time.now - Time.iso8601(iso.to_s)
223
+ seconds < 60 ? "#{[seconds.round, 0].max} s ago" : "#{MessageTime.ago(seconds)} ago"
224
+ rescue ArgumentError
225
+ "at #{iso}"
226
+ end
227
+
228
+ def local(iso)
229
+ Time.iso8601(iso.to_s).localtime.strftime("%Y-%m-%d %H:%M")
230
+ rescue ArgumentError
231
+ iso.to_s
232
+ end
233
+
234
+ def run_rm(_options, args)
235
+ name = one_name(args)
236
+ return name if name.is_a?(Integer)
237
+
238
+ Pages::Store.remove(name)
239
+ @stdout.puts("removed page #{name}")
240
+ CLI::Exit::OK
241
+ end
242
+ end
243
+ end
@@ -0,0 +1,186 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../pages"
4
+
5
+ module Samagotchi
6
+ module Pages
7
+ # What a page script's `ui` is: text, table and walk, each adding one
8
+ # block in order. #data is the page as stored (plain Hashes: it is the
9
+ # JSON edge). A rule broken raises Refused naming the block by its place
10
+ # on the page ("table 2: …"), and the run fails with it.
11
+ class Builder
12
+ attr_reader :title
13
+
14
+ def initialize(title)
15
+ @title = Builder.text_of(title).strip
16
+ raise Refused, "page needs a title" if @title.empty?
17
+
18
+ @blocks = []
19
+ end
20
+
21
+ # @return [Hash] {"title" => …, "blocks" => [...]}
22
+ def data = { "title" => @title, "blocks" => @blocks }
23
+
24
+ # A Markdown text block.
25
+ def text(markdown)
26
+ where = place("text")
27
+ text = Builder.text_of(markdown)
28
+ if text.bytesize > MAX_TEXT_BYTES
29
+ raise Refused, "#{where} is #{kb(text.bytesize)} (at most #{MAX_TEXT_BYTES / 1024} KB)"
30
+ end
31
+
32
+ add("type" => "text", "text" => text)
33
+ end
34
+
35
+ # A table of +rows+ (Hashes, string or symbol keys). +columns+ is a
36
+ # Hash key => label (its order kept) or an Array of keys; +format+ key
37
+ # => :money or :count; +key+ the columns a phone shows before a row is
38
+ # opened (default: the first two after the first whose cells are all
39
+ # numbers or nil); +total+ one more row, by column key.
40
+ def table(rows, columns:, format: {}, key: nil, total: nil)
41
+ where = place("table")
42
+ TableBlock.new(where).build(rows, columns: columns, format: format, key: key, total: total).then { |block| add(block) }
43
+ end
44
+
45
+ # A scenario walk: the data a chi-ui walk holds (title, actors, steps),
46
+ # checked by the same schema (InlineWidgets.check).
47
+ def walk(data = nil, **fields)
48
+ where = place("walk")
49
+ result = InlineWidgets.check("walk", data.nil? ? fields : data)
50
+ raise Refused, "#{where}: #{result.error}" unless result.ok?
51
+
52
+ add("type" => "walk", "data" => result.data)
53
+ end
54
+
55
+ # A value as text, scrubbed to valid UTF-8.
56
+ def self.text_of(value)
57
+ InlineWidgets::DataTree.text(value)
58
+ end
59
+
60
+ private
61
+
62
+ # "table 2": the block's type and its place on the page, 1 first. A
63
+ # page past MAX_BLOCKS fails here, before the block is built.
64
+ def place(type)
65
+ count = @blocks.size + 1
66
+ raise Refused, "the page has more than #{MAX_BLOCKS} blocks (#{type} #{count} is one too many)" if count > MAX_BLOCKS
67
+
68
+ "#{type} #{count}"
69
+ end
70
+
71
+ def add(block)
72
+ @blocks << block
73
+ nil
74
+ end
75
+
76
+ def kb(bytes) = format("%.1f KB", bytes / 1024.0)
77
+ end
78
+
79
+ # One table block, as Builder#table describes it.
80
+ class TableBlock
81
+ def initialize(where)
82
+ @where = where
83
+ end
84
+
85
+ def build(rows, columns:, format:, key:, total:)
86
+ keys, labels = columns(columns)
87
+ formats = formats(format, keys)
88
+ rows = rows(rows)
89
+ kept = rows.first(MAX_ROWS).map { |row| keys.map { |k| TableBlock.cell(row[k]) } }
90
+ key_columns = key_columns(key, keys, kept)
91
+ block = { "type" => "table",
92
+ "columns" => keys.each_with_index.map { |k, i| column(k, labels[i], formats[k], key_columns.include?(k)) },
93
+ "rows" => kept }
94
+ block["total"] = total(total, keys) unless total.nil?
95
+ block["dropped"] = [rows.size - MAX_ROWS, 0].max
96
+ block
97
+ end
98
+
99
+ # A cell as stored: a finite number stays a number (a Rational or a
100
+ # BigDecimal as a Float), nil and true/false stay, anything else is its
101
+ # text (NaN and Infinity too: JSON has neither), scrubbed, cut to
102
+ # MAX_CELL characters with an ellipsis.
103
+ def self.cell(value)
104
+ case value
105
+ when nil, true, false, Integer then value
106
+ when Float then value.finite? ? value : value.to_s
107
+ when Numeric then value.to_f.finite? ? value.to_f : value.to_s
108
+ else
109
+ text = Builder.text_of(value)
110
+ text.size > MAX_CELL ? "#{text[0, MAX_CELL - 1]}…" : text
111
+ end
112
+ end
113
+
114
+ private
115
+
116
+ def columns(columns)
117
+ pairs = case columns
118
+ when Hash then columns.map { |k, label| [Builder.text_of(k), Builder.text_of(label)] }
119
+ when Array then columns.map { |k| [Builder.text_of(k), Builder.text_of(k)] }
120
+ else raise Refused, "#{@where}: columns: must be a Hash of key => label or a list of keys"
121
+ end
122
+ raise Refused, "#{@where}: columns: is empty" if pairs.empty?
123
+ raise Refused, "#{@where} has #{pairs.size} columns (at most #{MAX_COLUMNS})" if pairs.size > MAX_COLUMNS
124
+
125
+ pairs.transpose
126
+ end
127
+
128
+ def formats(format, keys)
129
+ raise Refused, "#{@where}: format: must be a Hash of column => :money or :count" unless format.is_a?(Hash)
130
+
131
+ format.to_h do |k, value|
132
+ k = Builder.text_of(k)
133
+ raise Refused, "#{@where}: format names #{k.inspect}, which is no column" unless keys.include?(k)
134
+ unless value.is_a?(Symbol) && FORMATS.include?(value)
135
+ raise Refused, "#{@where}: column #{k.inspect} has format #{value.inspect} (use :money or :count)"
136
+ end
137
+
138
+ [k, value.to_s]
139
+ end
140
+ end
141
+
142
+ # Rows with string keys.
143
+ def rows(rows)
144
+ raise Refused, "#{@where}: rows must be a list of mappings" unless rows.is_a?(Array)
145
+
146
+ rows.each_with_index.map do |row, index|
147
+ raise Refused, "#{@where}: row #{index + 1} isn't a mapping" unless row.is_a?(Hash)
148
+
149
+ row.transform_keys { |key| Builder.text_of(key) }
150
+ end
151
+ end
152
+
153
+ # The first column always shows on a phone and isn't one of these.
154
+ def key_columns(key, keys, rows)
155
+ if key.nil?
156
+ return keys.each_index.drop(1).select { |i| rows.all? { |row| row[i].nil? || row[i].is_a?(Numeric) } }
157
+ .first(2).map { |i| keys[i] }
158
+ end
159
+
160
+ Array(key).map do |k|
161
+ k = Builder.text_of(k)
162
+ raise Refused, "#{@where}: key names #{k.inspect}, which is no column" unless keys.include?(k)
163
+
164
+ k
165
+ end - [keys.first]
166
+ end
167
+
168
+ def total(total, keys)
169
+ raise Refused, "#{@where}: total: must be a Hash by column" unless total.is_a?(Hash)
170
+
171
+ total = total.transform_keys { |key| Builder.text_of(key) }
172
+ extra = total.keys - keys
173
+ raise Refused, "#{@where}: total names #{extra.first.inspect}, which is no column" unless extra.empty?
174
+
175
+ keys.map { |k| TableBlock.cell(total[k]) }
176
+ end
177
+
178
+ def column(key, label, format, key_column)
179
+ column = { "key" => key, "label" => label }
180
+ column["format"] = format if format
181
+ column["key_column"] = true if key_column
182
+ column
183
+ end
184
+ end
185
+ end
186
+ end