samagotchi 0.178.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 (141) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -1
  3. data/docs/architecture.md +4 -2
  4. data/docs/bundles.md +48 -8
  5. data/docs/cli.md +3 -1
  6. data/docs/configuration.md +1 -1
  7. data/docs/context.md +32 -1
  8. data/docs/guardrails.md +2 -1
  9. data/docs/internals/attached-context.md +26 -4
  10. data/docs/internals/background-tasks.md +5 -1
  11. data/docs/internals/block-renderers.md +4 -3
  12. data/docs/internals/bridge.md +11 -2
  13. data/docs/internals/bundles.md +65 -34
  14. data/docs/internals/engine.md +1 -1
  15. data/docs/internals/web-frontend.md +81 -3
  16. data/docs/plugins.md +20 -5
  17. data/docs/releasing.md +3 -3
  18. data/docs/scheduling.md +4 -0
  19. data/docs/sessions.md +8 -2
  20. data/docs/testing.md +8 -1
  21. data/lib/samagotchi/block_renderers.rb +33 -16
  22. data/lib/samagotchi/bootstrap/bundles.rb +2 -2
  23. data/lib/samagotchi/bootstrap_command.rb +1 -1
  24. data/lib/samagotchi/bridge/card_wait.rb +34 -0
  25. data/lib/samagotchi/bridge/turn_accumulator.rb +22 -4
  26. data/lib/samagotchi/bundle_command/check.rb +10 -10
  27. data/lib/samagotchi/bundle_command/installed_check.rb +2 -2
  28. data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
  29. data/lib/samagotchi/bundle_command.rb +22 -18
  30. data/lib/samagotchi/bundle_manifest.rb +579 -0
  31. data/lib/samagotchi/bundle_needs.rb +9 -8
  32. data/lib/samagotchi/bundle_settings_check.rb +13 -9
  33. data/lib/samagotchi/bundles/claude-peer/manifest.yml +5 -3
  34. data/lib/samagotchi/bundles/claude-peer/plugin.rb +4 -4
  35. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +11 -6
  36. data/lib/samagotchi/bundles/codex-peer/manifest.yml +5 -3
  37. data/lib/samagotchi/bundles/codex-peer/plugin.rb +4 -3
  38. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +11 -6
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  41. data/lib/samagotchi/config.rb +2 -2
  42. data/lib/samagotchi/context_absorber.rb +36 -6
  43. data/lib/samagotchi/context_note.rb +8 -5
  44. data/lib/samagotchi/context_providers.rb +30 -29
  45. data/lib/samagotchi/context_sources.rb +42 -12
  46. data/lib/samagotchi/engine/messages.rb +1 -1
  47. data/lib/samagotchi/events.rb +6 -5
  48. data/lib/samagotchi/guardrail_wiring.rb +20 -21
  49. data/lib/samagotchi/guardrails/approval.rb +3 -2
  50. data/lib/samagotchi/guardrails/outside.rb +3 -3
  51. data/lib/samagotchi/{memory_bundle → installed_bundles}/bundle_hook.rb +1 -1
  52. data/lib/samagotchi/installed_bundles/dir.rb +91 -0
  53. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_digest.rb +1 -1
  54. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_standing.rb +2 -2
  55. data/lib/samagotchi/{memory_bundle/installed_manifest.rb → installed_bundles/manifest.rb} +21 -21
  56. data/lib/samagotchi/{memory_bundle → installed_bundles}/plugin_ref.rb +2 -2
  57. data/lib/samagotchi/{memory_bundle/installed_bundle.rb → installed_bundles/record.rb} +17 -17
  58. data/lib/samagotchi/installed_bundles/sha.rb +41 -0
  59. data/lib/samagotchi/installed_bundles/standing.rb +65 -0
  60. data/lib/samagotchi/installed_bundles.rb +105 -0
  61. data/lib/samagotchi/memory_bundle/asset_installer.rb +7 -7
  62. data/lib/samagotchi/memory_bundle/builder.rb +13 -13
  63. data/lib/samagotchi/memory_bundle/file_state.rb +9 -9
  64. data/lib/samagotchi/memory_bundle/installed_copy.rb +6 -6
  65. data/lib/samagotchi/memory_bundle/installer.rb +33 -33
  66. data/lib/samagotchi/memory_bundle/listing.rb +5 -5
  67. data/lib/samagotchi/memory_bundle/manifest_standing.rb +7 -7
  68. data/lib/samagotchi/memory_bundle/merger.rb +15 -15
  69. data/lib/samagotchi/memory_bundle/profile.rb +8 -8
  70. data/lib/samagotchi/memory_bundle/provenance.rb +59 -192
  71. data/lib/samagotchi/memory_bundle/remerge.rb +16 -16
  72. data/lib/samagotchi/memory_bundle/shas.rb +2 -2
  73. data/lib/samagotchi/memory_bundle/shipped_history.rb +1 -1
  74. data/lib/samagotchi/memory_bundle/shipped_update.rb +17 -17
  75. data/lib/samagotchi/memory_bundle/status.rb +19 -16
  76. data/lib/samagotchi/memory_bundle/system_bundle.rb +12 -12
  77. data/lib/samagotchi/memory_bundle/trash.rb +2 -2
  78. data/lib/samagotchi/memory_bundle/uninstaller.rb +8 -8
  79. data/lib/samagotchi/memory_bundle.rb +2 -2
  80. data/lib/samagotchi/memory_command.rb +4 -4
  81. data/lib/samagotchi/{memory_bundle → memory_index}/entry_size.rb +8 -8
  82. data/lib/samagotchi/{memory_bundle/index_size.rb → memory_index/size.rb} +6 -6
  83. data/lib/samagotchi/{memory_bundle/index_sync.rb → memory_index/sync.rb} +5 -5
  84. data/lib/samagotchi/{memory_bundle/index_updater.rb → memory_index/updater.rb} +2 -2
  85. data/lib/samagotchi/memory_usage.rb +5 -5
  86. data/lib/samagotchi/muted_memories.rb +1 -1
  87. data/lib/samagotchi/peer_exchanges.rb +76 -0
  88. data/lib/samagotchi/plugin/context.rb +4 -0
  89. data/lib/samagotchi/plugin/loader.rb +35 -33
  90. data/lib/samagotchi/plugin/peer.rb +42 -11
  91. data/lib/samagotchi/project_subfolders.rb +9 -9
  92. data/lib/samagotchi/reply_wait/target.rb +11 -4
  93. data/lib/samagotchi/self_report.rb +14 -14
  94. data/lib/samagotchi/session_access/local.rb +16 -1
  95. data/lib/samagotchi/session_access/remote.rb +2 -1
  96. data/lib/samagotchi/session_config.rb +29 -19
  97. data/lib/samagotchi/session_manager/running_tasks.rb +15 -2
  98. data/lib/samagotchi/session_retention.rb +13 -4
  99. data/lib/samagotchi/session_stores.rb +3 -0
  100. data/lib/samagotchi/system_prompt.rb +4 -4
  101. data/lib/samagotchi/terminal_ui/attach_launcher.rb +5 -1
  102. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  103. data/lib/samagotchi/terminal_ui/formatting.rb +15 -5
  104. data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
  105. data/lib/samagotchi/terminal_ui/model_segments_text.rb +5 -5
  106. data/lib/samagotchi/terminal_ui.rb +4 -1
  107. data/lib/samagotchi/testing/bundle.rb +3 -3
  108. data/lib/samagotchi/testing/install.rb +3 -3
  109. data/lib/samagotchi/testing/sandbox.rb +2 -2
  110. data/lib/samagotchi/tool_runner.rb +14 -14
  111. data/lib/samagotchi/tools/memory.rb +22 -22
  112. data/lib/samagotchi/tools/task_runtime.rb +12 -3
  113. data/lib/samagotchi/update_command.rb +4 -4
  114. data/lib/samagotchi/version.rb +1 -1
  115. data/lib/samagotchi/web/app.rb +14 -1
  116. data/lib/samagotchi/web/message_display.rb +6 -0
  117. data/lib/samagotchi/web/participant_view.rb +1 -1
  118. data/lib/samagotchi/web/proxy_gate.rb +1 -0
  119. data/lib/samagotchi/web/public/app.js +13 -1
  120. data/lib/samagotchi/web/public/card_kinds.js +8 -3
  121. data/lib/samagotchi/web/public/cards_place.js +15 -1
  122. data/lib/samagotchi/web/public/context_chips.js +184 -49
  123. data/lib/samagotchi/web/public/ctx.js +1 -1
  124. data/lib/samagotchi/web/public/history_shape.js +8 -3
  125. data/lib/samagotchi/web/public/index.html +66 -0
  126. data/lib/samagotchi/web/public/peer_chip.js +171 -0
  127. data/lib/samagotchi/web/public/peer_data.js +119 -0
  128. data/lib/samagotchi/web/public/peer_exchange.js +83 -0
  129. data/lib/samagotchi/web/public/peer_links.js +161 -0
  130. data/lib/samagotchi/web/public/peer_note.js +49 -0
  131. data/lib/samagotchi/web/public/session_view.js +6 -1
  132. data/lib/samagotchi/web/public/stream_handlers.js +17 -4
  133. data/lib/samagotchi/web/public/turn_block.js +46 -8
  134. data/lib/samagotchi/web/public/turn_html.js +11 -2
  135. data/lib/samagotchi/web/public/turn_settle.js +117 -0
  136. data/lib/samagotchi/web/push/notifier.rb +2 -2
  137. data/lib/samagotchi/web/session_access_routes.rb +21 -1
  138. data/lib/samagotchi/web/session_hub.rb +20 -4
  139. data/lib/samagotchi/worker_boot.rb +4 -1
  140. metadata +24 -12
  141. data/lib/samagotchi/memory_bundle/manifest.rb +0 -581
