samagotchi 0.178.0 → 0.179.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 (126) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +28 -1
  3. data/docs/architecture.md +4 -2
  4. data/docs/bundles.md +16 -7
  5. data/docs/cli.md +3 -1
  6. data/docs/context.md +25 -1
  7. data/docs/guardrails.md +2 -1
  8. data/docs/internals/attached-context.md +26 -4
  9. data/docs/internals/background-tasks.md +3 -0
  10. data/docs/internals/block-renderers.md +2 -2
  11. data/docs/internals/bridge.md +11 -2
  12. data/docs/internals/bundles.md +63 -34
  13. data/docs/internals/engine.md +1 -1
  14. data/docs/internals/web-frontend.md +18 -1
  15. data/docs/plugins.md +14 -3
  16. data/docs/releasing.md +3 -3
  17. data/docs/scheduling.md +4 -0
  18. data/docs/sessions.md +8 -2
  19. data/docs/testing.md +4 -1
  20. data/lib/samagotchi/block_renderers.rb +12 -14
  21. data/lib/samagotchi/bootstrap/bundles.rb +2 -2
  22. data/lib/samagotchi/bootstrap_command.rb +1 -1
  23. data/lib/samagotchi/bridge/card_wait.rb +34 -0
  24. data/lib/samagotchi/bridge/turn_accumulator.rb +22 -4
  25. data/lib/samagotchi/bundle_command/check.rb +10 -10
  26. data/lib/samagotchi/bundle_command/installed_check.rb +2 -2
  27. data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
  28. data/lib/samagotchi/bundle_command.rb +17 -17
  29. data/lib/samagotchi/bundle_manifest.rb +579 -0
  30. data/lib/samagotchi/bundle_needs.rb +9 -8
  31. data/lib/samagotchi/bundle_settings_check.rb +9 -8
  32. data/lib/samagotchi/bundles/claude-peer/manifest.yml +5 -3
  33. data/lib/samagotchi/bundles/claude-peer/plugin.rb +4 -4
  34. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +11 -6
  35. data/lib/samagotchi/bundles/codex-peer/manifest.yml +5 -3
  36. data/lib/samagotchi/bundles/codex-peer/plugin.rb +4 -3
  37. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +11 -6
  38. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  40. data/lib/samagotchi/config.rb +2 -2
  41. data/lib/samagotchi/context_absorber.rb +36 -6
  42. data/lib/samagotchi/context_note.rb +8 -5
  43. data/lib/samagotchi/context_providers.rb +30 -27
  44. data/lib/samagotchi/context_sources.rb +42 -12
  45. data/lib/samagotchi/engine/messages.rb +1 -1
  46. data/lib/samagotchi/events.rb +6 -5
  47. data/lib/samagotchi/guardrail_wiring.rb +20 -21
  48. data/lib/samagotchi/guardrails/approval.rb +3 -2
  49. data/lib/samagotchi/guardrails/outside.rb +3 -3
  50. data/lib/samagotchi/{memory_bundle → installed_bundles}/bundle_hook.rb +1 -1
  51. data/lib/samagotchi/installed_bundles/dir.rb +129 -0
  52. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_digest.rb +1 -1
  53. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_standing.rb +2 -2
  54. data/lib/samagotchi/{memory_bundle/installed_manifest.rb → installed_bundles/manifest.rb} +21 -21
  55. data/lib/samagotchi/{memory_bundle → installed_bundles}/plugin_ref.rb +2 -2
  56. data/lib/samagotchi/{memory_bundle/installed_bundle.rb → installed_bundles/record.rb} +17 -17
  57. data/lib/samagotchi/installed_bundles/sha.rb +41 -0
  58. data/lib/samagotchi/installed_bundles/standing.rb +45 -0
  59. data/lib/samagotchi/installed_bundles.rb +90 -0
  60. data/lib/samagotchi/memory_bundle/asset_installer.rb +7 -7
  61. data/lib/samagotchi/memory_bundle/builder.rb +13 -13
  62. data/lib/samagotchi/memory_bundle/file_state.rb +9 -9
  63. data/lib/samagotchi/memory_bundle/installed_copy.rb +6 -6
  64. data/lib/samagotchi/memory_bundle/installer.rb +33 -33
  65. data/lib/samagotchi/memory_bundle/listing.rb +5 -5
  66. data/lib/samagotchi/memory_bundle/manifest_standing.rb +7 -7
  67. data/lib/samagotchi/memory_bundle/merger.rb +15 -15
  68. data/lib/samagotchi/memory_bundle/profile.rb +8 -8
  69. data/lib/samagotchi/memory_bundle/provenance.rb +59 -192
  70. data/lib/samagotchi/memory_bundle/remerge.rb +16 -16
  71. data/lib/samagotchi/memory_bundle/shas.rb +2 -2
  72. data/lib/samagotchi/memory_bundle/shipped_history.rb +1 -1
  73. data/lib/samagotchi/memory_bundle/shipped_update.rb +17 -17
  74. data/lib/samagotchi/memory_bundle/status.rb +15 -15
  75. data/lib/samagotchi/memory_bundle/system_bundle.rb +12 -12
  76. data/lib/samagotchi/memory_bundle/trash.rb +2 -2
  77. data/lib/samagotchi/memory_bundle/uninstaller.rb +8 -8
  78. data/lib/samagotchi/memory_bundle.rb +2 -2
  79. data/lib/samagotchi/memory_command.rb +4 -4
  80. data/lib/samagotchi/{memory_bundle → memory_index}/entry_size.rb +8 -8
  81. data/lib/samagotchi/{memory_bundle/index_size.rb → memory_index/size.rb} +6 -6
  82. data/lib/samagotchi/{memory_bundle/index_sync.rb → memory_index/sync.rb} +5 -5
  83. data/lib/samagotchi/{memory_bundle/index_updater.rb → memory_index/updater.rb} +2 -2
  84. data/lib/samagotchi/memory_usage.rb +5 -5
  85. data/lib/samagotchi/muted_memories.rb +1 -1
  86. data/lib/samagotchi/peer_exchanges.rb +76 -0
  87. data/lib/samagotchi/plugin/context.rb +4 -0
  88. data/lib/samagotchi/plugin/loader.rb +35 -33
  89. data/lib/samagotchi/plugin/peer.rb +42 -11
  90. data/lib/samagotchi/project_subfolders.rb +9 -9
  91. data/lib/samagotchi/reply_wait/target.rb +11 -4
  92. data/lib/samagotchi/self_report.rb +14 -14
  93. data/lib/samagotchi/session_access/local.rb +16 -1
  94. data/lib/samagotchi/session_access/remote.rb +2 -1
  95. data/lib/samagotchi/session_config.rb +23 -19
  96. data/lib/samagotchi/session_manager/running_tasks.rb +15 -2
  97. data/lib/samagotchi/session_retention.rb +13 -4
  98. data/lib/samagotchi/session_stores.rb +3 -0
  99. data/lib/samagotchi/system_prompt.rb +4 -4
  100. data/lib/samagotchi/terminal_ui/attach_launcher.rb +5 -1
  101. data/lib/samagotchi/terminal_ui/formatting.rb +2 -2
  102. data/lib/samagotchi/terminal_ui/model_segments_text.rb +5 -5
  103. data/lib/samagotchi/terminal_ui.rb +4 -1
  104. data/lib/samagotchi/testing/bundle.rb +3 -3
  105. data/lib/samagotchi/testing/install.rb +3 -3
  106. data/lib/samagotchi/testing/sandbox.rb +2 -2
  107. data/lib/samagotchi/tool_runner.rb +14 -14
  108. data/lib/samagotchi/tools/memory.rb +22 -22
  109. data/lib/samagotchi/update_command.rb +4 -4
  110. data/lib/samagotchi/version.rb +1 -1
  111. data/lib/samagotchi/web/app.rb +14 -1
  112. data/lib/samagotchi/web/message_display.rb +6 -0
  113. data/lib/samagotchi/web/participant_view.rb +1 -1
  114. data/lib/samagotchi/web/proxy_gate.rb +1 -0
  115. data/lib/samagotchi/web/public/card_kinds.js +8 -3
  116. data/lib/samagotchi/web/public/cards_place.js +15 -1
  117. data/lib/samagotchi/web/public/ctx.js +1 -1
  118. data/lib/samagotchi/web/public/history_shape.js +3 -0
  119. data/lib/samagotchi/web/public/turn_block.js +46 -8
  120. data/lib/samagotchi/web/public/turn_settle.js +117 -0
  121. data/lib/samagotchi/web/push/notifier.rb +2 -2
  122. data/lib/samagotchi/web/session_access_routes.rb +21 -1
  123. data/lib/samagotchi/web/session_hub.rb +20 -4
  124. data/lib/samagotchi/worker_boot.rb +4 -1
  125. metadata +19 -12
  126. data/lib/samagotchi/memory_bundle/manifest.rb +0 -581
