samagotchi 0.182.0 → 0.183.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 (161) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +16 -6
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +2 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +13 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +18 -8
  14. data/docs/internals/remote-sessions.md +24 -5
  15. data/docs/internals/web-frontend.md +88 -28
  16. data/docs/internals/working-set.md +1 -1
  17. data/docs/mcp-server.md +80 -0
  18. data/docs/plugins.md +308 -21
  19. data/docs/sessions.md +3 -3
  20. data/docs/sub-agent.md +9 -0
  21. data/docs/testing.md +3 -1
  22. data/docs/thin-clients.md +146 -0
  23. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  24. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  25. data/lib/samagotchi/bridge.rb +59 -68
  26. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  27. data/lib/samagotchi/bundle_command/check.rb +36 -19
  28. data/lib/samagotchi/bundle_command.rb +50 -21
  29. data/lib/samagotchi/bundle_manifest.rb +101 -4
  30. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  32. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  33. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  35. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  36. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  37. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  38. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  41. data/lib/samagotchi/command_intake.rb +7 -0
  42. data/lib/samagotchi/commands/registry.rb +8 -3
  43. data/lib/samagotchi/continue_offer.rb +24 -15
  44. data/lib/samagotchi/engine/block_fix.rb +4 -4
  45. data/lib/samagotchi/engine/cards.rb +14 -5
  46. data/lib/samagotchi/engine/events.rb +10 -15
  47. data/lib/samagotchi/engine/models.rb +1 -1
  48. data/lib/samagotchi/engine/plugins.rb +3 -0
  49. data/lib/samagotchi/engine/recap.rb +1 -1
  50. data/lib/samagotchi/engine/side_requests.rb +1 -1
  51. data/lib/samagotchi/engine/sign_in.rb +142 -0
  52. data/lib/samagotchi/engine/turn_end.rb +3 -3
  53. data/lib/samagotchi/engine.rb +43 -27
  54. data/lib/samagotchi/engine_snapshots.rb +1 -1
  55. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  56. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  57. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  58. data/lib/samagotchi/hold_stop.rb +4 -4
  59. data/lib/samagotchi/idle_recap.rb +19 -11
  60. data/lib/samagotchi/idle_reminders.rb +7 -5
  61. data/lib/samagotchi/idle_scheduler.rb +7 -10
  62. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  63. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  64. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  65. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  66. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  67. data/lib/samagotchi/llm/http.rb +96 -5
  68. data/lib/samagotchi/mcp_command.rb +110 -0
  69. data/lib/samagotchi/mcp_server/http.rb +112 -0
  70. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  71. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  72. data/lib/samagotchi/mcp_server/text.rb +155 -0
  73. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  74. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  75. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  76. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  77. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  78. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  79. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  80. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  81. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  82. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  83. data/lib/samagotchi/plugin/api.rb +6 -1
  84. data/lib/samagotchi/plugin/card.rb +36 -11
  85. data/lib/samagotchi/plugin/context.rb +63 -6
  86. data/lib/samagotchi/plugin/http.rb +40 -15
  87. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  88. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  89. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  90. data/lib/samagotchi/plugin/loader.rb +18 -11
  91. data/lib/samagotchi/plugin/secrets.rb +266 -0
  92. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  93. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  94. data/lib/samagotchi/queued_command.rb +28 -4
  95. data/lib/samagotchi/recap_setup.rb +13 -4
  96. data/lib/samagotchi/ref.rb +3 -2
  97. data/lib/samagotchi/relay_verifier.rb +8 -7
  98. data/lib/samagotchi/relay_watcher.rb +4 -4
  99. data/lib/samagotchi/run_options.rb +2 -1
  100. data/lib/samagotchi/send_command.rb +54 -41
  101. data/lib/samagotchi/session_access/ask.rb +244 -0
  102. data/lib/samagotchi/session_access/contract.rb +5 -0
  103. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  104. data/lib/samagotchi/session_access/exchange.rb +173 -0
  105. data/lib/samagotchi/session_access/local.rb +25 -6
  106. data/lib/samagotchi/session_access/remote.rb +4 -1
  107. data/lib/samagotchi/session_command_catalog.rb +10 -0
  108. data/lib/samagotchi/session_commands.rb +17 -0
  109. data/lib/samagotchi/session_config.rb +4 -4
  110. data/lib/samagotchi/session_observer.rb +27 -0
  111. data/lib/samagotchi/steer_cut.rb +4 -3
  112. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  113. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  114. data/lib/samagotchi/testing/boundary.rb +4 -0
  115. data/lib/samagotchi/testing/bundle.rb +48 -2
  116. data/lib/samagotchi/testing/fake_http.rb +60 -15
  117. data/lib/samagotchi/testing/host.rb +4 -1
  118. data/lib/samagotchi/testing/recorder.rb +45 -5
  119. data/lib/samagotchi/tools/tool_index.rb +14 -3
  120. data/lib/samagotchi/version.rb +1 -1
  121. data/lib/samagotchi/web/app.rb +8 -6
  122. data/lib/samagotchi/web/ask_routes.rb +292 -0
  123. data/lib/samagotchi/web/mcp_route.rb +88 -0
  124. data/lib/samagotchi/web/public/app.js +2 -3
  125. data/lib/samagotchi/web/public/block_frame.js +72 -11
  126. data/lib/samagotchi/web/public/block_host.js +44 -8
  127. data/lib/samagotchi/web/public/block_regions.js +126 -0
  128. data/lib/samagotchi/web/public/card.js +22 -9
  129. data/lib/samagotchi/web/public/card_actions.js +21 -0
  130. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  131. data/lib/samagotchi/web/public/card_registry.js +3 -2
  132. data/lib/samagotchi/web/public/data.js +15 -12
  133. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  134. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  135. data/lib/samagotchi/web/public/format.js +3 -0
  136. data/lib/samagotchi/web/public/index.html +52 -7
  137. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  138. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  139. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  140. data/lib/samagotchi/web/public/refs.js +5 -3
  141. data/lib/samagotchi/web/public/region_hit.js +144 -0
  142. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  143. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  144. data/lib/samagotchi/web/public/session_actions.js +105 -100
  145. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  146. data/lib/samagotchi/web/session_control.rb +31 -9
  147. data/lib/samagotchi/web/session_create.rb +2 -2
  148. data/lib/samagotchi/worker/child_side.rb +3 -2
  149. data/lib/samagotchi/worker/command_queue.rb +13 -13
  150. data/lib/samagotchi/worker/leave.rb +3 -3
  151. data/lib/samagotchi/worker/scratch.rb +6 -6
  152. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  153. data/lib/samagotchi/worker/startup.rb +3 -3
  154. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  155. data/lib/samagotchi/worker.rb +32 -21
  156. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  157. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  158. data/lib/samagotchi/worker_inbound.rb +12 -7
  159. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  160. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  161. metadata +31 -1