@@ -316,7 +316,7 @@ module Samagotchi
316
316
 
317
317
  dir = MemoryRead.memories_dir(resolved_scope)
318
318
  FileUtils.mkdir_p(dir)
319
- require_relative "../memory_bundle/index_updater"
319
+ require_relative "../memory_index/updater"
320
320
 
321
321
  if current_model_only && model_key
322
322
  # Overlays are only read through their base entry (same scope), so an
@@ -340,7 +340,7 @@ module Samagotchi
340
340
  # And the memory's own size, for memory.entry_warn_tokens.
341
341
  entry_before = entry_size(resolved_scope, entry_name, file_path) unless entry_name == MEMORY_INDEX
342
342
  if entry_name == MEMORY_INDEX
343
- Samagotchi::MemoryBundle::IndexUpdater.locked_write(dir) { body }
343
+ Samagotchi::MemoryIndex::Updater.locked_write(dir) { body }
344
344
  else
345
345
  Samagotchi::AtomicFile.write(file_path, body)
346
346
  end
@@ -417,11 +417,11 @@ module Samagotchi
417
417
  "#{index_crossing_note(before, resolved_scope)}"
418
418
  end
419
419
 
420
- # +scope+'s index size (MemoryBundle::IndexSize), or nil when
420
+ # +scope+'s index size (MemoryIndex::Size), or nil when
421
421
  # memory.index_warn_tokens is off or the index can't be read.
