samagotchi 0.141.0 → 0.143.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 (165) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +111 -7
  3. data/README.md +2 -1
  4. data/bin/chi +2 -0
  5. data/docs/architecture.md +25 -289
  6. data/docs/bundle-authoring.md +7 -6
  7. data/docs/bundles.md +1232 -0
  8. data/docs/cli.md +51 -13
  9. data/docs/configuration.md +68 -30
  10. data/docs/context.md +12 -12
  11. data/docs/guardrails.md +27 -20
  12. data/docs/hooks.md +28 -9
  13. data/docs/internals/attached-context.md +225 -0
  14. data/docs/internals/background-tasks.md +1 -1
  15. data/docs/internals/bridge.md +380 -0
  16. data/docs/internals/bundles.md +6 -3
  17. data/docs/internals/context-telemetry.md +1 -1
  18. data/docs/internals/engine.md +31 -19
  19. data/docs/internals/participants.md +13 -12
  20. data/docs/internals/prompt-caching.md +12 -12
  21. data/docs/internals/remote-sessions.md +1 -1
  22. data/docs/internals/{tool-guardrails.md → tool-output-limits.md} +21 -2
  23. data/docs/internals/web-push.md +1 -1
  24. data/docs/memory.md +33 -3
  25. data/docs/plugins.md +127 -1231
  26. data/docs/sessions.md +51 -27
  27. data/docs/sub-agent.md +6 -6
  28. data/docs/system-one.md +122 -0
  29. data/docs/testing.md +3 -1
  30. data/lib/samagotchi/bridge.rb +2 -0
  31. data/lib/samagotchi/bundle_command/api_calls.rb +132 -0
  32. data/lib/samagotchi/bundle_command/check.rb +50 -34
  33. data/lib/samagotchi/bundle_command/installed_check.rb +86 -0
  34. data/lib/samagotchi/bundle_command/scaffold.rb +1 -0
  35. data/lib/samagotchi/bundle_settings_check.rb +58 -0
  36. data/lib/samagotchi/bundles/agents-md/manifest.yml +4 -2
  37. data/lib/samagotchi/bundles/agents-md/plugin.rb +1 -1
  38. data/lib/samagotchi/bundles/btw/manifest.yml +4 -2
  39. data/lib/samagotchi/bundles/btw/plugin.rb +1 -1
  40. data/lib/samagotchi/bundles/check-in/manifest.yml +7 -3
  41. data/lib/samagotchi/bundles/check-in/plugin.rb +101 -11
  42. data/lib/samagotchi/bundles/claude-peer/manifest.yml +3 -3
  43. data/lib/samagotchi/bundles/claude-peer/plugin.rb +1 -1
  44. data/lib/samagotchi/bundles/claude-peer/scripts/pair +1 -1
  45. data/lib/samagotchi/bundles/codex-peer/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/codex-peer/plugin.rb +1 -1
  47. data/lib/samagotchi/bundles/coordinator/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/coordinator/plugin.rb +1 -1
  49. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  50. data/lib/samagotchi/bundles/cost-cap/manifest.yml +6 -3
  51. data/lib/samagotchi/bundles/cost-cap/plugin.rb +5 -7
  52. data/lib/samagotchi/bundles/github-pr/manifest.yml +3 -1
  53. data/lib/samagotchi/bundles/known-names/manifest.yml +3 -1
  54. data/lib/samagotchi/bundles/loop-guard/manifest.yml +4 -2
  55. data/lib/samagotchi/bundles/loop-guard/plugin.rb +1 -1
  56. data/lib/samagotchi/bundles/mcp/manifest.yml +4 -2
  57. data/lib/samagotchi/bundles/mcp/plugin.rb +2 -2
  58. data/lib/samagotchi/bundles/ruby/manifest.yml +2 -2
  59. data/lib/samagotchi/bundles/ruby/plugin.rb +1 -1
  60. data/lib/samagotchi/bundles/skills/manifest.yml +4 -2
  61. data/lib/samagotchi/bundles/skills/plugin.rb +1 -1
  62. data/lib/samagotchi/bundles/slow-commands/manifest.yml +4 -2
  63. data/lib/samagotchi/bundles/slow-commands/plugin.rb +1 -1
  64. data/lib/samagotchi/bundles/source-links/manifest.yml +3 -1
  65. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -3
  66. data/lib/samagotchi/bundles/system/manifest.yml +4 -4
  67. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  68. data/lib/samagotchi/bundles/system/self_map.md +3 -3
  69. data/lib/samagotchi/bundles/work-cap/manifest.yml +6 -3
  70. data/lib/samagotchi/bundles/work-cap/plugin.rb +11 -13
  71. data/lib/samagotchi/config.rb +74 -14
  72. data/lib/samagotchi/context_candidate_choice.rb +20 -3
  73. data/lib/samagotchi/context_candidates.rb +4 -1
  74. data/lib/samagotchi/context_candidates_log.rb +36 -1
  75. data/lib/samagotchi/context_judge.rb +6 -2
  76. data/lib/samagotchi/context_status.rb +1 -2
  77. data/lib/samagotchi/engine.rb +96 -70
  78. data/lib/samagotchi/extension_load.rb +11 -4
  79. data/lib/samagotchi/guardrail_wiring.rb +36 -31
  80. data/lib/samagotchi/guardrails/chi_dirs.rb +7 -4
  81. data/lib/samagotchi/guardrails/path_resolve.rb +1 -1
  82. data/lib/samagotchi/guardrails/protected_paths.rb +7 -4
  83. data/lib/samagotchi/guardrails_command.rb +3 -3
  84. data/lib/samagotchi/hook_routes.rb +37 -2
  85. data/lib/samagotchi/hooks/bundle_loader.rb +20 -4
  86. data/lib/samagotchi/hooks/registry.rb +23 -5
  87. data/lib/samagotchi/host_model.rb +3 -3
  88. data/lib/samagotchi/host_registry.rb +14 -7
  89. data/lib/samagotchi/judgments_command.rb +155 -0
  90. data/lib/samagotchi/kernel_loop.rb +20 -3
  91. data/lib/samagotchi/llm/chat_loop.rb +79 -10
  92. data/lib/samagotchi/llm/errors.rb +7 -5
  93. data/lib/samagotchi/llm/stray_tool_call.rb +68 -0
  94. data/lib/samagotchi/log_line.rb +1 -1
  95. data/lib/samagotchi/memory_bundle/builder.rb +4 -2
  96. data/lib/samagotchi/memory_bundle/entry_size.rb +100 -0
  97. data/lib/samagotchi/memory_bundle/installed_bundle.rb +9 -2
  98. data/lib/samagotchi/memory_bundle/installed_copy.rb +92 -0
  99. data/lib/samagotchi/memory_bundle/installer.rb +2 -0
  100. data/lib/samagotchi/memory_bundle/manifest.rb +23 -13
  101. data/lib/samagotchi/memory_bundle/provenance.rb +4 -1
  102. data/lib/samagotchi/memory_bundle/shipped_update.rb +13 -1
  103. data/lib/samagotchi/model_catalog.rb +3 -2
  104. data/lib/samagotchi/models_command.rb +1 -1
  105. data/lib/samagotchi/plugin/api.rb +41 -7
  106. data/lib/samagotchi/plugin/context.rb +59 -1
  107. data/lib/samagotchi/plugin/judgments.rb +72 -0
  108. data/lib/samagotchi/plugin/loader.rb +6 -3
  109. data/lib/samagotchi/plugin/peer.rb +17 -22
  110. data/lib/samagotchi/plugin_session_state.rb +32 -5
  111. data/lib/samagotchi/prompt_warmup.rb +1 -9
  112. data/lib/samagotchi/run_options.rb +1 -0
  113. data/lib/samagotchi/self_report.rb +36 -0
  114. data/lib/samagotchi/session_access/contract.rb +1 -1
  115. data/lib/samagotchi/session_access/local.rb +1 -1
  116. data/lib/samagotchi/session_access/remote.rb +3 -3
  117. data/lib/samagotchi/session_archive_command.rb +3 -3
  118. data/lib/samagotchi/session_commands.rb +7 -4
  119. data/lib/samagotchi/session_config.rb +9 -3
  120. data/lib/samagotchi/session_continue.rb +1 -1
  121. data/lib/samagotchi/session_manager.rb +25 -5
  122. data/lib/samagotchi/session_retention.rb +10 -0
  123. data/lib/samagotchi/side_judgments.rb +12 -1
  124. data/lib/samagotchi/system_one/answer.rb +63 -11
  125. data/lib/samagotchi/system_one/approval_label.rb +56 -0
  126. data/lib/samagotchi/system_one/approval_question.rb +2 -0
  127. data/lib/samagotchi/system_one/client.rb +43 -17
  128. data/lib/samagotchi/system_one/fake_backend.rb +1 -1
  129. data/lib/samagotchi/system_one/http_backend.rb +12 -4
  130. data/lib/samagotchi/system_one/judgment_settings.rb +61 -0
  131. data/lib/samagotchi/system_one/judgments.rb +243 -0
  132. data/lib/samagotchi/system_one/log.rb +25 -2
  133. data/lib/samagotchi/system_one/recording.rb +117 -0
  134. data/lib/samagotchi/system_one/runs.rb +179 -0
  135. data/lib/samagotchi/system_one/runs_store.rb +230 -0
  136. data/lib/samagotchi/system_one.rb +9 -0
  137. data/lib/samagotchi/terminal_ui/attach_link.rb +2 -2
  138. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +1 -1
  139. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  140. data/lib/samagotchi/terminal_ui/local_link.rb +1 -1
  141. data/lib/samagotchi/terminal_ui/remote_link.rb +1 -2
  142. data/lib/samagotchi/testing/bundle.rb +9 -2
  143. data/lib/samagotchi/testing/host.rb +2 -1
  144. data/lib/samagotchi/testing/judgments.rb +176 -0
  145. data/lib/samagotchi/testing/recorder.rb +5 -0
  146. data/lib/samagotchi/testing/recording_api.rb +1 -1
  147. data/lib/samagotchi/tool_output_cut.rb +26 -6
  148. data/lib/samagotchi/tool_response.rb +1 -1
  149. data/lib/samagotchi/tool_runner.rb +63 -4
  150. data/lib/samagotchi/toolkit_suggest.rb +11 -2
  151. data/lib/samagotchi/tools/memory.rb +28 -0
  152. data/lib/samagotchi/turn_note.rb +9 -0
  153. data/lib/samagotchi/update_command.rb +49 -16
  154. data/lib/samagotchi/version.rb +1 -1
  155. data/lib/samagotchi/web/app.rb +1 -0
  156. data/lib/samagotchi/web/auto_update.rb +79 -49
  157. data/lib/samagotchi/web/auto_update_record.rb +59 -0
  158. data/lib/samagotchi/web/public/app.js +8 -4
  159. data/lib/samagotchi/web/public/hash_intent.js +24 -0
  160. data/lib/samagotchi/web/public/index.html +3 -1
  161. data/lib/samagotchi/web/public/revise_stack.js +14 -5
  162. data/lib/samagotchi/web/session_control.rb +3 -3
  163. data/lib/samagotchi/web/update_check.rb +7 -6
  164. data/lib/samagotchi/web/update_ops.rb +80 -25
  165. metadata +23 -2
