samagotchi 0.183.0 → 0.185.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 (151) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +84 -1
  3. data/docs/architecture.md +12 -11
  4. data/docs/bundles.md +63 -36
  5. data/docs/cli.md +10 -1
  6. data/docs/configuration.md +3 -2
  7. data/docs/context.md +76 -10
  8. data/docs/guardrails.md +7 -2
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/block-renderers.md +4 -2
  11. data/docs/internals/bridge.md +7 -3
  12. data/docs/internals/bundles.md +6 -2
  13. data/docs/internals/engine.md +2 -1
  14. data/docs/internals/llm-context-forget.md +6 -0
  15. data/docs/internals/participants.md +5 -2
  16. data/docs/internals/prompt-caching.md +8 -1
  17. data/docs/internals/remote-sessions.md +22 -4
  18. data/docs/internals/session-lifecycle.md +1 -1
  19. data/docs/internals/web-frontend.md +37 -15
  20. data/docs/internals/web-push.md +11 -0
  21. data/docs/internals/working-set.md +238 -6
  22. data/docs/mcp-server.md +11 -3
  23. data/docs/memory.md +2 -1
  24. data/docs/plugins.md +6 -6
  25. data/docs/scheduling.md +19 -0
  26. data/docs/sessions.md +13 -3
  27. data/docs/sub-agent.md +48 -3
  28. data/docs/thin-clients.md +38 -12
  29. data/lib/samagotchi/agent_caller.rb +97 -0
  30. data/lib/samagotchi/bridge.rb +7 -7
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/check.rb +20 -2
  33. data/lib/samagotchi/bundle_manifest.rb +5 -1
  34. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  35. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  37. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  39. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  40. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  41. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  42. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  43. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  44. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/http_client.rb +96 -54
  47. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  49. data/lib/samagotchi/bundles/system/self_map.md +9 -2
  50. data/lib/samagotchi/client_id.rb +61 -1
  51. data/lib/samagotchi/command_intake.rb +16 -8
  52. data/lib/samagotchi/context_absorber.rb +212 -46
  53. data/lib/samagotchi/delivery.rb +15 -0
  54. data/lib/samagotchi/driver_command.rb +68 -0
  55. data/lib/samagotchi/engine/block_fix.rb +2 -2
  56. data/lib/samagotchi/engine/session.rb +14 -6
  57. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  58. data/lib/samagotchi/engine.rb +13 -5
  59. data/lib/samagotchi/engine_peers.rb +6 -0
  60. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  61. data/lib/samagotchi/mcp_command.rb +7 -2
  62. data/lib/samagotchi/mcp_server/http.rb +3 -3
  63. data/lib/samagotchi/mcp_server/protocol.rb +23 -4
  64. data/lib/samagotchi/mcp_server/stdio.rb +1 -0
  65. data/lib/samagotchi/mcp_server/tools.rb +11 -4
  66. data/lib/samagotchi/model_notes.rb +34 -12
  67. data/lib/samagotchi/objectives_track.rb +2 -1
  68. data/lib/samagotchi/owner_prompt.rb +5 -1
  69. data/lib/samagotchi/parent_report.rb +9 -5
  70. data/lib/samagotchi/plugin/peer.rb +10 -4
  71. data/lib/samagotchi/prompt_files.rb +11 -4
  72. data/lib/samagotchi/prompt_layout.rb +88 -0
  73. data/lib/samagotchi/prompt_part.rb +82 -20
  74. data/lib/samagotchi/reply_wait.rb +16 -4
  75. data/lib/samagotchi/schedule_command.rb +18 -4
  76. data/lib/samagotchi/schedules.rb +49 -14
  77. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  78. data/lib/samagotchi/send_command.rb +45 -8
  79. data/lib/samagotchi/session.rb +9 -1
  80. data/lib/samagotchi/session_access/ask.rb +58 -14
  81. data/lib/samagotchi/session_access/contract.rb +2 -0
  82. data/lib/samagotchi/session_access/exchange.rb +5 -2
  83. data/lib/samagotchi/session_access/local.rb +13 -3
  84. data/lib/samagotchi/session_access/remote.rb +18 -2
  85. data/lib/samagotchi/session_access.rb +4 -2
  86. data/lib/samagotchi/session_command_catalog.rb +8 -0
  87. data/lib/samagotchi/session_commands.rb +9 -0
  88. data/lib/samagotchi/session_continue.rb +4 -1
  89. data/lib/samagotchi/session_inbox.rb +17 -0
  90. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  91. data/lib/samagotchi/session_manager/delivery.rb +58 -9
  92. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  93. data/lib/samagotchi/steer.rb +95 -20
  94. data/lib/samagotchi/system_prompt.rb +196 -161
  95. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  96. data/lib/samagotchi/tool_activity.rb +4 -0
  97. data/lib/samagotchi/tool_declarations.rb +22 -1
  98. data/lib/samagotchi/tool_names.rb +4 -0
  99. data/lib/samagotchi/toolkit.rb +3 -2
  100. data/lib/samagotchi/tools/ask_session.rb +208 -0
  101. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  102. data/lib/samagotchi/tools/builtins.rb +5 -0
  103. data/lib/samagotchi/tools/memory.rb +11 -3
  104. data/lib/samagotchi/turn_checkpoint.rb +19 -2
  105. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  106. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  107. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  108. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  109. data/lib/samagotchi/version.rb +1 -1
  110. data/lib/samagotchi/visitor.rb +37 -0
  111. data/lib/samagotchi/web/app.rb +2 -3
  112. data/lib/samagotchi/web/ask_routes.rb +95 -23
  113. data/lib/samagotchi/web/mcp_route.rb +7 -4
  114. data/lib/samagotchi/web/message_display.rb +15 -2
  115. data/lib/samagotchi/web/public/app.js +1 -1
  116. data/lib/samagotchi/web/public/block_fix.js +11 -3
  117. data/lib/samagotchi/web/public/delete_sheet.js +20 -18
  118. data/lib/samagotchi/web/public/history_shape.js +3 -1
  119. data/lib/samagotchi/web/public/index.html +8 -0
  120. data/lib/samagotchi/web/public/peer_links.js +27 -4
  121. data/lib/samagotchi/web/public/peer_note.js +19 -3
  122. data/lib/samagotchi/web/public/peer_text.js +45 -0
  123. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  124. data/lib/samagotchi/web/public/removal_sheet_model.js +3 -4
  125. data/lib/samagotchi/web/public/running_tasks.js +0 -16
  126. data/lib/samagotchi/web/public/session_actions.js +0 -9
  127. data/lib/samagotchi/web/public/turn_events.js +19 -0
  128. data/lib/samagotchi/web/public/working_set_view.js +178 -23
  129. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  130. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  131. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  132. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  133. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  134. data/lib/samagotchi/web/push/notifier.rb +33 -6
  135. data/lib/samagotchi/web/server.rb +1 -1
  136. data/lib/samagotchi/web/session_control.rb +1 -1
  137. data/lib/samagotchi/web/session_create.rb +11 -7
  138. data/lib/samagotchi/web/session_hub.rb +26 -4
  139. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  140. data/lib/samagotchi/worker/command_queue.rb +5 -2
  141. data/lib/samagotchi/worker/senders.rb +79 -0
  142. data/lib/samagotchi/worker.rb +21 -18
  143. data/lib/samagotchi/worker_inbound.rb +12 -4
  144. data/lib/samagotchi/worker_link.rb +2 -2
  145. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  146. data/lib/samagotchi/worker_wakes.rb +12 -0
  147. data/lib/samagotchi/working_set.rb +162 -90
  148. data/lib/samagotchi/working_set_locator.rb +221 -0
  149. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  150. data/lib/samagotchi/working_set_part.rb +281 -0
  151. metadata +13 -1