@@ -5,10 +5,10 @@ require "digest"
5
5
  require_relative "../atomic_file"
6
6
  require_relative "../memory_paths"
7
7
  module Samagotchi
8
- module MemoryBundle
8
+ module MemoryIndex
9
9
  # Updates the scoped index.md for a single entry, locked and atomically.
10
10
  # Used by Installer (P3) to keep index.md in sync.
11
- module IndexUpdater
11
+ module Updater
12
12
  MEMORY_INDEX = "index"
13
13
  LOCK_FILE = ".index.lock"
14
14
  # @param source [String, false, nil] the bundle the memory came from
@@ -3,7 +3,7 @@
3
3
  require "json"
4
4
 
5
5
  require_relative "memory_paths"
6
- require_relative "memory_bundle/index_size"
6
+ require_relative "memory_index/size"
7
7
  require_relative "model_notes"
8
8
  require_relative "session"
9
9
  require_relative "llm_context_stale"
@@ -115,8 +115,8 @@ module Samagotchi
115
115
  # @param root [String] the folder whose project's memories are the project scope
116
116
  # @param env [Hash] the XDG env the memories dirs resolve from
117
117
  def initialize(sessions:, entries:, scopes: SCOPES, unreadable: 0, baseline: [], root: Dir.pwd, env: ENV,
118
- chars_per_token: MemoryBundle::IndexSize.chars_per_token,
119
- warn_limit: MemoryBundle::IndexSize.warn_limit)
118
+ chars_per_token: MemoryIndex::Size.chars_per_token,
119
+ warn_limit: MemoryIndex::Size.warn_limit)
120
120
  @sessions = Array(sessions)
121
121
  @entries = Array(entries)
122
122
  @scopes = Array(scopes).map(&:to_s)
@@ -229,7 +229,7 @@ module Samagotchi
229
229
  # denominator nor an unread line.
230
230
  def index_row(scope, used)
231
231
  text = index_text(scope)
232
- size = MemoryBundle::IndexSize.of_text(scope, text, chars_per_token: @chars_per_token)
232
+ size = MemoryIndex::Size.of_text(scope, text, chars_per_token: @chars_per_token)
233
233
  names = text.each_line.filter_map { |line| (match = MemoryCommand::LINE.match(line)) && match[1] }.uniq