@@ -0,0 +1,245 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../client_id"
4
+ require_relative "../session_inbox"
5
+ require_relative "../turn_flow"
6
+ require_relative "../session_access/ask"
7
+ require_relative "../session_access/exchange"
8
+ require_relative "../session_access/exchange/token"
9
+ require_relative "text"
10
+
11
+ module Samagotchi
12
+ module McpServer
13
+ # The four tools an MCP host's model sees (chi_sessions, chi_ask,
14
+ # chi_wait, chi_answer): their definitions (#list) and their calls
15
+ # (#call). The only file of the server that names SessionAccess: it
16
+ # reaches sessions through the +access+ it is given (Local, Remote or
17
+ # chi web's per-request wrapper) and SessionAccess::Ask / Exchange,
18
+ # built per call (they keep no state). The caller is a parent agent:
19
+ # its turns go in as chi send's, its answers and its /continue yes as
20
+ # chi answer's, so guardrails.parent_answers holds it.
21
+ class Tools
22
+ # Seconds one call waits before it answers "still running" (spike D2:
23
+ # well inside Claude Code HTTP's 60 s and Codex's 300 s).
24
+ SLICE = 25
25
+ # The most seconds a chi_ask or a chi_answer takes in all
26
+ # (Web::AskRoutes::ASK_MAX_SECONDS).
27
+ CAP = 35
28
+ LIST_LIMIT = 20
29
+ LIST_MAX = 50
30
+
31
+ # Bad arguments: the message is the tool's error text.
32
+ class BadArguments < StandardError; end
33
+
34
+ DEFINITIONS = [
35
+ { name: "chi_sessions",
36
+ description: "List chi sessions, newest first: id, title, status, whether a question waits, project.",
37
+ inputSchema: { type: "object", additionalProperties: false,
38
+ properties: { dir: { type: "string", description: "only sessions in this folder or below" },
39
+ live: { type: "boolean", description: "only sessions a worker runs now" },
40
+ limit: { type: "integer", minimum: 1, maximum: LIST_MAX,
41
+ description: "at most this many (default #{LIST_LIMIT})" } } },
42
+ annotations: { readOnlyHint: true } },
43
+ { name: "chi_ask",
44
+ description: "Send a message to a chi session as its own turn and wait for the answer. A result that is " \
45
+ "still running carries a token for chi_wait; one with a question waiting is answered with " \
46
+ "chi_answer.",
47
+ inputSchema: { type: "object", additionalProperties: false, required: %w[session prompt],
48
+ properties: { session: { type: "string", description: "the session's id or an id prefix" },
49
+ prompt: { type: "string", description: "the message for the session's model" } } },
50
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false } },
51
+ { name: "chi_wait",
52
+ description: "Keep waiting for a chi turn that was still running, by the token its result carried.",
53
+ inputSchema: { type: "object", additionalProperties: false, required: %w[token],
54
+ properties: { token: { type: "string", description: "the token of a still-running result" } } },
55
+ annotations: { readOnlyHint: false, idempotentHint: false } },
56
+ { name: "chi_answer",
57
+ description: "Answer the question a chi session waits on (by its question_id), then wait for what comes next.",
58
+ inputSchema: { type: "object", additionalProperties: false, required: %w[session question_id],
59
+ properties: {
60
+ session: { type: "string", description: "the session's id" },
61
+ question_id: { type: "string", description: "the question's id, from the result" },
62
+ option: { type: %w[string integer], description: "one option: its label or its number (1-based)" },
63
+ options: { type: "array", items: { type: %w[string integer] },
64
+ description: "several options, on a question that takes several" },
65
+ text: { type: "string", description: "free text, where the question takes it" }
66
+ } },
67
+ annotations: { readOnlyHint: false, idempotentHint: false } }
68
+ ].freeze
69
+
70
+ # @param access [SessionAccess::Local, SessionAccess::Remote, #answer]
71
+ # @param slice [Numeric] seconds a call waits (SLICE)
72
+ # @param cap [Numeric] seconds a chi_ask or chi_answer takes in all (CAP)
73
+ # @param exchange [#call, nil] (access) -> the Exchange a call uses
74
+ # (chi web's carries its stop check); nil: a plain one
75
+ def initialize(access, slice: SLICE, cap: CAP, exchange: nil, cancelled: nil)
76
+ @access = access
77
+ @slice = slice
78
+ @cap = cap
79
+ @exchange = exchange || ->(backend) { SessionAccess::Exchange.new(backend) }
80
+ @cancelled = cancelled
81
+ end
82
+
83
+ def list = DEFINITIONS
84
+
85
+ # @return [Hash] a tools/call result; never raises (a call must
86
+ # always answer, or the host hangs to its own timeout)
87
+ def call(name, arguments)
88
+ case name
89
+ when "chi_sessions" then sessions(arguments)
90
+ when "chi_ask" then ask(arguments)
91
+ when "chi_wait" then wait(arguments)
92
+ when "chi_answer" then answer(arguments)
93
+ else raise ArgumentError, "no tool #{name}"
94
+ end
95
+ rescue BadArguments, SessionInbox::NoteRejected, SessionAccess::Exchange::Token::Invalid => e
96
+ Text.error(e.message)
97
+ rescue StandardError => e
98
+ Text.error(e.message.to_s.empty? ? e.class.name : e.message)
99
+ end
100
+
101
+ private
102
+
103
+ def sessions(arguments)
104
+ dir = optional(arguments, "dir", String)
105
+ live = optional(arguments, "live", [true, false])
106
+ limit = optional(arguments, "limit", Integer) || LIST_LIMIT
107
+ raise BadArguments, "limit is 1 to #{LIST_MAX}" unless limit.between?(1, LIST_MAX)
108
+
109
+ filters = { live: live == true, limit: limit }
110
+ filters[:cwd] = File.expand_path(dir) if dir && !@access.remote?
111
+ filters[:cwd] = dir if dir && @access.remote?
112
+ Text.sessions(@access.summaries(**filters).first(limit))
113
+ end
114
+
115
+ def ask(arguments)
116
+ given = required(arguments, "session")
117
+ prompt = SessionInbox.checked_text(required(arguments, "prompt"), noun: "message")
118
+ return Text.error(Text::COMMAND_REFUSED, reason: "command") if command_line?(prompt)
119
+
120
+ asker = SessionAccess::Ask.new(@access, exchange: exchange)
121
+ client_id = sender(asker, given, prompt)
122
+ return Text.refused(client_id) if client_id.is_a?(SessionAccess::Ask::Refused)
123
+
124
+ more = @cancelled ? { cancelled: @cancelled } : {}
125
+ outcome = asker.call(given, prompt: prompt, client_id: client_id, queue: true, timeout: @slice, cap: @cap, **more)
126
+ outcome(outcome)
127
+ end
128
+
129
+ def wait(arguments)
130
+ id, target = SessionAccess::Exchange::Token.load(required(arguments, "token"))
131
+ more = @cancelled ? { cancelled: @cancelled } : {}
132
+ result = exchange.wait(id, target, timeout: @slice, **more)
133
+ token = SessionAccess::Exchange::Token.dump(id, target) if result.status == :timeout
134
+ Text.wait_result(result, session_id: id, token: token, strategy: @access.parent_strategy(id))
135
+ end
136
+
137
+ def answer(arguments)
138
+ id = @access.resolve(required(arguments, "session"))
139
+ qid = required(arguments, "question_id")
140
+ text = optional(arguments, "text", String)
141
+ picks = picks(arguments)
142
+ raise BadArguments, "nothing to answer with: give option, options or text" if picks.empty? && text.nil?
143
+
144
+ pending = @access.show(id).pending_question
145
+ selected = pending && pending.id.to_s == qid ? selection(pending, picks) : []
146
+ more = @cancelled ? { cancelled: @cancelled } : {}
147
+ outcome(SessionAccess::Ask.new(@access, exchange: exchange)
148
+ .answer(id, question_id: qid, selected: selected, freeform: text,
149
+ client_id: ClientId::CLI_ANSWER, timeout: @slice, cap: @cap, **more),
150
+ question_id: qid)
151
+ end
152
+
153
+ # @param question_id [String, nil] chi_answer's: an answer that
154
+ # didn't go in says so in the text, not only in answered_here
155
+ def outcome(outcome, question_id: nil)
156
+ case outcome
157
+ when SessionAccess::Ask::Refused then Text.refused(outcome)
158
+ when SessionAccess::Ask::Ran then Text.ran(outcome.session_id)
159
+ else
160
+ extra = outcome.answered_here ? {} : { answered_here: false }
161
+ result = Text.wait_result(outcome.result, session_id: outcome.session_id, token: outcome.token,
162
+ strategy: @access.parent_strategy(outcome.session_id), extra: extra)
163
+ outcome.answered_here ? result : Text.not_answered(result, question_id)
164
+ end
165
+ end
166
+
167
+ # Who sends +prompt+ (Ask#agent_line): on this machine held to the
168
+ # parent_answers of the session asked and its chain's newest link; on
169
+ # a remote chi web's turn route gates the same ids itself.
170
+ def sender(asker, given, prompt)
171
+ return TurnFlow.continue_yes?(prompt) ? ClientId::CLI_ANSWER : ClientId::CLI_SEND if @access.remote?
172
+
173
+ asker.agent_line(prompt, session: targets(given))
174
+ end
175
+
176
+ def targets(given)
177
+ asked = @access.resolve(given)
178
+ [asked, @access.head(asked).id].uniq.filter_map do |id|
179
+ @access.show(id)
180
+ rescue ArgumentError # degrade-ok: the head not saved yet; the asked session's value still holds
181
+ nil
182
+ end
183
+ rescue ArgumentError # degrade-ok: no such session: the ask's own answer says so
184
+ []
185
+ end
186
+
187
+ # A shell line (!…) or a session command other than /continue.
188
+ def command_line?(prompt)
189
+ line = prompt.lstrip
190
+ return true if line.start_with?("!")
191
+
192
+ line.start_with?("/") && !line.match?(%r{\A/continue(\s|\z)})
193
+ end
194
+
195
+ # option / options as given (labels or 1-based numbers).
196
+ def picks(arguments)
197
+ one = arguments["option"]
198
+ many = arguments["options"]
199
+ raise BadArguments, "option is a label or a number" unless one.nil? || one.is_a?(String) || one.is_a?(Integer)
200
+ unless many.nil? || (many.is_a?(Array) && many.all? { |pick| pick.is_a?(String) || pick.is_a?(Integer) })
201
+ raise BadArguments, "options is a list of labels or numbers"
202
+ end
203
+
204
+ [*one, *many].map(&:to_s)
205
+ end
206
+
207
+ # The labels to send, as chi answer resolves them: an exact label
208
+ # wins over a number; several only on a multi-select question.
209
+ def selection(pending, picks)
210
+ offered = Array(pending.options).map(&:to_s)
211
+ labels = picks.map do |given|
212
+ next given if offered.include?(given)
213
+
214
+ index = Integer(given, exception: false)
215
+ next offered[index - 1] if index&.between?(1, offered.size)
216
+
217
+ listed = offered.each_with_index.map { |label, i| "#{i + 1}. #{label}" }.join(", ")
218
+ raise BadArguments, "no option #{given}; the options: #{listed}"
219
+ end
220
+ raise BadArguments, "one option only: the question is single-select" if labels.uniq.size > 1 && !pending.multi_select
221
+
222
+ labels.uniq
223
+ end
224
+
225
+ def exchange = @exchange.call(@access)
226
+
227
+ def required(arguments, key)
228
+ value = arguments[key]
229
+ raise BadArguments, "#{key} is required (a string)" unless value.is_a?(String) && !value.strip.empty?
230
+
231
+ value
232
+ end
233
+
234
+ def optional(arguments, key, kind)
235
+ value = arguments[key]
236
+ return nil if value.nil?
237
+
238
+ ok = kind.is_a?(Array) ? kind.include?(value) : value.is_a?(kind)
239
+ raise BadArguments, "#{key} has the wrong type" unless ok
240
+
241
+ value
242
+ end
243
+ end
244
+ end
245
+ end
@@ -32,7 +32,10 @@ module Samagotchi
32
32
  # empty / nil on a dry run).