@@ -0,0 +1,221 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "working_set"
4
+ require_relative "llm_context_stale"
5
+ require_relative "file_ref"
6
+ require_relative "tool_response"
7
+ require_relative "tools/memory"
8
+
9
+ module Samagotchi
10
+ module WorkingSet
11
+ # chi's own changes of files, from a conversation's paired runs: the
12
+ # latest successful one per target still in the stored conversation
13
+ # (so still sent: its arguments carry the text), in conversation order.
14
+ # What tells a prompt part chi changed itself from one someone else
15
+ # changed (WorkingSetPart.states), and a memory chi read then changed
16
+ # from one changed behind it (WorkingSet.build). See
17
+ # docs/internals/working-set.md (Stale prompt parts).
18
+ #
19
+ # - a memory_write with content: keyed [scope, name, nil], or
20
+ # [scope, name, KEY] for a current_model_only overlay (the key off its
21
+ # output, "for KEY saved": the handler's model key, never an argument);
22
+ # - a memory_write remove: true whose output says "removed from" (a
23
+ # file already gone, "its dangling index line was dropped", is none):
24
+ # the base's target, [scope, name, nil];
25
+ # - an edit or write: its FileRef path, with its stamp.
26
+ # Never a description-only write ("(file unchanged)"), the index
27
+ # (path: "index"), or a failed or interrupted run (WorkingSet.failed?).
28
+ # The scope comes off the output ("saved to project scope"), the scope
29
+ # the handler wrote in.
30
+ #
31
+ # Loaded only with what the testing kit already loads (sandbox_spec's
32
+ # file budget): no ModelNotes, Locator, TextDiff or PromptFiles here.
33
+ class OwnChanges
34
+ # One own change: the run's chi +tool_id+, its +step+
35
+ # (LLMContextStale::PairedRun#step), its entry's +index+ and +place+
36
+ # in the batch, +op+ (memory_write, remove, write, edit), a
37
+ # memory_write's +content+, a file tool's +stamp+ ({mtime_ns:, size:},
38
+ # nil without one), an exact-match edit's +undo+ ([old_text,
39
+ # new_text]; nil for a range edit, an empty new_text, a write).
40
+ Change = Data.define(:tool_id, :step, :index, :place, :op, :content, :stamp, :undo) do
41
+ # Conversation order.
42
+ def order = [index, place]
43
+
44
+ def to_h = { tool_id: tool_id, step: step, op: op }
45
+ end
46
+
47
+ MEMORY_WRITE = "memory_write"
48
+ REMOVE = "remove"
49
+ FILE_TOOLS = %w[write edit].freeze
50
+ SAVED = /\AMemory '.*' saved to (project|system) scope/
51
+ OVERLAY = /\AModel overlay '.*' for ([a-z0-9-]+) saved to (project|system) scope/
52
+ REMOVED = /\AMemory '.*' removed from (project|system) scope/
53
+
54
+ # @param runs [Array<LLMContextStale::PairedRun>] the conversation's
55
+ # paired runs (WorkingSet.build has them already: no second walk)
56
+ # @param conversation [Array<Hash>] the entries they came from (a
57
+ # file tool's stamp sits on its tool_response entry)
58
+ # @param cwd [String, nil] the session's folder (FileRef)
59
+ def self.from_runs(runs, conversation, cwd:)
60
+ memories = {}
61
+ files = {}
62
+ runs.each do |run|
63
+ # The name first: failed? copies the output, and most runs are no own change at all.
64
+ name = run.call[:name].to_s
65
+ next unless name == Tools::MemoryWrite::NAME || FILE_TOOLS.include?(name)
66
+ next if WorkingSet.failed?(run.text)
67
+
68
+ if name == Tools::MemoryWrite::NAME
69
+ target, change = memory_change(run)
70
+ memories[target] = change if target
71
+ elsif FILE_TOOLS.include?(name)
72
+ path = FileRef.for(name, run.call, cwd: cwd)&.path
73
+ (files[File.expand_path(path)] ||= []) << file_change(run, conversation) if path
74
+ end
75
+ end
76
+ new(memories, files)
77
+ end
78
+
79
+ # chi web's: one paired_runs walk of +conversation+.
80
+ def self.of(conversation, cwd:)
81
+ conversation = Array(conversation)
82
+ from_runs(LLMContextStale.paired_runs(conversation), conversation, cwd: cwd)
83
+ end
84
+
85
+ def self.memory_change(run)
86
+ name = run.call[:path].to_s.strip
87
+ return nil if name.empty? || name == Tools::MEMORY_INDEX
88
+
89
+ body = run.text.to_s.sub(ToolResponse::LEAD, "").lstrip
90
+ change = ->(op, content = nil) { change(run, op, content: content) }
91
+ if (match = SAVED.match(body))
92
+ [[match[1], name, nil], change.call(MEMORY_WRITE, run.call[:content].to_s)]
93
+ elsif (match = OVERLAY.match(body))
94
+ [[match[2], name, match[1]], change.call(MEMORY_WRITE, run.call[:content].to_s)]
95
+ elsif (match = REMOVED.match(body))
96
+ [[match[1], name, nil], change.call(REMOVE)]
97
+ end
98
+ end
99
+
100
+ def self.file_change(run, conversation)
101
+ entry = conversation[run.index]
102
+ stamps = entry.is_a?(Hash) ? entry[:tool_stamps] || entry["tool_stamps"] : nil
103
+ stamp = stamps.is_a?(Array) ? stamps[run.ref.run] : nil
104
+ stamp = nil unless stamp.is_a?(Hash) && (stamp.key?(:mtime_ns) || stamp.key?("mtime_ns"))
105
+ call = run.call
106
+ exact = call[:name].to_s == "edit" && call[:start_line].nil? && !call[:old_text].to_s.empty? && !call[:new_text].to_s.empty?
107
+ change(run, call[:name].to_s, stamp: stamp, undo: exact ? [call[:old_text].to_s, call[:new_text].to_s] : nil)
108
+ end
109
+
110
+ def self.change(run, op, content: nil, stamp: nil, undo: nil)
111
+ Change.new(tool_id: run.ref.id, step: run.step, index: run.index, place: run.ref.run, op: op, content: content,
112
+ stamp: stamp, undo: undo)
113
+ end
114
+
115
+ private_class_method :memory_change, :file_change, :change
116
+
117
+ def initialize(memories, files)
118
+ @memories = memories
119
+ @files = files
120
+ end
121
+
122
+ def empty? = @memories.empty? && @files.empty?
123
+
124
+ # The latest own change of the memory +name+ in +scope+ (+key+: its
125
+ # overlay's; a remove counts for the overlays too: it moves them).
126
+ # @return [Change, nil]
127
+ def memory(scope, name, key: nil)
128
+ base = @memories[[scope, name, nil]]
129
+ return base unless key
130
+
131
+ own = @memories[[scope, name, key]]
132
+ removed = base if base&.op == REMOVE
133
+ [own, removed].compact.max_by(&:order)
134
+ end
135
+
136
+ # The latest own change of one file a part was read from
137
+ # (WorkingSet::Locator::Source's +path+, +role+, +key+): a memory's by
138
+ # its folder among +dirs+ ({"project" => dir, "system" => dir}, the
139
+ # part's saved ones: the scope is the folder the file sits in, never a
140
+ # prefix test, as a project's folder is inside the system one) and its
141
+ # name, and an edit or write of that file (by basename, then realpath);
142
+ # the later of the two.
143
+ # @return [Change, nil]
144
+ def for_file(path, role:, key: nil, dirs: {})
145
+ [memory_of_file(path, role: role, key: key, dirs: dirs), file(File.expand_path(path.to_s))].compact.max_by(&:order)
146
+ end
147
+
148
+ # The latest memory_write (or remove) of the memory file at +path+, by
149
+ # its folder among +dirs+ (#for_file's rule), or nil.
150
+ # @return [Change, nil]
151
+ def memory_of_file(path, role:, key: nil, dirs: {})
152
+ path = File.expand_path(path.to_s)
153
+ folder = File.dirname(path)
154
+ scope = dirs.find { |_, dir| dir && File.expand_path(dir.to_s) == folder }&.first
155
+ scope && memory(scope, memory_name(path, role, key), key: role == :overlay ? key : nil)
156
+ end
157
+
158
+ # The latest edit or write of the file at +path+.
159
+ # @return [Change, nil]
160
+ def file(path) = file_history(path).last
161
+
162
+ # Every edit and write of the file at +path+, in conversation order.
163
+ # @return [Array<Change>]
164
+ def file_history(path)
165
+ base = File.basename(path)
166
+ wanted = real(path)
167
+ @files.select { |candidate, _| File.basename(candidate) == base && real(candidate) == wanted }.values.flatten.sort_by(&:order)
168
+ end
169
+
170
+ # Whether undoing chi's edits in +history+ (Change, conversation
171
+ # order), newest first, takes +now+ back to +sent+: each one's
172
+ # new_text found exactly once and put back to its old_text, and the
173
+ # text equal to +sent+ (stripped, as a prompt file's is) after one of
174
+ # them. A range edit, an empty new_text, a write or a text it can't
175
+ # find stops it: false. Proves chi's edits are all that changed the
176
+ # file since it was sent (an edit over a change chi never saw is not).
177
+ # +written+: chi's memory_write of the file before those edits; its
178
+ # content, reached by undoing the edits after it, holds too (chi has
179
+ # it whole).
180
+ def self.undoes_to?(now, sent, history, written: nil)
181
+ text = now.to_s
182
+ history.reverse_each do |change|
183
+ return text == written.content if written && (change.order <=> written.order).negative?
184
+
185
+ old_text, new_text = change.undo
186
+ return false unless change.op == "edit" && new_text && text.scan(new_text).size == 1
187
+
188
+ text = text.sub(new_text) { old_text }
189
+ return true if text == sent || text.strip == sent.to_s.strip
190
+ end
191
+ !written.nil? && text == written.content
192
+ end
193
+
194
+ # Whether the file at +path+ still holds what +change+ left: a
195
+ # memory_write's content byte for byte, a remove's absence, a file
196
+ # tool's stamp (mtime and size, as WorkingSet's stale check compares).
197
+ def current?(change, path, stat: File.method(:stat), read: ->(file) { File.binread(file) })
198
+ case change.op
199
+ when MEMORY_WRITE then read.call(path) == change.content.b
200
+ when REMOVE then !File.exist?(path)
201
+ else change.stamp ? !WorkingSet.differs?(path, change.stamp, stat) : false
202
+ end
203
+ rescue SystemCallError
204
+ false
205
+ end
206
+
207
+ private
208
+
209
+ def memory_name(path, role, key)
210
+ stem = File.basename(path, ".md")
211
+ role == :overlay && key ? stem.delete_suffix(".#{key}") : stem
212
+ end
213
+
214
+ def real(path)
215
+ File.realpath(path)
216
+ rescue SystemCallError, ArgumentError
217
+ File.expand_path(path)
218
+ end
219
+ end
220
+ end
221
+ end
@@ -0,0 +1,281 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "context_note"
4
+ require_relative "prompt_part"
5
+ require_relative "text_diff"
6
+ require_relative "version"
7
+ require_relative "working_set_locator"
8
+ require_relative "working_set_own_changes"
9
+
10
+ module Samagotchi
11
+ # One prompt part as chi sent it: what chi web's GET
12
+ # /api/sessions/:id/working_set/part answers (WorkingSetRoutes), the
13
+ # working set's "From the start" peek. The part is a slice of the head the
14
+ # session already keeps (messages[0], ContextNote.system_head?), at the
15
+ # place its build recorded (PromptPart#at, #len, #lead), when that head is
16
+ # the one the parts were built with (PromptPart#head). Otherwise one line
17
+ # says why, in the order below, the first that holds winning; under a
18
+ # changed head a part chi can fetch again shows its source now (cases 4
19
+ # and 5). See docs/internals/working-set.md (Prompt parts as sent).
20
+ module WorkingSetPart
21
+ # What the peek says instead of the sent text, one line per condition.
22
+ WORDS = {
23
+ older_worker: "This session's worker runs an older chi. Restart it to open prompt parts.",
24
+ older_chi: "This session's prompt was built by an older chi. It shows here after the session's next turn.",
25
+ no_prompt: "chi builds its prompt at the first turn.",
26
+ running: "chi rebuilt its prompt. This is the source now; the sent text shows when the turn ends.",
27
+ idle: "chi's prompt changed after it was sent. This is the source now; the sent text shows after the next turn."
28
+ }.freeze
29
+
30
+ # A part whose source changed since chi was sent it (#states).
31
+ STALE = "stale"
32
+
33
+ # The route's refusals.
34
+ INVALID = "expected key (a prompt part's key)"
35
+ UNKNOWN = "no such prompt part in this session"
36
+
37
+ module_function
38
+
39
+ # The answer for the part +key+ names (PromptPart.keys) among +parts+,
40
+ # with +messages+ from the same source (a live worker's snapshot, else
41
+ # the session file). +older_worker+: a live worker runs an older chi
42
+ # than this one (#older_worker?); a worker of this chi (one restarted,
43
+ # its parts still the file's until a turn builds them) gets the
44
+ # older_chi words, which are true for it; +running+: a turn runs;
45
+ # +root+: chi web's memories folder (MemoryPaths.system_dir); +cwd+: the
46
+ # session's working directory (its AGENTS.md chain); +now+: with the
47
+ # sent slice, the source now and its diff from what was sent
48
+ # ({text, diff, gone}, the page's "now" tab), when a locator fetches it,
49
+ # and +rebuild+: when chi's prompt gets the source now ("restart": a
50
+ # +live+ worker keeps its prompt until it is next built; "next_turn":
51
+ # a session with none builds it at its next turn). Never under a
52
+ # changed head (cases 4 and 5 say when in their own words).
53
+ # @return [Hash, nil] nil when no part has that key
54
+ def answer(parts:, messages:, key:, older_worker:, running:, root:, cwd:, now: false, live: false)
55
+ parts = PromptPart.list(parts)
56
+ index = PromptPart.keys(parts).index(key.to_s)
57
+ return nil unless index
58
+
59
+ part = parts[index]
60
+ shown = { part: part.to_h.slice(:kind, :label, :ref, :scope, :chars, :tokens) }
61
+ tools = part.kind == "tools" && part.params.is_a?(Hash) ? part.params["tools"] : nil
62
+ # Names and sizes, saved with the part: they open whatever the head.
63
+ return shown.merge(tools: tools) if tools.is_a?(Array)
64
+
65
+ if part.at.nil?
66
+ reason = older_worker ? :older_worker : :older_chi
67
+ return shown.merge(note: WORDS[reason], reason: reason.to_s)
68
+ end
69
+
70
+ head = Array(messages).first
71
+ text = head.is_a?(Hash) && ContextNote.system_head?(head) ? (head[:content] || head["content"]) : nil
72
+ return shown.merge(note: WORDS[:no_prompt], reason: "no_prompt") unless text.is_a?(String)
73
+
74
+ if PromptPart.digest_of(text, 16) != part.head
75
+ changed = running ? :running : :idle
76
+ source = now_of(part, root: root, cwd: cwd)
77
+ return shown.merge(note: WORDS[changed], reason: changed.to_s, changed: changed.to_s, now: source).compact
78
+ end
79
+
80
+ sent = sent_of(part, parts, text)
81
+ source = now && now_of(part, root: root, cwd: cwd)
82
+ return shown.merge(sent: sent) unless source
83
+
84
+ # Each side ends its last line: a stripped note's or file's text would draw "\ No newline" markers otherwise.
85
+ lined = ->(text) { text.end_with?("\n") ? text : "#{text}\n" }
86
+ diff = source[:gone] ? nil : TextDiff.unified(lined.call(sent[:text]), lined.call(source[:text])).merge(new_file: false)
87
+ shown.merge(sent: sent, now: source.merge(diff: diff), rebuild: live ? "restart" : "next_turn")
88
+ end
89
+
90
+ # The parts of +parts+ (a saved or wire list) whose source changed
91
+ # since chi was sent it: [{key: PromptPart.keys', state: "stale"}],
92
+ # only the stale ones. A part is stale when its locator
93
+ # (WorkingSet::Locator, origin :prompt: the saved params, the guard)
94
+ # fetches text whose PromptPart.digest_of differs from the part's saved
95
+ # digest, or finds the source gone. Only what a locator fetches gets a
96
+ # state (identity, preloads, notes, AGENTS.md): never an index (it
97
+ # changes at every memory write, D5), an appended file, chi's own text
98
+ # or a part an older chi built (no digest). A digest sees a part's text
99
+ # only: a note newly applying, a new AGENTS.md in the chain, a memory
100
+ # muted since change which parts exist, and say nothing here. +root+,
101
+ # +cwd+: as #answer's.
102
+ #
103
+ # +messages+ (the same source's, top-level keys either way): a stale
104
+ # part chi changed itself also gets +by_chi+ ({tool_id, step, op,
105
+ # current}, #by_chi): current when the files it was read from hold
106
+ # chi's own change, or what was sent, and one holds chi's (the row's
107
+ # "edited"); not current when chi changed one and it changed again (or
108
+ # the head the parts were built with is gone). The state stays "stale"
109
+ # (an older page draws that). +running+: a turn runs, its own writes
110
+ # not in +messages+ yet, so only a current by_chi goes out (a "changed
111
+ # again" could be chi's own newest write).
112
+ # @return [Array<Hash>]
113
+ def states(parts, root:, cwd:, messages: nil, running: false)
114
+ parts = PromptPart.list(parts)
115
+ keys = PromptPart.keys(parts)
116
+ own = nil
117
+ parts.each_with_index.filter_map do |part, index|
118
+ next unless part.digest && WorkingSet::Locator::FETCHED.include?(part.kind)
119
+
120
+ composed = WorkingSet::Locator.of_part(part).composed(root: root, cwd: cwd)
121
+ now = composed&.now
122
+ next unless now
123
+ next unless now.gone || PromptPart.digest_of(now.text) != part.digest
124
+
125
+ state = { key: keys[index], state: STALE }
126
+ next state unless messages
127
+
128
+ messages = symbolized(messages) unless own
129
+ own ||= WorkingSet::OwnChanges.of(messages, cwd: cwd)
130
+ found = by_chi(part, parts, composed, own, messages)
131
+ found && (found[:current] || !running) ? state.merge(by_chi: found) : state
132
+ end
133
+ end
134
+
135
+ # The top-level keys of +messages+ as symbols (a live snapshot's are
136
+ # strings; paired_runs reads symbols). Shared with chi web's builds.
137
+ def symbolized(messages)
138
+ Array(messages).map { |message| message.is_a?(Hash) ? message.transform_keys(&:to_sym) : message }
139
+ end
140
+
141
+ # Whether a worker that says it runs +version+ (its Bridge snapshot's
142
+ # chi_version; nil: an older worker that doesn't say) is older than
143
+ # this chi.
144
+ def older_worker?(version)
145
+ Gem::Version.new(version.to_s) < Gem::Version.new(VERSION)
146
+ rescue ArgumentError
147
+ true
148
+ end
149
+
150
+ # The part's slice of +head+: {text: its own text, lead: chi's line
151
+ # before it}; base's leaves out the declarations when they sit in it.
152
+ def sent_of(part, parts, head)
153
+ slice = head[part.at, part.len].to_s
154
+ lead = slice[0, part.lead.to_i].to_s
155
+ body = slice[lead.length..].to_s
156
+ tools = parts.first
157
+ if part.kind == "base" && tools&.kind == "tools" && tools.at && tools.at >= part.at && tools.at < part.at + part.len
158
+ from = tools.at - part.at - lead.length
159
+ body = body[0, from].to_s + body[(from + tools.len.to_i)..].to_s
160
+ end
161
+ { text: body, lead: lead }
162
+ end
163
+
164
+ # The part's source now ({text:, gone:}), nil when there is none to
165
+ # fetch or the guard refuses (WorkingSet::Locator, origin :prompt: a
166
+ # memory with the saved params, an AGENTS.md on the session's own
167
+ # chain, never an appended file).
168
+ def now_of(part, root:, cwd:)
169
+ now = WorkingSet::Locator.of_part(part).fetch(root: root, cwd: cwd)
170
+ # The file's bytes as they are: JSON wants them valid (the saved head was scrubbed at save).
171
+ now && { text: now.text && TextDiff.clean(now.text), gone: now.gone }
172
+ end
173
+
174
+ # A stale +part+'s own change ({tool_id, step, op, current}), or nil
175
+ # (the plan's rule): each file the part was read from (+composed+'s,
176
+ # the base and its overlay; a gone memory's base as sent) mapped to
177
+ # chi's latest change of it (+own+). Current (the row's "edited") when
178
+ # each file holds chi's change or what was sent (the sent slice split
179
+ # at the overlay's prefix: a part is the base's text with its overlay
180
+ # appended) and one holds chi's; else, when chi changed one, not
181
+ # current. Without the head the parts were built with nothing proves
182
+ # the other file unchanged: never current.
183
+ def by_chi(part, parts, composed, own, messages)
184
+ return nil if own.empty?
185
+
186
+ dirs = memory_dirs(part)
187
+ changes = composed.files.to_h do |file|
188
+ change = own.for_file(file.path, role: file.role, key: file.key, dirs: dirs)
189
+ [file, change && { change: change, current: own.current?(change, file.path) }]
190
+ end
191
+ latest = changes.values.compact.max_by { |found| found[:change].order }
192
+ return nil unless latest
193
+ # A file tool's change without a stamp can't say whether it still holds (an older session's): no word (L4).
194
+ return nil if changes.values.compact.any? { |found| WorkingSet::OwnChanges::FILE_TOOLS.include?(found[:change].op) && !found[:change].stamp }
195
+
196
+ sent = sent_text(part, parts, messages)
197
+ current = changes.values.compact.select { |found| found[:current] }
198
+ if sent && current.any? && unchanged_but_own?(composed, changes, sent, part)
199
+ # An edit is current only when undoing chi's edits gives back what was sent (D2, stricter): else no word.
200
+ return nil unless edits_undo?(composed, changes, sent, part, own)
201
+
202
+ return current.max_by { |found| found[:change].order }[:change].to_h.merge(current: true)
203
+ end
204
+
205
+ latest[:change].to_h.merge(current: false)
206
+ end
207
+
208
+ # Whether every file of +composed+ holds chi's change or what was sent.
209
+ def unchanged_but_own?(composed, changes, sent, part)
210
+ return composed.files.all? { |file| changes[file]&.dig(:current) } if composed.now.gone
211
+
212
+ sides = sides(composed, sent, part)
213
+ composed.files.all? do |file|
214
+ next true if changes[file]&.dig(:current)
215
+
216
+ now_side, sent_side = sides[file.role]
217
+ now_side == sent_side
218
+ end && (composed.files.any? { |file| file.role == :overlay } || sides[:overlay][0] == sides[:overlay][1])
219
+ end
220
+
221
+ # Each current edit of a file of +composed+ undone back to its sent side
222
+ # (OwnChanges.undoes_to?, over the file's edits and writes); true when
223
+ # none is an edit.
224
+ def edits_undo?(composed, changes, sent, part, own)
225
+ edited = composed.files.select { |file| changes[file]&.dig(:current) && changes[file][:change].op == "edit" }
226
+ return true if edited.empty?
227
+ return false if composed.now.gone
228
+
229
+ sides = sides(composed, sent, part)
230
+ edited.all? do |file|
231
+ now_side, sent_side = sides[file.role]
232
+ written = own.memory_of_file(file.path, role: file.role, key: file.key, dirs: memory_dirs(part))
233
+ written = nil unless written&.op == WorkingSet::OwnChanges::MEMORY_WRITE
234
+ WorkingSet::OwnChanges.undoes_to?(now_side, sent_side, own.file_history(file.path), written: written)
235
+ end
236
+ end
237
+
238
+ # The text now and the sent text split at the overlay's prefix:
239
+ # {base: [now body, sent body], overlay: [now tail, sent tail]}.
240
+ def sides(composed, sent, part)
241
+ overlay = composed.files.find { |file| file.role == :overlay }
242
+ now_body, now_tail = overlay ? split(composed.now.text, [overlay.key]) : [composed.now.text, ""]
243
+ keys = [overlay&.key, *%i[model_key fallback_model_key].map { |key| param(part, key) }]
244
+ sent_body, sent_tail = split(sent, keys)
245
+ { base: [now_body, sent_body], overlay: [now_tail, sent_tail] }
246
+ end
247
+
248
+ # +text+ split at the overlay prefix of the first of +keys+ found:
249
+ # [body, tail], the tail "" without one.
250
+ def split(text, keys)
251
+ keys.compact.uniq.each do |key|
252
+ tail = Tools::MemoryRead.overlay_tail(text, key)
253
+ return [text.delete_suffix(tail), tail] unless tail.empty?
254
+ end
255
+ [text, ""]
256
+ end
257
+
258
+ # The part's sent text when +messages+' head is the one the parts were
259
+ # built with, else nil.
260
+ def sent_text(part, parts, messages)
261
+ head = Array(messages).first
262
+ text = head.is_a?(Hash) && ContextNote.system_head?(head) ? (head[:content] || head["content"]) : nil
263
+ return nil unless text.is_a?(String) && part.at && PromptPart.digest_of(text, 16) == part.head
264
+
265
+ sent_of(part, parts, text)[:text]
266
+ end
267
+
268
+ # A memory part's saved folders by scope (none for an AGENTS.md).
269
+ def memory_dirs(part)
270
+ return {} unless WorkingSet::Locator::MEMORY_KINDS.include?(part.kind)
271
+
272
+ { "project" => param(part, :project_dir), "system" => param(part, :system_dir) }
273
+ end
274
+
275
+ def param(part, key)
276
+ part.params.is_a?(Hash) ? WorkingSet::MemoryGuard.field(part.params, key) : nil
277
+ end
278
+
279
+ private_class_method :sent_of, :now_of, :by_chi, :unchanged_but_own?, :edits_undo?, :sides, :split, :sent_text, :memory_dirs, :param
280
+ end
281
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: samagotchi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.183.0
4
+ version: 0.185.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dedov
@@ -185,6 +185,7 @@ files:
185
185
  - docs/testing.md