234
234
  entries = names.select { |name| entry_for(scope, name) }
235
235
  unread = entries.count { |name| !used.include?([scope, name]) }
@@ -298,7 +298,7 @@ module Samagotchi
298
298
 
299
299
  # A read of a memory's file: [scope, name], nil for any other file. The
300
300
  # session's own project folder (MemoryPaths.key_for_root), since
301
- # IndexSync.memory_scope knows only the folder chi is running in.
301
+ # MemoryIndex::Sync.memory_scope knows only the folder chi is running in.
302
302
  def memory_file(path, project_dir)
303
303
  return nil if path.nil? || !path.end_with?(".md")
304
304
 
@@ -9,7 +9,7 @@ module Samagotchi
9
9
  # guard). Nothing on disk changes: a muted memory keeps its file and its
10
10
  # index line.
11
11
  module MutedMemories
12
- # A managed index line (IndexUpdater.managed_line), plus the legacy
12
+ # A managed index line (MemoryIndex::Updater.managed_line), plus the legacy
13
13
  # `- **name**: desc` and `- **name.md** ·` shapes still found in indexes.
14
14
  INDEX_LINE = /\A- \*\*(.+?)\*\*[ \t]*(?:[·•].*|:.*)?\z/
15
15
 
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "context_absorber"
4
+ require_relative "jsonl_store"
5
+ require_relative "session"
6
+
7
+ module Samagotchi
8
+ # A session's peer exchange metadata, append-only and uncapped. No answer
9
+ # text is stored; readers join the log and return only the requested tail.
10
+ module PeerExchanges
11
+ FILE = "peer_exchanges.jsonl"
12
+ STORE = JsonlStore.new(FILE)
13
+
14
+ module_function
15
+
16
+ def append(session_id, entry, state_dir:)
17
+ STORE.write(Session.session_dir(session_id, state_dir: state_dir), **entry)
18
+ end
19
+
20
+ def read(session_id, state_dir:)
21
+ STORE.lines(Session.session_dir(session_id, state_dir: state_dir))
22
+ end
23
+
24
+ # Process in timestamp order, breaking equal timestamps by append order.
25
+ # Failed sends cannot claim an answer. One answer can claim a send; any
26
+ # further answers remain visible as unclaimed.
27
+ def joined(entries, last: 20)
28
+ rows = []
29
+ entries.each_with_index.sort_by { |entry, index| [JsonlStore.time_of(entry), index] }.each do |entry, index|
30
+ case entry["t"]
31
+ when "sent", "send_failed"
32
+ rows << [send_row(entry), index]
33
+ when "answer"
34
+ answer = answer_row(entry)
35
+ send = matching_send(rows, entry)
36
+ if send
37
+ send[:state] = "answered"
38
+ send[:answer] = answer
39
+ else
40
+ rows << [{ id: nil, at: entry["at"], state: "answered", answer: answer }, index]
41
+ end
42
+ end
43
+ end
44
+ rows.sort_by { |row, index| [JsonlStore.time_of("at" => row[:at]), index] }.last(last).reverse.map(&:first)
45
+ end
46
+
47
+ def send_row(entry)
48
+ state = if entry["t"] == "send_failed" then "failed"
49
+ elsif entry["kind"] == "context" then "none_expected"
50
+ else "waiting"
51
+ end
52
+ { id: entry["id"], kind: entry["kind"], title: entry["title"], by: entry["by"], at: entry["at"],
53
+ state: state, error: entry["error"] }.compact
54
+ end
55
+
56
+ def matching_send(rows, entry)
57
+ rows.reverse_each do |row, _index|
58
+ if entry["re"] && row[:id] == entry["re"] && row[:state] != "failed"
59
+ return row if %w[waiting none_expected].include?(row[:state])
60
+
61
+ return nil
62
+ end
63
+ next unless %w[waiting none_expected].include?(row[:state])
64
+
65
+ return row if !entry["re"] && row[:state] == "waiting" && %w[validate question].include?(row[:kind])
66
+ end
67
+ nil
68
+ end
69
+
70
+ def answer_row(entry)
71
+ verdict = entry["summary"].to_s.scan(ContextAbsorber::VERDICT).last&.first
72
+ { summary: entry["summary"], at: entry["at"], serial: entry["serial"],
73
+ verdict: (verdict if ContextAbsorber::VERDICTS.include?(verdict)) }.compact
74
+ end
75
+ end
76
+ end
@@ -172,6 +172,10 @@ module Samagotchi
172
172
  # @return [String, nil] the session's id (nil before the first one)
173
173
  def session_id = @host.session_id.call
174
174
 
175
+ # @api private
176
+ # The session store's root, as used by the host.
177
+ def session_state_dir = @host.state_dir&.call || Session.default_state_dir
178
+
175
179
  # @return [String, nil] the model the session runs on now: its
176
180
  # resolved ref ("host:id"), right after /model too
177
181
  def model = @host.model_name&.call
@@ -7,8 +7,8 @@ require_relative "../hooks"
7
7
  require_relative "../log"
8
8
  require_relative "../guardrails/load_failures"
9
9
  require_relative "../version"
10
- require_relative "../memory_bundle/manifest"
11
- require_relative "../memory_bundle/provenance"
10
+ require_relative "../bundle_manifest"
11
+ require_relative "../installed_bundles"
12
12
 
13
13
  module Samagotchi
14
14
  # Where installed bundles' plugin code is evaluated: one module per