@@ -21,8 +21,10 @@ module Samagotchi
21
21
  # bundle, the shipped bundles the user installed, and the macOS helper.
22
22
  # Unedited things update; edited ones are kept (.md) or replaced and
23
23
  # reported (hooks, plugin, rules, which didn't load once edited). Live
24
- # workers and a running chi web are reported, never restarted. Prints one
25
- # table; a second run changes nothing and says so.
24
+ # workers and a running chi web are reported, never restarted. The bundles
25
+ # chi didn't ship are only checked, under the chi that will run them
26
+ # (BundleCommand::InstalledCheck): what it finds is rows that fail nothing.
27
+ # Prints one table; a second run changes nothing and says so.
26
28
  class UpdateCommand
27
29
  include CLI::Command
28
30
 
@@ -32,12 +34,16 @@ module Samagotchi
32
34
  system bundle, the bundles chi ships that you installed (chi bundle
33
35
  list), and the desktop helper (macOS; rebuilt only when its sources
34
36
  changed). Edited memory files are kept and reported; nothing is
35
- installed that isn't already, and old gem versions stay.
36
- --dry-run show what would change; change nothing
37
+ installed that isn't already, and old gem versions stay. The bundles
38
+ chi doesn't ship are never changed: the new chi checks them and adds
39
+ a row per warning or error (these don't fail the update).
40
+ --dry-run show what would change; change nothing (with a newer
41
+ gem to install, bundles chi doesn't ship aren't checked:
42
+ that chi would)
37
43
  --to VERSION install exactly this gem version (must be newer than this chi)
38
44
  --json print update rows as one JSON document
39
45
  --no-gem don't install a newer gem (config update.gem: false)
40
- --no-bundles leave the shipped bundles alone (config update.bundles: false)
46
+ --no-bundles leave all bundles alone, unchecked too (config update.bundles: false)
41
47
  --no-desktop leave the desktop helper alone (config update.desktop: false)
42
48
  Running sessions keep their chi until restarted (chi sessions
43
49
  restart ID) or until they idle out with nothing attached; a running
@@ -68,8 +74,9 @@ module Samagotchi
68
74
  "--no-register" => :no_register, "--to" => :to, "--json" => :json }.freeze
