samagotchi 0.178.0 → 0.180.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -1
  3. data/docs/architecture.md +4 -2
  4. data/docs/bundles.md +48 -8
  5. data/docs/cli.md +3 -1
  6. data/docs/configuration.md +1 -1
  7. data/docs/context.md +32 -1
  8. data/docs/guardrails.md +2 -1
  9. data/docs/internals/attached-context.md +26 -4
  10. data/docs/internals/background-tasks.md +5 -1
  11. data/docs/internals/block-renderers.md +4 -3
  12. data/docs/internals/bridge.md +11 -2
  13. data/docs/internals/bundles.md +65 -34
  14. data/docs/internals/engine.md +1 -1
  15. data/docs/internals/web-frontend.md +81 -3
  16. data/docs/plugins.md +20 -5
  17. data/docs/releasing.md +3 -3
  18. data/docs/scheduling.md +4 -0
  19. data/docs/sessions.md +8 -2
  20. data/docs/testing.md +8 -1
  21. data/lib/samagotchi/block_renderers.rb +33 -16
  22. data/lib/samagotchi/bootstrap/bundles.rb +2 -2
  23. data/lib/samagotchi/bootstrap_command.rb +1 -1
  24. data/lib/samagotchi/bridge/card_wait.rb +34 -0
  25. data/lib/samagotchi/bridge/turn_accumulator.rb +22 -4
  26. data/lib/samagotchi/bundle_command/check.rb +10 -10
  27. data/lib/samagotchi/bundle_command/installed_check.rb +2 -2
  28. data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
  29. data/lib/samagotchi/bundle_command.rb +22 -18
  30. data/lib/samagotchi/bundle_manifest.rb +579 -0
  31. data/lib/samagotchi/bundle_needs.rb +9 -8
  32. data/lib/samagotchi/bundle_settings_check.rb +13 -9
  33. data/lib/samagotchi/bundles/claude-peer/manifest.yml +5 -3
  34. data/lib/samagotchi/bundles/claude-peer/plugin.rb +4 -4
  35. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +11 -6
  36. data/lib/samagotchi/bundles/codex-peer/manifest.yml +5 -3
  37. data/lib/samagotchi/bundles/codex-peer/plugin.rb +4 -3
  38. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +11 -6
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  41. data/lib/samagotchi/config.rb +2 -2
  42. data/lib/samagotchi/context_absorber.rb +36 -6
  43. data/lib/samagotchi/context_note.rb +8 -5
  44. data/lib/samagotchi/context_providers.rb +30 -29
  45. data/lib/samagotchi/context_sources.rb +42 -12
  46. data/lib/samagotchi/engine/messages.rb +1 -1
  47. data/lib/samagotchi/events.rb +6 -5
  48. data/lib/samagotchi/guardrail_wiring.rb +20 -21
  49. data/lib/samagotchi/guardrails/approval.rb +3 -2
  50. data/lib/samagotchi/guardrails/outside.rb +3 -3
  51. data/lib/samagotchi/{memory_bundle → installed_bundles}/bundle_hook.rb +1 -1
  52. data/lib/samagotchi/installed_bundles/dir.rb +91 -0
  53. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_digest.rb +1 -1
  54. data/lib/samagotchi/{memory_bundle → installed_bundles}/file_standing.rb +2 -2
  55. data/lib/samagotchi/{memory_bundle/installed_manifest.rb → installed_bundles/manifest.rb} +21 -21
  56. data/lib/samagotchi/{memory_bundle → installed_bundles}/plugin_ref.rb +2 -2
  57. data/lib/samagotchi/{memory_bundle/installed_bundle.rb → installed_bundles/record.rb} +17 -17
  58. data/lib/samagotchi/installed_bundles/sha.rb +41 -0
  59. data/lib/samagotchi/installed_bundles/standing.rb +65 -0
  60. data/lib/samagotchi/installed_bundles.rb +105 -0
  61. data/lib/samagotchi/memory_bundle/asset_installer.rb +7 -7
  62. data/lib/samagotchi/memory_bundle/builder.rb +13 -13
  63. data/lib/samagotchi/memory_bundle/file_state.rb +9 -9
  64. data/lib/samagotchi/memory_bundle/installed_copy.rb +6 -6
  65. data/lib/samagotchi/memory_bundle/installer.rb +33 -33
  66. data/lib/samagotchi/memory_bundle/listing.rb +5 -5
  67. data/lib/samagotchi/memory_bundle/manifest_standing.rb +7 -7
  68. data/lib/samagotchi/memory_bundle/merger.rb +15 -15
  69. data/lib/samagotchi/memory_bundle/profile.rb +8 -8
  70. data/lib/samagotchi/memory_bundle/provenance.rb +59 -192
  71. data/lib/samagotchi/memory_bundle/remerge.rb +16 -16
  72. data/lib/samagotchi/memory_bundle/shas.rb +2 -2
  73. data/lib/samagotchi/memory_bundle/shipped_history.rb +1 -1
  74. data/lib/samagotchi/memory_bundle/shipped_update.rb +17 -17
  75. data/lib/samagotchi/memory_bundle/status.rb +19 -16
  76. data/lib/samagotchi/memory_bundle/system_bundle.rb +12 -12
  77. data/lib/samagotchi/memory_bundle/trash.rb +2 -2
  78. data/lib/samagotchi/memory_bundle/uninstaller.rb +8 -8
  79. data/lib/samagotchi/memory_bundle.rb +2 -2
  80. data/lib/samagotchi/memory_command.rb +4 -4
  81. data/lib/samagotchi/{memory_bundle → memory_index}/entry_size.rb +8 -8
  82. data/lib/samagotchi/{memory_bundle/index_size.rb → memory_index/size.rb} +6 -6
  83. data/lib/samagotchi/{memory_bundle/index_sync.rb → memory_index/sync.rb} +5 -5
  84. data/lib/samagotchi/{memory_bundle/index_updater.rb → memory_index/updater.rb} +2 -2
  85. data/lib/samagotchi/memory_usage.rb +5 -5
  86. data/lib/samagotchi/muted_memories.rb +1 -1
  87. data/lib/samagotchi/peer_exchanges.rb +76 -0
  88. data/lib/samagotchi/plugin/context.rb +4 -0
  89. data/lib/samagotchi/plugin/loader.rb +35 -33
  90. data/lib/samagotchi/plugin/peer.rb +42 -11
  91. data/lib/samagotchi/project_subfolders.rb +9 -9
  92. data/lib/samagotchi/reply_wait/target.rb +11 -4
  93. data/lib/samagotchi/self_report.rb +14 -14
  94. data/lib/samagotchi/session_access/local.rb +16 -1
  95. data/lib/samagotchi/session_access/remote.rb +2 -1
  96. data/lib/samagotchi/session_config.rb +29 -19
  97. data/lib/samagotchi/session_manager/running_tasks.rb +15 -2
  98. data/lib/samagotchi/session_retention.rb +13 -4
  99. data/lib/samagotchi/session_stores.rb +3 -0
  100. data/lib/samagotchi/system_prompt.rb +4 -4
  101. data/lib/samagotchi/terminal_ui/attach_launcher.rb +5 -1
  102. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  103. data/lib/samagotchi/terminal_ui/formatting.rb +15 -5
  104. data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
  105. data/lib/samagotchi/terminal_ui/model_segments_text.rb +5 -5
  106. data/lib/samagotchi/terminal_ui.rb +4 -1
  107. data/lib/samagotchi/testing/bundle.rb +3 -3
  108. data/lib/samagotchi/testing/install.rb +3 -3
  109. data/lib/samagotchi/testing/sandbox.rb +2 -2
  110. data/lib/samagotchi/tool_runner.rb +14 -14
  111. data/lib/samagotchi/tools/memory.rb +22 -22
  112. data/lib/samagotchi/tools/task_runtime.rb +12 -3
  113. data/lib/samagotchi/update_command.rb +4 -4
  114. data/lib/samagotchi/version.rb +1 -1
  115. data/lib/samagotchi/web/app.rb +14 -1
  116. data/lib/samagotchi/web/message_display.rb +6 -0
  117. data/lib/samagotchi/web/participant_view.rb +1 -1
  118. data/lib/samagotchi/web/proxy_gate.rb +1 -0
  119. data/lib/samagotchi/web/public/app.js +13 -1
  120. data/lib/samagotchi/web/public/card_kinds.js +8 -3
  121. data/lib/samagotchi/web/public/cards_place.js +15 -1
  122. data/lib/samagotchi/web/public/context_chips.js +184 -49
  123. data/lib/samagotchi/web/public/ctx.js +1 -1
  124. data/lib/samagotchi/web/public/history_shape.js +8 -3
  125. data/lib/samagotchi/web/public/index.html +66 -0
  126. data/lib/samagotchi/web/public/peer_chip.js +171 -0
  127. data/lib/samagotchi/web/public/peer_data.js +119 -0
  128. data/lib/samagotchi/web/public/peer_exchange.js +83 -0
  129. data/lib/samagotchi/web/public/peer_links.js +161 -0
  130. data/lib/samagotchi/web/public/peer_note.js +49 -0
  131. data/lib/samagotchi/web/public/session_view.js +6 -1
  132. data/lib/samagotchi/web/public/stream_handlers.js +17 -4
  133. data/lib/samagotchi/web/public/turn_block.js +46 -8
  134. data/lib/samagotchi/web/public/turn_html.js +11 -2
  135. data/lib/samagotchi/web/public/turn_settle.js +117 -0
  136. data/lib/samagotchi/web/push/notifier.rb +2 -2
  137. data/lib/samagotchi/web/session_access_routes.rb +21 -1
  138. data/lib/samagotchi/web/session_hub.rb +20 -4
  139. data/lib/samagotchi/worker_boot.rb +4 -1
  140. metadata +24 -12
  141. data/lib/samagotchi/memory_bundle/manifest.rb +0 -581