33
33
  # guardrail_files, script_files basename => installed path
34
34
  # plugin_file the installed plugin file, nil without one
35
- Installed = Data.define(:guardrail_files, :plugin_file, :script_files)
35
+ # plugin_parts its parts' name => installed path, in load order
36
+ Installed = Data.define(:guardrail_files, :plugin_file, :script_files, :plugin_parts) do
37
+ def initialize(guardrail_files:, plugin_file:, script_files:, plugin_parts: {}) = super
38
+ end
36
39
 
37
40
  # The retire's summary words (Installer#summary): why the hooks went.
38
41
  RETIRED = "chi no longer loads class-file bundle hooks"
@@ -76,6 +79,7 @@ module Samagotchi
76
79
  # @raise [Installer::InstallError]
77
80
  def check_named_files
78
81
  plugin_source
82
+ part_sources
79
83
  scripts_sources
80
84
  end
81
85
 
@@ -90,11 +94,14 @@ module Samagotchi
90
94
 
91
95
  lines = []
92
96
  if @manifest.plugin
93
- lines << Installer.mismatch_refusal("plugin #{@manifest.plugin[:file]}", plugin_source,
97
+ lines << Installer.mismatch_refusal(label(:plugin, @manifest.plugin[:file]), plugin_source,
94
98
  @manifest.checksum_for_plugin, upgrade: @upgrade)
95
99
  end
100
+ part_sources.each do |name, src|
101
+ lines << Installer.mismatch_refusal(label(:plugin, name), src, @manifest.checksum_for_part(name), upgrade: @upgrade)
102
+ end
96
103
  scripts_sources.each do |name, src|
97
- lines << Installer.mismatch_refusal("script #{name}", src, declared_sha(:script, name), upgrade: @upgrade)
104
+ lines << Installer.mismatch_refusal(label(:script, name), src, declared_sha(:script, name), upgrade: @upgrade)
98
105
  end
99
106
  lines = lines.compact
100
107
  raise Installer::InstallError, lines.join("\n") unless lines.empty?
@@ -107,13 +114,15 @@ module Samagotchi
107
114
  incoming_rules = Dir.glob(File.join(@bundle_dir, "guardrails", "*.yml")).sort
108
115
  .reject { |src| linked_out?(src, "guardrails/#{File.basename(src)}") }
109
116
  guardrail_files = install_set(:rule, rules_incoming(incoming_rules))
110
- plugin_file = install_set(:plugin, plugin_incoming).values.first
117
+ plugin_set = install_set(:plugin, plugin_incoming)
118
+ plugin_file = @manifest&.plugin && plugin_set[@manifest.plugin[:file]]
111
119
  script_files = install_set(:script, scripts_incoming)
112
120
  # After the plugin and scripts, which raise for a file the manifest
113
121
  # names and the bundle lacks: a refused install leaves hooks/ as it was.
114
122
  retire_hooks
115
123
  warn_rules_requires_chi(incoming_rules)
116
- Installed.new(guardrail_files: guardrail_files, plugin_file: plugin_file, script_files: script_files)
124
+ Installed.new(guardrail_files: guardrail_files, plugin_file: plugin_file, script_files: script_files,
125
+ plugin_parts: plugin_set.except(@manifest&.plugin&.dig(:file)))
117
126
  end
118
127
 
119
128
  # Whether the bundle file +src+ reads through a symlink: it is one, or
@@ -162,9 +171,10 @@ module Samagotchi
162
171
  # The bundle's guardrails/*.yml, by basename.
163
172
  def rules_incoming(incoming_rules) = incoming_rules.to_h { |src| [File.basename(src), src] }
164
173
 
165
- # The manifest's plugin file, warning when this chi doesn't meet
166
- # requires_chi (the Engine then won't load it). {} without one.
167
- # @return [Hash{String => String}] its file => the source file
174
+ # The manifest's plugin parts, then its plugin file (the load order),
175
+ # warning when this chi doesn't meet requires_chi (the Engine then
176
+ # won't load it). {} without one.
177
+ # @return [Hash{String => String}] each file => the source file
168
178
  def plugin_incoming
169
179
  plugin = @manifest&.plugin
170
180
  return {} unless plugin
@@ -173,7 +183,7 @@ module Samagotchi
173
183
  if (failure = BundleManifest.requires_chi_failure(@manifest.requires_chi, @chi_version))
174
184
  @warnings << "Plugin #{plugin[:file]} won't load: #{failure}"
175
185
  end
176
- { plugin[:file] => src }
186
+ part_sources.merge(plugin[:file] => src)
177
187
  end
178
188
 
179
189
  # The manifest's plugin file in the source, checked; nil without one.
@@ -188,6 +198,18 @@ module Samagotchi
188
198
  src
189
199
  end
190
200
 
201
+ # The manifest's plugin parts in the source, checked, in load order.
202
+ # @return [Hash{String => String}] part name => the source file
203
+ def part_sources
204
+ (@manifest&.plugin_parts || {}).keys.to_h do |part|
205
+ src = File.join(@bundle_dir, part)
206
+ raise Installer::InstallError, BundleManifest.missing_part(part) unless File.file?(src)
207
+ raise Installer::InstallError, "plugin part #{part} is a symlink (not installed)" if linked?(src)
208
+
209
+ [part, src]
210
+ end
211
+ end
212
+
191
213
  # The manifest's scripts in the source, checked.
192
214
  # @return [Hash{String => String}] file name => the source file
193
215
  def scripts_sources
@@ -259,7 +281,7 @@ module Samagotchi
259
281
  @results[result_key(kind_of_file, name)] = results[name]
260
282
  FileUtils.chmod(0o755, dest) if kind_of_file == :script && !@dev
261
283
  if (declared = declared_sha(kind_of_file, name)) && results[name].action.do == :write_incoming && @strict && !@dev
262
- warning = InstalledBundles::FileDigest.mismatch("#{kind_of_file} #{name}", dest, declared)
284
+ warning = InstalledBundles::FileDigest.mismatch(label(kind_of_file, name), dest, declared)
263
285
  @warnings << warning if warning
264
286
  end
265
287
  [name, dest]
@@ -281,10 +303,16 @@ module Samagotchi
281
303
  # guardrails/r.yml, the plugin's own file name, a script's scripts/s.sh.
282
304
  def result_key(kind_of_file, name) = kind_of_file == :plugin ? name : "#{AssetState::FOLDERS.fetch(kind_of_file)}/#{name}"
283
305
 
284
- # The manifest's sha256 for a plugin or script (hex), nil for a rule.
306
+ # How a file is named in a Checksum mismatch, the refusal and the --force
307
+ # warning alike: plugin plugin.rb, plugin part client.rb, script s.sh, rule r.yml.
308
+ def label(kind_of_file, name)
309
+ kind_of_file == :plugin && name != @manifest&.plugin&.dig(:file) ? "plugin part #{name}" : "#{kind_of_file} #{name}"
310
+ end
311
+
312
+ # The manifest's sha256 for a plugin file, a part or a script (hex), nil for a rule.
285
313
  def declared_sha(kind_of_file, name)
286
314
  case kind_of_file
287
- when :plugin then @manifest.checksum_for_plugin
315
+ when :plugin then name == @manifest.plugin[:file] ? @manifest.checksum_for_plugin : @manifest.checksum_for_part(name)
288
316
  when :script then @manifest.scripts[name].to_s.delete_prefix("sha256:")
289
317
  end
290
318
  end
@@ -30,8 +30,9 @@ module Samagotchi
30
30
  # it doesn't read)
31
31
  # rules guardrails/*.yml paths
32
32
  # plugin the installed plugin file, nil without one
33
+ # plugin_parts its parts' name => installed path, in load order
33
34
  # scripts file name => path; context_providers, block_renderers the parsed lists
34
- InstalledParts = Data.define(:record, :rules, :plugin, :scripts, :context_providers, :block_renderers)
35
+ InstalledParts = Data.define(:record, :rules, :plugin, :plugin_parts, :scripts, :context_providers, :block_renderers)
35
36
 
36
37
  attr_reader :built_files, :warnings, :placeholder_warnings, :out_path, :staging_dir
37
38
 
@@ -165,12 +166,27 @@ module Samagotchi
165
166
  record: record,
166
167
  rules: Dir.exist?(rules_dir) ? Dir.glob(File.join(rules_dir, "*.yml")).sort : [],
167
168
  plugin: plugin && File.file?(plugin) ? plugin : nil,
169
+ plugin_parts: installed_plugin_parts(name, prov, record, plugin),
168
170
  scripts: installed_scripts(prov, record),
169
171
  context_providers: manifest ? manifest.context_providers : [],
170
172
  block_renderers: manifest ? manifest.block_renderers : []
171
173
  )