422
422
  def self.index_size(scope)
423
- require_relative "../memory_bundle/index_size"
424
- size = Samagotchi::MemoryBundle::IndexSize
423
+ require_relative "../memory_index/size"
424
+ size = Samagotchi::MemoryIndex::Size
425
425
  size.measure(scope) if size.warn_limit.positive?
426
426
  end
427
427
 
@@ -429,8 +429,8 @@ module Samagotchi
429
429
  # when memory.entry_warn_tokens is off, for a model note (its own
430
430
  # warning) or when it can't be measured.
431
431
  def self.entry_size(scope, name, file_path)
432
- require_relative "../memory_bundle/entry_size"
433
- size = Samagotchi::MemoryBundle::EntrySize
432
+ require_relative "../memory_index/entry_size"
433
+ size = Samagotchi::MemoryIndex::EntrySize
434
434
  return nil unless size.warn_limit.positive? && size.counted?(name)
435
435
 
436
436
  size.of_text(name, scope, File.file?(file_path) ? File.read(file_path, encoding: "UTF-8") : "")
@@ -443,7 +443,7 @@ module Samagotchi
443
443
  # (+before+: its size before the write), else "". +body+ is what was
444
444
  # written.
445
445
  def self.entry_crossing_note(before, scope, name, body)
446
- size = Samagotchi::MemoryBundle::EntrySize
446
+ size = Samagotchi::MemoryIndex::EntrySize
447
447
  note = size.crossing_note(before, size.of_text(name, scope, body))