69
75
 
70
76
  # A table row. info rows (live workers, chi web) say what runs; they
71
- # never fail.
72
- Row = Struct.new(:component, :from, :to, :status, :failed, :kept, keyword_init: true)
77
+ # never fail. level ("warn", "error"; else nil) marks a finding on a bundle
78
+ # chi didn't ship: it reports, changes nothing and fails nothing.
79
+ Row = Struct.new(:component, :from, :to, :status, :failed, :kept, :level, keyword_init: true)
73
80
 
74
81
  # What a row says after a change, and in a dry run.
75
82
  VERBS = { update: ["updated", "would update"], install: ["installed", "would install"],
@@ -137,12 +144,12 @@ module Samagotchi
137
144
  GemUpdate.new(gem_bin: ChiHome.gem_bin(@run_home), install_env: ChiHome.install_env(@run_home))
138
145
  @dry_run = options[:dry_run]
139
146
  gem = gem_row(options)
140
- rows = [gem, system_bundle_row, *bundle_rows(options), desktop_row(options), *live_rows].compact
147
+ rows = [gem, system_bundle_row, *bundle_rows(options), *external_rows(options), desktop_row(options), *live_rows].compact
141
148
  if options[:json]
142
149
  @stdout.puts(JSON.generate(rows.map { |row| row.to_h.merge(failed: !!row.failed, kept: row.kept || []) }))
143
150
  else
144
151
  print_table(rows)
145
- footers(options).each { |line| @stdout.puts(line) }
152
+ footers(options, rows).each { |line| @stdout.puts(line) }
146
153
  @stdout.puts(summary(rows))
147
154
  end
148
155
  rows.any?(&:failed) ? 1 : 0
@@ -233,20 +240,26 @@ module Samagotchi
233
240
  return up_to_date(row) unless options[:to] || @gem_update.newer?(latest)
234
241
 
235
242
  row.to = latest.version
236
- return done(row, :update) if @dry_run
243
+ if @dry_run
244
+ @not_checked = "chi #{latest.version} checks them once installed"
245
+ return done(row, :update)
246
+ end
237
247
 
238
248
  (options[:json] ? @stderr : @stdout).puts("installing samagotchi #{latest.version}…")
239
249
  output, ok = @gem_update.install(latest)
240
250
  return failed(row, output.lines.map(&:strip).reject(&:empty?).last.to_s) unless ok
241
251
 
242
- hand_over(options, row)
252
+ hand_over(options, row, latest.version)
243
253
  end
244
254
 
245
255
  # exec the newest installed samagotchi: the chi home's boot, else the
246
256
  # wrapper. Without either (installed with --bindir), this version syncs.
247
- def hand_over(options, row)
257
+ def hand_over(options, row, version)
248
258
  wrapper = InstalledGem.wrapper(@gem_spec) unless @run_home
249
- return done(row, :update, "run chi update again to sync with it") unless @run_home || wrapper
259
+ unless @run_home || wrapper
260
+ @not_checked = "chi #{version} checks them: run chi update again"
261
+ return done(row, :update, "run chi update again to sync with it")
262
+ end
250
263
 
251
264
  passed = options[:to] ? ["--to", options[:to]] : []
252
265
  passed += HANDED_OVER.except("--to").select { |_, key| options[key] }.keys
@@ -288,6 +301,22 @@ module Samagotchi
288
301
  rows.map { |r| bundle_row(r) }
289
302
  end
290
303
 
304
+ # The bundles chi doesn't ship, checked by the chi that will run them: this
305
+ # one, but when a newer gem is yet to take over (@not_checked: a dry run,
306
+ # or no way to hand over). The run handed over to is the new chi's own.
307
+ def external_rows(options)
308
+ return [] if off(options, "bundles")
309
+
310
+ bundles = MemoryBundle::ShippedUpdate.external(shipped_dir: @shipped_dir)
311
+ return [] if bundles.empty?
312
+ return [Row.new(component: "external bundles", status: "not checked (#{@not_checked})")] if @not_checked
313
+
314
+ require_relative "bundle_command/installed_check"
315
+ bundles.flat_map do |bundle|
316
+ BundleCommand::InstalledCheck.run(bundle).map { |found| Row.new(component: bundle.name, status: found.text, level: found.level) }
317
+ end
318
+ end
319
+
291
320
  def bundle_row(update)
292
321
  row = Row.new(component: update.name, from: update.from, to: update.to)
293
322
  case update.status
@@ -375,20 +404,24 @@ module Samagotchi
375
404
  "; or they idle out after #{minutes.round(1).to_s.delete_suffix(".0")} min with nothing attached"
376
405
  end
377
406
 
378
- def footers(options)
407
+ def footers(options, rows)
379
408
  return [] if off(options, "bundles")
380
409
 
410
+ lines = rows.any?(&:level) ? ["Bundles not from chi are left as they are: their author's next version, or chi bundle upgrade NAME, is what changes them"] : []
381
411
  names = MemoryBundle::ShippedUpdate.not_installed(shipped_dir: @shipped_dir).map do |s|
382
412
  s.includes.empty? ? s.source : "#{s.source} (#{s.includes.join(", ")})"
383
413
  end
384
- names.empty? ? [] : ["Also shipped, not installed: #{names.join(", ")} (chi bundle install NAME)"]
414
+ lines << "Also shipped, not installed: #{names.join(", ")} (chi bundle install NAME)" unless names.empty?
415
+ lines
385
416
  end
386
417
 
387
418
  def summary(rows)
388
419
  return "(dry run: nothing was changed)" if @dry_run
389
420
  return "some parts failed (see above)" if rows.any?(&:failed)
390
421
 
391
- rows.all? { |r| r.status.start_with?("up to date", "skipped", "not installed", "couldn't check") } ? "everything is up to date" : "done"
422
+ # A finding on a bundle chi didn't ship repeats until its bundle changes; it isn't a change.
423
+ changes = rows.reject(&:level)
424
+ changes.all? { |r| r.status.start_with?("up to date", "skipped", "not installed", "couldn't check") } ? "everything is up to date" : "done"
392
425
  end
393
426
 
394
427
  # "updated" (or "would update" in a dry run), with a note; the block
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.141.0"
4
+ VERSION = "0.143.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -765,6 +765,7 @@ module Samagotchi
765
765
  when :unavailable then error_response(503, "restart_unavailable", "chi web cannot restart itself in this process")
766
766
  when :busy then error_response(409, "update_running", UPDATE_RUNNING)
767
767
  when :started then json_response(202, { state: "restarting" })
768
+ when :start_failed then error_response(503, "restart_start_failed", "couldn't start chi web's restart")
768
769
  when :no_wrapper
769
770
  error_response(409, "restart_unavailable", "no chi wrapper to restart into (installed with --bindir?); " \
770
771
  "restart chi web in its terminal")
@@ -5,6 +5,7 @@ require "time"
5
5
  require_relative "../config"
6
6
  require_relative "../log"
7
7
  require_relative "../version"
8
+ require_relative "auto_update_record"
8
9
 
9
10
  module Samagotchi
10
11
  module Web
@@ -21,18 +22,24 @@ module Samagotchi
21
22
  #
22
23
  # With update.restart: idle (the default) the install is followed by:
23
24
  # 1. the stale workers, only those idle and quiet for QUIET seconds (the
24
- # worker still refuses atomically when it isn't), the left ones tried
25
- # again each step for RETRY_FOR;
25
+ # worker still refuses atomically when it isn't);
26
26
  # 2. chi web itself, once no operation and no turn runs: a preflight
27
27
  # (the newest chi must start and say its version) first, then the
28
28
  # exec. The restarted chi web's own AutoUpdate sees phase `web`,
29
29
  # counts the workers once more and says "chi updated": the process
30
30
  # that survives is the one that speaks, and that proves it is up.
31
+ # 3. the workers still left, tried again each step, by the same rule,
32
+ # until none is left or RETRY_FOR has passed since the install (in
33
+ # whichever chi web is up: `workers` before its restart, `retrying`
34
+ # after). "chi updated" doesn't wait for them, nothing more is said of
35
+ # them, and `retrying` holds no next release back: its install takes
36
+ # the workers over in a run of its own.
31
37
  # A preflight that fails leaves chi web as it is and says so.
32
38
  # update.restart: never stops after the install.
33
39
  #
34
- # The run's record lives in update_check.json (UpdateCheck#save_auto),
35
- # so a chi web restart finds it. See docs/architecture.md.
40
+ # The run's record (AutoUpdateRecord) lives in update_check.json
41
+ # (UpdateCheck#save_auto), so a chi web restart finds it. See
42
+ # docs/architecture.md.
36
43
  class AutoUpdate
37
44
  # Seconds between steps, and before the first (the checker's first
38
45
  # check is at 30).
@@ -45,8 +52,10 @@ module Samagotchi
45
52
  QUIET = 600
46
53
  # The workers a run couldn't restart are tried again this long.
47
54
  RETRY_FOR = 24 * 3600
48
- # The phases a run is still in.
55
+ # The phases a run is still on its way through; no next install starts.
49
56
  OPEN_PHASES = %w[installed workers web].freeze
57
+ # The phase after "chi updated" while workers are left.
58
+ RETRYING = "retrying"
50
59
  # How long stop waits for the thread: long enough for a preflight
51
60
  # (Server::PREFLIGHT_TIMEOUT, 20 s; a healthy one takes about a
52
61
  # second) to end on its own, so a stop never abandons one mid-way.
@@ -100,7 +109,9 @@ module Samagotchi
100
109
  return unless @auto == "install"
101
110
 
102
111
  record = @check.auto_state
103
- return carry_on(record) if record && OPEN_PHASES.include?(record[:phase])
112
+ return carry_on(record) if record && OPEN_PHASES.include?(record.phase)
113
+
114
+ retry_left(record) if record&.phase == RETRYING
104
115
 
105
116
  version = @check.available
106
117
  return unless version
@@ -117,21 +128,27 @@ module Samagotchi
117
128
  until @stopped
118
129
  break if @wakeup.pop(timeout: wait) == :stop
119
130
 
120
- step
131
+ guarded_step
121
132
  wait = @poll
122
133
  end
134
+ end
135
+
136
+ # A step that raises (a full disk, a hub hiccup) is taken again at the
137
+ # next poll: it only delays the run, and never ends the thread.
138
+ def guarded_step
139
+ step
123
140
  rescue StandardError => e
124
141
  Log.exception(:web, "auto_update_failed", e)
125
142
  end
126
143
 
127
144
  # A run that this chi web's start finds on its way to the web restart.
128
145
  def restarted?
129
- @check.auto_state&.dig(:phase) == "web"
146
+ @check.auto_state&.phase == "web"
130
147
  end
131
148
 
132
149
  # This release's run is already on record (installed, or given up on).
133
150
  def tried?(version)
134
- @check.auto_state&.dig(:version) == version
151
+ @check.auto_state&.version == version
135
152
  end
136
153
 
137
154
  # A turn runs, or a question waits for its answer, in any session.
@@ -146,10 +163,11 @@ module Samagotchi
146
163
  result = @ops.install(version, wait: true, auto: true)
147
164
  return Log.info(:web, "auto_update_deferred", version: version, why: result) if result.is_a?(Symbol)
148
165
 
149
- rows = result[:rows]
150
- record = { version: version, from: VERSION, at: @clock.call.iso8601, kept: kept_files(rows) }
151
- if result[:state] == "done"
152
- Log.info(:web, "auto_update_installed", version: version, kept: record[:kept].size)
166
+ rows = result.rows
167
+ record = AutoUpdateRecord.new(version: version, from: VERSION, at: @clock.call.iso8601, kept: kept_files(rows),
168
+ phase: "installed")
169
+ if result.done?
170
+ Log.info(:web, "auto_update_installed", version: version, kept: record.kept.size)
153
171
  installed(record)
154
172
  else
155
173
  failed(record, rows)
@@ -160,15 +178,15 @@ module Samagotchi
160
178
  # toast and idle exit carry chi web and the workers over; else the
161
179
  # restarts follow, here and now when nothing holds them.
162
180
  def installed(record)
163
- return carry_on(save(record.merge(phase: "installed"))) unless @restart == "never"
181
+ return carry_on(save(record)) unless @restart == "never"
164
182
 
165
- @hub.publish_notice(kind: "installed", version: record[:version], kept: record[:kept].size)
166
- save(record.merge(phase: "done", pushed: true))
183
+ save(record.with(phase: "done", pushed: true))
184
+ @hub.publish_notice(kind: "installed", version: record.version, kept: record.kept.size)
167
185
  end
168
186
 
169
187
  # The next step of a run on record.
170
188
  def carry_on(record)
171
- case record[:phase]
189
+ case record.phase
172
190
  when "installed", "workers" then workers_then_web(record)
173
191
  when "web" then finish(record)
174
192
  end
@@ -177,31 +195,26 @@ module Samagotchi
177
195
  def workers_then_web(record)
178
196
  return if @ops.running?
179
197
 
180
- record = restart_workers(record) if record[:phase] == "installed" || workers_left?(record)
198
+ record = restart_workers(record) if record.phase == "installed" || record.left_to_try?(@clock.call, RETRY_FOR)
181
199
  return unless record
182
200
 
183
201
  restart_web(record)
184
202
  end
185
203
 
186
- def workers_left?(record)
187
- record.dig(:workers, :left).to_i.positive? && @clock.call - recorded_at(record) < RETRY_FOR
188
- end
189
-
190
- def recorded_at(record)
191
- Time.iso8601(record[:at].to_s)
192
- rescue ArgumentError
193
- @clock.call
194
- end
195
-
196
204
  # A pass over the stale workers that are idle and quiet; the counts
197
- # add up over passes. nil when another operation took the turn.
205
+ # add up over passes. nil when another operation took the turn. Only a
206
+ # run's first pass shows on the page regardless: the later ones come
207
+ # every POLL, for up to RETRY_FOR, and show only when a worker restarts.
198
208
  def restart_workers(record)
199
- result = @ops.restart_workers(wait: true, auto: true, select: quiet_filter)
209
+ result = @ops.restart_workers(wait: true, auto: true, select: quiet_filter, quiet: record.phase != "installed")
200
210
  return if result.is_a?(Symbol)
201
211
 
202
- states = result[:rows].map { |row| row["state"] }
203
- restarted = record.dig(:workers, :restarted).to_i + states.count("restarted")
204
- save(record.merge(phase: "workers", workers: { restarted: restarted, left: states.size - states.count("restarted") }))
212
+ states = result.rows.map { |row| row["state"] }
213
+ restarted = states.count("restarted")
214
+ # The first pass moves the run on; a later one keeps its phase, so a
215
+ # finish cut short here finishes, rather than restarting chi web again.
216
+ phase = record.phase == "installed" ? "workers" : record.phase
217
+ save(record.with(phase: phase, restarted: record.restarted + restarted, left: states.size - restarted))
205
218
  end
206
219
 
207
220
  # Idle and quiet: no turn, no question, untouched for QUIET seconds.
@@ -229,43 +242,60 @@ module Samagotchi
229
242
  def restart_web(record)
230
243
  return if busy_turn?
231
244
 
232
- problem = @preflight&.call(record[:version])
245
+ problem = @preflight&.call(record.version)
233
246
  # Stopped meanwhile (chi web is shutting down): no exec, no record
234
247
  # of one; the next start takes it up again.
235
248
  return if @stopped
236
249
  return restart_failed(record, problem, "auto_restart_preflight_failed") if problem
237
250
 
238
- save(record.merge(phase: "web"))
239
- Log.info(:web, "auto_update_restart", version: record[:version])
251
+ save(record.with(phase: "web"))
252
+ Log.info(:web, "auto_update_restart", version: record.version)
240
253
  case (answer = @ops.restart_web)
241
254
  when :started then nil
242
- when :busy then save(record.merge(phase: "workers"))
255
+ when :busy then save(record.with(phase: "workers"))
243
256
  else restart_failed(record, "chi web can't restart itself here (#{answer})", "auto_restart_refused")
244
257
  end
245
258
  end
246
259
 
247
260
  def restart_failed(record, detail, event)
248
- Log.warn(:web, event, version: record[:version], detail: detail)
249
- @hub.publish_notice(kind: "restart_failed", version: record[:version], detail: detail)
250
- save(record.merge(phase: "failed", detail: detail, pushed: true))
261
+ Log.warn(:web, event, version: record.version, detail: detail)
262
+ save(record.with(phase: "failed", detail: detail, pushed: true))
263
+ @hub.publish_notice(kind: "restart_failed", version: record.version, detail: detail)
251
264
  end
252
265
 
253
266
  # In the restarted chi web: on the version, the workers counted once
254
267
  # more, "chi updated" said.
255
268
  def finish(record)
256
- if Gem::Version.new(VERSION) < Gem::Version.new(record[:version])
269
+ if Gem::Version.new(VERSION) < Gem::Version.new(record.version)
257
270
  return restart_failed(record, "chi web came back on #{VERSION}", "auto_restart_wrong_version")
258
271
  end
259
272
 
260
273
  @hub.scan
261
274
  record = restart_workers(record) || record
262
- workers = record[:workers] || {}
263
- Log.info(:web, "auto_update_done", version: record[:version], restarted: workers[:restarted], left: workers[:left])
264
- @hub.publish_notice(kind: "updated", version: record[:version], kept: record[:kept].to_a.size,
265
- restarted: workers[:restarted].to_i, left: workers[:left].to_i)
266
- save(record.merge(phase: "done", pushed: true))
275
+ Log.info(:web, "auto_update_done", version: record.version, restarted: record.restarted, left: record.left)
276
+ save(record.with(phase: record.left_to_try?(@clock.call, RETRY_FOR) ? RETRYING : "done", pushed: true))
277
+ @hub.publish_notice(kind: "updated", version: record.version, kept: record.kept.size,
278
+ restarted: record.restarted, left: record.left)
279
+ end
280
+
281
+ # After "chi updated": another pass over the workers left, until none is
282
+ # or RETRY_FOR is over. The time is looked at first, so a pass that keeps
283
+ # raising or being refused still ends the run.
284
+ def retry_left(record)
285
+ return close_retry(record) if @restart == "never" || !record.left_to_try?(@clock.call, RETRY_FOR)
286
+ return if @ops.running?
287
+
288
+ record = restart_workers(record)
289
+ close_retry(record) if record && !record.left.positive?
290
+ end
291
+
292
+ def close_retry(record)
293
+ Log.info(:web, "auto_update_retry_done", version: record.version, restarted: record.restarted, left: record.left)
294
+ save(record.with(phase: "done"))
267
295
  end
268
296
 
297
+ # The record first, then the telling: a save that raises takes the step
298
+ # again at the next poll, and the owner hears it once.
269
299
  def save(record)
270
300
  @check.save_auto(record)
271
301
  record
@@ -274,11 +304,11 @@ module Samagotchi
274
304
  def failed(record, rows)
275
305
  row = rows.find { |candidate| candidate["failed"] } || rows.first || {}
276
306
  detail = row["status"].to_s.lines.first.to_s.strip
277
- Log.warn(:web, "auto_update_failed_install", version: record[:version], detail: detail)
307
+ Log.warn(:web, "auto_update_failed_install", version: record.version, detail: detail)
278
308
  gem_installed = rows.any? { |candidate| candidate["component"] == "chi (gem)" && !candidate["failed"] }
279
- @hub.publish_notice(kind: "failed", version: record[:version], detail: detail.empty? ? nil : detail,
309
+ @check.save_auto(record.with(phase: "failed", detail: detail, pushed: true), failed: record.version)
310
+ @hub.publish_notice(kind: "failed", version: record.version, detail: detail.empty? ? nil : detail,
280
311
  installed: gem_installed)
281
- @check.save_auto(record.merge(phase: "failed", detail: detail, pushed: true), failed: record[:version])
282
312
  end
283
313
 
284
314
  def kept_files(rows)
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rubygems/version"
4
+ require "time"
5
+
6
+ module Samagotchi
7
+ module Web
8
+ # AutoUpdate's record of the run it started, as UpdateCheck keeps it in
9
+ # update_check.json (`auto`) so a chi web restart finds it. The file's
10
+ # shape is this class's: #to_store writes it, .from_h reads it, and
11
+ # nobody else sees its keys.
12
+ #
13
+ # +phase+: installed, workers, web (AutoUpdate::OPEN_PHASES), retrying,
14
+ # done or failed. +restarted+ and +left+ count the stale workers (`workers` in
15
+ # the file); +at+ is when the install ended, an ISO 8601 string.
16
+ AutoUpdateRecord = Data.define(:version, :from, :at, :kept, :phase, :restarted, :left, :detail, :pushed) do
17
+ def initialize(version:, phase:, from: nil, at: nil, kept: [], restarted: 0, left: 0, detail: nil, pushed: false)
18
+ super
19
+ end
20
+
21
+ # @param hash [Object] the file's `auto`, as JSON.parse answered it
22
+ # @return [AutoUpdateRecord, nil] nil when it isn't a run's record (no
23
+ # version or phase to go on: nothing a run could carry on from)
24
+ def self.from_h(hash)
25
+ return unless hash.is_a?(Hash)
26
+
27
+ version = hash["version"]
28
+ phase = hash["phase"]
29
+ return unless version.is_a?(String) && Gem::Version.correct?(version) && phase.is_a?(String)
30
+
31
+ workers = hash["workers"].is_a?(Hash) ? hash["workers"] : {}
32
+ new(version: version, phase: phase, from: hash["from"], at: hash["at"],
33
+ kept: Array(hash["kept"]).grep(String), restarted: workers["restarted"].to_i, left: workers["left"].to_i,
34
+ detail: hash["detail"], pushed: hash["pushed"] == true)
35
+ end
36
+
37
+ # What goes in the file, for .from_h to read back.
38
+ # @return [Hash{String => Object}]
39
+ def to_store
40
+ { "version" => version, "from" => from, "at" => at, "kept" => kept, "phase" => phase,
41
+ "workers" => { "restarted" => restarted, "left" => left }, "detail" => detail,
42
+ "pushed" => pushed ? true : nil }.compact
43
+ end
44
+
45
+ # Whether workers are left and the run, +window+ seconds from +at+, may
46
+ # still try them. A stamp that can't be read ends the trying, so a run
47
+ # can't go on for ever.
48
+ # @param now [Time]
49
+ def left_to_try?(now, window)
50
+ return false unless left.positive?
51
+
52
+ started = Time.iso8601(at.to_s)
53
+ now - started < window
54
+ rescue ArgumentError
55
+ false
56
+ end
57
+ end
58
+ end
59
+ end
@@ -79,7 +79,8 @@ import { PROMPT_LINE_PX, PROMPT_MIN_PX } from "./composer_size.js";
79
79
  import { mountComposer } from "./composer_mount.js";
80
80
  import { readStored, writeStored } from "./storage.js";
81
81
  import { createCommandList } from "./command_list.js";
82
- import { ALL_SESSIONS_HASH, sessionHash, sessionIdFromHash } from "./route.js";
82
+ import { ALL_SESSIONS_HASH, sessionHash } from "./route.js";
83
+ import { hashIntent } from "./hash_intent.js";
83
84
  import {
84
85
  claimFromHash, ownerClaimHash, participantClaimLink, selectionClaim, showClaim, turnIdOf,
85
86
  } from "./claim_link.js";
@@ -792,13 +793,16 @@ function setSessionHash(id) {
792
793
  // A #/s/<id> typed or pasted into the address bar, or reached by back.
793
794
  // A claim link (claim_link.js; #/s/<id>?t=…&q=…, or the participant's
794
795
  // #s=<id>&t=… opened in this browser) opens its session and, once drawn,
795
- // shows the claim.
796
+ // shows the claim. The start page's own hash ("#/", or none) while one is
797
+ // open is the start page: the same clear the + button does, so the page and
798
+ // the composer stop addressing the session the URL has left behind.
796
799
  function selectFromHash() {
797
800
  const claim = claimFromHash(location.hash);
798
- const id = sessionIdFromHash(location.hash) || claim?.sessionId || null;
799
801
  if (claim) pendingClaim = claim;
800
- if (id && id !== store.selected) select(id);
802
+ const intent = hashIntent(location.hash, { selected: store.selected, claim });
803
+ if (intent.kind === "session" && intent.id !== store.selected) select(intent.id);
801
804
  else if (claim) showPendingClaim();
805
+ else if (intent.kind === "start") clearSelection();
802
806
  }
803
807
  let pendingClaim = null;
804
808
  // Where a claim's text can be on this page: answers, own messages, steps.
@@ -0,0 +1,24 @@
1
+ // What the page's hash asks for, decided without the page: the session it
2
+ // names, the all-sessions view, or the start page. app.js does the work the
3
+ // intent describes (select / applyView / clearSelection); the "start" case is
4
+ // the one a "#/" typed in the address bar hits while a session is open.
5
+ //
6
+ // A module of its own: the page's static JS is cached at unversioned URLs, and
7
+ // a new export of an old module would leave a cached copy without it; it is
8
+ // pure, so it is testable where app.js is not.
9
+ import { ALL_SESSIONS_HASH, sessionIdFromHash } from "./route.js";
10
+
11
+ const START_HASHES = ["", "#", "#/"];
12
+
13
+ // +claim+: claim_link.js' parse of the same hash, which names the session a
14
+ // claim link belongs to when the hash has no session path of its own.
15
+ // @return {kind: "session", id} | {kind: "all"} | {kind: "start"} | {kind: "keep"}
16
+ export function hashIntent(hash = "", { selected = null, claim = null } = {}) {
17
+ const id = sessionIdFromHash(hash) || claim?.sessionId || null;
18
+ if (id) return { kind: "session", id };
19
+ if (hash === ALL_SESSIONS_HASH) return { kind: "all" };
20
+ // The start page's own hash with a session still held: the page goes there
21
+ // too. Any other fragment (an anchor clicked in a rendered answer) isn't
22
+ // about the page's session at all.
23
+ return selected && START_HASHES.includes(hash) ? { kind: "start" } : { kind: "keep" };
24
+ }
@@ -86,7 +86,9 @@ main{flex:1;display:flex;flex-direction:column;gap:16px;padding:16px;overflow:au
86
86
  .stack-stub::before{content:"▸";color:var(--accent);flex:none}
87
87
  .stack-stub.open::before{content:"▾"}
88
88
  .stack-stub.open{border-style:solid;border-color:transparent;border-left:3px solid var(--border-strong);border-radius:6px}
89
- .stack-stub-text{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
89
+ .stack-stub-text{display:flex;min-width:0}
90
+ .stack-stub-said{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
91
+ .stack-stub-by{flex:none;white-space:pre}
90
92
  .stack-stub-gap{flex:none;margin-left:auto;color:var(--time-gap);white-space:nowrap;font-variant-numeric:tabular-nums}
91
93
  .revise-row{position:relative;height:0;margin-top:-12px;display:flex;justify-content:flex-end;align-items:center;gap:8px}
92
94
  .revise-row.stacked{height:auto;margin-top:-6px;justify-content:flex-start}
@@ -87,11 +87,20 @@ export function stacks(messages) {
87
87
  return chains;
88
88
  }
89
89
 
90
- // A stub's words: "v1 · "‹label›" · 84 lines — superseded by v3".
91
- export function stubText({ version, label = "", lines = 0, top }) {
90
+ // A stub's words in two parts: "v1 · ‹label› · 84 lines" and " — superseded
91
+ // by v3". Only the first is ever clipped (the CSS gives the second flex:none),
92
+ // because it is what tells two stubs apart when their versions open with the
93
+ // same line — on a phone the ellipsis used to eat it. stubText is both parts
94
+ // as one string.
95
+ export function stubParts({ version, label = "", lines = 0, top }) {
92
96
  const said = label ? ` · “${label}”` : "";
93
97
  const size = lines ? ` · ${lines} line${lines === 1 ? "" : "s"}` : "";
94
- return `v${version}${said}${size} — superseded by v${top}`;
98
+ return { said: `v${version}${said}${size}`, by: ` — superseded by v${top}` };
99
+ }
100
+
101
+ export function stubText(opts) {
102
+ const { said, by } = stubParts(opts);
103
+ return `${said}${by}`;
95
104
  }
96
105
 
97
106
  // The version chip's words for version +at+ (0-based) on view of +count+:
@@ -218,8 +227,8 @@ export function installReviseStacks({
218
227
  const open = stub.classList.contains("open");
219
228
  stub.setAttribute("aria-expanded", open ? "true" : "false");
220
229
  stub.title = `${open ? "Fold" : "Show"} this earlier version${opening.title ? ` (${opening.title})` : ""}`;
221
- const text = stubText({ version, label: answerLabel(answer), lines: answer ? lineCount(bubbleCopyText(answer)) : 0, top });
222
- render(html`<span class="stack-stub-text">${text}</span>${gap ? html`<span class="stack-stub-gap">${gap}</span>` : nothing}`, stub);
230
+ const { said, by } = stubParts({ version, label: answerLabel(answer), lines: answer ? lineCount(bubbleCopyText(answer)) : 0, top });
231
+ render(html`<span class="stack-stub-text"><span class="stack-stub-said">${said}</span><span class="stack-stub-by">${by}</span></span>${gap ? html`<span class="stack-stub-gap">${gap}</span>` : nothing}`, stub);
223
232
  }
224
233
 
225
234
  function rowFor(id, answer) {
@@ -447,9 +447,9 @@ module Samagotchi
447
447
  # are refused (409).
448
448
  def handle_archive(_req, id)
449
449
  result = @manager.archive_session(id, state_dir: @state_dir, wait: STOP_WAIT_SECONDS)
450
- (result[:archived] + result[:discarded]).each { |sid| @hub&.touch(sid) }
451
- json_response(200, { status: "archived", session_id: result[:id], archived: result[:archived],
452
- stopped: result[:stopped], discarded: result[:discarded] })
450
+ (result.archived + result.discarded).each { |sid| @hub&.touch(sid) }
451
+ json_response(200, { status: "archived", session_id: result.id, archived: result.archived,
452
+ stopped: result.stopped, discarded: result.discarded })
453
453
  rescue SessionManager::OwnedByTUI => e
454
454
  owned_by_repl(id, e)
455
455
  rescue SessionManager::ArchiveRefused => e
@@ -12,6 +12,7 @@ require_relative "../installed_versions"
12
12
  require_relative "../log"
13
13
  require_relative "../paths"
14
14
  require_relative "../version"
15
+ require_relative "auto_update_record"
15
16
 
16
17
  module Samagotchi
17
18
  module Web
@@ -117,11 +118,10 @@ module Samagotchi
117
118
  still_newer(@state[:available])
118
119
  end
119
120
 
120
- # AutoUpdate's record of the run it started: {version:, from:, phase:,
121
- # kept:, workers:, pushed:, detail:} (symbol keys), nil when none.
122
- # @return [Hash, nil]
121
+ # AutoUpdate's record of the run it started, nil when none.
122
+ # @return [AutoUpdateRecord, nil]
123
123
  def auto_state
124
- @state_lock.synchronize { @state[:auto]&.dup }
124
+ @state_lock.synchronize { @state[:auto] }
125
125
  end
126
126
 
127
127
  # Whether AutoUpdate already tried +version+ and failed (one automatic
@@ -132,6 +132,7 @@ module Samagotchi
132
132
 
133
133
  # Saves AutoUpdate's record (nil clears it); +failed+ adds a version to
134
134
  # the ones it gave up on.
135
+ # @param auto [AutoUpdateRecord, nil]
135
136
  def save_auto(auto, failed: nil)
136
137
  @state_lock.synchronize do
137
138
  failed_list = failed && !@state[:auto_failed].include?(failed) ? @state[:auto_failed] + [failed] : @state[:auto_failed]
@@ -211,7 +212,7 @@ module Samagotchi
211
212
  checked_at: data["checked_at"],
212
213
  available: data["available"],
213
214
  notified: strings(data["notified"]),
214
- auto: data["auto"].is_a?(Hash) ? data["auto"].transform_keys(&:to_sym) : nil,
215
+ auto: AutoUpdateRecord.from_h(data["auto"]),
215
216
  auto_failed: strings(data["auto_failed"])
216
217
  }
217
218
  rescue JSON::ParserError, SystemCallError => e
@@ -225,7 +226,7 @@ module Samagotchi
225
226
 
226
227
  def persist(state)
227
228
  FileUtils.mkdir_p(File.dirname(@state_file))
228
- AtomicFile.write(@state_file, JSON.generate(state), perm: 0o600)
229
+ AtomicFile.write(@state_file, JSON.generate(state.merge(auto: state[:auto]&.to_store)), perm: 0o600)
229
230
  @state = state
230
231
  end
231
232