172
174
  end
173
175
 
176
+ # The record's plugin parts on disk, name => path, in load order ({}
177
+ # when the plugin file itself isn't there: nothing of it is built).
178
+ # @raise [BuildError] a recorded part is missing: the build couldn't load
179
+ def installed_plugin_parts(name, prov, record, plugin)
180
+ return {} unless plugin && File.file?(plugin)
181
+
182
+ record.plugin.parts.keys.to_h do |part|
183
+ path = File.join(prov.plugin_dir, part)
184
+ raise BuildError, "the installed #{name}'s plugin part #{part} is missing" unless File.file?(path)
185
+
186
+ [part, path]
187
+ end
188
+ end
189
+
174
190
  # The memories, guardrails/, the plugin and scripts/ into the
175
191
  # staging dir, laid out as Installer reads a bundle.
176
192
  def stage_files(staging, candidates, parts)
@@ -180,6 +196,7 @@ module Samagotchi
180
196
  parts.rules.each { |src| FileUtils.cp(src, File.join(staging, "guardrails", File.basename(src))) }
181
197
  end
182
198
  FileUtils.cp(parts.plugin, File.join(staging, File.basename(parts.plugin))) if parts.plugin
199
+ parts.plugin_parts.each { |part, src| FileUtils.cp(src, File.join(staging, part)) }
183
200
  return if parts.scripts.empty?
