samagotchi 0.194.0 → 0.196.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +80 -1
- data/docs/architecture.md +2 -1
- data/docs/bundle-authoring.md +23 -23
- data/docs/bundles.md +201 -7
- data/docs/cli.md +5 -1
- data/docs/configuration.md +25 -4
- data/docs/context.md +13 -3
- data/docs/guardrails.md +6 -4
- data/docs/hooks.md +3 -1
- data/docs/internals/attached-context.md +2 -0
- data/docs/internals/block-renderers.md +4 -1
- data/docs/internals/bridge.md +4 -0
- data/docs/internals/engine.md +15 -2
- data/docs/internals/knowledge.md +215 -0
- data/docs/internals/pages.md +17 -9
- data/docs/internals/panes.md +51 -13
- data/docs/internals/participants.md +15 -3
- data/docs/internals/peers.md +14 -9
- data/docs/internals/session-lifecycle.md +26 -12
- data/docs/internals/web-frontend.md +64 -27
- data/docs/memory.md +4 -2
- data/docs/pages.md +72 -1
- data/docs/peers.md +25 -14
- data/docs/plugins.md +132 -6
- data/docs/releasing.md +1 -1
- data/docs/scheduling.md +4 -0
- data/docs/sessions.md +9 -2
- data/docs/system-one.md +3 -1
- data/docs/testing.md +3 -1
- data/lib/samagotchi/bundle_manifest.rb +30 -5
- data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
- data/lib/samagotchi/bundles/claude-peer/plugin.rb +2 -2
- data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
- data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
- data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
- data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
- data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
- data/lib/samagotchi/bundles/core/manifest.yml +2 -2
- data/lib/samagotchi/bundles/cost-cap/manifest.yml +4 -4
- data/lib/samagotchi/bundles/cost-cap/plugin.rb +54 -3
- data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
- data/lib/samagotchi/bundles/github-pr/manifest.yml +4 -2
- data/lib/samagotchi/bundles/knowledge/adapters.rb +205 -0
- data/lib/samagotchi/bundles/knowledge/catalog.rb +151 -0
- data/lib/samagotchi/bundles/knowledge/chi_adapters.rb +178 -0
- data/lib/samagotchi/bundles/knowledge/chunker.rb +55 -0
- data/lib/samagotchi/bundles/knowledge/github.rb +246 -0
- data/lib/samagotchi/bundles/knowledge/manifest.yml +27 -0
- data/lib/samagotchi/bundles/knowledge/plugin.rb +807 -0
- data/lib/samagotchi/bundles/knowledge/query.rb +30 -0
- data/lib/samagotchi/bundles/knowledge/query_log.rb +55 -0
- data/lib/samagotchi/bundles/knowledge/refresh.rb +133 -0
- data/lib/samagotchi/bundles/knowledge/store.rb +264 -0
- data/lib/samagotchi/bundles/reflect/manifest.yml +17 -0
- data/lib/samagotchi/bundles/reflect/scripts/reflect.rb +439 -0
- data/lib/samagotchi/bundles/reflect/skill_reflect.md +100 -0
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/context_change.rb +44 -0
- data/lib/samagotchi/context_note.rb +1 -1
- data/lib/samagotchi/context_providers.rb +14 -0
- data/lib/samagotchi/context_sources.rb +3 -25
- data/lib/samagotchi/engine/plugins.rb +21 -0
- data/lib/samagotchi/events.rb +1 -0
- data/lib/samagotchi/guardrails/pair_boundary.rb +12 -4
- data/lib/samagotchi/guardrails/review_paths.rb +13 -3
- data/lib/samagotchi/guardrails/targets.rb +24 -2
- data/lib/samagotchi/guardrails_command.rb +3 -9
- data/lib/samagotchi/hook_label.rb +19 -0
- data/lib/samagotchi/hook_routes.rb +3 -2
- data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
- data/lib/samagotchi/memory_bundle/builder.rb +2 -1
- data/lib/samagotchi/memory_bundle/installed_copy.rb +2 -1
- data/lib/samagotchi/page_command.rb +90 -6
- data/lib/samagotchi/pages/launch.rb +16 -8
- data/lib/samagotchi/pages/runner.rb +7 -2
- data/lib/samagotchi/pages/runtime.rb +62 -2
- data/lib/samagotchi/pages.rb +4 -0
- data/lib/samagotchi/panes/kitty.rb +20 -5
- data/lib/samagotchi/panes.rb +81 -12
- data/lib/samagotchi/participants.rb +17 -6
- data/lib/samagotchi/peer_exchanges.rb +1 -2
- data/lib/samagotchi/peer_note.rb +38 -5
- data/lib/samagotchi/peer_presence.rb +20 -7
- data/lib/samagotchi/plugin/api.rb +11 -1
- data/lib/samagotchi/plugin/attached_context.rb +46 -1
- data/lib/samagotchi/plugin/chips.rb +125 -0
- data/lib/samagotchi/plugin/context.rb +43 -8
- data/lib/samagotchi/plugin/panes.rb +52 -9
- data/lib/samagotchi/plugin/peer_pairing.rb +2 -2
- data/lib/samagotchi/plugin/peer_start.rb +61 -36
- data/lib/samagotchi/plugin/peers.rb +6 -3
- data/lib/samagotchi/plugin/project.rb +63 -0
- data/lib/samagotchi/plugin/sessions.rb +36 -1
- data/lib/samagotchi/plugin/tool_spec.rb +28 -9
- data/lib/samagotchi/schedules.rb +8 -2
- data/lib/samagotchi/session.rb +22 -9
- data/lib/samagotchi/session_access/local.rb +34 -33
- data/lib/samagotchi/session_chain/sharing.rb +79 -0
- data/lib/samagotchi/session_chain/successor.rb +4 -2
- data/lib/samagotchi/session_chips.rb +133 -0
- data/lib/samagotchi/session_inbox_delivery.rb +11 -11
- data/lib/samagotchi/session_manager/emptiness.rb +4 -1
- data/lib/samagotchi/session_observer.rb +1 -1
- data/lib/samagotchi/session_stats.rb +437 -0
- data/lib/samagotchi/session_stores.rb +3 -0
- data/lib/samagotchi/session_window.rb +30 -0
- data/lib/samagotchi/speaker.rb +228 -0
- data/lib/samagotchi/steer.rb +36 -132
- data/lib/samagotchi/system_one/approval_choice.rb +22 -0
- data/lib/samagotchi/system_one/approval_label.rb +4 -6
- data/lib/samagotchi/system_prompt.rb +3 -1
- data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
- data/lib/samagotchi/testing/boundary.rb +17 -4
- data/lib/samagotchi/testing/bundle.rb +5 -0
- data/lib/samagotchi/testing/host.rb +1 -0
- data/lib/samagotchi/testing/recorder.rb +10 -0
- data/lib/samagotchi/testing/sessions.rb +11 -3
- data/lib/samagotchi/toolkit.rb +11 -4
- data/lib/samagotchi/toolkit_report_command.rb +14 -18
- data/lib/samagotchi/toolkit_suggest.rb +9 -2
- data/lib/samagotchi/tools/registry.rb +48 -18
- data/lib/samagotchi/tools/tool_index.rb +6 -2
- data/lib/samagotchi/turn_excerpts.rb +302 -0
- data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +21 -10
- data/lib/samagotchi/web/participant_view.rb +1 -1
- data/lib/samagotchi/web/peer_routes.rb +5 -2
- data/lib/samagotchi/web/plugin_chip_rows.rb +39 -0
- data/lib/samagotchi/web/public/agent_rows.js +1 -0
- data/lib/samagotchi/web/public/app.js +17 -25
- data/lib/samagotchi/web/public/chains.js +0 -26
- data/lib/samagotchi/web/public/command_list.js +2 -3
- data/lib/samagotchi/web/public/composer.js +2 -3
- data/lib/samagotchi/web/public/composer_mount.js +3 -6
- data/lib/samagotchi/web/public/context_chips.js +240 -93
- data/lib/samagotchi/web/public/context_groups.js +84 -0
- data/lib/samagotchi/web/public/draft_follow.js +33 -0
- data/lib/samagotchi/web/public/drafts.js +26 -22
- data/lib/samagotchi/web/public/index.html +32 -0
- data/lib/samagotchi/web/public/peer_chip_kind.js +49 -0
- data/lib/samagotchi/web/public/peer_note.js +2 -2
- data/lib/samagotchi/web/public/peer_row.js +10 -5
- data/lib/samagotchi/web/public/peer_wait.js +4 -2
- data/lib/samagotchi/web/public/plugin_chip.js +55 -0
- data/lib/samagotchi/web/public/plugin_chip_kind.js +48 -0
- data/lib/samagotchi/web/public/send_turn.js +8 -21
- data/lib/samagotchi/web/public/session_actions.js +10 -23
- data/lib/samagotchi/web/public/session_view.js +7 -3
- data/lib/samagotchi/web/public/stream_handlers.js +2 -0
- metadata +33 -1
|
@@ -0,0 +1,178 @@
|
|
|
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, the owner's and the model's text
|
|
7
|
+
# only (ctx.speaker: no participant's turn, tool output,
|
|
8
|
+
# thinking or notes), chunked by message so a
|
|
9
|
+
# hit points at its message (s:<id>#<message>, read with
|
|
10
|
+
# knowledge_search open:). Incremental: only the sessions
|
|
11
|
+
# written since the last listing are read; a deleted or
|
|
12
|
+
# pruned session's rows go (#gone, ctx.sessions.present_ids).
|
|
13
|
+
# Its text and titles go through Redact.text first, as
|
|
14
|
+
# TurnExcerpts' do: a key pasted in a prompt or quoted in
|
|
15
|
+
# an answer is never indexed.
|
|
16
|
+
# ContextAdapter the latest texts of this project's attached context
|
|
17
|
+
# (ctx.context.snapshots): one item per source, its
|
|
18
|
+
# revision the sig. Pointer c:<key>#<line>.
|
|
19
|
+
require "time"
|
|
20
|
+
require "samagotchi/redact"
|
|
21
|
+
|
|
22
|
+
class Plugin
|
|
23
|
+
class SessionsAdapter
|
|
24
|
+
# A session written within this many seconds before the last listing
|
|
25
|
+
# began is listed again (mtimes are whole seconds).
|
|
26
|
+
SLACK = 2
|
|
27
|
+
# What a hit's chunk says a message was, by its ctx.speaker.
|
|
28
|
+
SPEAKERS = { owner: "you", model: "model" }.freeze
|
|
29
|
+
# The owner's own lines: a prompt (no kind) or a mid-turn line.
|
|
30
|
+
USER_KINDS = [nil, "input"].freeze
|
|
31
|
+
# The rule an item was indexed by, its sig's prefix ("2:<updated_at>"):
|
|
32
|
+
# an index with a sig of another rule lists its sessions in full again
|
|
33
|
+
# (Plugin#adapter_for), so a session indexed before a participant's
|
|
34
|
+
# turns were dropped is read again.
|
|
35
|
+
RULE = "2"
|
|
36
|
+
# Secrets by shape and by name, the session's folder kept as it is.
|
|
37
|
+
VIEWER = Samagotchi::Redact::Viewer.new(cwd: nil)
|
|
38
|
+
|
|
39
|
+
# @param sessions [#list, #present_ids, #read] ctx.sessions
|
|
40
|
+
# @param listed_at [Integer, nil] when the last listing began (epoch)
|
|
41
|
+
# @param speaker [#call] who wrote a message (ctx.speaker)
|
|
42
|
+
def initialize(sessions, speaker:, listed_at: nil)
|
|
43
|
+
@sessions = sessions
|
|
44
|
+
@speaker = speaker
|
|
45
|
+
@since = listed_at && Time.at(listed_at.to_i - SLACK)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def skipped = {}
|
|
49
|
+
|
|
50
|
+
# The sessions written since the last listing (all of them the first time).
|
|
51
|
+
# @return [Array<Item>]
|
|
52
|
+
def items
|
|
53
|
+
@present = @sessions.present_ids
|
|
54
|
+
@sessions.list(changed_since: @since).filter_map do |row|
|
|
55
|
+
updated = Time.iso8601(row[:updated_at].to_s).to_i
|
|
56
|
+
title = SessionsAdapter.redact(row[:title].to_s).gsub(/\s+/, " ").strip[0, 80]
|
|
57
|
+
Item.new(key: row[:id], sig: "#{RULE}:#{row[:updated_at]}", title: "session #{title.empty? ? row[:id][0, 8] : title}",
|
|
58
|
+
ptr: "s:#{row[:id]}", url: nil, path: nil, updated_at: updated)
|
|
59
|
+
rescue ArgumentError
|
|
60
|
+
nil
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# The old keys of sessions no longer saved.
|
|
65
|
+
def gone(old_keys) = old_keys - (@present || @sessions.present_ids)
|
|
66
|
+
|
|
67
|
+
def text(_item) = nil
|
|
68
|
+
|
|
69
|
+
# Whether +sig+ was indexed by this RULE.
|
|
70
|
+
def self.current?(sig) = sig.to_s.start_with?("#{RULE}:")
|
|
71
|
+
|
|
72
|
+
# +text+ as valid UTF-8 with its secrets redacted.
|
|
73
|
+
def self.redact(text) = Samagotchi::Redact.text(text.dup.force_encoding(Encoding::UTF_8).scrub(""), VIEWER)
|
|
74
|
+
|
|
75
|
+
# The session's owner and model messages, as chunks of at most
|
|
76
|
+
# Chunker::MAX chars, each one's line the index of the message it
|
|
77
|
+
# starts at (ctx.sessions.read's messages); nil when it can't be read.
|
|
78
|
+
# A participant's turn goes whole, from its opening to the next one:
|
|
79
|
+
# their lines, the model's answers and any line merged into it.
|
|
80
|
+
def chunks(item)
|
|
81
|
+
messages = @sessions.read(item.key)[:messages]
|
|
82
|
+
out = []
|
|
83
|
+
body = +""
|
|
84
|
+
start = nil
|
|
85
|
+
participant = false
|
|
86
|
+
flush = lambda do
|
|
87
|
+
out << { title: item.title, body: body.strip, line: start } unless body.strip.empty?
|
|
88
|
+
body = +""
|
|
89
|
+
end
|
|
90
|
+
Array(messages).each_with_index do |message, index|
|
|
91
|
+
next unless message.is_a?(Hash)
|
|
92
|
+
|
|
93
|
+
speaker = @speaker.call(message)
|
|
94
|
+
participant = speaker == :participant if opening?(message)
|
|
95
|
+
next if participant
|
|
96
|
+
|
|
97
|
+
said = said(message, speaker) or next
|
|
98
|
+
|
|
99
|
+
Chunker.pieces("#{SPEAKERS.fetch(speaker)}: #{said}\n\n").each do |piece|
|
|
100
|
+
flush.call if body.length + piece.length > Chunker::MAX
|
|
101
|
+
start = index if body.empty?
|
|
102
|
+
body << piece
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
flush.call
|
|
106
|
+
out
|
|
107
|
+
rescue Samagotchi::Plugin::Sessions::Error
|
|
108
|
+
nil
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
private
|
|
112
|
+
|
|
113
|
+
# The owner's prompt or mid-turn line, or the model's answer: its text.
|
|
114
|
+
def said(message, speaker)
|
|
115
|
+
kind = message[:kind]&.to_s
|
|
116
|
+
keep = (speaker == :owner && USER_KINDS.include?(kind)) || (speaker == :model && kind.nil?)
|
|
117
|
+
return nil unless keep
|
|
118
|
+
|
|
119
|
+
text = message[:content]
|
|
120
|
+
return nil unless text.is_a?(String) && !text.strip.empty?
|
|
121
|
+
|
|
122
|
+
Chunker.clean(text)&.then { |clean| SessionsAdapter.redact(clean).strip }
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# A turn's first message: one with a turn_id (a prompt, anyone's) or a
|
|
126
|
+
# turn_start one (a wake turn's note or report). Not a kind-less user
|
|
127
|
+
# line without either: a running turn's merged input in a live snapshot
|
|
128
|
+
# (Bridge::TurnAccumulator) has no kind, and a `!cmd` line runs no
|
|
129
|
+
# turn; a participant's turn then runs on over it (dropping more, never
|
|
130
|
+
# less).
|
|
131
|
+
def opening?(message)
|
|
132
|
+
message[:turn_start] == true || !message[:turn_id].nil?
|
|
133
|
+
end
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
class ContextAdapter
|
|
137
|
+
# @param context [#snapshots] ctx.context
|
|
138
|
+
def initialize(context)
|
|
139
|
+
@context = context
|
|
140
|
+
@texts = {}
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def skipped = {}
|
|
144
|
+
|
|
145
|
+
# @return [Array<Item>] one per source with a text
|
|
146
|
+
def items
|
|
147
|
+
@context.snapshots.filter_map do |row|
|
|
148
|
+
key = ContextAdapter.key(row)
|
|
149
|
+
@texts[key] = row[:text]
|
|
150
|
+
own = row[:session_id] ? " (session #{row[:session_id][0, 8]})" : ""
|
|
151
|
+
hint = row[:hint].to_s
|
|
152
|
+
Item.new(key: key, sig: row[:revision].to_s, title: "context #{row[:name]}#{own}", ptr: "c:#{key}",
|
|
153
|
+
url: hint.match?(%r{\Ahttps?://}) ? hint : nil, path: nil, updated_at: epoch(row[:fetched_at]))
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def text(item) = Chunker.clean(@texts[item.key])
|
|
158
|
+
|
|
159
|
+
# project/<name>, or session:<id>/<name> for a session's own source.
|
|
160
|
+
def self.key(row) = row[:session_id] ? "session:#{row[:session_id]}/#{row[:name]}" : "project/#{row[:name]}"
|
|
161
|
+
|
|
162
|
+
# [scope, session id, name] of a key (#key's).
|
|
163
|
+
def self.parse(key)
|
|
164
|
+
case key
|
|
165
|
+
when %r{\Aproject/([^/]+)\z} then ["project", nil, Regexp.last_match(1)]
|
|
166
|
+
when %r{\Asession:([^/]+)/([^/]+)\z} then ["session", Regexp.last_match(1), Regexp.last_match(2)]
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
private
|
|
171
|
+
|
|
172
|
+
def epoch(value)
|
|
173
|
+
value ? Time.iso8601(value.to_s).to_i : nil
|
|
174
|
+
rescue ArgumentError
|
|
175
|
+
nil
|
|
176
|
+
end
|
|
177
|
+
end
|
|
178
|
+
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,27 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: knowledge
|
|
3
|
+
version: 0.1.1
|
|
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:7be6c875f2fd00f8513eb296c21f8d0dd7dc67a8b0a480faa647b24e4a75565e
|
|
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:897ef55c077df1fdab371753f6c0a9fabb5e477a3646ffc96a756b2364266ebb
|
|
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.196.0"
|
|
23
|
+
# ctx.speaker (a participant's turns left out of the sessions source) and
|
|
24
|
+
# chi.tool(participant:) (the catalog tools kept for the owner) are new.
|
|
25
|
+
needs: [sqlite3, gh, git]
|
|
26
|
+
# config.yml bundles: knowledge: (another key warns; an older chi ignores this)
|
|
27
|
+
settings: {refresh_budget_ms: number, max_files: number, sqlite3: string}
|