@@ -51,10 +51,12 @@ module Samagotchi
51
51
  # A failure is logged and added to +failures+ (not required: tool calls
52
52
  # still run), which the Engine announces once. A guardrail plugin's
53
53
  # (the manifest's plugin: required: true, read from the kept manifest:
54
- # InstalledManifest#plugin_required) goes to +guardrail_failures+ as
54
+ # InstalledBundles::Manifest#plugin_required) goes to +guardrail_failures+ as
55
55
  # required instead: every tool call is denied, as for a fail-closed
56
- # config hook. Its chi.on(..., on_error: :fail_closed) hooks deny the
57
- # call they raise on (Api#on).
56
+ # config hook. A bundle whose manifest.json doesn't read counts as
57
+ # required unless its kept manifest.yml reads and names no plugin or a
58
+ # plugin without required: true. Its chi.on(..., on_error: :fail_closed)
59
+ # hooks deny the call they raise on (Api#on).
58
60
  module Loader
59
61
  TAG = :plugins
60
62
 
@@ -69,9 +71,10 @@ module Samagotchi
69
71
  # @return [Array<String>] the bundles whose plugin loaded
70
72
  def load_installed(registries, failures: nil, guardrail_failures: nil, settings: {})
71
73
  loaded = []
72
- MemoryBundle::Provenance.each_installed(holding: :plugin) do |bundle_name, bundle|
73
- ok = load_bundle(bundle_name, bundle, registries, failures: failures, guardrail_failures: guardrail_failures,
74
- settings: settings[bundle_name.to_s] || {})
74
+ InstalledBundles.standings(holding: :plugin) do |standing|
75
+ bundle_name = standing.name
76
+ ok = load_bundle(bundle_name, standing.record, registries, failures: failures, guardrail_failures: guardrail_failures,
77
+ settings: settings[bundle_name.to_s] || {}, standing: standing)
75
78
  loaded << bundle_name if ok
76
79
  end
77
80
  loaded
@@ -81,16 +84,24 @@ module Samagotchi
81
84
  loaded || []
82
85
  end
83
86
 
87
+ # Whether it may load is the verdict's (InstalledBundles::Standing, then
88
+ # Dir#file_refusal(:plugin)); what a refusal does is the loader's: a
89
+ # failure, required for a guardrail plugin.
90
+ # @param standing [InstalledBundles::Standing] the bundle's (built from
91
+ # +bundle+ when not given)
84
92
  # @return [Boolean] whether the plugin loaded
85
- def load_bundle(bundle_name, bundle, registries, failures: nil, guardrail_failures: nil, settings: {})
86
- file = MemoryBundle::Provenance.new(name: bundle_name).plugin_path(bundle) unless bundle.error?
93
+ def load_bundle(bundle_name, bundle, registries, failures: nil, guardrail_failures: nil, settings: {},
94
+ standing: nil)
95
+ standing ||= InstalledBundles::Standing.of(bundle_name, bundle)
96
+ installed = InstalledBundles::Dir.new(name: bundle_name)
97
+ file = installed.plugin_path(bundle) unless standing.unreadable?
87
98
  basename = file ? File.basename(file) : "plugin"
88
99
  # Known before it registers anything: a guardrail that fails to load
89
100
  # (its sha, requires_chi, a raise) denies every tool call.
90
- required = !bundle.error? && bundle.manifest.plugin_required
101
+ required = standing.unreadable? ? unreadable_required?(bundle_name) : bundle.manifest.plugin_required
91
102
  into = required ? guardrail_failures || failures : failures
92
- reason = bundle.error || unloadable_reason(file, bundle)
93
- return failed(bundle_name, basename, reason, into, required: required) if reason
103
+ refusal = standing.refusal || installed.file_refusal(:plugin, bundle.plugin&.file, bundle.plugin&.sha256)
104
+ return failed(bundle_name, basename, refusal.text, into, required: required) if refusal
94
105
 
95
106
  api = register_file(bundle_name, file, registries, settings: settings)
96
107
  warn_unrequired(bundle_name, basename) if api.fail_closed? && !required
@@ -140,28 +151,19 @@ module Samagotchi
140
151
  # What a plugin's hooks, notices and failures are named by.
141
152
  def label(bundle_name, basename) = "#{basename} (bundle #{bundle_name})"
142
153
 
143
- # Why the installed file can't be loaded, or nil.
144
- def unloadable_reason(file, bundle)
145
- failure = bundle.manifest.requires_chi_failure
146
- return failure if failure
147
- return "the file is missing" unless file && File.file?(file)
154
+ # Decide from the last readable manifest whether an unreadable record
155
+ # might have been a required guardrail; unknown evidence fails closed.
156
+ def unreadable_required?(bundle_name)
157
+ path = InstalledBundles::Dir.new(name: bundle_name).kept_manifest_path
158
+ return true unless path && File.file?(path)
148
159
 
149
- sha_mismatch(file, bundle.plugin.sha256)
150
- end
151
-
152
- # Why +file+ doesn't match the sha256 recorded at install (+recorded+,
153
- # "sha256:<hex>" or bare hex), or nil. None recorded is a mismatch;
154
- # Provenance.unchecked? (a dev install) is none.
155
- def sha_mismatch(file, recorded)
156
- return nil if MemoryBundle::Provenance.unchecked?(recorded)
157
-
158
- expected = MemoryBundle::Provenance.recorded_sha(recorded)
159
- return "no sha256 recorded for it (reinstall the bundle)" if expected.empty?
160
+ kept, problems = BundleManifest.tolerant(path: path)
161
+ return true if problems.key?("plugin")
162
+ return false unless kept.plugin
160
163
 