448
448
  note ? "\n\n#{note}" : ""
449
449
  rescue StandardError
@@ -456,7 +456,7 @@ module Samagotchi
456
456
  def self.index_crossing_note(before, scope)
457
457
  return "" unless before
458
458
 
459
- note = Samagotchi::MemoryBundle::IndexSize.crossing_note(before, index_size(scope))
459
+ note = Samagotchi::MemoryIndex::Size.crossing_note(before, index_size(scope))
460
460
  note ? "\n\n#{note}" : ""
461
461
  end
462
462
 
@@ -469,8 +469,8 @@ module Samagotchi
469
469
  def self.remove(entry_name, scope)
470
470
  return "Error: the index can't be removed; it is kept up to date for you" if entry_name == MEMORY_INDEX
471
471
 
472
- require_relative "../memory_bundle/index_updater"
473
- require_relative "../memory_bundle/provenance"
472
+ require_relative "../memory_index/updater"
473
+ require_relative "../installed_bundles"
474
474
  require_relative "../memory_bundle/trash"
475
475
  resolved_scope = MemoryRead.normalize_scope(scope)
476
476
  dir = MemoryRead.memories_dir(resolved_scope)
@@ -479,20 +479,20 @@ module Samagotchi
479
479
  line = index_text[managed_pattern(entry_name)]
480
480
  file = File.join(dir, "#{entry_name}.md")
481
481
 
482
- owner = Samagotchi::MemoryBundle::Provenance.claimants("#{entry_name}.md", scope: resolved_scope).first ||
483
- (line && Samagotchi::MemoryBundle::IndexUpdater.extract_source(line))
482
+ owner = Samagotchi::InstalledBundles.claimants("#{entry_name}.md", scope: resolved_scope).first ||
483
+ (line && Samagotchi::MemoryIndex::Updater.extract_source(line))
484
484
  return "Error: memory '#{entry_name}' came from bundle #{owner}; `chi bundle uninstall #{owner}` removes it" if owner
485
485
 
486
486
  unless File.file?(file)
487
487
  return "Error: no memory '#{entry_name}' in #{resolved_scope} scope" unless line
488
488
 
489
- Samagotchi::MemoryBundle::IndexUpdater.remove_index(resolved_scope, entry_name)
489
+ Samagotchi::MemoryIndex::Updater.remove_index(resolved_scope, entry_name)
490
490
  return "Memory '#{entry_name}' had no file in #{resolved_scope} scope; its dangling index line was dropped."
491
491
  end
492
492
 
493
493
  trash = Samagotchi::MemoryBundle::Trash.new("memory-#{entry_name}")
494
494
  ([file] + overlay_files(dir, entry_name, index_text)).each { |path| trash.move(path) }
495
- Samagotchi::MemoryBundle::IndexUpdater.remove_index(resolved_scope, entry_name)
495
+ Samagotchi::MemoryIndex::Updater.remove_index(resolved_scope, entry_name)
496
496
  "Memory '#{entry_name}' removed from #{resolved_scope} scope: moved to #{trash.dir} " \
497
497
  "(`chi bundle trash` lists and empties it)#{"; index line dropped" if line}."
498
498
  end
@@ -513,30 +513,30 @@ module Samagotchi
513
513
 
514
514
  # Adds or refreshes a single managed line for `entry_name` in the given
515
515
  # scope's index.md, preserving every other byte byte-for-byte.
516
- # Delegates to IndexUpdater to maintain a single source of truth.
516
+ # Delegates to MemoryIndex::Updater to maintain a single source of truth.
517
517
  # Returns true when an entry was written (i.e. the index was managed).
518
518
  def self.manage_index(scope, entry_name, byte_count, description = nil)
519
- require_relative "../memory_bundle/index_updater"
520
- Samagotchi::MemoryBundle::IndexUpdater.update_index(scope, entry_name, byte_count, description)
519
+ require_relative "../memory_index/updater"
520
+ Samagotchi::MemoryIndex::Updater.update_index(scope, entry_name, byte_count, description)
521
521
  end
