samagotchi 0.193.0 → 0.195.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 (191) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +116 -1
  3. data/docs/bundle-authoring.md +2 -2
  4. data/docs/bundles.md +223 -12
  5. data/docs/cli.md +27 -11
  6. data/docs/configuration.md +93 -6
  7. data/docs/desktop.md +3 -0
  8. data/docs/guardrails.md +11 -1
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/attached-context.md +2 -0
  11. data/docs/internals/bridge.md +4 -0
  12. data/docs/internals/engine.md +59 -4
  13. data/docs/internals/knowledge.md +205 -0
  14. data/docs/internals/pages.md +17 -9
  15. data/docs/internals/panes.md +104 -0
  16. data/docs/internals/peers.md +102 -5
  17. data/docs/internals/prompt-caching.md +4 -0
  18. data/docs/internals/session-lifecycle.md +9 -2
  19. data/docs/internals/web-frontend.md +16 -4
  20. data/docs/memory.md +4 -2
  21. data/docs/pages.md +72 -1
  22. data/docs/peers.md +90 -5
  23. data/docs/plugins.md +100 -6
  24. data/docs/releasing.md +1 -1
  25. data/docs/scheduling.md +4 -0
  26. data/docs/sessions.md +23 -7
  27. data/docs/sub-agent.md +6 -4
  28. data/docs/system-one.md +4 -0
  29. data/docs/testing.md +5 -0
  30. data/lib/samagotchi/bridge/card_store.rb +1 -1
  31. data/lib/samagotchi/broadcast/triage_model.rb +17 -0
  32. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -5
  33. data/lib/samagotchi/bundles/claude-peer/plugin.rb +24 -5
  34. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +28 -7
  35. data/lib/samagotchi/bundles/claude-peer/scripts/pair +31 -8
  36. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -5
  37. data/lib/samagotchi/bundles/codex-peer/plugin.rb +62 -6
  38. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +23 -2
  39. data/lib/samagotchi/bundles/codex-peer/scripts/pair +28 -7
  40. data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
  41. data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
  42. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
  43. data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
  44. data/lib/samagotchi/bundles/knowledge/adapters.rb +205 -0
  45. data/lib/samagotchi/bundles/knowledge/catalog.rb +151 -0
  46. data/lib/samagotchi/bundles/knowledge/chi_adapters.rb +160 -0
  47. data/lib/samagotchi/bundles/knowledge/chunker.rb +55 -0
  48. data/lib/samagotchi/bundles/knowledge/github.rb +246 -0
  49. data/lib/samagotchi/bundles/knowledge/manifest.yml +25 -0
  50. data/lib/samagotchi/bundles/knowledge/plugin.rb +788 -0
  51. data/lib/samagotchi/bundles/knowledge/query.rb +30 -0
  52. data/lib/samagotchi/bundles/knowledge/query_log.rb +55 -0
  53. data/lib/samagotchi/bundles/knowledge/refresh.rb +133 -0
  54. data/lib/samagotchi/bundles/knowledge/store.rb +264 -0
  55. data/lib/samagotchi/bundles/reflect/manifest.yml +17 -0
  56. data/lib/samagotchi/bundles/reflect/scripts/reflect.rb +439 -0
  57. data/lib/samagotchi/bundles/reflect/skill_reflect.md +100 -0
  58. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  59. data/lib/samagotchi/chi_invocation.rb +7 -0
  60. data/lib/samagotchi/client.rb +18 -0
  61. data/lib/samagotchi/codex_rollout.rb +93 -0
  62. data/lib/samagotchi/config.rb +15 -6
  63. data/lib/samagotchi/effective_model.rb +28 -2
  64. data/lib/samagotchi/engine/cards.rb +9 -4
  65. data/lib/samagotchi/engine/hooks.rb +8 -0
  66. data/lib/samagotchi/engine/models.rb +180 -7
  67. data/lib/samagotchi/engine/side_requests.rb +72 -13
  68. data/lib/samagotchi/engine/toolkit.rb +1 -1
  69. data/lib/samagotchi/engine/turn_helpers.rb +1 -1
  70. data/lib/samagotchi/engine.rb +11 -8
  71. data/lib/samagotchi/engine_snapshots.rb +16 -3
  72. data/lib/samagotchi/events.rb +1 -0
  73. data/lib/samagotchi/guardrails/review_paths.rb +13 -3
  74. data/lib/samagotchi/guardrails_command.rb +3 -9
  75. data/lib/samagotchi/hook_label.rb +19 -0
  76. data/lib/samagotchi/hook_routes.rb +3 -2
  77. data/lib/samagotchi/hooks.rb +3 -1
  78. data/lib/samagotchi/host_registry.rb +146 -16
  79. data/lib/samagotchi/idle_client.rb +13 -2
  80. data/lib/samagotchi/idle_recap.rb +33 -3
  81. data/lib/samagotchi/idle_target.rb +27 -7
  82. data/lib/samagotchi/llm/adapter_common.rb +4 -2
  83. data/lib/samagotchi/llm/anthropic_messages.rb +3 -2
  84. data/lib/samagotchi/llm/errors.rb +35 -4
  85. data/lib/samagotchi/llm/model_listing.rb +19 -0
  86. data/lib/samagotchi/llm/openai_chat.rb +3 -2
  87. data/lib/samagotchi/model_binding.rb +46 -4
  88. data/lib/samagotchi/model_catalog.rb +68 -8
  89. data/lib/samagotchi/model_profile.rb +35 -0
  90. data/lib/samagotchi/models_command.rb +8 -4
  91. data/lib/samagotchi/page_command.rb +90 -6
  92. data/lib/samagotchi/pages/launch.rb +16 -8
  93. data/lib/samagotchi/pages/runner.rb +7 -2
  94. data/lib/samagotchi/pages/runtime.rb +62 -2
  95. data/lib/samagotchi/pages.rb +4 -0
  96. data/lib/samagotchi/panes/kitty.rb +137 -0
  97. data/lib/samagotchi/panes.rb +254 -0
  98. data/lib/samagotchi/peer_announce.rb +245 -0
  99. data/lib/samagotchi/peer_command.rb +97 -11
  100. data/lib/samagotchi/peer_continue.rb +10 -0
  101. data/lib/samagotchi/peer_mailbox.rb +30 -7
  102. data/lib/samagotchi/peer_pair_here.rb +149 -0
  103. data/lib/samagotchi/peer_presence.rb +434 -0
  104. data/lib/samagotchi/peer_say.rb +17 -10
  105. data/lib/samagotchi/peer_wait_expiry.rb +47 -0
  106. data/lib/samagotchi/plugin/api.rb +18 -1
  107. data/lib/samagotchi/plugin/attached_context.rb +46 -1
  108. data/lib/samagotchi/plugin/card.rb +68 -11
  109. data/lib/samagotchi/plugin/context.rb +42 -6
  110. data/lib/samagotchi/plugin/panes.rb +97 -0
  111. data/lib/samagotchi/plugin/peer.rb +52 -10
  112. data/lib/samagotchi/plugin/peer_pairing.rb +290 -0
  113. data/lib/samagotchi/plugin/peer_start.rb +326 -0
  114. data/lib/samagotchi/plugin/peer_start_hook.rb +207 -0
  115. data/lib/samagotchi/plugin/peers.rb +76 -3
  116. data/lib/samagotchi/plugin/project.rb +63 -0
  117. data/lib/samagotchi/plugin/sessions.rb +36 -1
  118. data/lib/samagotchi/plugin/tool_spec.rb +16 -7
  119. data/lib/samagotchi/recap_setup.rb +40 -3
  120. data/lib/samagotchi/self_report.rb +25 -6
  121. data/lib/samagotchi/send_command.rb +6 -6
  122. data/lib/samagotchi/served_lookup.rb +225 -0
  123. data/lib/samagotchi/served_ref.rb +41 -0
  124. data/lib/samagotchi/session.rb +22 -9
  125. data/lib/samagotchi/session_access/contract.rb +6 -0
  126. data/lib/samagotchi/session_access/local.rb +54 -6
  127. data/lib/samagotchi/session_access/remote.rb +4 -4
  128. data/lib/samagotchi/session_access/remote_peers.rb +7 -4
  129. data/lib/samagotchi/session_commands.rb +40 -8
  130. data/lib/samagotchi/session_continue.rb +6 -2
  131. data/lib/samagotchi/session_lifecycle/allowed.rb +4 -2
  132. data/lib/samagotchi/session_manager/delivery.rb +5 -0
  133. data/lib/samagotchi/session_manager/lifecycle.rb +58 -7
  134. data/lib/samagotchi/session_manager/removal.rb +3 -0
  135. data/lib/samagotchi/session_model_settings.rb +7 -3
  136. data/lib/samagotchi/session_stats.rb +436 -0
  137. data/lib/samagotchi/session_stores.rb +9 -0
  138. data/lib/samagotchi/session_window.rb +30 -0
  139. data/lib/samagotchi/sessions_command.rb +16 -3
  140. data/lib/samagotchi/system_one/approval_choice.rb +22 -0
  141. data/lib/samagotchi/system_one/approval_label.rb +4 -6
  142. data/lib/samagotchi/system_one/http_backend.rb +111 -10
  143. data/lib/samagotchi/system_prompt.rb +14 -5
  144. data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
  145. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -1
  146. data/lib/samagotchi/terminal_ui/formatting.rb +26 -12
  147. data/lib/samagotchi/terminal_ui/status_row.rb +20 -3
  148. data/lib/samagotchi/terminal_ui.rb +1 -1
  149. data/lib/samagotchi/testing/boundary.rb +17 -4
  150. data/lib/samagotchi/testing/bundle.rb +6 -2
  151. data/lib/samagotchi/testing/sessions.rb +11 -3
  152. data/lib/samagotchi/toolkit.rb +11 -4
  153. data/lib/samagotchi/toolkit_report_command.rb +14 -18
  154. data/lib/samagotchi/toolkit_suggest.rb +9 -2
  155. data/lib/samagotchi/tools/registry.rb +43 -18
  156. data/lib/samagotchi/tools/tool_index.rb +6 -2
  157. data/lib/samagotchi/turn_endings.rb +6 -2
  158. data/lib/samagotchi/turn_excerpts.rb +298 -0
  159. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
  160. data/lib/samagotchi/user_typed.rb +29 -0
  161. data/lib/samagotchi/version.rb +1 -1
  162. data/lib/samagotchi/web/app.rb +8 -20
  163. data/lib/samagotchi/web/participant_review.rb +1 -1
  164. data/lib/samagotchi/web/participant_view.rb +1 -1
  165. data/lib/samagotchi/web/peer_routes.rb +33 -13
  166. data/lib/samagotchi/web/public/app.js +1 -1
  167. data/lib/samagotchi/web/public/card.js +26 -10
  168. data/lib/samagotchi/web/public/context_chips.js +24 -2
  169. data/lib/samagotchi/web/public/copy.js +8 -2
  170. data/lib/samagotchi/web/public/data.js +2 -1
  171. data/lib/samagotchi/web/public/format.js +9 -1
  172. data/lib/samagotchi/web/public/index.html +18 -0
  173. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  174. data/lib/samagotchi/web/public/model_pick.js +18 -5
  175. data/lib/samagotchi/web/public/model_picker.js +1 -1
  176. data/lib/samagotchi/web/public/peer_chip.js +15 -5
  177. data/lib/samagotchi/web/public/peer_data.js +4 -2
  178. data/lib/samagotchi/web/public/peer_wait.js +36 -0
  179. data/lib/samagotchi/web/public/served_ref.js +9 -0
  180. data/lib/samagotchi/web/public/session_fields.js +1 -0
  181. data/lib/samagotchi/web/public/session_state.js +4 -0
  182. data/lib/samagotchi/web/public/stage_missing.js +23 -6
  183. data/lib/samagotchi/web/public/stream_handlers.js +16 -0
  184. data/lib/samagotchi/web/public/version_notices.js +7 -1
  185. data/lib/samagotchi/web/session_control.rb +19 -10
  186. data/lib/samagotchi/web/session_show.rb +20 -0
  187. data/lib/samagotchi/web/update_ops.rb +2 -2
  188. data/lib/samagotchi/worker/command_queue.rb +3 -0
  189. data/lib/samagotchi/worker/mail.rb +14 -1
  190. data/lib/samagotchi/worker.rb +1 -0
  191. metadata +39 -1