@@ -0,0 +1,579 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require "digest"
5
+ require "fileutils"
6
+ require_relative "context_providers"
7
+ require_relative "version"
8
+
9
+ module Samagotchi
10
+ autoload :BlockRenderers, File.expand_path("block_renderers", __dir__)
11
+
12
+ # Parses and validates a bundle manifest.yml.
13
+ #
14
+ # Expected structure:
15
+ # name: my-bundle
16
+ # version: 1.0.0
17
+ # scope: system # optional — CLI --scope wins over this
18
+ # description: "…" # optional
19
+ # files:
20
+ # identity.md: sha256:abc123...
21
+ # skill_x.md: # or a mapping: the description is the
22
+ # sha256: sha256:def456... # memory's index.md line
23
+ # description: "Use when …"
24
+ # plugin: # optional — the bundle's plugin.rb (docs/plugins.md)
25
+ # file: plugin.rb
26
+ # sha256: sha256:0a1b...
27
+ # required: true # optional: a guardrail; when it fails to load
28
+ # # chi denies every tool call (docs/hooks.md)
29
+ # requires_chi: ">= 0.1.28" # optional — a Gem::Requirement for chi's VERSION
30
+ # requires_chi_next: true # optional, shipped bundles — ignored here:
31
+ # # `rake release:bump` raises requires_chi to
32
+ # # the released chi (docs/releasing.md)
33
+ # needs: # optional — outside commands the memories rely on
34
+ # - command: gh # (checked on PATH, never installed; docs/memory.md)
35
+ # why: reads PRs # optional
36
+ # hint: brew install gh # optional
37
+ # - jq # short form: just the command
38
+ # scripts: # optional — files in scripts/ a context
39
+ # pr_context.rb: sha256:… # provider's command runs (installed into
40
+ # # the bundle's own dir, scripts/)
41
+ # context_providers: # optional — URL → attached context source
42
+ # - match: '\Ahttps://…/pull/(\d+)' # (ContextProviders)
43
+ # name: 'pr-\1'
44
+ # cmd: '{ruby} {bundle_dir}/scripts/pr_context.rb {url}'
45
+ # why: GitHub PR # optional
46
+ # every_seconds: 300 # optional
47
+ # block_renderers: # optional — a fence's language → the scripts/
48
+ # - lang: mermaid # files chi web's page loads to draw it
49
+ # load: [lib.js, draw.js] # (BlockRenderers); each one a scripts: key
50
+ # session_settings: [cap] # optional — the settings a session may set
51
+ # # (chi --set cost-cap.cap=3), read by the
52
+ # # plugin from ctx.settings at call time;
53
+ # # or {cap: number}: each with the type
54
+ # # --set checks (SESSION_SETTING_TYPES)
55
+ # settings: [default] # optional — the keys config.yml bundles: <name>:
56
+ # # may have, as session_settings: is written (a
57
+ # # list, or {key: type}; a value may also be
58
+ # # any Hash or list under any); with it, another
59
+ # # key warns (BundleSettingsCheck). A session
60
+ # # setting needn't be listed twice
61
+ # includes: [a, b] # optional — a profile (meta bundle): the
62
+ # # shipped bundles it installs; its dir holds
63
+ # # only manifest.yml (MemoryBundle::Profile)
64
+ class BundleManifest
65
+ class ValidationError < StandardError; end
66
+
67
+ # Class-file bundle hooks (hooks/*.rb, the manifest's hooks:) are
68
+ # retired: chi installs and loads none. WORDS is the one wording of
69
+ # it, wherever chi meets one (the Engine's first-turn line, install,
70
+ # chi bundle check and status, chi update's row). A strict read of a
71
+ # manifest with a hooks: entry raises it (.for_key's message); a
72
+ # tolerant read (a kept manifest.yml) ignores the key.
73
+ class HooksRetired < ValidationError
74
+ WORDS = "class-file bundle hooks are retired: chi loads no hooks/*.rb; a bundle hooks events from its " \
75
+ "plugin.rb with chi.on, see docs/plugins.md"
76
+
77
+ # The manifest's hooks: key.
78
+ def self.for_key = new("hooks: #{WORDS}")
79
+
80
+ # A source's hooks/*.rb (+files+, relative), with or without the key.
81
+ def self.for_files(files) = new("#{files.join(", ")}: #{WORDS}")
82
+
83
+ # The source's hooks/*.rb, relative and sorted ([] for none).
84
+ def self.files_in(dir) = Dir.glob(File.join(dir, "hooks", "*.rb")).map { |f| "hooks/#{File.basename(f)}" }.sort
85
+
86
+ # Refuse a source's class-file hooks before parsing its manifest.
87
+ def self.refuse_source_files(dir)
88
+ files = files_in(dir)
89
+ raise for_files(files) unless files.empty?
90
+ end
91
+ end
92
+
93
+ # A plugin file is a plain .rb name in the bundle's top directory.
94
+ PLUGIN_FILE = /\A[A-Za-z0-9_][A-Za-z0-9_.-]*\.rb\z/
95
+ # A script is a plain file name in the bundle's scripts/.
96
+ SCRIPT_FILE = /\A[A-Za-z0-9_][A-Za-z0-9_.-]*\z/
97
+ # A need is a plain executable name: no path, no spaces.
98
+ NEED_COMMAND = /\A[A-Za-z0-9][A-Za-z0-9._+-]*\z/
99
+ # A bundle name, as `chi bundle install <name>` takes a shipped one.
100
+ BUNDLE_NAME = /\A[A-Za-z0-9][A-Za-z0-9_-]*\z/
101
+
102
+ # Every top-level manifest key this chi reads (requires_chi_next is known
103
+ # but read only by the release tooling: docs/releasing.md). A key not
104
+ # here is one this chi ignores: #unknown_keys, which `chi bundle check`
105
+ # and the Installer say.
106
+ KEYS = %w[name version scope description files hooks trust_level plugin requires_chi requires_chi_next needs
107
+ scripts context_providers block_renderers includes session_settings settings].freeze
108
+
109
+ # The first chi release that reads each manifest key or shape (from git:
110
+ # the first tag whose manifest.rb reads it), for `chi bundle check`'s
111
+ # requires-chi-floor on the manifest itself: a bundle whose requires_chi
112
+ # admits a chi that never saw the key. A key the first tag (v0.2.0)
113
+ # already reads has no entry. `files.description` is a files: entry given
114
+ # as a mapping, `*.types` a session_settings:/settings: given as a mapping
115
+ # of keys to types. A key
116
+ # whose release is not out yet waits here as a comment naming it, the way
117
+ # Plugin::Api::SINCE does, until `release:bump` gives it its version
118
+ # (docs/releasing.md).
119
+ SINCE = {
120
+ "includes" => "0.8.0",
121
+ "scripts" => "0.32.0",
122
+ "context_providers" => "0.32.0",
123
+ "files.description" => "0.34.0",
124
+ "session_settings" => "0.84.0",
125
+ "session_settings.types" => "0.92.0",
126
+ "settings.types" => "0.92.0",
127
+ "settings" => "0.143.0",
128
+ "block_renderers" => "0.151.0",
129
+ "plugin.required" => "0.157.0"
130
+ }.freeze
131
+
132
+ # files: name → "sha256:<hex>" (both forms); file_descriptions: name →
133
+ # the description a mapping gave, for the files that have one.
134
+ attr_reader :name, :version, :scope, :description, :files, :file_descriptions, :trust_level, :plugin, :requires_chi, :needs, :includes,
135
+ :scripts, :context_providers, :block_renderers, :session_settings, :session_setting_types, :settings, :setting_types, :unknown_keys
136
+
137
+ def initialize(path:)
138
+ @path = path
139
+ raw = load_mapping(path)
140
+ # Every key of the manifest, for #floor_keys to look at the shapes a
141
+ # newer chi reads.
142
+ @raw = raw
143
+ # A key this chi's parser never reads is one it ignores, in the order
144
+ # the manifest lists it.
145
+ @unknown_keys = raw.keys - KEYS
146
+ @name = require_str(raw, "name")
147
+ # The name is a directory under .bundles/: never a path.
148
+ if @name.match?(%r{[/\\\0]}) || %w[. ..].include?(@name)
149
+ raise ValidationError, "name: #{@name.inspect} is not a bundle name (no path separators, not . or ..)"
150
+ end
151
+
152
+ @version = require_str(raw, "version")
153
+ @scope = normalize_scope(raw["scope"])
154
+ @description = (raw["description"] || "").to_s
155
+ @files = parse_files(raw["files"] || {})
156
+ raise HooksRetired.for_key if self.class.lists_hooks?(raw["hooks"])
157
+
158
+ @file_descriptions = parse_file_descriptions(raw["files"])
159
+ @trust_level = (raw["trust_level"] || "experimental").to_s
160
+ @plugin = parse_plugin(raw["plugin"])
161
+ @requires_chi = parse_requires_chi(raw["requires_chi"])
162
+ @needs = self.class.parse_needs(raw["needs"])
163
+ @scripts = parse_scripts(raw["scripts"])
164
+ @context_providers = parse_context_providers(raw["context_providers"])
165
+ @block_renderers = parse_block_renderers(raw["block_renderers"])
166
+ @includes = parse_includes(raw["includes"])
167
+ @session_settings = self.class.parse_session_settings(raw["session_settings"])
168
+ @session_setting_types = self.class.parse_session_setting_types(raw["session_settings"])
169
+ # nil: the manifest says nothing of them (unlike settings: []).
170
+ @settings = raw["settings"].nil? ? nil : self.class.parse_session_settings(raw["settings"], key: "settings")
171
+ @setting_types = self.class.parse_session_setting_types(raw["settings"], key: "settings")
172
+ end
173
+
174
+ # Why the install refuses this bundle's session_settings: a key whose
175
+ # NAME.KEY is chi's own session setting (SessionConfig.clash, the
176
+ # words chi bundle check reports too), nil when none clashes.
177
+ # @return [String, nil]
178
+ def session_settings_clash
179
+ return nil if @session_settings.empty?
180
+
181
+ require_relative "session_config"
182
+ SessionConfig.clash(@name, @session_settings)
183
+ end
184
+
185
+ # A profile: it installs the bundles in includes instead of files.
186
+ def meta?
187
+ !@includes.empty?
188
+ end
189
+
190
+ # An installed bundle's kept manifest.yml read key by key
191
+ # (InstalledBundles::Manifest): each key parsed as #initialize parses it, in its
192
+ # own rescue and in this order, so a key that doesn't parse under this
193
+ # chi (a newer chi tightened it, or an older one wrote it) costs only
194
+ # that key, which reads as empty with its message in the problems:
195
+ # name, version (never checked: identity is the record's), scope;
196
+ # files and their descriptions, scripts, plugin (hooks: is ignored,
197
+ # HooksRetired); needs, context_providers; block_renderers
198
+ # (against +fallback_scripts+ when scripts: failed); includes (after
199
+ # what its check reads); session_settings with its types, settings
200
+ # with theirs (one raw value each, so one problem); requires_chi,
201
+ # trust_level, description. Then unknown_keys.
202
+ # @param fallback_scripts [Array<String>] the script names block_renderers
203
+ # is checked against when scripts: doesn't parse (the record's)
204
+ # @return [Array(BundleManifest, Hash{String => String})] the manifest and
205
+ # key => message for each key that didn't parse
206
+ # @raise [ValidationError] the file isn't YAML or isn't a mapping
207
+ def self.tolerant(path:, fallback_scripts: [])
208
+ manifest = allocate
209
+ [manifest, manifest.send(:read_tolerantly, path, fallback_scripts)]
210
+ end
211
+
212
+ # Whether a manifest's hooks: value lists anything (none, {} and []
213
+ # don't: a manifest may keep an empty key).
214
+ def self.lists_hooks?(raw) = !(raw.nil? || ((raw.is_a?(Hash) || raw.is_a?(Array)) && raw.empty?))
215
+
216
+ def self.read(dir:)
217
+ manifest_path = File.join(dir, "manifest.yml")
218
+ raise ValidationError, "manifest.yml not found in #{dir}" unless File.exist?(manifest_path)
219
+
220
+ new(path: manifest_path)
221
+ end
222
+
223
+ # Returns the expected sha256 hex digest for a given file key
224
+ # (e.g. "identity.md"), with the "sha256:" prefix stripped, nil when
225
+ # the entry declares none (an empty value is nothing to verify).
226
+ def checksum_for(file_key)
227
+ raw = @files[file_key]
228
+ return nil unless raw
229
+
230
+ hex = raw.start_with?("sha256:") ? raw[7..] : raw
231
+ hex unless hex.nil? || hex.empty?
232
+ end
233
+
234
+ # @return [String, nil] the plugin's sha256 hex, "sha256:" stripped
235
+ def checksum_for_plugin
236
+ sha = @plugin && @plugin[:sha256].to_s
237
+ return nil if sha.nil? || sha.empty?
238
+
239
+ sha.delete_prefix("sha256:")
240
+ end
241
+
242
+ # Why chi +version+ can't load this bundle's plugin, or nil when it can
243
+ # (or the bundle names no requirement).
244
+ def self.requires_chi_failure(requirement, version)
245
+ return nil if requirement.nil? || requirement.to_s.strip.empty?
246
+ return nil if Gem::Requirement.new(*requirement.to_s.split(",").map(&:strip)).satisfied_by?(Gem::Version.new(version.to_s))
247
+
248
+ "it requires chi #{requirement} (this is chi #{version})"
249
+ rescue ArgumentError, EncodingError => e
250
+ # Gem::Requirement::BadRequirementError is an ArgumentError; bytes that
251
+ # aren't UTF-8 (a record another chi wrote) raise an EncodingError out
252
+ # of Gem::Requirement. Either way this chi can't read the requirement,
253
+ # which is a failure: the bundle is refused, not loaded.
254
+ "its requires_chi #{requirement.inspect} is not a version requirement (#{e.message})"
255
+ end
256
+
257
+ # What an unknown manifest key means, said once (docs/cli.md): the
258
+ # Installer and `chi bundle check` add their own fix to it.
259
+ def self.unknown_key_line(key, version = Samagotchi::VERSION)
260
+ "this chi (#{version}) doesn't know the manifest key #{key}:, so it ignores it"
261
+ end
262
+
263
+ # The SINCE keys this manifest actually uses, each with the chi release
264
+ # that first read it: the plain keys, and the shapes only a newer chi
265
+ # reads — a files: entry given as a mapping, a session_settings:/settings:
266
+ # given as a mapping of keys to types.
267
+ # @return [Hash{String => String}]
268
+ def floor_keys
269
+ raw = @raw
270
+ found = {}
271
+ found["includes"] = SINCE["includes"] unless @includes.empty?
272
+ found["scripts"] = SINCE["scripts"] unless @scripts.empty?
273
+ found["context_providers"] = SINCE["context_providers"] unless @context_providers.empty?
274
+ found["block_renderers"] = SINCE["block_renderers"] unless @block_renderers.empty?
275
+ found["plugin.required"] = SINCE["plugin.required"] if @plugin&.dig(:required) && SINCE.key?("plugin.required")
276
+ found["session_settings"] = SINCE["session_settings"] unless @session_settings.empty?
277
+ found["settings"] = SINCE["settings"] unless @settings.nil?
278
+ found["files.description"] = SINCE["files.description"] if raw["files"].is_a?(Hash) && raw["files"].values.any?(Hash)
279
+ found["session_settings.types"] = SINCE["session_settings.types"] if raw["session_settings"].is_a?(Hash)
280
+ found["settings.types"] = SINCE["settings.types"] if raw["settings"].is_a?(Hash)
281
+ found
282
+ end
283
+
284
+ # Writes a fresh manifest.yml from computed checksums at `dir`.
285
+ # +file_descriptions+ (name → text) writes those files as mappings.
286
+ def self.write(dir:, name:, version:, files:, scope: nil, description: "", trust_level: nil,
287
+ plugin: nil, requires_chi: nil, needs: nil, scripts: {}, context_providers: [], block_renderers: [], file_descriptions: {},
288
+ session_settings: [], session_setting_types: {}, settings: nil, setting_types: {})
289
+ FileUtils.mkdir_p(dir)
290
+ manifest = {
291
+ "name" => name,
292
+ "version" => version,
293
+ "description" => description
294
+ }
295
+ manifest["scope"] = scope if scope
296
+ manifest["files"] = files.to_h do |key, sha| # { "file.md" => "sha256:abc..." }
297
+ text = file_descriptions[key].to_s.strip
298
+ [key, text.empty? ? sha : { "sha256" => sha, "description" => text }]
299
+ end
300
+ manifest["trust_level"] = trust_level.to_s if trust_level && !trust_level.to_s.empty?
301
+ if plugin
302
+ sha = plugin[:sha256].to_s
303
+ manifest["plugin"] = { "file" => plugin[:file].to_s, "sha256" => sha.start_with?("sha256:") ? sha : "sha256:#{sha}" }
304
+ manifest["plugin"]["required"] = true if plugin[:required]
305
+ end
306
+ manifest["requires_chi"] = requires_chi.to_s if requires_chi && !requires_chi.to_s.empty?
307
+ needs = parse_needs(needs)
308
+ manifest["needs"] = needs.map { |n| n.transform_keys(&:to_s).compact } unless needs.empty?
309
+ manifest["scripts"] = scripts.transform_keys(&:to_s) unless scripts.empty?
310
+ manifest["context_providers"] = context_providers.map(&:to_h) unless context_providers.empty?
311
+ manifest["block_renderers"] = block_renderers.map(&:to_h) unless block_renderers.empty?
312
+ manifest["session_settings"] = session_settings_entry(session_settings, session_setting_types) unless Array(session_settings).empty?
313
+ manifest["settings"] = session_settings_entry(settings, setting_types) unless settings.nil?
314
+ File.write(File.join(dir, "manifest.yml"), YAML.dump(manifest))
315
+ end
316
+
317
+ # A setting key a session may set (SessionConfig::KEY).
318
+ SESSION_SETTING = /\A[A-Za-z0-9_][A-Za-z0-9_-]*\z/
319
+
320
+ # The types a session setting may be given (session_settings: {key:
321
+ # type}), checked by SessionConfig.check!: number (or off),
322
+ # boolean, string; any (or a list's key) takes every scalar.
323
+ SESSION_SETTING_TYPES = %w[number boolean string any].freeze
324
+
325
+ # session_settings: (or settings:, +key+) → the keys, [] when absent: a
326
+ # list of plain key names, or a mapping of them to types; anything else
327
+ # is a ValidationError.
328
+ def self.parse_session_settings(raw, key: "session_settings")
329
+ return [] if raw.nil?
330
+
331
+ keys = raw.is_a?(Hash) && raw.values.all?(String) ? raw.keys : raw
332
+ keys = nil unless keys.is_a?(Array)
333
+ unless keys&.all? { |name| (name.is_a?(String) || name.is_a?(Symbol)) && name.to_s.match?(SESSION_SETTING) }
334
+ raise ValidationError, "#{key}: a list of setting names, or a mapping of them to types (#{raw.inspect})"
335
+ end
336
+
337
+ keys.map(&:to_s).uniq
338
+ end
339
+
340
+ # session_settings: (or settings:, +key+) → {key => type} for the keys a mapping types
341
+ # (any left out), {} for a list or none.
342
+ # @raise [ValidationError] a type that isn't one of SESSION_SETTING_TYPES
343
+ def self.parse_session_setting_types(raw, key: "session_settings")
344
+ return {} unless raw.is_a?(Hash)
345
+
346
+ raw.each_with_object({}) do |(name, type), types|
347
+ unless SESSION_SETTING_TYPES.include?(type)
348
+ raise ValidationError, "#{key}: #{name}'s type is #{SESSION_SETTING_TYPES[0..-2].join(", ")} or " \
349
+ "#{SESSION_SETTING_TYPES.last}, not #{type.inspect}"
350
+ end
351
+ types[name.to_s] = type unless type == "any"
352
+ end
353
+ end
354
+
355
+ # session_settings: as written back: a list without types, else a
356
+ # mapping (an untyped key as any).
357
+ def self.session_settings_entry(keys, types)
358
+ keys = Array(keys).map(&:to_s)
359
+ return keys if types.nil? || types.empty?
360
+
361
+ keys.to_h { |key| [key, types[key] || "any"] }
362
+ end
363
+
364
+ # needs: → [{command:, why:, hint:}] (why/hint a String or nil), [] when
365
+ # absent. Takes the manifest's string-keyed YAML or the symbol-keyed
366
+ # form provenance stores. Duplicates merge (the first one's why/hint
367
+ # win); a list that isn't one, or a command that isn't a plain name,
368
+ # is a ValidationError.
369
+ def self.parse_needs(raw)
370
+ return [] if raw.nil?
371
+ raise ValidationError, "needs: must be a list of commands" unless raw.is_a?(Array)
372
+
373
+ raw.each_with_object([]) do |item, acc|
374
+ unless item.is_a?(Hash) || item.is_a?(String) || item.is_a?(Symbol)
375
+ raise ValidationError, "needs: each item must be a command name or a mapping with command:, not #{item.inspect}"
376
+ end
377
+
378
+ need = item.is_a?(Hash) ? item.transform_keys(&:to_s) : { "command" => item }
379
+ command = need["command"].to_s.strip
380
+ raise ValidationError, "needs: #{command.inspect} is not a plain command name" unless command.match?(NEED_COMMAND)
381
+ next if acc.any? { |n| n[:command] == command }
382
+
383
+ acc << { command: command, why: optional_text(need["why"]), hint: optional_text(need["hint"]) }
384
+ end
385
+ end
386
+
387
+ def self.optional_text(value)
388
+ text = value.to_s.strip
389
+ text.empty? ? nil : text
390
+ end
391
+ private_class_method :optional_text
392
+
393
+ private
394
+
395
+ # BundleManifest.tolerant's read: the order and the keys are its comment's.
396
+ def read_tolerantly(path, fallback_scripts)
397
+ @path = path
398
+ raw = @raw = load_mapping(path)
399
+ problems = {}
400
+ @name = raw["name"].to_s
401
+ @version = raw["version"].to_s
402
+ @scope = normalize_scope(raw["scope"])
403
+ @files, @file_descriptions = tolerate(problems, "files", [{}, {}]) do
404
+ [parse_files(raw["files"] || {}), parse_file_descriptions(raw["files"])]
405
+ end
406
+ @scripts = tolerate(problems, "scripts", {}) { parse_scripts(raw["scripts"]) }
407
+ @plugin = tolerate(problems, "plugin", nil) { parse_plugin(raw["plugin"]) }
408
+ # An old kept manifest's hooks: is no problem: it isn't read (HooksRetired).
409
+ @needs = tolerate(problems, "needs", []) { self.class.parse_needs(raw["needs"]) }
410
+ @context_providers = tolerate(problems, "context_providers", []) { parse_context_providers(raw["context_providers"]) }
411
+ script_names = problems.key?("scripts") ? fallback_scripts.map(&:to_s) : @scripts.keys
412
+ @block_renderers = tolerate(problems, "block_renderers", []) { parse_block_renderers(raw["block_renderers"], script_names) }
413
+ @includes = tolerate(problems, "includes", []) { parse_includes(raw["includes"]) }
414
+ @session_settings, @session_setting_types = tolerate(problems, "session_settings", [[], {}]) do
415
+ [self.class.parse_session_settings(raw["session_settings"]), self.class.parse_session_setting_types(raw["session_settings"])]
416
+ end
417
+ @settings, @setting_types = tolerate(problems, "settings", [nil, {}]) do
418
+ next [nil, {}] if raw["settings"].nil?
419
+
420
+ [self.class.parse_session_settings(raw["settings"], key: "settings"),
421
+ self.class.parse_session_setting_types(raw["settings"], key: "settings")]
422
+ end
423
+ @requires_chi = tolerate(problems, "requires_chi", nil) { parse_requires_chi(raw["requires_chi"]) }
424
+ @trust_level = tolerate(problems, "trust_level", "experimental") { (raw["trust_level"] || "experimental").to_s }
425
+ @description = tolerate(problems, "description", "") { (raw["description"] || "").to_s }
426
+ @unknown_keys = raw.keys - KEYS
427
+ problems
428
+ end
429
+
430
+ # The block's value, else +empty+ with the key's problem noted. Anything
431
+ # a parser raises counts: the file is a load-time input, and one key
432
+ # must never cost the bundle.
433
+ def tolerate(problems, key, empty)
434
+ yield
435
+ rescue StandardError => e
436
+ problems[key] = e.message
437
+ empty
438
+ end
439
+
440
+ # The manifest.yml's top-level mapping ({} for an empty file); YAML that
441
+ # doesn't parse, or isn't a mapping, raises ValidationError, as every
442
+ # other manifest problem does.
443
+ def load_mapping(path)
444
+ raw = YAML.load_file(path) || {}
445
+ raise ValidationError, "manifest.yml is not a YAML mapping in #{File.dirname(path)}" unless raw.is_a?(Hash)
446
+
447
+ raw
448
+ rescue Psych::SyntaxError => e
449
+ raise ValidationError, "manifest.yml is not valid YAML in #{File.dirname(path)}: line #{e.line}, column #{e.column}: #{e.problem}"
450
+ rescue Psych::Exception => e
451
+ raise ValidationError, "manifest.yml is not valid YAML in #{File.dirname(path)}: #{e.message}"
452
+ end
453
+
454
+ def require_str(hash, key)
455
+ val = hash[key]
456
+ return val if val.is_a?(String) && !val.empty?
457
+
458
+ raise ValidationError, "manifest missing required field: #{key}"
459
+ end
460
+
461
+ def normalize_scope(val)
462
+ return nil if val.nil?
463
+
464
+ v = val.to_s.strip.downcase
465
+ %w[project system].include?(v) ? v : nil
466
+ end
467
+
468
+ def parse_files(raw)
469
+ return {} unless raw.is_a?(Hash)
470
+
471
+ raw.each_with_object({}) do |(k, v), acc|
472
+ next unless k.is_a?(String) && !k.empty?
473
+
474
+ str = (v.is_a?(Hash) ? v["sha256"] : v).to_s
475
+ acc[k] = if str.start_with?("sha256:")
476
+ str
477
+ else
478
+ "sha256:#{str}"
479
+ end
480
+ end
481
+ end
482
+
483
+ # The descriptions of the files: entries given as a mapping.
484
+ def parse_file_descriptions(raw)
485
+ return {} unless raw.is_a?(Hash)
486
+
487
+ raw.each_with_object({}) do |(k, v), acc|
488
+ next unless k.is_a?(String) && v.is_a?(Hash)
489
+
490
+ text = v["description"].to_s.strip
491
+ acc[k] = text unless text.empty?
492
+ end
493
+ end
494
+
495
+ # plugin: {file:, sha256:, required:} → {file:, sha256:} (sha "" when
496
+ # not given) with required: true when it says so, or nil; a file that
497
+ # isn't a plain .rb name, or a required: that isn't true or false, is a
498
+ # validation error.
499
+ def parse_plugin(raw)
500
+ return nil if raw.nil?
501
+ raise ValidationError, "plugin: must be a mapping with file: and sha256:" unless raw.is_a?(Hash)
502
+
503
+ file = (raw["file"] || raw[:file]).to_s.strip
504
+ unless file.match?(PLUGIN_FILE)
505
+ raise ValidationError, "plugin file must be a .rb file name in the bundle's top directory, not #{file.inspect}"
506
+ end
507
+
508
+ sha = (raw["sha256"] || raw[:sha256]).to_s.strip
509
+ sha = "sha256:#{sha}" unless sha.empty? || sha.start_with?("sha256:")
510
+ required = raw.key?("required") ? raw["required"] : raw[:required]
511
+ raise ValidationError, "plugin required: must be true or false, not #{required.inspect}" unless [nil, true, false].include?(required)
512
+
513
+ required ? { file: file, sha256: sha, required: true } : { file: file, sha256: sha }
514
+ end
515
+
516
+ # scripts: {file => sha256} → the same, "sha256:" prefixed; {} when absent.
517
+ def parse_scripts(raw)
518
+ return {} if raw.nil?
519
+ raise ValidationError, "scripts: must be a mapping of file name to sha256" unless raw.is_a?(Hash)
520
+
521
+ raw.to_h do |file, sha|
522
+ file = file.to_s
523
+ raise ValidationError, "scripts: #{file.inspect} isn't a plain file name in scripts/" unless file.match?(SCRIPT_FILE)
524
+
525
+ sha = sha.to_s.strip
526
+ [file, sha.empty? || sha.start_with?("sha256:") ? sha : "sha256:#{sha}"]
527
+ end
528
+ end
529
+
530
+ # @return [Array<ContextProviders::Provider>]
531
+ def parse_context_providers(raw)
532
+ ContextProviders.parse_list(raw)
533
+ rescue ContextProviders::Invalid => e
534
+ raise ValidationError, e.message
535
+ end
536
+
537
+ # @param script_names [Array<String>] the scripts: keys each load must be
538
+ # @return [Array<BlockRenderers::Renderer>] each load is a scripts: key
539
+ def parse_block_renderers(raw, script_names = @scripts.keys)
540
+ return [] if raw.nil?
541
+
542
+ renderers = BlockRenderers.parse_list(raw)
543
+ renderers.each do |renderer|
544
+ missing = renderer.load - script_names
545
+ raise ValidationError, "block_renderers: #{renderer.lang} loads #{missing.join(", ")}, not under scripts:" unless missing.empty?
546
+ end
547
+ renderers
548
+ rescue BlockRenderers::Invalid => e
549
+ raise ValidationError, e.message
550
+ end
551
+
552
+ # includes: → the names in order, duplicates dropped; [] when absent.
553
+ # A meta ships nothing of its own, so files, hooks or a plugin next
554
+ # to it is a ValidationError.
555
+ def parse_includes(raw)
556
+ return [] if raw.nil?
557
+ raise ValidationError, "includes: must be a list of bundle names" unless raw.is_a?(Array)
558
+
559
+ names = raw.map do |item|
560
+ name = item.to_s.strip
561
+ raise ValidationError, "includes: #{item.inspect} is not a bundle name" unless name.match?(BUNDLE_NAME)
562
+
563
+ name
564
+ end.uniq
565
+ if !names.empty? && (!@files.empty? || @plugin || !@scripts.empty?)
566
+ raise ValidationError, "a bundle with includes: holds only its includes (no files, plugin or scripts)"
567
+ end
568
+
569
+ names
570
+ end
571
+
572
+ def parse_requires_chi(raw)
573
+ return nil if raw.nil?
574
+
575
+ text = raw.to_s.strip
576
+ text.empty? ? nil : text
577
+ end
578
+ end
579
+ end
@@ -1,12 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "installed_bundles"
4
+
3
5
  module Samagotchi