522
522
 
523
523
  def self.managed_line(name, scope, byte_count, description)
524
- Samagotchi::MemoryBundle::IndexUpdater.managed_line(name, scope, byte_count, description)
524
+ Samagotchi::MemoryIndex::Updater.managed_line(name, scope, byte_count, description)
525
525
  end
526
526
 
527
527
  # Extracts the human description from an existing managed line so that a
528
528
  # legacy `- **name**: desc` or a new-format line with a description keeps
529
529
  # its description when the entry is updated without a new one.
530
530
  def self.extract_description(line)
531
- Samagotchi::MemoryBundle::IndexUpdater.extract_description(line)
531
+ Samagotchi::MemoryIndex::Updater.extract_description(line)
532
532
  end
533
533
 
534
534
  def self.auto_index_header
535
- Samagotchi::MemoryBundle::IndexUpdater.auto_index_header
535
+ Samagotchi::MemoryIndex::Updater.auto_index_header
536
536
  end
537
537
 
538
538
  def self.date_str
539
- Samagotchi::MemoryBundle::IndexUpdater.date_str
539
+ Samagotchi::MemoryIndex::Updater.date_str
540
540
  end
541
541
 
542
542
  def self.index_path_for(scope)
@@ -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
@@ -9,7 +9,7 @@ require_relative "desktop"
9
9
  require_relative "gem_update"
10
10
  require_relative "installed_gem"
11
11
  require_relative "live_versions"
12
- require_relative "memory_bundle/file_standing"
12
+ require_relative "installed_bundles/file_standing"
13
13
  require_relative "memory_bundle/manifest_standing"
14
14
  require_relative "memory_bundle/shipped_update"
15
15
  require_relative "memory_bundle/system_bundle"
@@ -384,8 +384,8 @@ module Samagotchi
384
384
  row.kept = behind.map(&:file)
385
385
  @unsure_behind ||= behind.any?(&:unsure)
386
386
  row.trash_copy = trash_copy
387
- notes = MemoryBundle::FileStanding.clauses(bundle, version, merged: merged, behind: behind, earlier: earlier, dry_run: @dry_run)
388
- trash_copy || earlier.any?(&:trash) ? [*notes, MemoryBundle::FileStanding::IN_THE_TRASH] : notes
387
+ notes = InstalledBundles::FileStanding.clauses(bundle, version, merged: merged, behind: behind, earlier: earlier, dry_run: @dry_run)
388
+ trash_copy || earlier.any?(&:trash) ? [*notes, InstalledBundles::FileStanding::IN_THE_TRASH] : notes
389
389
  end
390
390
 
391
391
  # Whether a row printed now ends the notes for what it printed, this run's
@@ -494,7 +494,7 @@ module Samagotchi
494
494
  return "some parts failed (see above)" if rows.any?(&:failed)
495
495
 
496
496
  behind = rows.sum { |row| Array(row.kept).size }
497
- return "#{MemoryBundle::FileStanding.stay_behind(behind, unsure: @unsure_behind)} (see above)" if behind.positive?
497
+ return "#{InstalledBundles::FileStanding.stay_behind(behind, unsure: @unsure_behind)} (see above)" if behind.positive?
498
498
 
499
499
  # A finding on a bundle chi didn't ship repeats until its bundle changes; it isn't a change.
500
500
  changes = rows.reject(&:level)
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.178.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
@@ -329,6 +329,7 @@ module Samagotchi
329
329
  ["POST", %r{\A/api/sessions/([^/]+)/images\z}, :handle_image_upload, :participant, :session],
330
330
  ["GET", %r{\A/api/sessions/([^/]+)/images/([^/]+)\z}, :handle_image, :participant, :session],
331
331
  ["GET", %r{\A/api/sessions/([^/]+)/context\z}, :handle_context_list, :owner, :session],
332
+ ["GET", %r{\A/api/sessions/([^/]+)/peers\z}, :handle_peers, :owner, :session],
332
333
  ["GET", %r{\A/api/sessions/([^/]+)/context/([^/]+)\z}, :handle_context_show, :owner, :session],