184
201
 
185
202
  FileUtils.mkdir_p(File.join(staging, "scripts"))
@@ -204,7 +221,8 @@ module Samagotchi
204
221
  files: files_map,
205
222
  trust_level: trust_level,
206
223
  plugin: parts.plugin && { file: File.basename(parts.plugin), sha256: InstalledBundles::FileDigest.sha256(parts.plugin),
207
- required: manifest&.plugin_required },
224
+ required: manifest&.plugin_required,
225
+ parts: parts.plugin_parts.transform_values { |src| InstalledBundles::FileDigest.sha256(src) } },
208
226
  requires_chi: manifest&.requires_chi,
209
227
  needs: manifest&.needs,
210
228
  scripts: parts.scripts.transform_values { |src| InstalledBundles::FileDigest.sha256(src) },
@@ -87,7 +87,7 @@ module Samagotchi
87
87
 
88
88
  file = bundle.plugin.file
89
89
  { file: file, sha256: copy(provenance.plugin_path(bundle), File.join(dir, file), bundle.plugin.sha256),
90
- required: bundle.manifest.plugin_required }
90
+ required: bundle.manifest.plugin_required, parts: copies(bundle.plugin.parts, provenance.plugin_dir, dir) }
91
91
  end
92
92
  private_class_method :plugin