6
+ autoload :BundleManifest, File.expand_path("bundle_manifest", __dir__)
4
7
  autoload :MutedMemories, File.expand_path("muted_memories", __dir__)
5
8
  autoload :Log, File.expand_path("log", __dir__)
6
- module MemoryBundle
7
- autoload :Provenance, File.expand_path("memory_bundle/provenance", __dir__)
8
- autoload :Manifest, File.expand_path("memory_bundle/manifest", __dir__)
9
- end
10
9
 
11
10
  # The outside commands a bundle declares in its manifest's `needs:`
12
11
  # (docs/memory.md). Advisory only: a PATH lookup in Ruby, no subprocess,
@@ -32,7 +31,7 @@ module Samagotchi
32
31
  end
33
32
 
34
33
  # "[needs gh, jq: not found on PATH]", or nil when nothing is missing.
35
- # No em dash: IndexUpdater.extract_description splits on " — ".
34
+ # No em dash: MemoryIndex::Updater.extract_description splits on " — ".
36
35
  def self.marker(missing)
37
36
  commands = Array(missing).map { |need| need[:command] }
38
37
  return nil if commands.empty?
@@ -47,7 +46,7 @@ module Samagotchi
47
46
  def self.annotate_index(text, scope, path: ENV["PATH"], bundles_dir: nil)