161
- actual = MemoryBundle::Provenance.file_sha(file)
162
- return nil if actual == expected
163
-
164
- "its sha256 #{actual[0, 12]}… differs from the installed #{expected[0, 12]}… (edited after install? reinstall the bundle)"
164
+ kept.plugin[:required] == true
165
+ rescue StandardError # degrade-ok: unreadable kept manifests must be treated as required
166
+ true
165
167
  end
166
168
 
167
169
  # The (lazily created) namespace module for a bundle, under
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
3
4
  require "fileutils"
4
5
  require "json"
5
6
  require "open3"
@@ -7,6 +8,7 @@ require "tempfile"
7
8
  require "time"
8
9
  require_relative "../paths"
9
10
  require_relative "../session"
11
+ require_relative "../peer_exchanges"
10
12
 
11
13
  module Samagotchi
12
14
  module Plugin
@@ -18,10 +20,13 @@ module Samagotchi
18
20
  # its answers come back as pushes that wake chi.
19
21
  #
20
22
  # The `<peer>_send` tool sends a part of the work (a plan step, a diff, a
21
- # finding): a header, `chi <id> · <kind> · <title>`, then a short part
22
- # inline, or a long one's file under the bundle's data dir
23
+ # finding): a header, `chi <id> · <kind> · <title>`, a `ref: <send id>`
24
+ # line (.send_id: the peer's answer echoes it as `re`), then a short
25
+ # part inline, or a long one's file under the bundle's data dir
23
26
  # (sessions/<id>/, removed with the session), named in the message
24
- # (`payload: <path>`). The tool is declared whether or not the peer is
27
+ # (`payload: <path>`). The tool's row carries the same id as a `peer`
28
+ # ref (derived from the call's args, so it is there before the call
29
+ # runs: also on a send that then didn't happen). The tool is declared whether or not the peer is
25
30
  # paired, so pairing never changes the tools (no prompt rebuild); without
26
31
  # a paired peer it fails with how to pair.
27
32
  #
@@ -85,10 +90,21 @@ module Samagotchi
85
90
  @last_answer = nil
86
91
  end
87
92
 
93
+ # A send's id, from what the caller gave (before the title is cut):
94
+ # `s-` and 6 hex of SHA-256 over +kind+, +title+ and +text+. Equal
95
+ # args give the same id (the tool row's ref is computed from them
96
+ # before the call runs); the peer's answer names it (`re`).
97
+ def self.send_id(kind, title, text) = "s-#{Digest::SHA256.hexdigest([kind, title, text].join("\0"))[0, 6]}"
98
+
88
99
  def register(chi)
89
100
  peer = self.class
101
+ refs = lambda do |args|
102
+ id = Peer.send_id(args["kind"].to_s, args["title"].to_s, args["text"].to_s)
103
+ [{ kind: "peer", target: { id: id }, label: "#{peer::NAME} · #{args["kind"].to_s[0, 40]}" }]
104
+ end
90
105
  chi.tool peer::TOOL, peer::TOOL_DESCRIPTION, params: peer::TOOL_PARAMS, label: "sent to #{peer::NAME}",
91
- preview: ->(args) { "#{args["kind"]}: #{args["title"]}" } do |args, ctx|
106
+ preview: ->(args) { "#{args["kind"]}: #{args["title"]}" },
107
+ refs: refs do |args, ctx|
92
108
  sent = deliver(ctx, kind: args["kind"].to_s, title: args["title"].to_s, text: args["text"].to_s)
93
109
  "#{sent}. #{follow_up(args["kind"].to_s)}"
94
110
  rescue SendError => e
@@ -115,17 +131,19 @@ module Samagotchi
115
131
  end
116
132
  end
117
133
 
118
- # Sends +text+ to the paired peer: the header, then the text inline or
119
- # a payload file's path. Records it as the last send.
134
+ # Sends +text+ to the paired peer: the header, the `ref:` line
135
+ # (.send_id of the args as given), then the text inline or a payload
136
+ # file's path. Records it as the last send, with its id.
120
137
  # @return [String] what was sent ("sent to Claude: validate · title")
121
138
  # @raise [SendError]
122
- def deliver(ctx, kind:, title:, text:)
139
+ def deliver(ctx, kind:, title:, text:, by: "model")
123
140
  raise SendError, "kind must be one of #{KINDS.join(", ")}" unless KINDS.include?(kind)
124
141
  raise SendError, "nothing to send: the text is empty" if text.strip.empty?
125
142
  if text.length > MAX_CHARS
126
143
  raise SendError, "the text is #{text.length} chars, over #{MAX_CHARS}: send a part, not a session"
127
144
  end
128
145
 
146
+ send_id = Peer.send_id(kind, title, text)
129
147
  id = ctx.session_id or raise SendError, "this session has no id yet: send after its first turn"
130
148
  hint = peer_hint!(ctx)
131
149
  title = one_line(title.strip.empty? ? text.strip.lines.first : title)
@@ -135,8 +153,14 @@ module Samagotchi
135
153
  path = write_payload(ctx, title, text)
136
154
  ["payload: #{path} (#{text.lines.size} lines, #{text.length} chars)", path]
137
155
  end
