samagotchi 0.179.0 → 0.180.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 (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -1
  3. data/docs/bundles.md +32 -1
  4. data/docs/configuration.md +1 -1
  5. data/docs/context.md +7 -0
  6. data/docs/internals/background-tasks.md +2 -1
  7. data/docs/internals/block-renderers.md +2 -1
  8. data/docs/internals/bundles.md +12 -10
  9. data/docs/internals/web-frontend.md +63 -2
  10. data/docs/plugins.md +6 -2
  11. data/docs/testing.md +4 -0
  12. data/lib/samagotchi/block_renderers.rb +22 -3
  13. data/lib/samagotchi/bundle_command.rb +5 -1
  14. data/lib/samagotchi/bundle_needs.rb +1 -1
  15. data/lib/samagotchi/bundle_settings_check.rb +5 -2
  16. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  17. data/lib/samagotchi/context_providers.rb +6 -8
  18. data/lib/samagotchi/installed_bundles/dir.rb +17 -55
  19. data/lib/samagotchi/installed_bundles/standing.rb +23 -3
  20. data/lib/samagotchi/installed_bundles.rb +26 -11
  21. data/lib/samagotchi/memory_bundle/status.rb +8 -5
  22. data/lib/samagotchi/session_config.rb +15 -9
  23. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  24. data/lib/samagotchi/terminal_ui/formatting.rb +13 -3
  25. data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
  26. data/lib/samagotchi/tools/task_runtime.rb +12 -3
  27. data/lib/samagotchi/version.rb +1 -1
  28. data/lib/samagotchi/web/public/app.js +13 -1
  29. data/lib/samagotchi/web/public/context_chips.js +184 -49
  30. data/lib/samagotchi/web/public/history_shape.js +5 -3
  31. data/lib/samagotchi/web/public/index.html +66 -0
  32. data/lib/samagotchi/web/public/peer_chip.js +171 -0
  33. data/lib/samagotchi/web/public/peer_data.js +119 -0
  34. data/lib/samagotchi/web/public/peer_exchange.js +83 -0
  35. data/lib/samagotchi/web/public/peer_links.js +161 -0
  36. data/lib/samagotchi/web/public/peer_note.js +49 -0
  37. data/lib/samagotchi/web/public/session_view.js +6 -1
  38. data/lib/samagotchi/web/public/stream_handlers.js +17 -4
  39. data/lib/samagotchi/web/public/turn_html.js +11 -2
  40. metadata +6 -1
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
+ autoload :Log, File.expand_path("../log", __dir__)
5
+
4
6
  module InstalledBundles
5
7
  # Why chi won't use an installed bundle, or one of its files: the verdict's
6
8
  # answer, which each reader reacts to in its own way (fail closed, a note,
@@ -17,17 +19,23 @@ module Samagotchi
17
19
  def initialize(kind:, text:, actual: nil, expected: nil) = super
18
20
  end
19
21
 
22
+ # The [bundle, reason] pairs Standing.warn_unreadable has logged.
23
+ UNREADABLE_WARNED = Set.new
24
+ UNREADABLE_LOCK = Mutex.new
25
+
20
26
  # One installed bundle as the verdict sees it, before any of its files is
21
27
  # looked at: its record (one with error set when it doesn't read) and why
22
28
  # chi won't use it, nil when it may.
23
29
  Standing = Data.define(:name, :record, :refusal) do
24
- # The bundle-level gate, on a record already read: an unreadable record,
25
- # then requires_chi. Reads the record's manifest (cached); a cache miss
26
- # hashes the kept manifest.yml (Manifest.of), and no other file.
30
+ # The bundle-level gate, on a record already read: an unreadable record
31
+ # (warned of once, .warn_unreadable), then requires_chi. Reads the
32
+ # record's manifest (cached); a cache miss hashes the kept manifest.yml
33
+ # (Manifest.of), and no other file.
27
34
  # @param record [Record]
28
35
  # @return [Standing]
29
36
  def self.of(name, record)
30
37
  refusal = if record.error?
38
+ warn_unreadable(name, record.error)
31
39
  Refusal.new(kind: :unreadable, text: record.error)
32
40
  elsif (failure = record.manifest.requires_chi_failure)
33
41
  Refusal.new(kind: :too_new, text: failure)
@@ -35,6 +43,18 @@ module Samagotchi
35
43
  new(name: name, record: record, refusal: refusal)
36
44
  end
37
45
 
46
+ # A record that doesn't read, said in the log once per process per
47
+ # bundle (and reason), whichever reader came across it: most readers
48
+ # only skip it (providers, renderers, settings, needs, memory owners).
49
+ def self.warn_unreadable(name, text)
50
+ return unless UNREADABLE_LOCK.synchronize { UNREADABLE_WARNED.add?([name, text]) }
51
+
52
+ Log.warn(:memory, "bundle_unreadable", bundle: name, msg: text)
53
+ end
54
+
55
+ # Forget what was warned of (specs).
56
+ def self.reset_warnings! = UNREADABLE_LOCK.synchronize { UNREADABLE_WARNED.clear }
57
+
38
58
  def usable? = refusal.nil?
39
59
 
40
60
  def unreadable? = refusal&.kind == :unreadable
@@ -16,6 +16,10 @@ module Samagotchi
16
16
  # removing a bundle is MemoryBundle's, which builds on this and never the
17
17
  # reverse (docs/internals/bundles.md).
18
18
  module InstalledBundles
19
+ # What reading a manifest.json may raise: it doesn't parse, it holds a
20
+ # key that isn't UTF-8 (which can't be a symbol), or it can't be read.
21
+ UNREADABLE = [JSON::ParserError, EncodingError, SystemCallError].freeze
22
+
19
23
  def self.dir
20
24
  MemoryPaths.bundles_dir
21
25
  end
@@ -41,10 +45,8 @@ module Samagotchi
41
45
 
42
46
  begin
43
47
  data = JSON.parse(File.read(mjson), symbolize_names: true)
44
- rescue JSON::ParserError, EncodingError, SystemCallError => e # a key that isn't UTF-8 can't be a symbol
45
- if holding.nil? || ::Dir.exist?(File.join(dir, name, holding.to_s))
46
- yield name, Record.unreadable(name, "manifest.json is unreadable: #{e.message}")
47
- end
48
+ rescue *UNREADABLE => e
49
+ yield name, unreadable(name, e) if holding.nil? || ::Dir.exist?(File.join(dir, name, holding.to_s))
48
50
  next
49
51
  end
50
52
  next if holding && !(data.is_a?(Hash) && data[holding].is_a?(Hash) && !data[holding].empty?)
@@ -63,24 +65,37 @@ module Samagotchi
63
65
  each(holding: holding, dir: dir) { |name, record| yield Standing.of(name, record) }
64
66
  end
65
67
 
66
- # One installed bundle's Standing, by name (one record read, no walk).
68
+ # One installed bundle's Standing, by name (one record read, no walk); a
69
+ # manifest.json that doesn't read is :unreadable, in .each's words.
67
70
  # @return [Standing, nil] nil when it isn't installed
68
- # @raise [JSON::ParserError] manifest.json doesn't parse (as Dir#record:
69
- # ContextProviders.command_for lets it out today, the plan's D7)
70
71
  def self.standing(name, dir: InstalledBundles.dir)
71
- record = Dir.new(name: name, dir: dir).record
72
+ record = begin
73
+ Dir.new(name: name, dir: dir).record
74
+ rescue *UNREADABLE => e
75
+ unreadable(name, e)
76
+ end
72
77
  record && Standing.of(name, record)
73
78
  end
74
79
 
80
+ # The one record of a manifest.json that raised +error+ when read.
81
+ def self.unreadable(name, error) = Record.unreadable(name, "manifest.json is unreadable: #{error.message}")
82
+ private_class_method :unreadable
83
+
75
84
  # The other installed bundles of +scope+ whose record lists the memory
76
85
  # file +file_key+, by name (a manifest that doesn't read is left out).
77
86
  # A project-scoped record doesn't say which project: one from another
78
87
  # repo counts too, which errs on keeping the file.
79
- # A record that doesn't read is skipped off the record itself: a claimant
80
- # check reads no manifest (Standing's requires_chi is no question here).
88
+ # A record that doesn't read is skipped off the record itself (warned of
89
+ # once, as Standing.of does): a claimant check reads no manifest
90
+ # (Standing's requires_chi is no question here).
81
91
  def self.claimants(file_key, scope:, except: nil, dir: InstalledBundles.dir)
82
92
  each(dir: dir).filter_map do |name, record|
83
- next if name == except || record.error?
93
+ next if name == except
94
+
95
+ if record.error?
96
+ Standing.warn_unreadable(name, record.error)
97
+ next
98
+ end
84
99
  next unless record.effective_scope == scope.to_s && record.owns?(file_key)
85
100
 
86
101
  name
@@ -113,17 +113,20 @@ module Samagotchi
113
113
  "needs #{need[:command]}#{why} #{state}#{hint}"
114
114
  end
115
115
 
116
+ # A plugin's state word in `chi bundle status`, by its file refusal's kind.
117
+ PLUGIN_STATES = { nil => "ok", file_unrecorded: "unrecorded", file_missing: "missing", file_changed: "modified" }.freeze
118
+
116
119
  # The installed plugin: {file:, path:, state:, requires_chi:,
117
- # requires_failure:}; state is "ok", "modified" (its sha256 differs
118
- # from the installed one, or none is recorded: it won't load) or
119
- # "missing", from the verdict (Dir#file_refusal(:plugin),
120
- # InstalledBundles::Standing). nil without one.
120
+ # requires_failure:}; state is "ok", "unrecorded" (no sha256 recorded
121
+ # for it), "missing" or "modified" (its sha256 differs from the
122
+ # installed one), from the verdict (Dir#file_refusal(:plugin),
123
+ # InstalledBundles::Standing): any but "ok" won't load. nil without one.
121
124
  def self.plugin_status(provenance, bundle)
122
125
  path = provenance.plugin_path(bundle)
123
126
  return nil unless path
124
127
 
125
128
  refusal = provenance.file_refusal(:plugin, bundle.plugin.file, bundle.plugin.sha256)
126
- state = { nil => "ok", file_missing: "missing" }.fetch(refusal&.kind, "modified")
129
+ state = PLUGIN_STATES.fetch(refusal&.kind)
127
130
  standing = InstalledBundles::Standing.of(provenance.name, bundle)
128
131
  { file: File.basename(path), path: path, state: state, requires_chi: bundle.manifest.requires_chi,
129
132
  requires_failure: standing.too_new? ? standing.refusal.text : nil }
@@ -213,6 +213,9 @@ module Samagotchi
213
213
  def no_installed_bundle(bundle) = "no installed bundle #{bundle}"
214
214
  def takes_keys(bundle, keys) = keys.empty? ? "#{bundle} takes no settings" : "#{bundle} takes #{keys.join(", ")}"
215
215
  def wrong_type(bundle, key, what, value) = "#{bundle} takes #{what} for #{key}, not #{value.inspect}"
216
+ # A bundle the verdict refuses as a whole (InstalledBundles::Standing:
217
+ # requires_chi), +reason+ its refusal's text.
218
+ def unusable(bundle, reason) = "#{bundle} is installed but this chi can't use it: #{reason}"
216
219
 
217
220
  # --set's values parsed and checked (.parse, .check!) against the
218
221
  # installed bundles (.availability).
@@ -288,9 +291,10 @@ module Samagotchi
288
291
  def offered(dir: nil) = availability(dir: dir).offered
289
292
 
290
293
  # The installed bundles a session may set settings of: a record that
291
- # doesn't read is left out, and so is one whose plugin doesn't load, as
292
- # the verdict says for the loader (InstalledBundles::Standing: requires_chi;
293
- # Dir#file_refusal(:plugin): the file, its sha256), with a note saying why. A record with no
294
+ # doesn't read is left out, and so is one this chi is too old for
295
+ # (InstalledBundles::Standing: requires_chi, plugin or not) or whose
296
+ # plugin doesn't load (Dir#file_refusal(:plugin): the file, its sha256),
297
+ # with a note saying why. A record with no
294
298
  # session_settings whose shipped bundle lists some (installed before
295
299
  # them) gets a note on refreshing it.
296
300
  # @return [Availability]
@@ -306,6 +310,10 @@ module Samagotchi
306
310
 
307
311
  name = standing.name
308
312
  bundle = standing.record
313
+ if standing.too_new?
314
+ notes[name] = unusable(name, standing.refusal.text)
315
+ next
316
+ end
309
317
  if (reason = unloadable(dir, standing))
310
318
  notes[name] = "#{name} is installed but its plugin doesn't load: #{reason}"
311
319
  next
@@ -376,16 +384,14 @@ module Samagotchi
376
384
  "setting#{"s" unless clashing.size == 1} (--set #{clashing.first}=… sets chi's); rename the setting or the bundle"
377
385
  end
378
386
 
379
- # Why +standing+'s plugin doesn't load, as the plugin loader would refuse
380
- # it (InstalledBundles' verdict), nil when it does or it has none. A bundle
381
- # with no plugin is never refused here, even one too new (the plan's D2).
387
+ # Why a usable +standing+'s plugin doesn't load, as the plugin loader
388
+ # would refuse it (Dir#file_refusal(:plugin)), nil when it does or it has
389
+ # none.
382
390
  def unloadable(dir, standing)
383
391
  plugin = standing.record.plugin
384
392
  return nil unless plugin
385
393
 
386
- refusal = standing.refusal ||
387
- InstalledBundles::Dir.new(name: standing.name, dir: dir).file_refusal(:plugin, plugin.file, plugin.sha256)
388
- refusal&.text
394
+ InstalledBundles::Dir.new(name: standing.name, dir: dir).file_refusal(:plugin, plugin.file, plugin.sha256)&.text
389
395
  end
390
396
 
391
397
  # Whether chi ships a bundle +name+ whose manifest lists session_settings.
@@ -324,7 +324,7 @@ module Samagotchi
324
324
  # line in the scrollback; the notes slot is for question choices.
325
325
  when :context_added
326
326
  mark_activity
327
- @screen.commit(context_note_line(event[:label], event[:text]))
327
+ @screen.commit(context_note_line(event[:label], event[:text], event[:peer]))
328
328
  when :continue_offered then offer_continue(event)
329
329
  when :continue_resolved then continue_resolved(event)
330
330
  # The note comes with the kernel's :pending_input_merged (EventRenderer),
@@ -325,8 +325,18 @@ module Samagotchi
325
325
 
326
326
  CONTEXT_NOTE_PREVIEW = 60
327
327
 
328
- # "note from slack: <first line>", cut to one line.
329
- def context_note_line(label, text)
328
+ # "note from slack: <first line>", cut to one line. A peer's answer
329
+ # (+peer+, the note's peer hash) reads "Claude answered · <summary>".
330
+ def context_note_line(label, text, peer = nil)
331
+ peer = peer.transform_keys(&:to_s) if peer.is_a?(Hash)
332
+ summary = peer && peer["summary"].to_s.strip.split("\n").first.to_s
333
+ who = peer && (peer["label"] || peer["peer"]).to_s.strip
334
+ return context_note_preview("#{who} answered \u00b7 ", summary) if summary && !summary.empty? && !who.empty?
335
+
336
+ context_note_preview("note from #{label || "?"}: ", text)
337
+ end
338
+
339
+ def context_note_preview(prefix, text)
330
340
  lines = text.to_s.strip.split("\n")
331
341
  first = lines.first.to_s
332
342
  if first.length > CONTEXT_NOTE_PREVIEW
@@ -334,7 +344,7 @@ module Samagotchi
334
344
  elsif lines.size > 1
335
345
  first += " \u2026"
336
346
  end
337
- paint("note from #{label || "?"}: #{first}", 2)
347
+ paint("#{prefix}#{first}", 2)
338
348
  end
339
349
 
340
350
  # A tool call from the snapshot: it has no action text, only the tool.
@@ -209,7 +209,7 @@ module Samagotchi
209
209
  return if after_exchange != !from.nil?
210
210
 
211
211
  messages[(from ? from + 1 : 0)..].select { |m| ContextNote.note?(m) }.each do |m|
212
- @screen.commit(context_note_line(ContextNote.label_of(m), ContextNote.text_of(m)))
212
+ @screen.commit(context_note_line(ContextNote.label_of(m), ContextNote.text_of(m), ContextNote.fetch(m, :peer)))
213
213
  end
214
214
  end
215
215
 
@@ -242,8 +242,8 @@ module Samagotchi
242
242
  def settle_pending!(timeout:)
243
243
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
244
244
  threads = @waiters_lock.synchronize do
245
- @waiters.values.filter_map do |thread, _pid, detach|
246
- thread if thread != Thread.current && thread.alive? && (!detach.alive? || thread[SETTLING])
245
+ @waiters.values.filter_map do |thread, pid, detach|
246
+ thread if thread != Thread.current && thread.alive? && shell_reaped?(thread, pid, detach)
247
247
  end
248
248
  end
249
249
  threads.each { |thread| thread.join([deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max) }
@@ -252,6 +252,15 @@ module Samagotchi
252
252
  alive
253
253
  end
254
254
 
255
+ # Whether a waiter's shell is reaped: its detach thread ended, the
256
+ # waiter is past the reap (SETTLING), or the pid is gone. Right after
257
+ # Process.detach reaps the shell its thread still runs a moment and
258
+ # SETTLING isn't set yet; kill(0) reads ESRCH only after the reap
259
+ # (a zombie answers), and a reused pid reads alive and is skipped.
260
+ def shell_reaped?(thread, pid, detach)
261
+ !detach.alive? || thread[SETTLING] || (ProcessGroup.signalable?(pid) && !ProcessGroup.alive?(pid))
262
+ end
263
+
255
264
  # Joins every live EXIT_STATUS_THREAD, for up to +timeout+ s in all: a
256
265
  # spec calls it (with_task_dir) after stopping its tasks and before it
257
266
  # removes their folder, which a recorder may still write into. chi
@@ -612,7 +621,7 @@ module Samagotchi
612
621
  :status_code, :correct_finished_record, :record_at,
613
622
  :leftover_group?, :settle_from_refresh, :chis_group?, :mark_not_chis, :not_found,
614
623
  :record_json, :ensure_tasks_dir, :normalize_cwd, :mark_finished_without_exit_code, :finished_with, :current_record,
615
- :mark_stopped, :read_exit_code, :timestamp
624
+ :mark_stopped, :read_exit_code, :timestamp, :shell_reaped?
616
625
  end
617
626
  end
618
627
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.179.0"
4
+ VERSION = "0.180.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -132,6 +132,9 @@ import { IMAGES_NOT_HERE } from "./images.js";
132
132
  import { withoutStaleParams } from "./stale_params.js";
133
133
  import { createViewer } from "./viewer.js";
134
134
  import { createParticipantMain } from "./participant_main.js";
135
+ import { createPeers } from "./peer_data.js";
136
+ import { peerStatusCommand } from "./peer_chip.js";
137
+ import { createPeerLinks } from "./peer_links.js";
135
138
  import { PARTICIPANT_REVISE_UNAVAILABLE, participantMayRevise, participantReviseUnavailable } from "./participant_revise.js";
136
139
 
137
140
  // A link's #code= (behind an auth proxy): traded for the cookie before
@@ -170,6 +173,10 @@ const contextChips = viewer.can("context") ? createContextChips({
170
173
  el: $("#contextChips"),
171
174
  api: { list: listContext, show: getContext, detach: detachContext },
172
175
  toast: (text) => showToast(text),
176
+ // A paired peer's one chip (peer_chip.js): its exchanges are the peers model's (below).
177
+ peers: () => peers,
178
+ peerActions: { status: (name) => peerStatusCommand(store.current.commands, name), run: (line) => runSessionCommand(line),
179
+ drawn: (id) => peerLinks.hasSend(id), jump: (id) => peerLinks.showSend(id) },
173
180
  }) : null;
174
181
  // The open session's ⚙ chip in the info bar, and its panel (thinking,
175
182
  // reasoning history, LLM context): a pick runs its command in the session's
@@ -427,6 +434,10 @@ if (viewer.can("answer_cards")) turnRoots().forEach((root) => root.addEventListe
427
434
  function findInTurnRoots(selector) {
428
435
  return turnRoots().flatMap((root) => [...root.querySelectorAll(selector)]);
429
436
  }
437
+ // The open session's peers (peer_data.js, owner only) and their exchange drawn in the conversation (peer_links.js).
438
+ const peers = contextChips ? createPeers({ sessionId: () => store.selected, onChange: () => { peerLinks.draw(); contextChips.peersChanged(); },
439
+ hasPeer: () => peerLinks.hasPeer() || contextChips.rows.some((row) => row.peer) }) : null;
440
+ const peerLinks = peers && createPeerLinks({ peers, roots: turnRoots, running: () => liveTurn.running, showText: (name) => contextChips.showText?.(name) });
430
441
  // The running turn as the page follows it (live_turn.js): whether one
431
442
  // runs, its timing line and the turns this page saw end (live_timing.js),
432
443
  // its merges' bubble flags, its turn-end reads.
@@ -536,7 +547,7 @@ turnRoots().forEach((root) => root.addEventListener("click", cards.onCardAction)
536
547
  const sessionView = createSessionView({
537
548
  store, historyEl, getSession,
538
549
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet, wsPreview, gapClock,
539
- bubbles, cards, markdown: markdownPlace, cardRegistry,
550
+ bubbles, cards, markdown: markdownPlace, cardRegistry, peerLinks,
540
551
  capabilities: () => pageCapabilities,
541
552
  page: {
542
553
  setReviseAnchor, renderInitRow, setMarkdownWarning, setCapabilities, findInTurnRoots, appendToHistory,
@@ -1170,6 +1181,7 @@ const streamHandlers = observeCards(cardRegistry, (participant ? participant.wra
1170
1181
  shownTexts,
1171
1182
  questionCards,
1172
1183
  contextChips,
1184
+ peers,
1173
1185
  workingSet,
1174
1186
  participantsControl,
1175
1187
  placeVerdict: ownerVerify.placeVerdict,