48
47
  return text if text.nil? || text.empty?
49
48
 
50
- markers = entry_markers(scope, path: path, bundles_dir: bundles_dir || MemoryBundle::Provenance.bundles_dir)
49
+ markers = entry_markers(scope, path: path, bundles_dir: bundles_dir || InstalledBundles.dir)
51
50
  return text if markers.empty?
52
51
 
53
52
  text.each_line.map do |line|
@@ -65,8 +64,10 @@ module Samagotchi
65
64
  # entry name → marker, for the installed bundles of +scope+ with a
66
65
  # missing need. A manifest.json or needs: that doesn't parse is skipped.
67
66
  def self.entry_markers(scope, path:, bundles_dir:)
68
- MemoryBundle::Provenance.each_installed(dir: bundles_dir).each_with_object({}) do |(_name, bundle), acc|
69
- next if bundle.error? || bundle.effective_scope != scope.to_s
67
+ InstalledBundles.standings(dir: bundles_dir).each_with_object({}) do |standing, acc|
68
+ bundle = standing.record
69
+ # A bundle too new for this chi keeps its markers: its memories are read.
70
+ next if standing.unreadable? || bundle.effective_scope != scope.to_s
70
71
 
71
72
  needs = bundle.manifest.needs
72
73
  next if needs.empty?