138
- post(hint, "chi #{id[0, 8]} · #{kind} · #{title}\n#{body}")
139
- record(ctx, kind: kind, title: title, chars: text.length, payload: where == "inline" ? nil : where)
156
+ begin
157
+ post(hint, "chi #{id[0, 8]} · #{kind} · #{title}\nref: #{send_id}\n#{body}")
158
+ rescue SendError => e
159
+ exchange(ctx, t: "send_failed", id: send_id, kind: kind, title: title, error: e.message)
160
+ raise
161
+ end
162
+ exchange(ctx, t: "sent", id: send_id, kind: kind, title: title, chars: text.length, by: by)
163
+ record(ctx, id: send_id, kind: kind, title: title, chars: text.length, payload: where == "inline" ? nil : where)
140
164
  "sent to #{self.class::NAME}: #{kind} · #{title}#{" (the text in #{where})" unless where == "inline"}"
141
165
  end
142
166
 
@@ -225,7 +249,7 @@ module Samagotchi
225
249
  end
226
250
 
227
251
  def send_text(ctx, kind, text)
228
- "#{deliver(ctx, kind: kind, title: text_title(text), text: text)}; #{self.class::NAME}'s answer comes as the " \
252
+ "#{deliver(ctx, kind: kind, title: text_title(text), text: text, by: "user")}; #{self.class::NAME}'s answer comes as the " \
229
253
  "#{self.class::OUTBOX} context"
230
254
  rescue SendError => e
231
255
  "#{self.class::COMMAND}: #{e.message}"
@@ -244,7 +268,7 @@ module Samagotchi
244
268
  command = self.class::COMMAND
245
269
  return "#{command} last: no completed answer to send yet (the last turn has none); #{command} context <text> sends a text" unless answer
246
270
 
247
- deliver(ctx, kind: "context", title: "chi's last answer: #{answer.strip.lines.first}", text: answer)
271
+ deliver(ctx, kind: "context", title: "chi's last answer: #{answer.strip.lines.first}", text: answer, by: "user")
248
272
  rescue SendError => e
249
273
  "#{command}: #{e.message}"
250
274
  end
@@ -445,6 +469,13 @@ module Samagotchi
445
469
  ctx.log.info(:last_send_not_saved, error: e.message)
446
470
  end
447
471
 
472
+ def exchange(ctx, **entry)
473
+ peer = ContextSources.peer_leg(self.class::INBOX)&.first || self.class::NAME.downcase
474
+ PeerExchanges.append(ctx.session_id, { peer: peer, **entry }, state_dir: ctx.session_state_dir)
475
+ rescue SystemCallError, IOError, JSON::GeneratorError => e
476
+ ctx.log.warn("peer_exchange_not_saved", error: e.message)
477
+ end
478
+
448
479
  def slug(title)
449
480
  slug = title.downcase.gsub(/[^a-z0-9]+/, "-").gsub(/\A-+|-+\z/, "")[0, SLUG_CHARS].delete_suffix("-")
450
481
  slug.empty? ? "part" : slug
@@ -30,7 +30,7 @@ module Samagotchi
30
30
  INDEX = "index.md"
31
31
  # What an emptied folder may still hold, none of it moved: the index
32
32
  # (removed only when #hand_written? says it holds nothing of the user's),
33
- # IndexUpdater's lock, and .root: ProjectIdClash's claim, written only in
33
+ # MemoryIndex::Updater's lock, and .root: ProjectIdClash's claim, written only in
34
34
  # an id folder, so in a path-keyed one it is a copy's stray (a copied
35
35
  # id folder renamed by hand) that names no folder this key belongs to.
36
36
  LEFTOVERS = [INDEX, ".index.lock", ".root"].freeze
@@ -100,8 +100,8 @@ module Samagotchi
100
100
  # a folder made there again from #find.
101
101
  # @return [Array<String>] the report's lines
102
102
  def merge(found, target:, env: ENV)
103
- require_relative "memory_bundle/index_updater"
104
- require_relative "memory_bundle/provenance"
103
+ require_relative "memory_index/updater"
104
+ require_relative "installed_bundles"
105
105
  require_relative "tools/memory"
106
106
  lines = []
107
107
  found.each { |item| lines.concat(merge_one(item, target, env)) }
@@ -135,18 +135,18 @@ module Samagotchi
135
135
  kept = []
136
136
  entries(from).each do |name, line|
137
137
  files = [File.join(from, "#{name}.md")] + Tools::MemoryWrite.overlay_files(from, name, index_text)
138
- owner = MemoryBundle::Provenance.claimants("#{name}.md", scope: "project",
138
+ owner = InstalledBundles.claimants("#{name}.md", scope: "project",
139
139
  dir: MemoryPaths.bundles_dir(env: env)).first ||
140
- (line && MemoryBundle::IndexUpdater.extract_source(line))
140
+ (line && MemoryIndex::Updater.extract_source(line))
141
141
  next kept << "#{name} (from bundle #{owner})" if owner
142
142
  next kept << "#{name} (the project has one by that name)" if files.any? { |path| File.exist?(File.join(target, File.basename(path))) }
143
143
 
144
144
  FileUtils.mkdir_p(target)
145
145
  bytes = File.size(files.first)
146
146
  files.each { |path| File.rename(path, File.join(target, File.basename(path))) }
147
- description = line && MemoryBundle::IndexUpdater.extract_description(line)
148
- MemoryBundle::IndexUpdater.update_index("project", name, bytes, description, target_dir: target)
149
- MemoryBundle::IndexUpdater.remove_index("project", name, target_dir: from)
147
+ description = line && MemoryIndex::Updater.extract_description(line)
148
+ MemoryIndex::Updater.update_index("project", name, bytes, description, target_dir: target)
149
+ MemoryIndex::Updater.remove_index("project", name, target_dir: from)
150
150
  moved << name
151
151
  end
152
152
 
@@ -177,7 +177,7 @@ module Samagotchi
177
177
  # managed line (memory_write keeps every other line byte for byte; a
178
178
  # dangling managed line, its file gone, may go with the folder).
179
179
  def hand_written?(text)
180
- header = MemoryBundle::IndexUpdater.auto_index_header.lines.map(&:strip)
180
+ header = MemoryIndex::Updater.auto_index_header.lines.map(&:strip)
181
181
  text.each_line.any? do |line|
182
182
  line = line.strip
183
183
  !(line.empty? || header.include?(line) || line.match?(/\A- \*\*[^*]+\*\*[ \t]*(?:[·•].*|:.*)?\z/))
@@ -18,6 +18,13 @@ module Samagotchi
18
18
  super
19
19
  end
20
20
 
21
+ # ReplyWait's grace for a gone worker, read when a wait is built
22
+ # (reply_wait.rb requires this file, so it is loaded by then).
23
+ def self.gone_after
24
+ require_relative "../reply_wait"
25
+ ReplyWait::GONE_AFTER
26
+ end
27
+
21
28
  # A --new session's first message: its own turn, the ack's id (a
22
29
  # file-delivered one's also names the outcome of a session command
23
30
  # that runs no turn), so a worker that dies in it and the next one's
@@ -35,7 +42,7 @@ module Samagotchi
35
42
  # @param direct_turn [String, nil] that first turn's id, for a direct
36
43
  # start
37
44
  def self.first_message(start, delivered, direct_turn: nil)
38
- reads = { cursor: start&.cursor, baseline: start&.baseline, owner_grace: ReplyWait::GONE_AFTER }
45
+ reads = { cursor: start&.cursor, baseline: start&.baseline, owner_grace: gone_after }
39
46
  return new(**reads) unless delivered || !direct_turn.to_s.strip.empty?
40
47
 
41
48
  return new(turn: direct_turn, report_turn_id: direct_turn, queued: true, **reads) if delivered.nil?
@@ -60,7 +67,7 @@ module Samagotchi
60
67
  queue ||= delivered.delivery == Delivery::QUEUE
61
68
  turn = delivered.enqueued_id
62
69
  new(turn: turn, report_turn_id: turn || (start.own_turn if start.running && !queue), queued: queue && !turn.nil?,
63
- cursor: start.cursor, baseline: start.baseline, owner_grace: ReplyWait::GONE_AFTER)
70
+ cursor: start.cursor, baseline: start.baseline, owner_grace: gone_after)
64
71
  end
65
72
 
66
73
  # --wait with no message: --turn's (+requested+), or the turn running
@@ -75,7 +82,7 @@ module Samagotchi
75
82
  turn = requested || start.own_turn
76
83
  ended_before = requested ? start.last_turn_id == requested : start.settled
77
84
  new(turn: turn, report_turn_id: turn || (start.last_turn_id if start.settled), ended_before: ended_before,
78
- cursor: start.cursor, baseline: start.baseline, owner_grace: start.live ? ReplyWait::GONE_AFTER : nil)
85
+ cursor: start.cursor, baseline: start.baseline, owner_grace: start.live ? gone_after : nil)
79
86
  end