93
93
 
@@ -157,7 +157,17 @@ module Samagotchi
157
157
  end
158
158
  end
159
159
 
160
- def summary
160
+ # Every file the run read was already the bundle's, and nothing else
161
+ # was written or said: the bundle is current (`chi bundle upgrade`
162
+ # says so on its version line).
163
+ def current?
164
+ !@results.empty? && @results.values.all? { |result| result.word == :up_to_date } &&
165
+ @conflicts.empty? && !@source_change && !@reinstall
166
+ end
167
+
168
+ # @param current [Boolean] leave out the "Up to date" line and the
169
+ # "No files to install." fallback (the caller said it is current)
170
+ def summary(current: false)
161
171
  lines = []
162
172
  lines << "Source changes: #{@source_change.join(" → ")}" if @source_change
163
173
  installed = with_word(:installed)
@@ -190,14 +200,16 @@ module Samagotchi
190
200
  lines << "Removed (#{AssetInstaller::RETIRED}): #{retired.join(", ")}" unless retired.empty?
191
201
  lines << "Would remove (#{AssetInstaller::RETIRED}): #{would_retire.join(", ")}" unless would_retire.empty?
192
202
  lines << "Kept (local edits preserved): #{kept.join(", ")}" unless kept.empty?
193
- lines << "Up to date: #{up_to_date.join(", ")}" unless up_to_date.empty?
203
+ lines << "Up to date: #{up_to_date.join(", ")}" unless up_to_date.empty? || current
194
204
  lines << "Skipped: #{skipped.join(", ")}" unless skipped.empty?
195
205
  lines << trash_copy_line if trash_copy_line
196
206
  lines.concat(@warnings) unless @warnings.empty?
197
207
  lines.concat(@placeholder_warnings) unless @placeholder_warnings.empty?
198
208
  lines << reinstall_line if @reinstall
199
209
 
200
- lines.any? ? lines.join("\n") : "No files to install."
210
+ return lines.join("\n") if lines.any? || current
211
+
212
+ "No files to install."
201
213
  end
202
214
 
203
215
  # The one words for a record whose source can't be read again (relative,
@@ -684,6 +696,7 @@ module Samagotchi
684
696
  source_commit: @source_commit,
685
697
  guardrails_files: installed.guardrail_files,
686
698
  plugin_file: installed.plugin_file,
699
+ plugin_parts: installed.plugin_parts,
687
700
  plugin_required: @manifest.plugin&.dig(:required) == true,
688
701
  requires_chi: @manifest.requires_chi,
689
702
  needs: @manifest.needs,
@@ -169,6 +169,9 @@ module Samagotchi
169
169
  # @param plugin_file [String, nil] the installed plugin file; its name