@@ -6,7 +6,7 @@ require_relative "atomic_file"
6
6
  require_relative "config"
7
7
  require_relative "paths"
8
8
  require_relative "session_config"
9
- require_relative "memory_bundle/provenance"
9
+ require_relative "installed_bundles"
10
10
 
11
11
  module Samagotchi
12
12
  # config.yml `bundles:` against what's installed, for a typo that would
@@ -14,7 +14,8 @@ module Samagotchi
14
14
  # value's type a manifest's settings: rules out. A config file only warns:
15
15
  # the rest of it still runs, and `chi --set` is what refuses
16
16
  # (SessionConfig.check!, in the same words). A manifest with no settings:
17
- # (a record from before them too) has its keys left alone. A digest of the
17
+ # (a record from before them too) has its keys left alone; one this chi is
18
+ # too old for (requires_chi) gets one line saying why. A digest of the
18
19
  # lines last shown is stamped in $XDG_STATE_HOME/samagotchi/bundles_warned.
19
20
  module BundleSettingsCheck
20
21
  STAMP_FILE = "bundles_warned"
@@ -23,16 +24,19 @@ module Samagotchi
23
24
 
24
25
  # @param section [Hash{String => Hash}] ConfigFile.bundle_settings
25
26
  # @return [Array<String>] one line per finding