186
186
  - docs/thin-clients.md
187
187
  - lib/samagotchi.rb
188
+ - lib/samagotchi/agent_caller.rb
188
189
  - lib/samagotchi/analytics_file.rb
189
190
  - lib/samagotchi/answer_command.rb
190
191
  - lib/samagotchi/answer_display.rb
@@ -254,6 +255,7 @@ files:
254
255
  - lib/samagotchi/bundles/claude-peer/plugin.rb
255
256
  - lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md
256
257
  - lib/samagotchi/bundles/claude-peer/scripts/pair
258
+ - lib/samagotchi/bundles/claude-peer/scripts/pair-remote
257
259
  - lib/samagotchi/bundles/claude-peer/skill_claude_peer.md
258
260
  - lib/samagotchi/bundles/codex-peer/manifest.yml
259
261
  - lib/samagotchi/bundles/codex-peer/plugin.rb
@@ -379,6 +381,7 @@ files:
379
381
  - lib/samagotchi/desktop/macos/Sessions.swift
380
382
  - lib/samagotchi/desktop/macos/Tmux.swift
381
383
  - lib/samagotchi/desktop_command.rb
384
+ - lib/samagotchi/driver_command.rb
382
385
  - lib/samagotchi/edit_preview.rb
383
386
  - lib/samagotchi/effective_model.rb