170
170
  # and sha256 are recorded (the Engine checks it at load) with a base
171
171
  # snapshot
172
+ # @param plugin_parts [Hash{String => String}] its parts' name =>
173
+ # installed file, in load order (never sorted: it is the load order),
174
+ # recorded under the plugin as "parts" with a base snapshot each
172
175
  # @param plugin_required [Boolean] the manifest's plugin: required: true
173
176
  # (a guardrail plugin), recorded with it as "required": true, so the
174
177
  # Engine knows it whatever becomes of the kept manifest.yml
@@ -200,7 +203,7 @@ module Samagotchi
200
203
  # The record has no hooks ("hooks" => {}: class-file hooks are retired)
201
204
  # and an older record's hook bases go.
202
205
  def write(files:, scope:, version:, source_path:, trust_level: nil, source_commit: nil,
203
- guardrails_files: {}, plugin_file: nil, plugin_required: false, requires_chi: nil, needs: nil, marks: [], incoming_dir: nil, includes: nil,
206
+ guardrails_files: {}, plugin_file: nil, plugin_parts: {}, plugin_required: false, requires_chi: nil, needs: nil, marks: [], incoming_dir: nil, includes: nil,
204
207
  scripts_files: {}, context_providers: [], block_renderers: [], file_descriptions: {}, session_settings: [], session_setting_types: {}, settings: nil, setting_types: {},
205
208
  dev: false, manifest_from: nil)
206
209
  record_extra = format_record(read)&.extra || {}
@@ -274,6 +277,7 @@ module Samagotchi
274
277
  manifest_data["plugin"]["required"] = true if plugin_required
275
278
  FileUtils.mkdir_p(File.join(bases_dir, "plugin"))
276
279
  File.binwrite(plugin_base_path(File.basename(plugin_file.to_s)), content)
280
+ write_plugin_parts(manifest_data["plugin"], plugin_parts, dev)
277
281
  end
