samagotchi 0.178.0 → 0.179.0

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