384
387
  - lib/samagotchi/empty_answer_error.rb
@@ -652,6 +655,7 @@ files:
652
655
  - lib/samagotchi/prompt.rb
653
656
  - lib/samagotchi/prompt_files.rb
654
657
  - lib/samagotchi/prompt_history.rb
658
+ - lib/samagotchi/prompt_layout.rb
655
659
  - lib/samagotchi/prompt_literal_guard.rb
656
660
  - lib/samagotchi/prompt_note.rb
657
661
  - lib/samagotchi/prompt_part.rb
@@ -874,6 +878,7 @@ files:
874
878
  - lib/samagotchi/toolkit_report_command.rb
875
879
  - lib/samagotchi/toolkit_suggest.rb
876
880
  - lib/samagotchi/tools/args.rb
881
+ - lib/samagotchi/tools/ask_session.rb
877
882
  - lib/samagotchi/tools/ask_user_question.rb
878
883
  - lib/samagotchi/tools/builtin_calls.rb
879
884
  - lib/samagotchi/tools/builtins.rb
@@ -942,6 +947,7 @@ files:
942
947
  - lib/samagotchi/version.rb
943
948
  - lib/samagotchi/vision_context.rb
944
949
  - lib/samagotchi/vision_support.rb
950
+ - lib/samagotchi/visitor.rb
945
951
  - lib/samagotchi/waiting_steer.rb