80
87
 
81
88
  # chi answer: the turn the question is about (start's own_turn: the
@@ -83,7 +90,7 @@ module Samagotchi
83
90
  # reply.
84
91
  def self.answer(start)
85
92
  new(turn: start.own_turn, report_turn_id: start.own_turn, cursor: start.cursor, baseline: start.baseline,
86
- owner_grace: ReplyWait::GONE_AFTER)
93
+ owner_grace: gone_after)
87
94
  end
88
95
 
89
96
  # A participant's --wait -m: their review turn just queued (+turn+),
@@ -19,11 +19,11 @@ require_relative "host_keys"
19
19
  require_relative "llm/adapters"
20
20
  require_relative "tools/memory"
21
21
  require_relative "hooks/loader"
22
- require_relative "memory_bundle/provenance"
23
- require_relative "memory_bundle/manifest"
22
+ require_relative "installed_bundles"
23
+ require_relative "bundle_manifest"
24
24
  require_relative "memory_bundle/system_bundle"
25
- require_relative "memory_bundle/index_size"
26
- require_relative "memory_bundle/entry_size"
25
+ require_relative "memory_index/size"
26
+ require_relative "memory_index/entry_size"
27
27
  require_relative "desktop"
28
28
  require_relative "live_versions"
29
29
  require_relative "web/lan"
@@ -122,8 +122,8 @@ module Samagotchi
122
122
  # context.chars_per_token from Config, which reads the process's ENV
123
123
  # and config.yml as the rest of chi self's settings (web.port) do.
124
124
  def memory_index_summary(env)
125
- limit = MemoryBundle::IndexSize.warn_limit
126
- %w[system project].map { |scope| MemoryBundle::IndexSize.of_scope(scope, env: env).summary(limit) }.join(", ")
125
+ limit = MemoryIndex::Size.warn_limit
126
+ %w[system project].map { |scope| MemoryIndex::Size.of_scope(scope, env: env).summary(limit) }.join(", ")
127
127
  rescue StandardError => e
128
128
  "(unreadable: #{e.message})"
129
129
  end
@@ -138,13 +138,13 @@ module Samagotchi
138
138
  # tighten). "none" when there are none, "off" with the limit 0. A scope
139
139
  # that can't be read is named instead.
140
140
  def big_memories_summary(env)
141
- limit = MemoryBundle::EntrySize.warn_limit
141
+ limit = MemoryIndex::EntrySize.warn_limit
142
142
  return "off (memory.entry_warn_tokens 0)" unless limit.positive?
143
143
 
144
144
  big = []