333
334
  ["POST", %r{\A/api/sessions/([^/]+)/context\z}, :handle_context_add, :owner, :session],
334
335
  ["POST", %r{\A/api/sessions/([^/]+)/context/([^/]+)/push\z}, :handle_context_push, :owner, :session],
@@ -1010,7 +1011,7 @@ module Samagotchi
1010
1011
 
1011
1012
  root = dir && ProjectScope.root_for(dir)
1012
1013
  # Lazy retention sweep (once per 24h)
1013
- Degrade.call(:web, "retention_sweep_failed") { @manager.retention_sweep_if_due(state_dir: @state_dir) }
1014
+ @hub.sweep_if_due
1014
1015
  limit = sanitize_limit(req.GET["limit"])
1015
1016
  offset = sanitize_offset(req.GET["offset"])
1016
1017
  all = @hub.snapshot(project_root: root, sort: sanitize_sort(req.GET["sort"]), order: sanitize_order(req.GET["order"]))
@@ -1443,6 +1444,7 @@ module Samagotchi
1443
1444
  state_dir: default_state_dir)
1444
1445
  .map { |candidate, status| candidate.to_h.merge("name" => candidate.name, "status" => status) }
1445
1446
  end
1447
+
1446
1448
  json_response(200, body)
1447
1449
  end
1448
1450
 
@@ -1581,11 +1583,22 @@ module Samagotchi
1581
1583
  why: source.why, hint: snapshot.hint || source.hint, summary: snapshot.summary, error: snapshot.error,
1582
1584
  fetched_at: snapshot.fetched_at, has_text: snapshot.text?, muted: own.muted?(source.name),
1583
1585
  unread: snapshot.text? && subs[source.name]&.read != snapshot.revision }
1586
+ row.merge!(context_peer(attached))
1584
1587
  return row unless full
1585
1588
 
1586
1589
  row.merge(source: source.to_h, snapshot: snapshot.to_h.except("text", :text), shadowed: attached.shadowed)
1587
1590
  end
1588
1591
 
1592
+ # A pushed session source named <peer>-inbox / -outbox: the pairing's
1593
+ # peer ("claude"), its leg and label, by name (docs/context.md, Peer
1594
+ # sources); {} for any other.
1595
+ def context_peer(attached)
1596
+ return {} unless attached.source.push? && attached.location.session?
1597
+
1598
+ peer, leg = ContextSources.peer_leg(attached.name)
1599
+ peer ? { peer: peer, leg: leg, label: ContextSources.peer_label(peer) } : {}
1600
+ end
1601
+
1589
1602
  def handle_stream(req, id)
1590
1603
  # Validate session exists
1591
1604
  begin
@@ -123,6 +123,12 @@ module Samagotchi
123
123
  content = (m[:content] || m["content"]).to_s
124
124
  if Samagotchi::ContextNote.note?(m)
125
125
  note = { role: "note", content: Samagotchi::ContextNote.text_of(m), label: Samagotchi::ContextNote.label_of(m), **time_of(m) }
126
+ # The chip it is about and, for a peer's answer, whose (as the
127
+ # live :context_added carries them).
128
+ context_source = Samagotchi::ContextNote.fetch(m, :context_source)
129
+ note[:context_source] = context_source.to_s if context_source
130
+ peer = Samagotchi::ContextNote.fetch(m, :peer)
131
+ note[:peer] = peer if peer.is_a?(Hash)
126
132
  payload = Samagotchi::ContextNote.fetch(m, :objectives)
127
133
  entry = payload && Samagotchi::Objectives.entry(payload, before: objectives)
128
134
  if entry
@@ -86,7 +86,7 @@ module Samagotchi
86
86
  after_generation after_tool_call after_turn answer_display before_generation before_tool_call before_turn
87
87
  card command_output command_queued command_ran context_added empty_answer_retry
88
88
  generation_cancelled generation_progress generation_started guardrail_warning hook_notice
89
- llm_context_edited merged_input objectives_updated participants_changed pending_input_merged plugin_init_finished
89
+ llm_context_edited merged_input objectives_updated part_settled participants_changed pending_input_merged plugin_init_finished
90
90
  plugin_init_started plugin_init_wait question question_relay reasoning_history_refused