946
952
  - lib/samagotchi/web/app.rb
947
953
  - lib/samagotchi/web/ask_routes.rb
@@ -1082,6 +1088,7 @@ files:
1082
1088
  - lib/samagotchi/web/public/peer_exchange.js
1083
1089
  - lib/samagotchi/web/public/peer_links.js
1084
1090
  - lib/samagotchi/web/public/peer_note.js
1091
+ - lib/samagotchi/web/public/peer_text.js
1085
1092
  - lib/samagotchi/web/public/picture_regions.js
1086
1093
  - lib/samagotchi/web/public/picture_viewer.js
1087
1094
  - lib/samagotchi/web/public/plain_line.js
@@ -1206,6 +1213,7 @@ files:
1206
1213
  - lib/samagotchi/web/public/ws_item_sig.js
1207
1214
  - lib/samagotchi/web/public/ws_markdown.js
1208
1215
  - lib/samagotchi/web/public/ws_order.js
1216
+ - lib/samagotchi/web/public/ws_part_peek.js
1209
1217
  - lib/samagotchi/web/public/ws_peek.js
1210
1218
  - lib/samagotchi/web/public/ws_preview.css
1211
1219
  - lib/samagotchi/web/public/ws_reader.js
@@ -1247,6 +1255,7 @@ files:
1247
1255
  - lib/samagotchi/worker/command_queue.rb
1248
1256
  - lib/samagotchi/worker/leave.rb
1249
1257
  - lib/samagotchi/worker/scratch.rb
1258
+ - lib/samagotchi/worker/senders.rb
1250
1259
  - lib/samagotchi/worker/signal_grace.rb
1251
1260
  - lib/samagotchi/worker/startup.rb
1252
1261
  - lib/samagotchi/worker/wake_turns.rb
@@ -1263,6 +1272,9 @@ files:
1263
1272
  - lib/samagotchi/worker_wakes.rb
1264
1273
  - lib/samagotchi/working_set.rb
1265
1274
  - lib/samagotchi/working_set_command.rb
1275
+ - lib/samagotchi/working_set_locator.rb
1276
+ - lib/samagotchi/working_set_own_changes.rb
1277
+ - lib/samagotchi/working_set_part.rb
1266
1278
  - lib/samagotchi/working_set_pin.rb
1267
1279
  - lib/samagotchi/working_set_steer.rb
1268
1280
  - lib/samagotchi/yaml_lines.rb