145
145
  unreadable = []
146
146
  %w[system project].each do |scope|
147
- big.concat(MemoryBundle::EntrySize.over_limit(scope, limit: limit, env: env))
147
+ big.concat(MemoryIndex::EntrySize.over_limit(scope, limit: limit, env: env))
148
148
  rescue StandardError => e
149
149
  unreadable << "#{scope} memories unreadable: #{e.message}"
150
150
  end
@@ -155,11 +155,11 @@ module Samagotchi
155
155
  end
156
156
 
157
157
  def big_memory(size, env)
158
- owner = MemoryBundle::Provenance.claimants("#{size.name}.md", scope: size.scope, dir: MemoryPaths.bundles_dir(env: env)).first
158
+ owner = InstalledBundles.claimants("#{size.name}.md", scope: size.scope, dir: MemoryPaths.bundles_dir(env: env)).first
159
159
  where = [size.scope, ("from #{owner}" if owner)].compact.join(", ")
160
- "#{size.name} ~#{MemoryBundle::IndexSize.count_text(size.tokens)} tokens (#{where})"
160
+ "#{size.name} ~#{MemoryIndex::Size.count_text(size.tokens)} tokens (#{where})"
161
161
  rescue StandardError
162
- "#{size.name} ~#{MemoryBundle::IndexSize.count_text(size.tokens)} tokens (#{size.scope})"
162
+ "#{size.name} ~#{MemoryIndex::Size.count_text(size.tokens)} tokens (#{size.scope})"
163
163
  end
164
164
 
165
165
  def with_presence(path)
@@ -490,14 +490,14 @@ module Samagotchi
490
490
  # "samagotchi-system 0.1.5 (shipped 0.1.5), other 1.0.0"
491
491
  def bundles_summary
492
492
  shipped = Degrade.call(:memory, "shipped_bundle_unreadable") do
493
- MemoryBundle::Manifest.read(dir: MemoryBundle::SystemBundle::GEM_BUNDLE_DIR).version
493
+ BundleManifest.read(dir: MemoryBundle::SystemBundle::GEM_BUNDLE_DIR).version
494
494
  end
495
- installed = MemoryBundle::Provenance.each_installed.map do |name, bundle|
495
+ installed = InstalledBundles.each.map do |name, bundle|
496
496
  version = bundle.version || "?"
497
497
  label = "#{name} #{version}"
498
498
  label += " (shipped #{shipped})" if name == MemoryBundle::SystemBundle::BUNDLE_NAME
499
499
  behind = bundle.behind_files
500
- label += " (#{MemoryBundle::FileStanding.behind_count(behind.size, unsure: behind.any?(&:unsure))})" if behind.any?
500
+ label += " (#{InstalledBundles::FileStanding.behind_count(behind.size, unsure: behind.any?(&:unsure))})" if behind.any?
501
501
  label
502
502
  end
503
503
  installed.empty? ? "(none installed; shipped system bundle #{shipped || "?"})" : installed.join(", ")
@@ -14,6 +14,7 @@ require_relative "../image_store"
14
14
  require_relative "../context_candidates"
15
15
  require_relative "../worker_inbound"
16
16
  require_relative "../context_sources"
17
+ require_relative "../peer_exchanges"
17
18
  require_relative "../archive_store"
18
19
  require_relative "../session_chain"
19
20
  require_relative "../send_command/busy"
@@ -345,7 +346,14 @@ module Samagotchi
345
346
 
346
347
  record = lambda do
347
348
  attached.location.locked(name) do
348
- [attached.location.snapshot(name).revision, attached.location.record_text(name, fetched)]
349
+ before = attached.location.snapshot(name).revision
350
+ written = attached.location.record_text(name, fetched)
351
+ peer, leg = ContextSources.peer_leg(name)
352
+ if !target.project? && attached.location.session? && attached.source.scope == "session" &&
353
+ leg == "outbox" && before != written.revision
354
+ record_peer_answer(target.session_id, peer, written)
355
+ end
356
+ [before, written]
349
357
  end
350
358
  end
351
359
  unless !target.project? && attached.location.session? && attached.source.scope == "session"
@@ -520,6 +528,13 @@ module Samagotchi
520
528
  ContextPush.new(status: :pushed, before: before, revision: written.revision, wake: asked ? delivered&.wake : nil)
521
529
  end
522
530
 
531
+ def record_peer_answer(session_id, peer, snapshot)
532
+ PeerExchanges.append(session_id, { t: "answer", peer: peer, re: snapshot.re, summary: snapshot.summary,
533
+ serial: snapshot.serial, wake: snapshot.wake }, state_dir: state_dir!)
534
+ rescue SystemCallError, IOError, JSON::GeneratorError => e
535
+ Log.exception(:context, "peer_exchange_not_saved", e, sid: session_id, source: "#{peer}-outbox")
536
+ end
537
+
523
538
  def context_wake_allowed?(location, name)
524
539
  return false if Config.get("context.wake") == false
525
540
 
@@ -580,7 +580,8 @@ module Samagotchi
580
580
  def context_push(target, name, fetched)
581
581
  ContextSources.check_name!(name)
582
582
  reply = request(:post, "#{session_path(target.session_id)}/context/#{name}/push",
583
- body: { text: fetched.text, summary: fetched.summary, wake: fetched.wake, hint: fetched.hint })
583
+ body: { text: fetched.text, summary: fetched.summary, wake: fetched.wake, hint: fetched.hint,
584
+ re: fetched.re })
584
585
  case reply.status
585
586
  when 200
586
587
  # An older chi web's answer names no wake: the line is as it was.