278
282
  manifest_data.merge!(mirror_fields(trust_level: trust_level, requires_chi: requires_chi, needs: needs,
279
283
  context_providers: context_providers, block_renderers: block_renderers,
@@ -294,6 +298,18 @@ module Samagotchi
294
298
  prune_incoming(marked.keys)
295
299
  end
296
300
 
301
+ # #write's plugin parts: "parts" under +entry+ (the record's plugin),
302
+ # in the order given, and a base snapshot of each.
303
+ def write_plugin_parts(entry, parts, dev)
304
+ return if parts.empty?
305
+
306
+ entry["parts"] = parts.to_h do |part, path|
307
+ File.binwrite(plugin_base_path(part), File.binread(path.to_s))
308
+ [part.to_s, dev ? InstalledBundles::Sha::DEV : InstalledBundles::FileDigest.sha256(path.to_s)]
309
+ end
310
+ end
311
+ private :write_plugin_parts
312
+
297
313
  # After a conflict was settled: each file's base becomes the incoming
298
314
  # file and its conflict mark goes. The rest of the manifest (its
299
315
  # description too) stays as is. A file whose incoming copy is gone keeps
@@ -645,6 +661,7 @@ module Samagotchi
645
661
  if bundle.plugin
646
662
  file = manifest.plugin && manifest.plugin[:file].to_s
647
663
  shas[file && File.basename(file) == bundle.plugin.file ? file : bundle.plugin.file] = bundle.plugin.sha256
664
+ bundle.plugin.parts.each { |part, sha| shas[part] = sha }
648
665
  end
649
666
  bundle.scripts.each { |file, sha| shas["scripts/#{file}"] = sha }
650
667
  bundle.guardrails.each { |file, sha| shas["guardrails/#{file}"] = sha }
@@ -31,6 +31,7 @@ module Samagotchi
31
31
  # files: a.md: sha256:<hex> (dir/a.md)
32
32
  # a.md:\n sha256: sha256:<hex> (dir/a.md, with description:)
33
33
  # plugin: file: p.rb\n sha256: sha256:<hex> (dir/p.rb)
34
+ # parts:\n c.rb: sha256:<hex> (dir/c.rb, a plugin part)
34
35
  # scripts: s.rb: sha256:<hex> (dir/scripts/s.rb)
35
36
  # Returns [text, [[relative file, old sha, new sha], ...]] for the lines
36
37
  # that changed. +text+ defaults to dir/manifest.yml. A named file that's
@@ -86,10 +87,10 @@ module Samagotchi
86
87
  # take a placeholder (`chi bundle check`) parse this text.
87
88
  def parseable(text) = text.gsub(/^(\s*(?:["']?[^"':\s][^"':]*["']?: )?)sha256:(?=[ \t]*(?:#[^\r\n]*)?\r?$)/, "\\1sha256:0")
88
89
 
89
- # The code files the manifest names (plugin, scripts), as paths
90
- # relative to the bundle dir.
90
+ # The code files the manifest names (plugin, its parts, scripts), as
91
+ # paths relative to the bundle dir.
91
92
  def coded(parsed, plugin_file)
92
- (plugin_file.is_a?(String) ? [plugin_file] : []) +
93
+ (plugin_file.is_a?(String) ? [plugin_file] : []) + keys(parsed["plugin"].is_a?(Hash) ? parsed["plugin"]["parts"] : nil) +
93
94
  keys(parsed["scripts"]).map { |s| File.join("scripts", s) }
94
95
  end
95
96
  private_class_method :coded
@@ -114,7 +115,8 @@ module Samagotchi
114
115
  m = line.match(/\A( sha256: )sha256:\h*#{TAIL}/) and return sub && [sub.delete("\"'"), m[1]]
115
116
  m = line.match(/\A( ["']?([^"':]+)["']?: )sha256:\h*#{TAIL}/) and [m[2], m[1]]
116
117
  when "plugin"
117
- m = line.match(/\A( sha256: )sha256:\h*#{TAIL}/) and plugin_file and [plugin_file, m[1]]
118
+ m = line.match(/\A( sha256: )sha256:\h*#{TAIL}/) and plugin_file and return [plugin_file, m[1]]
119
+ m = line.match(/\A( ["']?([^"':]+)["']?: )sha256:\h*#{TAIL}/) and sub == "parts" and [m[2], m[1]]
118
120
  when "scripts"
119
121
  m = line.match(/\A( ["']?([^"':]+)["']?: )sha256:\h*#{TAIL}/) and [File.join("scripts", m[2]), m[1]]
120
122
  end
@@ -308,7 +308,7 @@ module Samagotchi
308
308
  provenance = Provenance.new(name: name)
309
309
  rules = Dir.glob(File.join(source_dir, "guardrails", "*.yml")).sort
310
310
  .reject { |file| AssetInstaller.linked?(file, source_dir) }
311
- plugin = manifest.plugin ? { manifest.plugin[:file] => File.join(source_dir, manifest.plugin[:file]) } : {}
311
+ plugin = manifest.plugin_files.to_h { |file, _| [file, File.join(source_dir, file)] }
312
312
  scripts = manifest.scripts.keys.to_h { |file| [file, File.join(source_dir, "scripts", file)] }
313
313
  assets = AssetState.in(provenance.guardrails_dir, kind_of_file: :rule, recorded: bundle.guardrails,
314
314
  incoming: rules.to_h { |file| [File.basename(file), file] }) +
@@ -318,14 +318,18 @@ module Samagotchi
318
318
  assets.select(&:edited?).map(&:label)
319
319
  end
320
320
 
321
- # Installed rules and the plugin whose sha differs from the recorded
322
- # one (they didn't load), as guardrails/F, plugin/F.
321
+ # Installed rules and the plugin's files (its parts first, in the load
322
+ # order, then the file) whose sha differs from the recorded one (they
323
+ # didn't load), as guardrails/F, plugin/F.
323
324
  def edited_executables(name, bundle)
324
325
  provenance = Provenance.new(name: name)
325
326
  edited = []
326
327
  bundle.guardrails.each do |file, sha|
327
328
  edited << "guardrails/#{file}" if edited?(File.join(provenance.guardrails_dir, file), sha)
328
329
  end
330
+ bundle.plugin&.parts&.each do |part, sha|
331
+ edited << "plugin/#{part}" if edited?(File.join(provenance.plugin_dir, part), sha)
332
+ end
329
333
  plugin = provenance.plugin_path(bundle)
330
334
  edited << "plugin/#{File.basename(plugin)}" if plugin && edited?(plugin, bundle.plugin.sha256)
331
335
  edited
@@ -115,21 +115,30 @@ module Samagotchi
115
115
  end
116
116
 
117
117
  # A plugin's state word in `chi bundle status`, by its file refusal's kind.
118
- PLUGIN_STATES = { nil => "ok", file_unrecorded: "unrecorded", file_missing: "missing", file_changed: "modified" }.freeze
118
+ PLUGIN_STATES = { nil => "ok", file_unrecorded: "unrecorded", file_missing: "missing", file_changed: "modified",
119
+ parts_missing: "parts missing" }.freeze
119
120
 
120
- # The installed plugin: {file:, path:, state:, requires_chi:,
121
+ # The installed plugin: {file:, path:, state:, parts:, requires_chi:,
121
122
  # requires_failure:}; state is "ok", "unrecorded" (no sha256 recorded
122
- # for it), "missing" or "modified" (its sha256 differs from the
123
- # installed one), from the verdict (Dir#file_refusal(:plugin),
124
- # InstalledBundles::Standing): any but "ok" won't load. nil without one.
123
+ # for it), "missing", "modified" (its sha256 differs from the
124
+ # installed one) or "parts missing" (the kept manifest names parts the
125
+ # record hasn't), from the verdict (Dir#plugin_refusal,
126
+ # InstalledBundles::Standing): any but "ok" won't load, and neither does
127
+ # a plugin with a part that isn't "ok". The entry's state is the plugin
128
+ # file's; each part's is its own (parts: [{file:, state:}], in load
129
+ # order). nil without one.
125
130
  def self.plugin_status(provenance, bundle)
126
131
  path = provenance.plugin_path(bundle)
127
132
  return nil unless path
128
133
 
134
+ parts = bundle.plugin.parts.map do |part, sha|
135
+ { file: part, state: PLUGIN_STATES.fetch(provenance.file_refusal(:plugin, part, sha)&.kind) }
136
+ end
129
137
  refusal = provenance.file_refusal(:plugin, bundle.plugin.file, bundle.plugin.sha256)
138
+ refusal ||= provenance.plugin_refusal(bundle) if parts.all? { |part| part[:state] == "ok" }
130
139
  state = PLUGIN_STATES.fetch(refusal&.kind)
131
140
  standing = InstalledBundles::Standing.of(provenance.name, bundle)
132
- { file: File.basename(path), path: path, state: state, requires_chi: bundle.manifest.requires_chi,
141
+ { file: File.basename(path), path: path, state: state, parts: parts, requires_chi: bundle.manifest.requires_chi,
133
142
  requires_failure: standing.too_new? ? standing.refusal.text : nil }
134
143
  end
135
144