26
- def warnings(section, dir: MemoryBundle::Provenance.bundles_dir)
27
+ def warnings(section, dir: InstalledBundles.dir)
27
28
  return [] if section.empty?
28
29
 
29
- installed = MemoryBundle::Provenance.each_installed(dir: dir).to_h
30
+ installed = InstalledBundles.standings(dir: dir).to_h { |standing| [standing.name, standing] }
30
31
  section.flat_map do |name, values|
31
- bundle = installed[name]
32
- next ["config.yml bundles: #{name}: #{SessionConfig.no_installed_bundle(name)}#{near(name, installed.keys)}"] unless bundle
33
- next [] if bundle.error?
32
+ standing = installed[name]
33
+ next ["config.yml bundles: #{name}: #{SessionConfig.no_installed_bundle(name)}#{near(name, installed.keys)}"] unless standing
34
+ next [] if standing.unreadable?
35
+ # One this chi is too old for isn't used: its keys aren't checked
36
+ # against a manifest this chi may not read right.
37
+ next ["config.yml bundles: #{name}: #{SessionConfig.unusable(name, standing.refusal.text)}"] if standing.too_new?
34
38
 
35
- record_warnings(bundle.manifest, values)
39
+ record_warnings(standing.record.manifest, values)
36
40
  end
37
41
  end
38
42
 
@@ -64,7 +68,7 @@ module Samagotchi
64
68
 
65
69
  # One bundle's +values+ against its manifest (an installed one's or a
66
70
  # source's); none while it declares no settings:.
67
- # @param manifest [MemoryBundle::InstalledManifest, MemoryBundle::Manifest]
71
+ # @param manifest [InstalledBundles::Manifest, BundleManifest]
68
72
  # name, settings, session_settings, setting_types
69
73
  # @return [Array<String>]
70
74
  def record_warnings(manifest, values)