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.
Files changed (152) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +80 -1
  3. data/docs/architecture.md +2 -1
  4. data/docs/bundle-authoring.md +23 -23
  5. data/docs/bundles.md +201 -7
  6. data/docs/cli.md +5 -1
  7. data/docs/configuration.md +25 -4
  8. data/docs/context.md +13 -3
  9. data/docs/guardrails.md +6 -4
  10. data/docs/hooks.md +3 -1
  11. data/docs/internals/attached-context.md +2 -0
  12. data/docs/internals/block-renderers.md +4 -1
  13. data/docs/internals/bridge.md +4 -0
  14. data/docs/internals/engine.md +15 -2
  15. data/docs/internals/knowledge.md +215 -0
  16. data/docs/internals/pages.md +17 -9
  17. data/docs/internals/panes.md +51 -13
  18. data/docs/internals/participants.md +15 -3
  19. data/docs/internals/peers.md +14 -9
  20. data/docs/internals/session-lifecycle.md +26 -12
  21. data/docs/internals/web-frontend.md +64 -27
  22. data/docs/memory.md +4 -2
  23. data/docs/pages.md +72 -1
  24. data/docs/peers.md +25 -14
  25. data/docs/plugins.md +132 -6
  26. data/docs/releasing.md +1 -1
  27. data/docs/scheduling.md +4 -0
  28. data/docs/sessions.md +9 -2
  29. data/docs/system-one.md +3 -1
  30. data/docs/testing.md +3 -1
  31. data/lib/samagotchi/bundle_manifest.rb +30 -5
  32. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  33. data/lib/samagotchi/bundles/claude-peer/plugin.rb +2 -2
  34. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  35. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
  37. data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
  38. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
  39. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/cost-cap/manifest.yml +4 -4
  41. data/lib/samagotchi/bundles/cost-cap/plugin.rb +54 -3
  42. data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
  43. data/lib/samagotchi/bundles/github-pr/manifest.yml +4 -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 +178 -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 +27 -0
  50. data/lib/samagotchi/bundles/knowledge/plugin.rb +807 -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/context_change.rb +44 -0
  60. data/lib/samagotchi/context_note.rb +1 -1
  61. data/lib/samagotchi/context_providers.rb +14 -0
  62. data/lib/samagotchi/context_sources.rb +3 -25
  63. data/lib/samagotchi/engine/plugins.rb +21 -0
  64. data/lib/samagotchi/events.rb +1 -0
  65. data/lib/samagotchi/guardrails/pair_boundary.rb +12 -4
  66. data/lib/samagotchi/guardrails/review_paths.rb +13 -3
  67. data/lib/samagotchi/guardrails/targets.rb +24 -2
  68. data/lib/samagotchi/guardrails_command.rb +3 -9
  69. data/lib/samagotchi/hook_label.rb +19 -0
  70. data/lib/samagotchi/hook_routes.rb +3 -2
  71. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  72. data/lib/samagotchi/memory_bundle/builder.rb +2 -1
  73. data/lib/samagotchi/memory_bundle/installed_copy.rb +2 -1
  74. data/lib/samagotchi/page_command.rb +90 -6
  75. data/lib/samagotchi/pages/launch.rb +16 -8
  76. data/lib/samagotchi/pages/runner.rb +7 -2
  77. data/lib/samagotchi/pages/runtime.rb +62 -2
  78. data/lib/samagotchi/pages.rb +4 -0
  79. data/lib/samagotchi/panes/kitty.rb +20 -5
  80. data/lib/samagotchi/panes.rb +81 -12
  81. data/lib/samagotchi/participants.rb +17 -6
  82. data/lib/samagotchi/peer_exchanges.rb +1 -2
  83. data/lib/samagotchi/peer_note.rb +38 -5
  84. data/lib/samagotchi/peer_presence.rb +20 -7
  85. data/lib/samagotchi/plugin/api.rb +11 -1
  86. data/lib/samagotchi/plugin/attached_context.rb +46 -1
  87. data/lib/samagotchi/plugin/chips.rb +125 -0
  88. data/lib/samagotchi/plugin/context.rb +43 -8
  89. data/lib/samagotchi/plugin/panes.rb +52 -9
  90. data/lib/samagotchi/plugin/peer_pairing.rb +2 -2
  91. data/lib/samagotchi/plugin/peer_start.rb +61 -36
  92. data/lib/samagotchi/plugin/peers.rb +6 -3
  93. data/lib/samagotchi/plugin/project.rb +63 -0
  94. data/lib/samagotchi/plugin/sessions.rb +36 -1
  95. data/lib/samagotchi/plugin/tool_spec.rb +28 -9
  96. data/lib/samagotchi/schedules.rb +8 -2
  97. data/lib/samagotchi/session.rb +22 -9
  98. data/lib/samagotchi/session_access/local.rb +34 -33
  99. data/lib/samagotchi/session_chain/sharing.rb +79 -0
  100. data/lib/samagotchi/session_chain/successor.rb +4 -2
  101. data/lib/samagotchi/session_chips.rb +133 -0
  102. data/lib/samagotchi/session_inbox_delivery.rb +11 -11
  103. data/lib/samagotchi/session_manager/emptiness.rb +4 -1
  104. data/lib/samagotchi/session_observer.rb +1 -1
  105. data/lib/samagotchi/session_stats.rb +437 -0
  106. data/lib/samagotchi/session_stores.rb +3 -0
  107. data/lib/samagotchi/session_window.rb +30 -0
  108. data/lib/samagotchi/speaker.rb +228 -0
  109. data/lib/samagotchi/steer.rb +36 -132
  110. data/lib/samagotchi/system_one/approval_choice.rb +22 -0
  111. data/lib/samagotchi/system_one/approval_label.rb +4 -6
  112. data/lib/samagotchi/system_prompt.rb +3 -1
  113. data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
  114. data/lib/samagotchi/testing/boundary.rb +17 -4
  115. data/lib/samagotchi/testing/bundle.rb +5 -0
  116. data/lib/samagotchi/testing/host.rb +1 -0
  117. data/lib/samagotchi/testing/recorder.rb +10 -0
  118. data/lib/samagotchi/testing/sessions.rb +11 -3
  119. data/lib/samagotchi/toolkit.rb +11 -4
  120. data/lib/samagotchi/toolkit_report_command.rb +14 -18
  121. data/lib/samagotchi/toolkit_suggest.rb +9 -2
  122. data/lib/samagotchi/tools/registry.rb +48 -18
  123. data/lib/samagotchi/tools/tool_index.rb +6 -2
  124. data/lib/samagotchi/turn_excerpts.rb +302 -0
  125. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
  126. data/lib/samagotchi/version.rb +1 -1
  127. data/lib/samagotchi/web/app.rb +21 -10
  128. data/lib/samagotchi/web/participant_view.rb +1 -1
  129. data/lib/samagotchi/web/peer_routes.rb +5 -2
  130. data/lib/samagotchi/web/plugin_chip_rows.rb +39 -0
  131. data/lib/samagotchi/web/public/agent_rows.js +1 -0
  132. data/lib/samagotchi/web/public/app.js +17 -25
  133. data/lib/samagotchi/web/public/chains.js +0 -26
  134. data/lib/samagotchi/web/public/command_list.js +2 -3
  135. data/lib/samagotchi/web/public/composer.js +2 -3
  136. data/lib/samagotchi/web/public/composer_mount.js +3 -6
  137. data/lib/samagotchi/web/public/context_chips.js +240 -93
  138. data/lib/samagotchi/web/public/context_groups.js +84 -0
  139. data/lib/samagotchi/web/public/draft_follow.js +33 -0
  140. data/lib/samagotchi/web/public/drafts.js +26 -22
  141. data/lib/samagotchi/web/public/index.html +32 -0
  142. data/lib/samagotchi/web/public/peer_chip_kind.js +49 -0
  143. data/lib/samagotchi/web/public/peer_note.js +2 -2
  144. data/lib/samagotchi/web/public/peer_row.js +10 -5
  145. data/lib/samagotchi/web/public/peer_wait.js +4 -2
  146. data/lib/samagotchi/web/public/plugin_chip.js +55 -0
  147. data/lib/samagotchi/web/public/plugin_chip_kind.js +48 -0
  148. data/lib/samagotchi/web/public/send_turn.js +8 -21
  149. data/lib/samagotchi/web/public/session_actions.js +10 -23
  150. data/lib/samagotchi/web/public/session_view.js +7 -3
  151. data/lib/samagotchi/web/public/stream_handlers.js +2 -0
  152. metadata +33 -1
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The knowledge bundle's FTS5 query (manifest.yml plugin: parts:): the
4
+ # model's words become a MATCH string the bundle builds, never one it
5
+ # passes on. A word with no letter or digit is dropped (`"login" AND "--"`
6
+ # finds nothing, and an empty MATCH is a syntax error); each kept word is
7
+ # quoted (a quote in it doubled), the last also as a prefix ("sqli"*).
8
+ class Plugin
9
+ module Query
10
+ # Words past this are left out.
11
+ MAX_WORDS = 16
12
+
13
+ module_function
14
+
15
+ # The words of +text+ that have a letter or a digit.
16
+ # @return [Array<String>]
17
+ def words(text)
18
+ text.to_s.split(/\s+/).select { |word| word.match?(/[\p{L}\p{N}]/) }.first(MAX_WORDS)
19
+ end
20
+
21
+ # The MATCH string joining +words+ by +op+ ("AND", "OR"); nil for none.
22
+ def build(words, op: "AND")
23
+ return nil if words.empty?
24
+
25
+ quoted = words.map { |word| %("#{word.gsub('"', '""')}") }
26
+ quoted[-1] = "#{quoted[-1]}*"
27
+ quoted.join(" #{op} ")
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The knowledge bundle's query log (manifest.yml plugin: parts:):
4
+ # queries.jsonl beside a catalog's index, 0600, one line per search (what
5
+ # was asked, what it found, how long it took) and, raw, the next tool calls
6
+ # of the same turn after it ({after:, tool:, arg:}, arg the call's target).
7
+ # Nothing is classified here and nothing leaves the machine: an offline
8
+ # script reads it when the embeddings gate is checked
9
+ # (docs/internals/knowledge.md). At MAX bytes it moves to queries.1.jsonl
10
+ # (one kept).
11
+ require "fileutils"
12
+ require "json"
13
+
14
+ class Plugin
15
+ class QueryLog
16
+ FILE = "queries.jsonl"
17
+ OLD = "queries.1.jsonl"
18
+ MAX = 5 * 1024 * 1024
19
+ # A follow-up's arg: a plugin call's first of these args, cut (a
20
+ # built-in's is its path, else its main argument: QueryLog.arg).
21
+ ARG_KEYS = %w[path name url open query].freeze
22
+ ARG_CHARS = 200
23
+
24
+ def initialize(dir)
25
+ @dir = dir
26
+ end
27
+
28
+ def path = File.join(@dir, FILE)
29
+
30
+ def append(record)
31
+ FileUtils.mkdir_p(@dir, mode: 0o700)
32
+ File.rename(path, File.join(@dir, OLD)) if File.size?(path).to_i >= MAX
33
+ File.open(path, File::WRONLY | File::APPEND | File::CREAT, 0o600) do |file|
34
+ file.flock(File::LOCK_EX)
35
+ file.write("#{JSON.generate(record)}\n")
36
+ end
37
+ rescue SystemCallError, JSON::GeneratorError
38
+ nil
39
+ end
40
+
41
+ # A plugin call's (args:) path / name / url / open / query arg, or
42
+ # only +keys+; a built-in's (Tools::BuiltinCalls.build: no args:) path,
43
+ # else its content (read's path, execute's command; path first, so a
44
+ # write logs its file, not its body), never its name. Cut; nil
45
+ # without one.
46
+ def self.arg(call, keys: ARG_KEYS)
47
+ return nil unless call.is_a?(Hash)
48
+
49
+ args = call[:args] || call["args"]
50
+ candidates = args.is_a?(Hash) ? keys.map { |key| args[key] || args[key.to_sym] } : [call[:path], call[:content]]
51
+ value = candidates.find { |candidate| candidate.is_a?(String) && !candidate.empty? }
52
+ value&.[](0, ARG_CHARS)
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The knowledge bundle's refresh (manifest.yml plugin: parts:): a source is
4
+ # re-read only when a search (or knowledge_add, for its new source) finds
5
+ # it stale, never between searches. The stale sources refresh on a thread
6
+ # the caller waits for at most its budget; past that, the answer is read
7
+ # from the index as it is and the thread finishes in the background (it is
8
+ # not joined at worker exit: a killed sqlite3 child is safe under WAL, and
9
+ # the next refresh redoes that batch). Each source refreshes under its own
10
+ # lock, taken without waiting: one held elsewhere is skipped.
11
+ class Plugin
12
+ class Refresh
13
+ # Items per index write (each one transaction under the index lock).
14
+ GROUP = 200
15
+
16
+ # @param build [#call] (source Hash, ctx) → its adapter
17
+ # @param background [#call] (source Hash) → whether a search never
18
+ # waits for it (a github fetch): it refreshes on a thread of its own
19
+ def initialize(catalog, store, build:, background: ->(_source) { false }, clock: -> { Time.now.to_i })
20
+ @catalog = catalog
21
+ @store = store
22
+ @build = build
23
+ @background = background
24
+ @clock = clock
25
+ @progress = {}
26
+ end
27
+
28
+ # Refresh the +sources+ (records) that are stale, or every one of
29
+ # +force+ (names), waiting at most +budget_ms+ (never for a background
30
+ # one, unless forced). +cancel+ (#cancelled?: ctx.cancel_controller)
31
+ # ends one between groups; +ctx+ goes to the adapters.
32
+ # @return [Hash{String => Symbol}] name => :refreshed, :failed,
33
+ # :elsewhere (another refresh holds it) or :refreshing (still running)
34
+ def run(sources, budget_ms:, force: [], cancel: nil, ctx: nil)
35
+ now = @clock.call
36
+ due = sources.select { |source| force.include?(source["name"]) || Catalog.stale?(source, now) }
37
+ return {} if due.empty?
38
+
39
+ states = {}
40
+ later, waited = due.partition { |source| !force.include?(source["name"]) && @background.call(source) }
41
+ start = lambda do |group|
42
+ Thread.new do
43
+ Thread.current.report_on_exception = false
44
+ group.each { |source| states[source["name"]] = one(source, cancel, ctx) }
45
+ end
46
+ end
47
+ start.call(later) unless later.empty?
48
+ start.call(waited).join(budget_ms / 1000.0) unless waited.empty?
49
+ due.to_h { |source| [source["name"], states.fetch(source["name"], :refreshing)] }
50
+ end
51
+
52
+ # The share of +name+'s changed items written so far (0..1), nil when
53
+ # it isn't running here.
54
+ def progress(name) = @progress[name]
55
+
56
+ private
57
+
58
+ def one(source, cancel, ctx)
59
+ name = source["name"]
60
+ return :refreshing if @progress.key?(name)
61
+
62
+ state = :refreshed
63
+ held = @catalog.with_source_lock(name) do
64
+ @progress[name] = 0.0
65
+ state = refresh(source, cancel, ctx)
66
+ ensure
67
+ @progress.delete(name)
68
+ end
69
+ held ? state : :elsewhere
70
+ end
71
+
72
+ # An adapter with #gone lists only what changed since its source's
73
+ # listed_at (the sessions one): #gone says which old keys are gone. An
74
+ # item that couldn't be read keeps listed_at at or before its
75
+ # updated_at, so the next listing reads it again.
76
+ def refresh(source, cancel, ctx)
77
+ name = source["name"]
78
+ listed_at = @clock.call
79
+ @catalog.lock { @store.ensure_schema! }
80
+ adapter = @build.call(source, ctx)
81
+ items = adapter.items
82
+ old = @store.sigs(name)
83
+ changed = items.reject { |item| old[item.key] == item.sig }
84
+ gone = adapter.respond_to?(:gone) ? adapter.gone(old.keys) : old.keys - items.map(&:key)
85
+ changed.each_slice(GROUP).with_index do |group, index|
86
+ return record(name, error: "cancelled") if cancel&.cancelled?
87
+
88
+ rows = group.filter_map do |item|
89
+ row(name, item, adapter).tap { |made| listed_at = [listed_at, item.updated_at.to_i].min if made.nil? && item.updated_at }
90
+ end
91
+ @catalog.lock { @store.put(rows) }
92
+ @progress[name] = ((index + 1) * GROUP.to_f / changed.size).clamp(0.0, 1.0)
93
+ end
94
+ @catalog.lock { @store.delete(gone.map { |key| [name, key] }) } unless gone.empty?
95
+ record(name, skipped: adapter.skipped, listed_at: listed_at)
96
+ :refreshed
97
+ rescue StandardError => e
98
+ record(name, error: "#{e.class.name.split("::").last}: #{e.message}"[0, 300])
99
+ :failed
100
+ end
101
+
102
+ # The item as Store#put takes it, nil when its text can't be read. An
103
+ # adapter with #chunks makes its own (a session's: one line per message).
104
+ def row(name, item, adapter)
105
+ chunks = if adapter.respond_to?(:chunks)
106
+ adapter.chunks(item)
107
+ else
108
+ (text = adapter.text(item)) && Chunker.chunks(text, name: File.basename(item.title.to_s))
109
+ end
110
+ return nil if chunks.nil?
111
+
112
+ { source: name, key: item.key, title: item.title, ptr: item.ptr, url: item.url, path: item.path,
113
+ updated_at: item.updated_at, sig: item.sig, chunks: chunks }
114
+ end
115
+
116
+ def record(name, error: nil, skipped: nil, listed_at: nil)
117
+ counts = @store.exists? ? @store.counts.fetch(name, { items: 0, chunks: 0 }) : { items: 0, chunks: 0 }
118
+ @catalog.update do |data|
119
+ source = data["sources"].find { |entry| entry["name"] == name } or next
120
+ if error
121
+ source.merge!("last_error" => error, "last_error_at" => @clock.call)
122
+ else
123
+ source.merge!("refreshed_at" => @clock.call, "listed_at" => listed_at, "last_error" => nil, "last_error_at" => nil)
124
+ source["skipped"] = skipped.transform_keys(&:to_s).reject { |_, n| n.zero? } if skipped
125
+ end
126
+ source.merge!("items" => counts[:items], "chunks" => counts[:chunks])
127
+ end
128
+ error ? :failed : :refreshed
129
+ rescue StandardError
130
+ error ? :failed : :refreshed
131
+ end
132
+ end
133
+ end
@@ -0,0 +1,264 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The knowledge bundle's first part (manifest.yml plugin: parts:): Store, one
4
+ # catalog's SQLite FTS5 index, through the sqlite3 CLI (no gem). The rules
5
+ # (docs/internals/knowledge.md):
6
+ # - every run is `sqlite3 -init /dev/null -safe -bail -nofollow [-json] DB`
7
+ # with the SQL on stdin (after `.timeout BUSY_MS`), never argv, and no
8
+ # shell: no rc file is read
9
+ # (a user's .mode would break the JSON), -safe refuses .shell, ATTACH,
10
+ # readfile() and the rest, -nofollow a db reached through a symlink;
11
+ # - the SQL text is constant per operation: every value, and the MATCH
12
+ # string, goes in as a hex literal (cast(x'…' as text)), JSON arrays
13
+ # read with json_each; numbers are Integer()s;
14
+ # - the folder is realpath'd once and index.db made here, 0600, before the
15
+ # CLI opens it (-nofollow can't create one): built whole as index.db.new
16
+ # and renamed into place, so a search never sees it half made;
17
+ # - searches open it read-write with `pragma query_only=1` first (Apple's
18
+ # -readonly fails on a WAL db whose -wal/-shm are gone) and never wait on
19
+ # a write transaction (WAL); the exclusive lock a sole connection takes
20
+ # when it opens or closes the db (WAL recovery, the close-time checkpoint)
21
+ # is waited out by the busy timeout, every run's, a few ms in practice;
22
+ # - -json prints nothing, not [], for no rows.
23
+ require "fileutils"
24
+ require "json"
25
+ require "open3"
26
+
27
+ class Plugin
28
+ class Store
29
+ # A sqlite3 run failed: its first error line.
30
+ class Error < StandardError; end
31
+
32
+ SCHEMA_VERSION = "1"
33
+ DB = "index.db"
34
+ BASE_ARGS = ["-init", File::NULL, "-safe", "-bail", "-nofollow"].freeze
35
+ # Every run's busy timeout: what it waits on is another sqlite3's
36
+ # open/close-time exclusive lock (and a writer, another's transaction).
37
+ BUSY_MS = 2000
38
+ # A batch's JSON stays well under the CLI's line and memory limits.
39
+ BATCH_BYTES = 1_500_000
40
+
41
+ SCHEMA = <<~SQL
42
+ pragma journal_mode=wal;
43
+ create table if not exists meta(k text primary key, v text);
44
+ create table if not exists items(id integer primary key, source text, key text, title text, ptr text, url text,
45
+ path text, updated_at integer, sig text, unique(source, key));
46
+ create table if not exists chunk_map(chunk integer primary key, item integer, line integer);
47
+ create index if not exists chunk_map_item on chunk_map(item);
48
+ create virtual table if not exists chunks using fts5(title, body, tokenize='porter unicode61');
49
+ insert or ignore into meta(k, v) values('schema', '#{SCHEMA_VERSION}');
50
+ select v from meta where k = 'schema';
51
+ SQL
52
+
53
+ # Upserts a batch of items (their old chunks gone) and inserts their
54
+ # chunks: temp.batch holds the JSON array, one row per item.
55
+ PUT = <<~SQL
56
+ create temp table batch as select value as v from json_each(cast(%<json>s as text));
57
+ create temp table keys as select json_extract(v, '$.source') as s, json_extract(v, '$.key') as k from temp.batch;
58
+ delete from chunks where rowid in (select chunk from chunk_map where item in
59
+ (select id from items where (source, key) in (select s, k from temp.keys)));
60
+ delete from chunk_map where item in (select id from items where (source, key) in (select s, k from temp.keys));
61
+ insert into items(source, key, title, ptr, url, path, updated_at, sig)
62
+ select json_extract(v, '$.source'), json_extract(v, '$.key'), json_extract(v, '$.title'), json_extract(v, '$.ptr'),
63
+ json_extract(v, '$.url'), json_extract(v, '$.path'), json_extract(v, '$.updated_at'), json_extract(v, '$.sig')
64
+ from temp.batch where true
65
+ on conflict(source, key) do update set title = excluded.title, ptr = excluded.ptr, url = excluded.url,
66
+ path = excluded.path, updated_at = excluded.updated_at, sig = excluded.sig;
67
+ create temp table bchunks as
68
+ select i.id as item, json_extract(c.value, '$.title') as title, json_extract(c.value, '$.body') as body,
69
+ json_extract(c.value, '$.line') as line
70
+ from temp.batch b join items i on i.source = json_extract(b.v, '$.source') and i.key = json_extract(b.v, '$.key'),
71
+ json_each(b.v, '$.chunks') c;
72
+ create temp table base as select coalesce(max(rowid), 0) as b from chunks;
73
+ insert into chunks(rowid, title, body) select (select b from temp.base) + rowid, title, body from temp.bchunks;
74
+ insert into chunk_map(chunk, item, line) select (select b from temp.base) + rowid, item, line from temp.bchunks;
75
+ drop table temp.batch; drop table temp.keys; drop table temp.bchunks; drop table temp.base;
76
+ SQL
77
+
78
+ # Deletes the items (and their chunks) temp.gone names.
79
+ DELETE_GONE = <<~SQL
80
+ delete from chunks where rowid in (select chunk from chunk_map where item in
81
+ (select id from items where (source, key) in (select s, k from temp.gone)));
82
+ delete from chunk_map where item in (select id from items where (source, key) in (select s, k from temp.gone));
83
+ delete from items where (source, key) in (select s, k from temp.gone);
84
+ drop table temp.gone;
85
+ SQL
86
+
87
+ # @param dir [String] the catalog's folder (made 0700, realpath'd here)
88
+ # @param sqlite [String] the sqlite3 CLI
89
+ def initialize(dir, sqlite:)
90
+ FileUtils.mkdir_p(dir, mode: 0o700)
91
+ @dir = File.realpath(dir)
92
+ @db = File.join(@dir, DB)
93
+ @sqlite = sqlite
94
+ end
95
+
96
+ attr_reader :dir
97
+
98
+ # cast(x'…' as text)'s literal for +text+: no quote, newline or
99
+ # dot-command of it reaches the SQL as anything but a value.
100
+ def self.hex(text) = "x'#{text.to_s.b.unpack1("H*")}'"
101
+
102
+ # The SQL literal of +value+ as JSON (hex), for json_each.
103
+ def self.json(value) = hex(JSON.generate(value))
104
+
105
+ # Whether the index has been made (a search of a catalog never indexed
106
+ # finds nothing, without making it).
107
+ def exists? = File.file?(@db) && !File.symlink?(@db)
108
+
109
+ # Make the db (0600) and its schema; a schema of another version is
110
+ # dropped and made again (re-creatable data). Call under the catalog's
111
+ # index lock.
112
+ def ensure_schema!
113
+ if exists?
114
+ return if run(SCHEMA).lines.last.to_s.strip == SCHEMA_VERSION
115
+
116
+ [@db, "#{@db}-wal", "#{@db}-shm"].each { |path| FileUtils.rm_f(path) }
117
+ end
118
+ build!
119
+ end
120
+
121
+ # One write transaction of +sql+ (constant text with hex values).
122
+ def write(sql) = run("begin immediate;\n#{sql}\ncommit;\n")
123
+
124
+ # Put +items+ ({source:, key:, title:, ptr:, url:, path:, updated_at:,
125
+ # sig:, chunks: [{title:, body:, line:}]}), in transactions of at most
126
+ # BATCH_BYTES of JSON. +stop+ (→ true) ends it between batches.
127
+ def put(items, stop: -> { false })
128
+ batches(items).each do |batch|
129
+ break if stop.call
130
+
131
+ write(format(PUT, json: Store.json(batch)))
132
+ end
133
+ end
134
+
135
+ # Delete the items +keys+ ([source, key] pairs) and their chunks.
136
+ def delete(keys)
137
+ keys.each_slice(2000) do |slice|
138
+ rows = slice.map { |source, key| { s: source, k: key } }
139
+ write("create temp table gone as select json_extract(value, '$.s') as s, json_extract(value, '$.k') as k " \
140
+ "from json_each(cast(#{Store.json(rows)} as text));\n#{DELETE_GONE}")
141
+ end
142
+ end
143
+
144
+ # Delete every item of +source+.
145
+ def delete_source(source)
146
+ write("create temp table gone as select source as s, key as k from items where source = cast(#{Store.hex(source)} as text);\n" \
147
+ "#{DELETE_GONE}")
148
+ end
149
+
150
+ # {key => sig} of +source+'s items.
151
+ def sigs(source)
152
+ select("select key, sig from items where source = cast(#{Store.hex(source)} as text);")
153
+ .to_h { |row| [row["key"], row["sig"]] }
154
+ end
155
+
156
+ # {source => {items:, chunks:}}.
157
+ def counts
158
+ select("select i.source as source, count(distinct i.id) as items, count(m.chunk) as chunks " \
159
+ "from items i left join chunk_map m on m.item = i.id group by i.source;")
160
+ .to_h { |row| [row["source"], { items: row["items"].to_i, chunks: row["chunks"].to_i }] }
161
+ end
162
+
163
+ # The db's bytes on disk (with its -wal).
164
+ def size = [@db, "#{@db}-wal"].sum { |path| File.file?(path) ? File.size(path) : 0 }
165
+
166
+ # The best chunks for an FTS5 +match+ string (Query#build's), as rows
167
+ # {source, key, title, ptr, url, path, updated_at, chunk_title, snippet,
168
+ # line, part (the chunk's place among its line's: a long message's
169
+ # pieces share one line), score}, best first (bm25 with the title weighted 5, ties by the
170
+ # newer item); only +sources+ (names), items updated at or after
171
+ # +since+ (epoch seconds), none of +skip+ ([source, key] pairs: the
172
+ # searching session's own), at most +limit+ rows. Read-only.
173
+ def search(match, sources:, since: nil, limit: 40, skip: [])
174
+ return [] unless exists?
175
+
176
+ filters = ["chunks match cast(#{Store.hex(match)} as text)",
177
+ "i.source in (select value from json_each(cast(#{Store.json(sources)} as text)))"]
178
+ filters << "i.updated_at >= #{Integer(since)}" if since
179
+ unless skip.empty?
180
+ pairs = Store.json(skip.map { |source, key| { s: source, k: key } })
181
+ filters << "(i.source, i.key) not in (select json_extract(value, '$.s'), json_extract(value, '$.k') " \
182
+ "from json_each(cast(#{pairs} as text)))"
183
+ end
184
+ select(<<~SQL, read_only: true)
185
+ select i.source as source, i.key as key, i.title as title, i.ptr as ptr, i.url as url, i.path as path,
186
+ i.updated_at as updated_at, chunks.title as chunk_title, m.line as line,
187
+ (select count(*) from chunk_map p where p.item = m.item and p.line = m.line and p.chunk < m.chunk) as part,
188
+ snippet(chunks, 1, '«', '»', '…', 14) as snippet, bm25(chunks, 5.0, 1.0) as score
189
+ from chunks join chunk_map m on m.chunk = chunks.rowid join items i on i.id = m.item
190
+ where #{filters.join(" and ")}
191
+ order by score, i.updated_at desc
192
+ limit #{Integer(limit)};
193
+ SQL
194
+ end
195
+
196
+ # The stored chunks of item +key+ in one of +sources+ (names), in line
197
+ # order: rows {source, key, title, updated_at, line, chunk_title, body}
198
+ # (knowledge_search open:). Read-only.
199
+ def chunks_of(key, sources:)
200
+ return [] unless exists?
201
+
202
+ select(<<~SQL, read_only: true)
203
+ select i.source as source, i.key as key, i.title as title, i.updated_at as updated_at, m.line as line,
204
+ chunks.title as chunk_title, chunks.body as body
205
+ from items i join chunk_map m on m.item = i.id join chunks on chunks.rowid = m.chunk
206
+ where i.key = cast(#{Store.hex(key)} as text)
207
+ and i.source in (select value from json_each(cast(#{Store.json(sources)} as text)))
208
+ order by i.source, m.line, m.chunk;
209
+ SQL
210
+ end
211
+
212
+ # Rows of a select, as Hashes; +read_only+ runs it under query_only.
213
+ def select(sql, read_only: false)
214
+ out = run(read_only ? "pragma query_only=1;\n#{sql}" : sql, json: true)
215
+ out.strip.empty? ? [] : JSON.parse(out)
216
+ end
217
+
218
+ private
219
+
220
+ # index.db.new made 0600 with the schema, then renamed to index.db: a
221
+ # search finds no db or a whole one, never one without its tables or
222
+ # one switching to WAL. Its -wal, checkpointed and truncated (Apple's
223
+ # sqlite3 keeps it at close), is removed before the rename.
224
+ def build!
225
+ fresh = "#{@db}.new"
226
+ leftovers = ["#{fresh}-wal", "#{fresh}-shm"]
227
+ [fresh, *leftovers].each { |path| FileUtils.rm_f(path) }
228
+ File.open(fresh, File::CREAT | File::EXCL | File::NOFOLLOW | File::WRONLY, 0o600) { nil }
229
+ run("#{SCHEMA}pragma wal_checkpoint(truncate);\n", db: fresh)
230
+ leftovers.each { |path| FileUtils.rm_f(path) }
231
+ raise Error, "#{@db} is not a plain file" if File.symlink?(@db) || (File.exist?(@db) && !File.file?(@db))
232
+
233
+ File.rename(fresh, @db)
234
+ end
235
+
236
+ def run(sql, json: false, db: @db)
237
+ args = [*BASE_ARGS, *(json ? ["-json"] : []), db]
238
+ out, err, status = Open3.capture3(@sqlite, *args, stdin_data: ".timeout #{BUSY_MS}\n#{sql}")
239
+ raise(Error, err.to_s.lines.first.to_s.strip.then { |line| line.empty? ? "sqlite3 failed (#{status.exitstatus})" : line }) unless status.success?
240
+
241
+ out
242
+ rescue SystemCallError => e
243
+ raise Error, "#{@sqlite}: #{e.message}"
244
+ end
245
+
246
+ def batches(items)
247
+ batch = []
248
+ bytes = 0
249
+ out = []
250
+ items.each do |item|
251
+ size = JSON.generate(item).bytesize
252
+ if !batch.empty? && bytes + size > BATCH_BYTES
253
+ out << batch
254
+ batch = []
255
+ bytes = 0
256
+ end
257
+ batch << item
258
+ bytes += size
259
+ end
260
+ out << batch unless batch.empty?
261
+ out
262
+ end
263
+ end
264
+ end
@@ -0,0 +1,17 @@
1
+ ---
2
+ name: reflect
3
+ version: 0.2.0
4
+ scope: system
5
+ description: "A Reflect page in chi web (#/p/reflect, chi page run reflect): how one project's sessions went over 14 days and the last 24 hours (failures, cancels, tool errors, approvals, plugins, cost, context) and the worst turns' failing calls; read-only, no model. And skill_reflect, the steps of a nightly reflect session that suggests changes and never applies them"
6
+ trust_level: reviewed
7
+ # runtime.sessions, turn_excerpts, launch_dir and settings are new in the next chi: release:bump raises requires_chi.
8
+ requires_chi: ">= 0.195.0"
9
+ files:
10
+ skill_reflect.md:
11
+ sha256: sha256:5168dee1341d677f9a1c02df1561f5add71e489e00c036d066b5bd78c24065c6
12
+ description: "Nightly reflect: read this project's reflect page, pick at most 3 problems, verify each, suggest the exact change; never apply"
13
+ scripts:
14
+ reflect.rb: sha256:9de6973c9f6671ef71a0b6f489d054b46eeeb61c5a36fc4003897f95aeab5486
15
+ pages: [reflect.rb]
16
+ # config.yml bundles: reflect: (another key warns)
17
+ settings: [include_text, mask_names]