91
91
  recap_ready reminder_injected sampling_refused session_end session_start side_usage steer_cut thinking_dropped
92
92
  thinking_refused tool_dispatch_completed tool_dispatch_started used_memories_updated
@@ -124,6 +124,7 @@ module Samagotchi
124
124
 
125
125
  return proxy_refuse(req, "owner token with identity #{shown}#{identity_hint(req)}")
126
126
  end
127
+ require_relative "../grants"
127
128
  grant_tokens = given.select { |value| Grants.token?(value) }
128
129
  return proxy_refuse(req, "no token (identity #{shown})") if grant_tokens.empty?
129
130
 
@@ -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,
@@ -34,9 +34,14 @@ export function continueWait() {
34
34
  }
35
35
 
36
36
  // A plugin card's wait: a running turn's card with an action asks (as
37
- // check-in's), a warning stays in sight; null: it doesn't wait.
38
- export function cardWait(card) {
39
- const asks = !!card?.in_turn && (card.actions || []).some((a) => a && a.command);
37
+ // check-in's), a warning stays in sight; null: it doesn't wait. The one rule
38
+ // cards_place.js upsertCard and turn_block.js drawnTurnNodes ask; the DOM
39
+ // readers (stage_cards.js, stage_waiting.js waitingKind, card.js
40
+ // isNoticeCard) stay the cross-check. +inTurn+ overrides the card's own
41
+ // in_turn: a caller that already knows the card's turn (a drawing's card, an
42
+ // update of a card already shown, which asks by its actions alone).
43
+ export function cardWait(card, { inTurn = !!card?.in_turn } = {}) {
44
+ const asks = inTurn && (card?.actions || []).some((a) => a && a.command);
40
45
  return { kind: asks ? "asks" : card?.level === "warn" ? "warn" : null, approval: false, summary: String(card?.title || "") };
41
46
  }
42
47
 
@@ -73,7 +73,9 @@ export function createCardsPlace({
73
73
  if (!card || !card.id) return;
74
74
  turnDom.settleFold?.();
75
75
  const existing = cardElement(card.id);
76
- const asks = (card.actions || []).some((a) => a && a.command);
76
+ // Asking by its actions alone: an update of a card shown between turns
77
+ // with actions counts as asking (it settles nothing on the stage).
78
+ const asks = cardWait(card, { inTurn: true }).kind === "asks";
77
79
  if (existing) {
78
80
  const wasWarn = existing.classList.contains("warn");
79
81
  const drawn = drawCard(existing, card);
@@ -122,6 +124,9 @@ export function createCardsPlace({
122
124
  else if (entry.in_turn) placeTurnNotice(entry, before);
123
125
  else if (entry.type === "hook_notice") bubbles.showHookNotice(entry, { before });
124
126
  }
127
+ // A drawn turn's question slot whose question never came (CardStore
128
+ // dropped it, a pending one): nothing in its place.
129
+ historyEl.querySelectorAll("[data-question-slot]").forEach((slot) => slot.remove());
125
130
  }
126
131
 
127
132
  // An in-turn entry (not a question) of a turn the history drew from its
@@ -179,6 +184,15 @@ export function createCardsPlace({
179
184
  const card = questionCards.questionCard();
180
185
  if (!card || card.dataset.qid !== String(pq.id)) return;
181
186
  questionCards.resolveQuestion(pq.id, { answer: entry.answer || null, cancelled: !!entry.cancelled, reason: entry.reason || "" });
187
+ // A drawn turn keeps its place (turn_block.js drawnTurnNodes, the order
188
+ // live left it in: turn_settle.js); an undrawn one (an old drawing
189
+ // without question events) goes before the later lines and the answer.
190
+ const slot = turnEls.find((el) => el.dataset.questionSlot === String(pq.id));
191
+ if (slot) {
192
+ if (slot.dataset.drawn) card.dataset.drawn = slot.dataset.drawn;
193
+ slot.replaceWith(card);
194
+ return;
195
+ }
182
196
  const later = turnEls.find((el) => el.matches(".bubble.user.steered") && Number(el.dataset.step) > asked);
183
197
  historyEl.insertBefore(card, later || turnAnswerEl(turnEls) || before);
184
198
  }