@@ -0,0 +1,151 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The knowledge bundle's catalogs (manifest.yml plugin: parts:): which
4
+ # sources a catalog has, their max_age, when each was last refreshed and how
5
+ # that went, in catalog.json beside the catalog's index:
6
+ # <data_dir>/projects/<key>/ a project's (ctx.project.key; worktrees share it)
7
+ # <data_dir>/system/ a session in no project's
8
+ # <data_dir>/catalogs/<name>/ a named catalog (catalog: NAME), shared across projects
9
+ # catalog.json is read without a lock and written (AtomicFile, 0600) only
10
+ # under the catalog's index.lock, which every write to the index takes too.
11
+ require "digest"
12
+ require "fileutils"
13
+ require "json"
14
+
15
+ class Plugin
16
+ class Catalog
17
+ # A catalog name or source name that can't be one: the message says why.
18
+ class Error < StandardError; end
19
+
20
+ FILE = "catalog.json"
21
+ LOCK = "index.lock"
22
+ NAME = /\A[a-z0-9][a-z0-9-]{0,31}\z/
23
+ RESERVED = %w[system projects].freeze
24
+ SOURCE_NAME = /\A[a-z0-9-]{1,32}\z/
25
+ # A project key used as a folder name as it is when it looks like one.
26
+ SAFE_KEY = /\A[A-Za-z0-9][A-Za-z0-9_.-]{0,80}\z/
27
+ AGE = /\A(\d{1,4})([mhd])\z/
28
+ UNITS = { "m" => 60, "h" => 3600, "d" => 86_400 }.freeze
29
+
30
+ # The catalog a call reads: the named one (+name+), else the project's
31
+ # (+project+.key), else the system one.
32
+ # @raise [Error] a name that can't be a catalog's
33
+ def self.locate(data_dir, project:, name: nil)
34
+ unless name.to_s.strip.empty?
35
+ name = name.to_s.strip
36
+ if !name.match?(NAME) || RESERVED.include?(name)
37
+ raise Error, "catalog #{name.inspect} isn't a catalog name (a-z, 0-9 and -, at most 32; not system or projects)"
38
+ end
39
+
40
+ return new(File.join(data_dir, "catalogs", name), kind: :named, label: "catalog #{name}", name: name)
41
+ end
42
+ return new(File.join(data_dir, "system"), kind: :system, label: "system") unless project.key
43
+
44
+ key = project.key.match?(SAFE_KEY) ? project.key : "p_#{Digest::SHA256.hexdigest(project.key)[0, 16]}"
45
+ new(File.join(data_dir, "projects", key), kind: :project, label: "project #{project.key}")
46
+ end
47
+
48
+ # The named catalogs in +data_dir+.
49
+ def self.named(data_dir)
50
+ dir = File.join(data_dir, "catalogs")
51
+ File.directory?(dir) ? Dir.children(dir).select { |name| File.file?(File.join(dir, name, FILE)) }.sort : []
52
+ end
53
+
54
+ # Seconds of a max_age (30m, 6h, 2d), nil for never.
55
+ # @raise [Error] anything else
56
+ def self.max_age_seconds(text)
57
+ text = text.to_s.strip
58
+ return nil if text == "never"
59
+
60
+ match = text.match(AGE) or raise Error, "max_age #{text.inspect} isn't 30m, 6h, 2d … or never"
61
+ match[1].to_i * UNITS.fetch(match[2])
62
+ end
63
+
64
+ attr_reader :dir, :kind, :label, :name
65
+
66
+ def initialize(dir, kind:, label:, name: nil)
67
+ @dir = dir
68
+ @kind = kind
69
+ @label = label
70
+ @name = name
71
+ end
72
+
73
+ def named? = @kind == :named
74
+ def path = File.join(@dir, FILE)
75
+ def exists? = File.file?(path)
76
+
77
+ # The catalog's data: {"sources" => [...], "removed_defaults" => [...],
78
+ # "seeded" => bool, "notes" => [...]}.
79
+ def load
80
+ data = exists? ? JSON.parse(File.read(path)) : {}
81
+ data = {} unless data.is_a?(Hash)
82
+ { "sources" => [], "removed_defaults" => [], "seeded" => false, "notes" => [] }.merge(data)
83
+ rescue JSON::ParserError, SystemCallError
84
+ { "sources" => [], "removed_defaults" => [], "seeded" => false, "notes" => [] }
85
+ end
86
+
87
+ def sources = load["sources"]
88
+
89
+ def source(name) = sources.find { |source| source["name"] == name }
90
+
91
+ # The block, under the catalog's index.lock (made 0700 / 0600).
92
+ def lock
93
+ FileUtils.mkdir_p(@dir, mode: 0o700)
94
+ File.open(File.join(@dir, LOCK), File::RDWR | File::CREAT, 0o600) do |file|
95
+ file.flock(File::LOCK_EX)
96
+ yield
97
+ end
98
+ end
99
+
100
+ # Load, let the block change the data, save it; under the lock.
101
+ # @return the block's value
102
+ def update
103
+ lock do
104
+ data = load
105
+ result = yield data
106
+ Samagotchi::AtomicFile.write(path, "#{JSON.pretty_generate(data)}\n", perm: 0o600)
107
+ result
108
+ end
109
+ end
110
+
111
+ # The block with +source+'s refresh lock held, without waiting: false
112
+ # when another refresh holds it (in this process or another).
113
+ def with_source_lock(source)
114
+ dir = File.join(@dir, "sources")
115
+ FileUtils.mkdir_p(dir, mode: 0o700)
116
+ File.open(File.join(dir, "#{source}.lock"), File::RDWR | File::CREAT, 0o600) do |file|
117
+ return false unless file.flock(File::LOCK_EX | File::LOCK_NB)
118
+
119
+ yield
120
+ true
121
+ end
122
+ end
123
+
124
+ # Whether +source+ is due a refresh at +now+ (epoch seconds): never
125
+ # refreshed, or older than its max_age (never: once indexed, never).
126
+ # Reads the catalog's record only: no walk, no stat.
127
+ def self.stale?(source, now)
128
+ refreshed = source["refreshed_at"]
129
+ return true if refreshed.nil?
130
+
131
+ age = source["max_age_seconds"]
132
+ !age.nil? && now - refreshed.to_i > age
133
+ end
134
+
135
+ # A free source name: +base+, else base-2, base-3 …
136
+ def self.free_name(base, taken)
137
+ return base unless taken.include?(base)
138
+
139
+ (2..).each do |n|
140
+ name = "#{base[0, 32 - n.to_s.size - 1]}-#{n}"
141
+ return name unless taken.include?(name)
142
+ end
143
+ end
144
+
145
+ # +text+ as a source name's words: a-z, 0-9 and -.
146
+ def self.slug(text)
147
+ slug = text.to_s.downcase.gsub(/[^a-z0-9]+/, "-").gsub(/\A-+|-+\z/, "")
148
+ slug.empty? ? "source" : slug[0, 24].sub(/-+\z/, "")
149
+ end
150
+ end
151
+ end
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The knowledge bundle's chi-data adapters (manifest.yml plugin: parts:),
4
+ # the opt-in sources `knowledge_add kind: chi` adds (docs/bundles.md):
5
+ # SessionsAdapter this project's saved sessions (ctx.sessions.list, read):
6
+ # one item per session, its user and model text only (no
7
+ # tool output, thinking or notes), chunked by message so a
8
+ # hit points at its message (s:<id>#<message>, read with
9
+ # knowledge_search open:). Incremental: only the sessions
10
+ # written since the last listing are read; a deleted or
11
+ # pruned session's rows go (#gone, ctx.sessions.present_ids).
12
+ # Its text and titles go through Redact.text first, as
13
+ # TurnExcerpts' do: a key pasted in a prompt or quoted in
14
+ # an answer is never indexed.
15
+ # ContextAdapter the latest texts of this project's attached context
16
+ # (ctx.context.snapshots): one item per source, its
17
+ # revision the sig. Pointer c:<key>#<line>.
18
+ require "time"
19
+ require "samagotchi/redact"
20
+
21
+ class Plugin
22
+ class SessionsAdapter
23
+ # A session written within this many seconds before the last listing
24
+ # began is listed again (mtimes are whole seconds).
25
+ SLACK = 2
26
+ # What a hit's chunk says a message was.
27
+ SPEAKERS = { "user" => "you", "model" => "model" }.freeze
28
+ # The user's own lines: a prompt (no kind) or a mid-turn line.
29
+ USER_KINDS = [nil, "input"].freeze
30
+ # Secrets by shape and by name, the session's folder kept as it is.
31
+ VIEWER = Samagotchi::Redact::Viewer.new(cwd: nil)
32
+
33
+ # @param sessions [#list, #present_ids, #read] ctx.sessions
34
+ # @param listed_at [Integer, nil] when the last listing began (epoch)
35
+ def initialize(sessions, listed_at: nil)
36
+ @sessions = sessions
37
+ @since = listed_at && Time.at(listed_at.to_i - SLACK)
38
+ end
39
+
40
+ def skipped = {}
41
+
42
+ # The sessions written since the last listing (all of them the first time).
43
+ # @return [Array<Item>]
44
+ def items
45
+ @present = @sessions.present_ids
46
+ @sessions.list(changed_since: @since).filter_map do |row|
47
+ updated = Time.iso8601(row[:updated_at].to_s).to_i
48
+ title = SessionsAdapter.redact(row[:title].to_s).gsub(/\s+/, " ").strip[0, 80]
49
+ Item.new(key: row[:id], sig: row[:updated_at].to_s, title: "session #{title.empty? ? row[:id][0, 8] : title}",
50
+ ptr: "s:#{row[:id]}", url: nil, path: nil, updated_at: updated)
51
+ rescue ArgumentError
52
+ nil
53
+ end
54
+ end
55
+
56
+ # The old keys of sessions no longer saved.
57
+ def gone(old_keys) = old_keys - (@present || @sessions.present_ids)
58
+
59
+ def text(_item) = nil
60
+
61
+ # +text+ as valid UTF-8 with its secrets redacted.
62
+ def self.redact(text) = Samagotchi::Redact.text(text.dup.force_encoding(Encoding::UTF_8).scrub(""), VIEWER)
63
+
64
+ # The session's user and model messages, as chunks of at most
65
+ # Chunker::MAX chars, each one's line the index of the message it
66
+ # starts at (ctx.sessions.read's messages); nil when it can't be read.
67
+ def chunks(item)
68
+ messages = @sessions.read(item.key)[:messages]
69
+ out = []
70
+ body = +""
71
+ start = nil
72
+ flush = lambda do
73
+ out << { title: item.title, body: body.strip, line: start } unless body.strip.empty?
74
+ body = +""
75
+ end
76
+ Array(messages).each_with_index do |message, index|
77
+ said = said(message) or next
78
+
79
+ Chunker.pieces("#{SPEAKERS.fetch(message[:role].to_s)}: #{said}\n\n").each do |piece|
80
+ flush.call if body.length + piece.length > Chunker::MAX
81
+ start = index if body.empty?
82
+ body << piece
83
+ end
84
+ end
85
+ flush.call
86
+ out
87
+ rescue Samagotchi::Plugin::Sessions::Error
88
+ nil
89
+ end
90
+
91
+ private
92
+
93
+ def said(message)
94
+ return nil unless message.is_a?(Hash)
95
+
96
+ role = message[:role].to_s
97
+ user = role == "user" && USER_KINDS.include?(message[:kind]&.to_s) && message[:source].nil? && !chi_line?(message)
98
+ return nil unless user || (role == "model" && message[:kind].nil?)
99
+
100
+ text = message[:content]
101
+ return nil unless text.is_a?(String) && !text.strip.empty?
102
+
103
+ Chunker.clean(text)&.then { |clean| SessionsAdapter.redact(clean).strip }
104
+ end
105
+
106
+ # A user message chi wrote, not the user: a `!cmd` line ("!(cmd)\n<its
107
+ # output>", no turn_id: Steer.shell_line?'s shape, an env or a .env
108
+ # it printed), or /continue no's reason line (an opening_id, no
109
+ # turn_id: TurnFlow#abort_continue!, a template around the original
110
+ # prompt and the interrupted tools' trace).
111
+ def chi_line?(message)
112
+ return false if message[:turn_id]
113
+
114
+ message[:content].to_s.start_with?("!(") || message[:opening_id].is_a?(String)
115
+ end
116
+ end
117
+
118
+ class ContextAdapter
119
+ # @param context [#snapshots] ctx.context
120
+ def initialize(context)
121
+ @context = context
122
+ @texts = {}
123
+ end
124
+
125
+ def skipped = {}
126
+
127
+ # @return [Array<Item>] one per source with a text
128
+ def items
129
+ @context.snapshots.filter_map do |row|
130
+ key = ContextAdapter.key(row)
131
+ @texts[key] = row[:text]
132
+ own = row[:session_id] ? " (session #{row[:session_id][0, 8]})" : ""
133
+ hint = row[:hint].to_s
134
+ Item.new(key: key, sig: row[:revision].to_s, title: "context #{row[:name]}#{own}", ptr: "c:#{key}",
135
+ url: hint.match?(%r{\Ahttps?://}) ? hint : nil, path: nil, updated_at: epoch(row[:fetched_at]))
136
+ end
137
+ end
138
+
139
+ def text(item) = Chunker.clean(@texts[item.key])
140
+
141
+ # project/<name>, or session:<id>/<name> for a session's own source.
142
+ def self.key(row) = row[:session_id] ? "session:#{row[:session_id]}/#{row[:name]}" : "project/#{row[:name]}"
143
+
144
+ # [scope, session id, name] of a key (#key's).
145
+ def self.parse(key)
146
+ case key
147
+ when %r{\Aproject/([^/]+)\z} then ["project", nil, Regexp.last_match(1)]
148
+ when %r{\Asession:([^/]+)/([^/]+)\z} then ["session", Regexp.last_match(1), Regexp.last_match(2)]
149
+ end
150
+ end
151
+
152
+ private
153
+
154
+ def epoch(value)
155
+ value ? Time.iso8601(value.to_s).to_i : nil
156
+ rescue ArgumentError
157
+ nil
158
+ end
159
+ end
160
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The knowledge bundle's chunker (manifest.yml plugin: parts:): a text as
4
+ # chunks of at most MAX chars, cut on line boundaries; a markdown heading
5
+ # starts a new one (not in a code or config file, where `# ` is a
6
+ # comment), and each chunk's title is the file's name and the nearest
7
+ # heading above it.
8
+ class Plugin
9
+ module Chunker
10
+ MAX = 1500
11
+ HEADING = /\A\#{1,6}\s+(\S.*)\z/
12
+ # Files whose `# ` lines are comments, not headings.
13
+ NO_HEADINGS = %w[.txt .rb .py .sh .yml .yaml .toml .rs .go .js .ts .c .h .java .kt .swift .sql .css .html .json].freeze
14
+
15
+ module_function
16
+
17
+ # Valid UTF-8 (bad bytes dropped), or nil for a binary text (a NUL in
18
+ # its first 8 KB).
19
+ def clean(text)
20
+ text = text.to_s
21
+ return nil if text.byteslice(0, 8192).to_s.include?("\0")
22
+
23
+ text.dup.force_encoding(Encoding::UTF_8).scrub("")
24
+ end
25
+
26
+ # @return [Array<Hash>] {title:, body:, line:} (line: the chunk's first, from 1)
27
+ def chunks(text, name:)
28
+ headings = !NO_HEADINGS.include?(File.extname(name.to_s).downcase)
29
+ chunks = []
30
+ heading = nil
31
+ body = +""
32
+ start = 1
33
+ flush = lambda do
34
+ chunks << { title: [name, heading].compact.join(" · "), body: body.strip, line: start } unless body.strip.empty?
35
+ body = +""
36
+ end
37
+ text.each_line.with_index(1) do |line, number|
38
+ if headings && (match = line.chomp.match(HEADING))
39
+ flush.call
40
+ heading = match[1].strip
41
+ end
42
+ pieces(line).each do |piece|
43
+ flush.call if body.length + piece.length > MAX
44
+ start = number if body.empty?
45
+ body << piece
46
+ end
47
+ end
48
+ flush.call
49
+ chunks
50
+ end
51
+
52
+ # A line longer than MAX as pieces of at most MAX.
53
+ def pieces(line) = line.length > MAX ? line.scan(/.{1,#{MAX}}/m) : [line]
54
+ end
55
+ end
@@ -0,0 +1,246 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The knowledge bundle's github adapter (manifest.yml plugin: parts:): a
4
+ # GitHub repository (github.com only) as a source, through a shallow clone
5
+ # of the bundle's own under the catalog's clones/ folder, pulled at refresh
6
+ # (never in a search's own budget: Refresh runs it in the background).
7
+ # Auth is gh's own login (gh repo clone, and `gh auth git-credential` as the
8
+ # fetch's credential helper): no token here.
9
+ #
10
+ # The location is model-supplied on a tool that runs unasked, so it is
11
+ # parsed strictly (GithubAdapter.parse): OWNER/REPO[@REF][:SUBPATH] or
12
+ # https://github.com/OWNER/REPO[/tree/REF[/SUBPATH]], OWNER and REPO in
13
+ # GitHub's charset, no leading "-" anywhere, REF through `git
14
+ # check-ref-format`, SUBPATH relative with no "..". Every spawn is argv (no
15
+ # shell), positionals after "--" where the command takes one, with
16
+ # GIT_TERMINAL_PROMPT=0, GIT_LFS_SKIP_SMUDGE=1, core.hooksPath=/dev/null
17
+ # and core.fsmonitor=false, killed after TIMEOUT s. The tree's files follow
18
+ # the folder rules: no symlink or submodule, a real path inside the clone,
19
+ # no secret-named file, the size and count caps, no binary.
20
+ require "digest"
21
+ require "fileutils"
22
+ require "open3"
23
+ require "time"
24
+
25
+ class Plugin
26
+ class GithubAdapter
27
+ # A location that can't be one, or a clone/fetch that failed: why.
28
+ class Error < StandardError; end
29
+
30
+ OWNER = /\A[A-Za-z0-9][A-Za-z0-9-]{0,38}\z/
31
+ REPO = /\A[A-Za-z0-9._-]{1,100}\z/
32
+ SHORT = %r{\A([^/@:\s]+)/([^/@:\s]+)(?:@([^:\s]+))?(?::(\S+))?\z}
33
+ URL = %r{\Ahttps://github\.com/([^/\s]+)/([^/\s]+?)(?:\.git)?(?:/tree/([^/\s]+)(?:/(\S+?))?)?/?\z}
34
+ TIMEOUT = 120
35
+ ENV_SET = { "GIT_TERMINAL_PROMPT" => "0", "GIT_LFS_SKIP_SMUDGE" => "1" }.freeze
36
+ # No hooks, no fsmonitor, no submodules, and only the https and ssh
37
+ # transports (no file://, ext:: or other remote helper a repo's
38
+ # config could name).
39
+ SAFE = ["core.hooksPath=/dev/null", "core.fsmonitor=false", "protocol.allow=never", "protocol.https.allow=always",
40
+ "protocol.ssh.allow=always", "submodule.recurse=false"].freeze
41
+ GIT = ["git", *SAFE.flat_map { |setting| ["-c", setting] }].freeze
42
+ # The fetch's credentials: gh's login, no other helper.
43
+ CREDENTIAL = ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential"].freeze
44
+ CLONE_FLAGS = ["--depth", "1", "--single-branch", "--no-tags", *SAFE.flat_map { |setting| ["--config", setting] }].freeze
45
+ # ls-tree modes that aren't a plain file: a symlink, a submodule.
46
+ LINK_MODES = %w[120000 160000].freeze
47
+
48
+ Location = Data.define(:owner, :repo, :ref, :subpath) do
49
+ def to_s = "#{owner}/#{repo}#{"@#{ref}" if ref}#{":#{subpath}" if subpath}"
50
+
51
+ # The clone's folder name under clones/: the repo, and a digest of
52
+ # the whole location (two refs of one repo, a case-insensitive disk).
53
+ def clone_name = "#{owner}__#{repo}__#{Digest::SHA256.hexdigest(to_s)[0, 8]}"
54
+ end
55
+
56
+ # @return [Location]
57
+ # @raise [Error] anything but the two forms, or a part that fails its rule
58
+ def self.parse(text)
59
+ text = text.to_s.strip
60
+ match = text.match(URL) || text.match(SHORT) or
61
+ raise Error, "#{text.inspect} isn't OWNER/REPO[@REF][:SUBPATH] or https://github.com/OWNER/REPO[/tree/REF[/PATH]]"
62
+
63
+ owner, repo, ref, subpath = match.captures
64
+ raise Error, "#{owner.inspect} isn't a GitHub owner" unless owner.match?(OWNER)
65
+ raise Error, "#{repo.inspect} isn't a GitHub repository name" if !repo.match?(REPO) || %w[. ..].include?(repo) || repo.start_with?("-")
66
+
67
+ Location.new(owner: owner, repo: repo, ref: ref && check_ref!(ref), subpath: subpath && check_subpath!(subpath))
68
+ end
69
+
70
+ def self.check_ref!(ref)
71
+ if ref.start_with?("-") || ref.include?("..") || ref.match?(/\s|[[:cntrl:]]/)
72
+ raise Error, "ref #{ref.inspect} isn't a branch or tag name"
73
+ end
74
+
75
+ _out, status = Open3.capture2e(Samagotchi::GitEnv::UNSET, "git", "check-ref-format", "--allow-onelevel", ref)
76
+ raise Error, "ref #{ref.inspect} isn't a branch or tag name" unless status.success?
77
+
78
+ ref
79
+ rescue SystemCallError => e
80
+ raise Error, "git: #{e.message}"
81
+ end
82
+
83
+ def self.check_subpath!(subpath)
84
+ path = subpath.delete_suffix("/")
85
+ if path.empty? || path.start_with?("-", "/") || path.split("/").any? { |part| part.empty? || part == ".." || part.start_with?("-") } ||
86
+ path.match?(/[[:cntrl:]]/)
87
+ raise Error, "path #{subpath.inspect} isn't a folder inside the repository"
88
+ end
89
+
90
+ path
91
+ end
92
+
93
+ attr_reader :skipped
94
+
95
+ # @param source [Hash] the catalog's record (location, include, exclude)
96
+ # @param dir [String] the clone's folder (the bundle's own)
97
+ def initialize(source, dir:, project:, max_files: FolderAdapter::MAX_FILES, timeout: TIMEOUT)
98
+ @location = GithubAdapter.parse(source["location"])
99
+ @dir = dir
100
+ @project = project
101
+ include = Array(source["include"])
102
+ @include = include.empty? ? FolderAdapter::DEFAULT_INCLUDE : include
103
+ @exclude = Array(source["exclude"])
104
+ @max_files = max_files
105
+ @timeout = timeout
106
+ @skipped = { secret: 0, symlink: 0, large: 0, capped: 0 }
107
+ end
108
+
109
+ # Pull the clone (a failing fetch clones again), then list its tree.
110
+ # @return [Array<Item>]
111
+ def items
112
+ sync!
113
+ commit, time = head
114
+ real = File.realpath(@dir)
115
+ entries = tree.select { |_mode, path| wanted?(path) }
116
+ links = entries.select { |mode, _path| LINK_MODES.include?(mode) }
117
+ @skipped[:symlink] += links.size
118
+ entries -= links
119
+ if entries.size > @max_files
120
+ @skipped[:capped] = entries.size - @max_files
121
+ entries = entries.first(@max_files)
122
+ end
123
+ entries.filter_map { |_mode, path| item(path, real, commit, time) }
124
+ end
125
+
126
+ def text(item)
127
+ return nil if File.symlink?(item.path)
128
+
129
+ Chunker.clean(File.binread(item.path, FolderAdapter::MAX_FILE_BYTES))
130
+ rescue SystemCallError
131
+ nil
132
+ end
133
+
134
+ private
135
+
136
+ def sync!
137
+ if File.directory?(File.join(@dir, ".git"))
138
+ fetched = git(*CREDENTIAL, "fetch", "--depth", "1", "--no-tags", "origin", "--", @location.ref || "HEAD").first
139
+ return if fetched && git("reset", "-q", "--hard", "FETCH_HEAD").first
140
+
141
+ FileUtils.rm_rf(@dir)
142
+ end
143
+ clone!
144
+ end
145
+
146
+ # gh repo clone takes no "--" before its positionals: the validated
147
+ # OWNER/REPO and the bundle's own folder are its only ones; the git
148
+ # flags after its "--" are constants and the validated REF.
149
+ def clone!
150
+ FileUtils.mkdir_p(File.dirname(@dir), mode: 0o700)
151
+ partial = "#{@dir}.partial"
152
+ FileUtils.rm_rf(partial)
153
+ flags = CLONE_FLAGS + (@location.ref ? ["--branch", @location.ref] : [])
154
+ ok, out = run(["gh", "repo", "clone", "--no-upstream", "#{@location.owner}/#{@location.repo}", partial, "--", *flags])
155
+ raise Error, "gh repo clone #{@location.owner}/#{@location.repo}: #{last_line(out)}" unless ok
156
+
157
+ File.rename(partial, @dir)
158
+ ensure
159
+ FileUtils.rm_rf(partial) if partial
160
+ end
161
+
162
+ def head
163
+ ok, out = git("log", "-1", "--format=%H %ct")
164
+ raise Error, "git log: #{last_line(out)}" unless ok
165
+
166
+ commit, time = out.split
167
+ [commit, time.to_i]
168
+ end
169
+
170
+ # [[mode, path], …] of HEAD's files (a symlink's and a submodule's too,
171
+ # for the count), each blob's sha kept in @shas.
172
+ def tree
173
+ ok, out = git("ls-tree", "-r", "-z", "--full-tree", "HEAD")
174
+ raise Error, "git ls-tree: #{last_line(out)}" unless ok
175
+
176
+ @shas = {}
177
+ out.split("\0").filter_map do |line|
178
+ meta, path = line.split("\t", 2)
179
+ mode, type, sha = meta.to_s.split
180
+ next unless path && (type == "blob" || LINK_MODES.include?(mode))
181
+
182
+ @shas[path] = sha
183
+ [mode, path]
184
+ end
185
+ end
186
+
187
+ def wanted?(path)
188
+ rel = relative(path) or return false
189
+ @include.any? { |glob| File.fnmatch?(glob, rel, FolderAdapter::GLOB) } &&
190
+ @exclude.none? { |glob| File.fnmatch?(glob, rel, FolderAdapter::GLOB) }
191
+ end
192
+
193
+ # +path+ inside the source's SUBPATH, relative to it; nil outside.
194
+ def relative(path)
195
+ return path unless @location.subpath
196
+
197
+ path.delete_prefix("#{@location.subpath}/") if path.start_with?("#{@location.subpath}/")
198
+ end
199
+
200
+ def item(path, real, commit, time)
201
+ local = File.join(@dir, path)
202
+ stat = File.lstat(local)
203
+ return skip(:symlink) if stat.symlink?
204
+ return nil unless stat.file?
205
+ return skip(:symlink) unless File.realpath(local).start_with?("#{real}/")
206
+ return skip(:secret) if @project.secret_name?(path)
207
+ return skip(:large) if stat.size > FolderAdapter::MAX_FILE_BYTES
208
+
209
+ name = "#{@location.owner}/#{@location.repo}"
210
+ Item.new(key: path, sig: @shas.fetch(path), title: path, ptr: "#{name}:#{path}",
211
+ url: "https://github.com/#{name}/blob/#{commit}/#{path}", path: local, updated_at: time)
212
+ rescue SystemCallError
213
+ nil
214
+ end
215
+
216
+ def skip(why)
217
+ @skipped[why] += 1
218
+ nil
219
+ end
220
+
221
+ def git(*args) = run([*GIT, "-C", @dir, *args])
222
+
223
+ # [success, output] of +argv+ (no shell), killed with its process
224
+ # group after @timeout s.
225
+ def run(argv)
226
+ Open3.popen2e(Samagotchi::GitEnv::UNSET.merge(ENV_SET), *argv, pgroup: true) do |stdin, out, wait|
227
+ stdin.close
228
+ reader = Thread.new { out.read }
229
+ unless wait.join(@timeout)
230
+ begin
231
+ Process.kill("KILL", -wait.pid)
232
+ rescue Errno::ESRCH
233
+ # gone in between
234
+ end
235
+ wait.join
236
+ raise Error, "#{argv.first} #{argv[1]} took over #{@timeout} s"
237
+ end
238
+ [wait.value.success?, reader.value.to_s]
239
+ end
240
+ rescue SystemCallError => e
241
+ raise Error, "#{argv.first}: #{e.message}"
242
+ end
243
+
244
+ def last_line(out) = out.to_s.lines.map(&:strip).reject(&:empty?).last.to_s[0, 300]
245
+ end
246
+ end
@@ -0,0 +1,25 @@
1
+ ---
2
+ name: knowledge
3
+ version: 0.1.0
4
+ scope: system
5
+ description: "knowledge_search: search a project's docs, memories and the folders, GitHub repos, past sessions and attached context added to its catalog (or a named catalog) in one local SQLite index, each answer saying how old each source is; knowledge_add/list/remove for a kit that adds them (the coordinator kit); /knowledge lists the catalog"
6
+ trust_level: reviewed
7
+ plugin:
8
+ file: plugin.rb
9
+ sha256: sha256:9491e3da1663f01f24586343c7bc4802806e504516196aa03b2f550030fa46f5
10
+ # Loaded in this order, before plugin.rb.
11
+ parts:
12
+ store.rb: sha256:bdc29f55521895d545c706ad3ff2f3778390264bebbcc10cb93b3d354b0f4a33
13
+ query.rb: sha256:9578ea7392bc6d8a27c5d9b68e47a310b0a8ca937428c80e47b513394d75110f
14
+ chunker.rb: sha256:169c638ed109ce28e2530868e36b60df7ccffdf64ad64ef027403ba998d7c79e
15
+ adapters.rb: sha256:11fee1ca0473d9b65a1b66ff50e49b6daf8fdc63d1651e6edc31c02d794ccc1a
16
+ chi_adapters.rb: sha256:8c1a98ef7f1fdbcbad186231eef6763d88582f75ea0d79b2fe15a5f72a76e6c1
17
+ github.rb: sha256:ced3a64d7b03a8b2e724b9d3d8bb8626ffaf66bcdaafd2f2ff41b5888b076a9c
18
+ catalog.rb: sha256:ffa07afcfb8c3358ac3500bc80f5a028ece79e4adb7e0be5153ef50f95359251
19
+ refresh.rb: sha256:085545276488772f830757f9f1fe2da9807fb0fdc3a6f1c8851737412ffd3938
20
+ query_log.rb: sha256:f85602bb073223532ba976189f5bab2ae2a19b98a65c66812d56247dd27e8cfe
21
+ # chi.tool(declare:) and ctx.project are new: release:bump raises requires_chi.
22
+ requires_chi: ">= 0.195.0"
23
+ needs: [sqlite3, gh, git]
24
+ # config.yml bundles: knowledge: (another key warns; an older chi ignores this)
25
+ settings: {refresh_budget_ms: number, max_files: number, sqlite3: string}