samagotchi 0.201.0 → 0.202.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 (175) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +57 -1
  3. data/docs/architecture.md +47 -7
  4. data/docs/cli.md +20 -1
  5. data/docs/configuration.md +2 -1
  6. data/docs/internals/bridge.md +4 -4
  7. data/docs/internals/engine.md +9 -6
  8. data/docs/internals/knowledge.md +26 -6
  9. data/docs/internals/objectives.md +2 -2
  10. data/docs/internals/pages.md +4 -2
  11. data/docs/internals/participants.md +1 -1
  12. data/docs/internals/peers.md +9 -7
  13. data/docs/internals/remote-sessions.md +6 -6
  14. data/docs/internals/session-lifecycle.md +37 -15
  15. data/docs/internals/web-frontend.md +18 -7
  16. data/docs/pages.md +6 -3
  17. data/docs/plugins.md +2 -2
  18. data/docs/scheduling.md +40 -12
  19. data/docs/sessions.md +48 -6
  20. data/docs/sub-agent.md +1 -2
  21. data/docs/testing.md +92 -8
  22. data/lib/samagotchi/answer_display.rb +3 -2
  23. data/lib/samagotchi/answer_tail.rb +4 -4
  24. data/lib/samagotchi/bridge/card_places.rb +5 -5
  25. data/lib/samagotchi/bridge/turn_accumulator.rb +5 -5
  26. data/lib/samagotchi/bridge/turn_drawings/synth.rb +5 -5
  27. data/lib/samagotchi/bridge/turn_drawings.rb +2 -2
  28. data/lib/samagotchi/bridge/turn_ranges.rb +15 -8
  29. data/lib/samagotchi/bridge.rb +5 -5
  30. data/lib/samagotchi/broadcast_command.rb +3 -3
  31. data/lib/samagotchi/bundle_command/try/trace.rb +18 -6
  32. data/lib/samagotchi/bundles/knowledge/embedder.rb +2 -0
  33. data/lib/samagotchi/bundles/knowledge/github.rb +19 -0
  34. data/lib/samagotchi/bundles/knowledge/manifest.yml +6 -6
  35. data/lib/samagotchi/bundles/knowledge/plugin.rb +26 -54
  36. data/lib/samagotchi/bundles/knowledge/refresh.rb +89 -14
  37. data/lib/samagotchi/bundles/knowledge/store.rb +36 -2
  38. data/lib/samagotchi/bundles/schedules/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +24 -3
  40. data/lib/samagotchi/bundles/system/config_modification_protocol.md +1 -1
  41. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  42. data/lib/samagotchi/bundles/system/skill_pages.md +1 -1
  43. data/lib/samagotchi/chi_invocation.rb +1 -1
  44. data/lib/samagotchi/child_move.rb +6 -3
  45. data/lib/samagotchi/child_reports.rb +3 -3
  46. data/lib/samagotchi/children_status.rb +4 -2
  47. data/lib/samagotchi/client_id.rb +2 -2
  48. data/lib/samagotchi/compat.rb +4 -6
  49. data/lib/samagotchi/config.rb +3 -0
  50. data/lib/samagotchi/context_note.rb +1 -1
  51. data/lib/samagotchi/continue_intent.rb +1 -1
  52. data/lib/samagotchi/continue_offer.rb +2 -2
  53. data/lib/samagotchi/continue_repair_backoff.rb +71 -0
  54. data/lib/samagotchi/delivery.rb +1 -4
  55. data/lib/samagotchi/engine/participants.rb +1 -1
  56. data/lib/samagotchi/engine/recap.rb +1 -1
  57. data/lib/samagotchi/engine/turn_end.rb +1 -1
  58. data/lib/samagotchi/grants.rb +2 -2
  59. data/lib/samagotchi/guardrail_wiring.rb +1 -1
  60. data/lib/samagotchi/guardrails/approval.rb +3 -3
  61. data/lib/samagotchi/guardrails/pair_boundary.rb +3 -3
  62. data/lib/samagotchi/guardrails/participant_refusal.rb +2 -2
  63. data/lib/samagotchi/idle_recap.rb +6 -6
  64. data/lib/samagotchi/kernel_loop.rb +1 -1
  65. data/lib/samagotchi/last_turn.rb +9 -6
  66. data/lib/samagotchi/llm/chat_loop.rb +5 -2
  67. data/lib/samagotchi/mcp_command.rb +2 -2
  68. data/lib/samagotchi/memory_usage.rb +7 -6
  69. data/lib/samagotchi/note_command.rb +1 -1
  70. data/lib/samagotchi/note_delivery.rb +5 -5
  71. data/lib/samagotchi/objectives_backing.rb +3 -3
  72. data/lib/samagotchi/objectives_record.rb +2 -2
  73. data/lib/samagotchi/objectives_track.rb +2 -2
  74. data/lib/samagotchi/owner_lock.rb +28 -2
  75. data/lib/samagotchi/owner_prompt.rb +3 -3
  76. data/lib/samagotchi/pages/runtime.rb +9 -4
  77. data/lib/samagotchi/participant_revise.rb +6 -6
  78. data/lib/samagotchi/peer_receipts.rb +11 -4
  79. data/lib/samagotchi/plugin/side_question.rb +1 -1
  80. data/lib/samagotchi/recap_place.rb +5 -5
  81. data/lib/samagotchi/reply_for.rb +3 -3
  82. data/lib/samagotchi/reply_wait/liveness.rb +2 -2
  83. data/lib/samagotchi/reply_wait/poll.rb +3 -3
  84. data/lib/samagotchi/schedule_command.rb +1 -1
  85. data/lib/samagotchi/schedule_display.rb +4 -3
  86. data/lib/samagotchi/schedules/busy_part.rb +29 -5
  87. data/lib/samagotchi/schedules/history_part.rb +47 -7
  88. data/lib/samagotchi/schedules/marks_part.rb +52 -29
  89. data/lib/samagotchi/schedules/notices_part.rb +31 -4
  90. data/lib/samagotchi/schedules/protection_part.rb +69 -11
  91. data/lib/samagotchi/schedules/prune_part.rb +3 -2
  92. data/lib/samagotchi/schedules.rb +37 -47
  93. data/lib/samagotchi/send_command.rb +12 -12
  94. data/lib/samagotchi/session.rb +71 -59
  95. data/lib/samagotchi/session_access/contract.rb +7 -0
  96. data/lib/samagotchi/session_access/exchange.rb +1 -1
  97. data/lib/samagotchi/session_access/local.rb +9 -9
  98. data/lib/samagotchi/session_access/remote.rb +20 -24
  99. data/lib/samagotchi/session_access.rb +1 -1
  100. data/lib/samagotchi/session_chain/delete.rb +15 -8
  101. data/lib/samagotchi/session_chain/delete_preview.rb +3 -3
  102. data/lib/samagotchi/session_chain/links.rb +18 -4
  103. data/lib/samagotchi/session_chain/successor.rb +1 -1
  104. data/lib/samagotchi/session_chain.rb +3 -3
  105. data/lib/samagotchi/session_continue.rb +83 -32
  106. data/lib/samagotchi/session_inbox.rb +6 -17
  107. data/lib/samagotchi/session_inbox_delivery.rb +36 -13
  108. data/lib/samagotchi/session_lifecycle/allowed.rb +5 -5
  109. data/lib/samagotchi/session_manager/delegate_rule.rb +2 -2
  110. data/lib/samagotchi/session_manager/delivery.rb +13 -38
  111. data/lib/samagotchi/session_manager/emptiness.rb +35 -15
  112. data/lib/samagotchi/session_manager/lifecycle.rb +3 -2
  113. data/lib/samagotchi/session_manager/listing.rb +35 -10
  114. data/lib/samagotchi/session_manager/removal.rb +16 -0
  115. data/lib/samagotchi/session_manager/spawn.rb +9 -6
  116. data/lib/samagotchi/session_manager.rb +6 -4
  117. data/lib/samagotchi/session_messages.rb +602 -0
  118. data/lib/samagotchi/session_metrics.rb +7 -4
  119. data/lib/samagotchi/session_participants.rb +4 -4
  120. data/lib/samagotchi/session_protection.rb +16 -2
  121. data/lib/samagotchi/session_retention.rb +26 -12
  122. data/lib/samagotchi/session_row.rb +1 -1
  123. data/lib/samagotchi/session_stats.rb +17 -8
  124. data/lib/samagotchi/session_stores.rb +5 -0
  125. data/lib/samagotchi/session_transition.rb +3 -2
  126. data/lib/samagotchi/sessions_command.rb +55 -3
  127. data/lib/samagotchi/steer.rb +16 -50
  128. data/lib/samagotchi/storage_migration.rb +234 -0
  129. data/lib/samagotchi/terminal_ui/attached_loop.rb +3 -3
  130. data/lib/samagotchi/terminal_ui/formatting.rb +5 -5
  131. data/lib/samagotchi/terminal_ui/join_replay.rb +3 -3
  132. data/lib/samagotchi/terminal_ui/question_prompt.rb +2 -2
  133. data/lib/samagotchi/toolkit_report_command.rb +1 -1
  134. data/lib/samagotchi/tools/ask_session.rb +2 -2
  135. data/lib/samagotchi/tools/send_note.rb +1 -1
  136. data/lib/samagotchi/turn_context.rb +3 -3
  137. data/lib/samagotchi/turn_endings.rb +17 -0
  138. data/lib/samagotchi/turn_excerpts.rb +7 -4
  139. data/lib/samagotchi/turn_flow.rb +1 -1
  140. data/lib/samagotchi/turn_note.rb +30 -2
  141. data/lib/samagotchi/turn_origin.rb +7 -7
  142. data/lib/samagotchi/turn_outcome.rb +11 -0
  143. data/lib/samagotchi/turn_stages/verify_anchors.rb +4 -4
  144. data/lib/samagotchi/verify_fresh.rb +6 -6
  145. data/lib/samagotchi/verify_fresh_origin.rb +4 -4
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +4 -3
  148. data/lib/samagotchi/web/last_ask.rb +2 -2
  149. data/lib/samagotchi/web/message_display.rb +12 -12
  150. data/lib/samagotchi/web/page_routes.rb +9 -3
  151. data/lib/samagotchi/web/participant_view.rb +4 -4
  152. data/lib/samagotchi/web/participants_admin.rb +1 -1
  153. data/lib/samagotchi/web/public/bubbles.js +1 -1
  154. data/lib/samagotchi/web/public/composer_fold.js +0 -3
  155. data/lib/samagotchi/web/public/composer_grip.js +0 -2
  156. data/lib/samagotchi/web/public/page_view.js +29 -4
  157. data/lib/samagotchi/web/public/participant_model.js +1 -1
  158. data/lib/samagotchi/web/public/peer_wait.js +2 -4
  159. data/lib/samagotchi/web/public/schedule_marks.js +2 -5
  160. data/lib/samagotchi/web/public/schedule_name.js +14 -0
  161. data/lib/samagotchi/web/public/session_actions.js +5 -0
  162. data/lib/samagotchi/web/public/start_page.js +1 -1
  163. data/lib/samagotchi/web/public/stop_sheet.js +2 -4
  164. data/lib/samagotchi/web/public/working_set_rail.js +0 -3
  165. data/lib/samagotchi/web/push/attention.rb +1 -1
  166. data/lib/samagotchi/web/session_create.rb +1 -1
  167. data/lib/samagotchi/web/session_hub.rb +68 -20
  168. data/lib/samagotchi/web/session_summary.rb +18 -14
  169. data/lib/samagotchi/web/verify_fresh_routes.rb +4 -4
  170. data/lib/samagotchi/worker/turn_drain.rb +158 -0
  171. data/lib/samagotchi/worker.rb +8 -144
  172. data/lib/samagotchi/worker_boot.rb +21 -5
  173. data/lib/samagotchi/worker_participant_gate.rb +5 -5
  174. data/lib/samagotchi/worker_presence.rb +24 -1
  175. metadata +6 -1
@@ -456,11 +456,11 @@ module Samagotchi
456
456
  private :last_turn_drawing
457
457
 
458
458
  # The turn id of the last user message that opens a turn
459
- # (Steer.turn_prompt?, as JoinReplay finds the prompt it draws), nil
459
+ # (Speaker.turn_prompt?, as JoinReplay finds the prompt it draws), nil
460
460
  # for none or one with no id (a `!cmd`'s record, a line from before
461
461
  # turn ids).
462
462
  def last_prompt_turn_id(messages)
463
- prompt = messages.reverse_each.find { |m| m.is_a?(Hash) && (m[:role] || m["role"]).to_s == "user" && Steer.turn_prompt?(m) }
463
+ prompt = messages.reverse_each.find { |m| m.is_a?(Hash) && (m[:role] || m["role"]).to_s == "user" && Speaker.turn_prompt?(m) }
464
464
  id = prompt && (prompt[:turn_id] || prompt["turn_id"])
465
465
  id.is_a?(String) && !id.empty? ? id : nil
466
466
  end
@@ -1316,7 +1316,7 @@ module Samagotchi
1316
1316
  # How many of a participant's turns may be running or waiting
1317
1317
  # (chi web's, from their grant: its queue limit plus the running one).
1318
1318
  pending_limit = nil
1319
- if Steer.participant_author?(author)
1319
+ if Speaker.participant_author?(author)
1320
1320
  # A participant's message never cuts, nor is a command or a shell
1321
1321
  # line: chi web refuses those first, and this is the worker's own
1322
1322
  # layer. It goes into a running turn only when that turn is theirs
@@ -1481,7 +1481,7 @@ module Samagotchi
1481
1481
  # only (none running: theirs runs as the next turn, a queue). Read with
1482
1482
  # the event log held.
1483
1483
  def same_author_steer?(author)
1484
- sender = Steer.sender_author(author)
1484
+ sender = Speaker.sender_author(author)
1485
1485
  running = @accumulator.participant_author
1486
1486
  return running.nil? if sender.nil?
1487
1487
  return false if @accumulator.current_turn.nil?
@@ -1499,7 +1499,7 @@ module Samagotchi
1499
1499
  # 403 not_permitted for a participant's +what+ (a command, a shell
1500
1500
  # line), with its audit line.
1501
1501
  def participant_refused(sid, author, what)
1502
- Participants.log(sid, :refused, state_dir: File.dirname(session_dir), participant: Steer.participant_id(author), what: what,
1502
+ Participants.log(sid, :refused, state_dir: File.dirname(session_dir), participant: Speaker.participant_id(author), what: what,
1503
1503
  reason: "not_permitted")
1504
1504
  [{}, 403, { error: "not_permitted", detail: Participants::NOT_PERMITTED }]
1505
1505
  end
@@ -254,7 +254,7 @@ module Samagotchi
254
254
  lines = decisions.map do |d|
255
255
  next [d, "skipped", d.verdict.reason] unless d.deliver?
256
256
 
257
- head = SessionInbox::Head.resolve(:note, d.recipient.id, state_dir: @state_dir)
257
+ head = InboxDelivery::Head.resolve(:note, d.recipient.id, state_dir: @state_dir)
258
258
  next [d, "skipped", "#{head.id[0, 8]}, its chain's newest link, got it already"] if got[head.id]
259
259
 
260
260
  result = NoteDelivery.deliver(d.recipient.id, text: body(broadcast.text, d.verdict), source: SOURCE,
@@ -341,7 +341,7 @@ module Samagotchi
341
341
  end
342
342
  ids = sessions.map { |given| resolve_session(given) }
343
343
  # Two links of one chain are one session: the note goes once (Head).
344
- results = ids.compact.map { |id| SessionInbox::Head.resolve(:note, id, state_dir: @state_dir) }
344
+ results = ids.compact.map { |id| InboxDelivery::Head.resolve(:note, id, state_dir: @state_dir) }
345
345
  .uniq(&:id).map { |head| deliver_anyway(record, head) }
346
346
  unless results.empty?
347
347
  begin
@@ -368,7 +368,7 @@ module Samagotchi
368
368
  nil
369
369
  end
370
370
 
371
- # @param head [SessionInbox::Resolved] the session named (+asked+, a full
371
+ # @param head [InboxDelivery::Resolved] the session named (+asked+, a full
372
372
  # id: #resolve_session) and the link that gets it (a continued one's
373
373
  # chain's newest)
374
374
  # @return [Broadcast::TriageLog::Delivery]
@@ -4,6 +4,7 @@ require "json"
4
4
  require_relative "../../analytics_file"
5
5
  require_relative "../../bridge/card_store"
6
6
  require_relative "../../session"
7
+ require_relative "../../session_messages"
7
8
  require_relative "../../session_metrics"
8
9
  require_relative "../../tool_response"
9
10
 
@@ -30,8 +31,8 @@ module Samagotchi
30
31
 
31
32
  sessions_dir = File.join(@state_home, SessionPaths::STATE_SUBDIR)
32
33
  session_dir = Session.session_dir(@session_id, state_dir: sessions_dir)
33
- session = json_file(Session.session_file(@session_id, state_dir: sessions_dir)) || {}
34
- messages = Array(session["messages"]).select { |message| message.is_a?(Hash) }
34
+ session_path = Session.session_file(@session_id, state_dir: sessions_dir)
35
+ session, messages = saved_session(session_path)
35
36
  analytics = AnalyticsFile.read(session_dir) || {}
36
37
  entries = card_entries(session_dir)
37
38
  tool_rows, denied = tools(messages, analytics)
@@ -147,10 +148,21 @@ module Samagotchi
147
148
  [estimate, true]
148
149
  end
149
150
 
150
- def json_file(path)
151
- JSON.parse(File.read(path))
152
- rescue JSON::ParserError, SystemCallError
153
- nil
151
+ # The run's session file (its mapping; {} when it can't be read) and
152
+ # its saved messages, both from one read of it (SessionMessages.parse:
153
+ # a generation gone since reads the file again); no messages when
154
+ # they can't be read (as a file that doesn't parse).
155
+ def saved_session(path)
156
+ session = {}
157
+ messages = SessionMessages.parse(path) do |data|
158
+ session = data.is_a?(Hash) ? data : {}
159
+ SessionMessages.of_file(data, path: path).select { |message| message.is_a?(Hash) }
160
+ end
161
+ [session, messages]
162
+ rescue SessionMessages::Corrupt, SystemCallError
163
+ [session, []]
164
+ rescue JSON::ParserError
165
+ [{}, []]
154
166
  end
155
167
 
156
168
  def tail(text)
@@ -137,6 +137,8 @@ class Plugin
137
137
  store.vec_error = nil if meta.key?("vec_error")
138
138
  end
139
139
  :done
140
+ rescue Store::NewerSchema
141
+ :failed # a newer chi's index: nothing written in it, not even the error (ensure_schema! logged it)
140
142
  rescue Error, Store::Error => e
141
143
  record(catalog, store, e.message)
142
144
  :failed
@@ -33,6 +33,9 @@ class Plugin
33
33
  SHORT = %r{\A([^/@:\s]+)/([^/@:\s]+)(?:@([^:\s]+))?(?::(\S+))?\z}
34
34
  URL = %r{\Ahttps://github\.com/([^/\s]+)/([^/\s]+?)(?:\.git)?(?:/tree/([^/\s]+)(?:/(\S+?))?)?/?\z}
35
35
  TIMEOUT = 120
36
+ # A catalog's clones: <catalog>/clones/<name>.
37
+ CLONES = "clones"
38
+ CLONE_NAME = /\A[A-Za-z0-9._-]+\z/
36
39
  ENV_SET = { "GIT_TERMINAL_PROMPT" => "0", "GIT_LFS_SKIP_SMUDGE" => "1" }.freeze
37
40
  # No hooks, no fsmonitor, no submodules, and only the https and ssh
38
41
  # transports (no file://, ext:: or other remote helper a repo's
@@ -93,6 +96,22 @@ class Plugin
93
96
 
94
97
  attr_reader :skipped
95
98
 
99
+ # A github source's clone: <catalog_dir>/clones/<name>, nil for a name
100
+ # that isn't the bundle's own.
101
+ def self.clone_dir(catalog_dir, source)
102
+ name = source["clone"].to_s
103
+ name.match?(CLONE_NAME) && !name.start_with?(".") ? File.join(catalog_dir, CLONES, name) : nil
104
+ end
105
+
106
+ # A removed github source's clone goes, unless a source of the +catalog+
107
+ # still names it (the location added again). Also when a refresh finds
108
+ # its source removed: its fetch may have renamed a clone into place
109
+ # after knowledge_remove deleted it.
110
+ def self.drop_clone(catalog, source)
111
+ dir = clone_dir(catalog.dir, source) or return
112
+ FileUtils.rm_rf(dir) if catalog.sources.none? { |entry| entry["clone"] == source["clone"] }
113
+ end
114
+
96
115
  # @param source [Hash] the catalog's record (location, include, exclude)
97
116
  # @param dir [String] the clone's folder (the bundle's own)
98
117
  def initialize(source, dir:, project:, max_files: FolderAdapter::MAX_FILES, timeout: TIMEOUT)
@@ -1,25 +1,25 @@
1
1
  ---
2
2
  name: knowledge
3
- version: 0.3.1
3
+ version: 0.3.2
4
4
  scope: system
5
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. And a Knowledge page in chi web (#/p/knowledge, chi page run knowledge): how searches went on this machine (rankings, what the agent did next, speed by week, the last searches) and each catalog's health; read-only, no model"
6
6
  trust_level: reviewed
7
7
  plugin:
8
8
  file: plugin.rb
9
- sha256: sha256:d88f72dd6470729595fc5f6fc8147e1c8e30a3a8bf06f55f9d15f9464a441152
9
+ sha256: sha256:928fd623e4ec93f379d6a0abd8ada40e043780da7bc2b599900564d4226c7d75
10
10
  # Loaded in this order, before plugin.rb.
11
11
  parts:
12
- store.rb: sha256:d2f10ad13de9640d97b5b692ab776c555e119f57b2b10c84ebcf09b796e59c01
12
+ store.rb: sha256:2b06f74bfb16e823885a2c8b194726c6cbef51d22e2ccfea7cc2a86625996d2c
13
13
  query.rb: sha256:9578ea7392bc6d8a27c5d9b68e47a310b0a8ca937428c80e47b513394d75110f
14
14
  chunker.rb: sha256:169c638ed109ce28e2530868e36b60df7ccffdf64ad64ef027403ba998d7c79e
15
15
  adapters.rb: sha256:11fee1ca0473d9b65a1b66ff50e49b6daf8fdc63d1651e6edc31c02d794ccc1a
16
16
  chi_adapters.rb: sha256:897ef55c077df1fdab371753f6c0a9fabb5e477a3646ffc96a756b2364266ebb
17
- github.rb: sha256:bd9906738f32b1e33d66f94ccd04ac97ed1eb6fb30ef0c669c24a4db2a5d1ffb
17
+ github.rb: sha256:83e5f539c17d456712de1c48c221ac8010fe33c7b9c99e8689089f6fc07ccb6e
18
18
  catalog.rb: sha256:ffa07afcfb8c3358ac3500bc80f5a028ece79e4adb7e0be5153ef50f95359251
19
- refresh.rb: sha256:085545276488772f830757f9f1fe2da9807fb0fdc3a6f1c8851737412ffd3938
19
+ refresh.rb: sha256:3a1d85d182c081b4465c8f7a93fb620258de39e4d6e3a4b7040b92e7c01c2014
20
20
  query_log.rb: sha256:57841260a62451862ba75e3a5d8f5326cafaf89189ca1032ef7493f964d24f37
21
21
  vectors.rb: sha256:0225fd830df75aa0a78b92b3422065fc8e33a9debd4a35fa6cfe78d3fa02831c
22
- embedder.rb: sha256:22af7c9401aa9da0e122c0815066e3ebf8c65732b14eb17f14ec97667602b50b
22
+ embedder.rb: sha256:e8e7fd78c9cf8478be670b77d769ca592c739081066cc74807359bbe8b4ef894
23
23
  # chi.tool(declare:) and ctx.project are new: release:bump raises requires_chi.
24
24
  requires_chi: ">= 0.199.0"
25
25
  # 0.199.0 brings what the bundle needs: runtime.data_dir (the page's data folder),
@@ -43,6 +43,7 @@
43
43
  # FTS5 table, a hex-literal json_each insert, a snippet()/bm25() select
44
44
  # with a hex MATCH); a CLI that fails it gets no tools (no dead tool in
45
45
  # every session) and one warning.
46
+ require "securerandom"
46
47
  require "time"
47
48
 
48
49
  class Plugin
@@ -71,8 +72,6 @@ class Plugin
71
72
  FOLDER_KIND = "folder"
72
73
  GITHUB_KIND = "github"
73
74
  KINDS = [FOLDER_KIND, GITHUB_KIND, CHI_KIND].freeze
74
- CLONES = "clones"
75
- CLONE_NAME = /\A[A-Za-z0-9._-]+\z/
76
75
  CHI_LOCATIONS = %w[memories sessions context].freeze
77
76
  # The chi locations read through the session's own project
78
77
  # (ctx.sessions, ctx.context): a named catalog's refreshes only from
@@ -138,6 +137,14 @@ class Plugin
138
137
  # (Thread.new by default; a spec runs it inline, or not at all).
139
138
  attr_writer :spawn
140
139
 
140
+ # The catalog a call with +ctx+ reads: the named one (+name+), else the
141
+ # project's, else the system one (Catalog.locate).
142
+ # @raise [Catalog::Error] a name that can't be a catalog's
143
+ def catalog_for(ctx, name) = Catalog.locate(data_dir(ctx), project: ctx.project, name: name)
144
+
145
+ # The +catalog+'s index (made on its first write: Store#ensure_schema!).
146
+ def store_for(catalog) = Store.new(catalog.dir, sqlite: @sqlite)
147
+
141
148
  def register(chi)
142
149
  chi.command "/knowledge", "this project's knowledge catalog (or a named one): its sources, their age and size",
143
150
  anytime: true do |args, ctx|
@@ -242,7 +249,6 @@ class Plugin
242
249
  store = store_for(catalog)
243
250
  states = refresh_for(catalog, store).run(refreshable(selected, ctx), budget_ms: budget_ms,
244
251
  cancel: ctx.cancel_controller, ctx: ctx)
245
- sweep(catalog, store, selected, ctx)
246
252
  names = selected.map { |source| source["name"] }
247
253
  hits, ranked_by, timing = if @embedder
248
254
  ranked(store, words, args["query"], names, since, limit, own_rows(selected, ctx), ctx)
@@ -662,13 +668,18 @@ class Plugin
662
668
  def globs(list) = Array(list).map { |glob| glob.to_s.strip }.reject(&:empty?).first(32)
663
669
 
664
670
  # Puts +record+ in the catalog's data (the same kind and location: that
665
- # one is updated, never a second), named +wanted+ or from its location.
671
+ # one is updated, never a second), named +wanted+ or from its location,
672
+ # with a new gen: a refresh that began before stops (Refresh#current!).
666
673
  # @return [String] the source's name, or an error line
667
674
  def put_source(data, record, wanted)
675
+ record = record.merge("gen" => SecureRandom.hex(6))
668
676
  existing = data["sources"].find { |source| source["kind"] == record["kind"] && source["location"] == record["location"] }
669
677
  if existing
670
678
  existing.merge!(record.except("kind", "location"))
671
679
  existing.delete("listed_at") # added again (its project may differ): the next listing is a full one
680
+ # Due again: the add's own refresh records it, else (a refresh of the
681
+ # old gen holds it, and stops) the next search refreshes it.
682
+ existing.delete("refreshed_at")
672
683
  return existing["name"]
673
684
  end
674
685
 
@@ -703,7 +714,7 @@ class Plugin
703
714
 
704
715
  def clear_rows(catalog, name)
705
716
  store = store_for(catalog)
706
- catalog.lock { store.delete_source(name) } if store.exists?
717
+ catalog.lock { store.delete_source(name) } if store.exists? && !store.newer?
707
718
  end
708
719
 
709
720
  def add_result(catalog, name, ctx)
@@ -769,12 +780,14 @@ class Plugin
769
780
  return "Error: no source #{name} (sources: #{catalog.sources.map { |s| s["name"] }.join(", ")})"
770
781
 
771
782
  store = store_for(catalog)
772
- catalog.lock { store.delete_source(name) } if store.exists?
773
- FileUtils.rm_rf(clone_dir(catalog, source)) if source["kind"] == GITHUB_KIND && clone_dir(catalog, source)
783
+ # Its rows and its record go under one hold of the index lock: a
784
+ # refresh running meanwhile puts nothing after (Refresh#current!).
774
785
  catalog.update do |data|
786
+ store.delete_source(name) if store.exists? && !store.newer?
775
787
  data["sources"].reject! { |entry| entry["name"] == name }
776
788
  data["removed_defaults"] |= [name] if source["default"]
777
789
  end
790
+ GithubAdapter.drop_clone(catalog, source) if source["kind"] == GITHUB_KIND
778
791
  "removed #{name}: #{source["items"].to_i} items, #{source["chunks"].to_i} chunks"
779
792
  rescue Catalog::Error, Store::Error => e
780
793
  "Error: #{e.message}"
@@ -782,28 +795,20 @@ class Plugin
782
795
 
783
796
  # ── catalogs, defaults, refresh ──────────────────────────────────────
784
797
 
785
- def catalog_for(ctx, name) = Catalog.locate(data_dir(ctx), project: ctx.project, name: name)
786
-
787
798
  # ctx.data_dir realpath'd once (the index's -nofollow refuses a path
788
799
  # through a symlink).
789
800
  def data_dir(ctx) = @data_dir ||= File.realpath(ctx.data_dir).tap { |dir| File.chmod(0o700, dir) }
790
801
 
791
- def store_for(catalog) = Store.new(catalog.dir, sqlite: @sqlite)
792
-
793
802
  def refresh_for(catalog, store)
794
803
  @mutex.synchronize do
795
804
  @refreshes[catalog.dir] ||= Refresh.new(catalog, store, build: ->(source, ctx) { adapter_for(source, ctx, catalog) },
796
- background: ->(source) { source["kind"] == GITHUB_KIND })
805
+ background: ->(source) { source["kind"] == GITHUB_KIND },
806
+ dropped: lambda { |source|
807
+ GithubAdapter.drop_clone(catalog, source) if source["kind"] == GITHUB_KIND
808
+ })
797
809
  end
798
810
  end
799
811
 
800
- # A github source's clone: <catalog>/clones/<name>, nil for a name that
801
- # isn't the bundle's own.
802
- def clone_dir(catalog, source)
803
- name = source["clone"].to_s
804
- name.match?(CLONE_NAME) && !name.start_with?(".") ? File.join(catalog.dir, CLONES, name) : nil
805
- end
806
-
807
812
  def budget_ms = (@settings["refresh_budget_ms"] || DEFAULT_BUDGET_MS).to_i.clamp(0, 60_000)
808
813
 
809
814
  def max_files = (@settings["max_files"] || FolderAdapter::MAX_FILES).to_i.clamp(1, 200_000)
@@ -811,13 +816,13 @@ class Plugin
811
816
  def adapter_for(source, ctx, catalog)
812
817
  case source["kind"]
813
818
  when GITHUB_KIND
814
- dir = clone_dir(catalog, source) or raise GithubAdapter::Error, "the source has no clone folder"
819
+ dir = GithubAdapter.clone_dir(catalog.dir, source) or raise GithubAdapter::Error, "the source has no clone folder"
815
820
  GithubAdapter.new(source, dir: dir, project: ctx.project, max_files: max_files)
816
821
  when CHI_KIND
817
822
  case source["location"]
818
823
  when "sessions"
819
824
  # An index that lost its rows (rebuilt, deleted), or holds one of
820
- # another rule (#sweep deletes those), lists in full again.
825
+ # another rule (Refresh#sweep deletes those), lists in full again.
821
826
  indexed = store_for(catalog).then do |store|
822
827
  sigs = store.exists? ? store.sigs(source["name"]) : {}
823
828
  !sigs.empty? && sigs.values.all? { |sig| SessionsAdapter.current?(sig) }
@@ -848,39 +853,6 @@ class Plugin
848
853
 
849
854
  def sessions?(source) = source["kind"] == CHI_KIND && source["location"] == "sessions"
850
855
 
851
- # A deleted, pruned or never-indexable session's rows leave at the next
852
- # search that selects a sessions source (ctx.sessions.present_ids:
853
- # file names only), before they can be hits; so do the rows an older
854
- # SessionsAdapter rule indexed (#sweep_old_rule), whatever the source's
855
- # age, project or the search's budget.
856
- def sweep(catalog, store, sources, ctx)
857
- names = sources.select { |source| sessions?(source) }.map { |source| source["name"] }
858
- return if names.empty? || !store.exists?
859
-
860
- present = ctx.sessions.present_ids.to_h { |id| [id, true] }
861
- names.each do |name|
862
- sweep_old_rule(catalog, store, name)
863
- gone = store.sigs(name).keys.reject { |id| present.key?(id) }
864
- catalog.lock { store.delete(gone.map { |id| [name, id] }) } unless gone.empty?
865
- end
866
- end
867
-
868
- # The sessions source +name+'s rows of an older rule (a sig without
869
- # RULE's prefix: indexed before a participant's turns were dropped) go,
870
- # read and deleted under the catalog lock (a refresh's put is too), and
871
- # its listed_at is cleared: the next listing is a full one, and stays
872
- # full until one completes.
873
- def sweep_old_rule(catalog, store, name)
874
- old = catalog.lock do
875
- store.sigs(name).reject { |_key, sig| SessionsAdapter.current?(sig) }.keys.tap do |keys|
876
- store.delete(keys.map { |key| [name, key] }) unless keys.empty?
877
- end
878
- end
879
- return if old.empty?
880
-
881
- catalog.update { |data| data["sources"].find { |entry| entry["name"] == name }&.delete("listed_at") }
882
- end
883
-
884
856
  # The searching session's own rows in the sessions sources: never a hit.
885
857
  def own_rows(sources, ctx)
886
858
  id = ctx.session_id
@@ -7,20 +7,31 @@
7
7
  # from the index as it is and the thread finishes in the background (it is
8
8
  # not joined at worker exit: a killed sqlite3 child is safe under WAL, and
9
9
  # the next refresh redoes that batch). Each source refreshes under its own
10
- # lock, taken without waiting: one held elsewhere is skipped.
10
+ # lock, taken without waiting: one held elsewhere is skipped. A source
11
+ # removed or added again (knowledge_add stamps a new gen) while it refreshes
12
+ # stops it: every index write and the record check, under the index lock,
13
+ # that the catalog still has the source at the gen it started with.
11
14
  class Plugin
12
15
  class Refresh
13
16
  # Items per index write (each one transaction under the index lock).
14
17
  GROUP = 200
15
18
 
19
+ # The source was removed or added again since the refresh began.
20
+ class Dropped < StandardError; end
21
+
16
22
  # @param build [#call] (source Hash, ctx) → its adapter
17
23
  # @param background [#call] (source Hash) → whether a search never
18
24
  # 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 })
25
+ # @param dropped [#call] (source Hash) once a refresh finds its source
26
+ # removed or added again, after its listing (a github clone renamed
27
+ # into place under a removed source)
28
+ def initialize(catalog, store, build:, background: ->(_source) { false }, dropped: ->(_source) {},
29
+ clock: -> { Time.now.to_i })
20
30
  @catalog = catalog
21
31
  @store = store
22
32
  @build = build
23
33
  @background = background
34
+ @dropped = dropped
24
35
  @clock = clock
25
36
  @progress = {}
26
37
  end
@@ -28,10 +39,44 @@ class Plugin
28
39
  # Refresh the +sources+ (records) that are stale, or every one of
29
40
  # +force+ (names), waiting at most +budget_ms+ (never for a background
30
41
  # one, unless forced). +cancel+ (#cancelled?: ctx.cancel_controller)
31
- # ends one between groups; +ctx+ goes to the adapters.
42
+ # ends one between groups; +ctx+ goes to the adapters. Then #sweep,
43
+ # whichever sources were due.
32
44
  # @return [Hash{String => Symbol}] name => :refreshed, :failed,
33
- # :elsewhere (another refresh holds it) or :refreshing (still running)
45
+ # :elsewhere (another refresh holds it, or the source changed under
46
+ # it: removed or added again) or :refreshing (still running)
34
47
  def run(sources, budget_ms:, force: [], cancel: nil, ctx: nil)
48
+ refresh_due(sources, budget_ms, force, cancel, ctx).tap { sweep(ctx) }
49
+ end
50
+
51
+ # The share of +name+'s changed items written so far (0..1), nil when
52
+ # it isn't running here.
53
+ def progress(name) = @progress[name]
54
+
55
+ # Every sessions source of the catalog, whichever a call selected,
56
+ # loses the rows of a deleted, pruned or never-indexable session
57
+ # (ctx.sessions.present_ids: file names only) before they can be hits,
58
+ # and those an older SessionsAdapter rule indexed (#sweep_old_rule),
59
+ # whatever the source's age, project or the call's budget. Not on a
60
+ # participant's turn (its search never reads chi sources), nor in a
61
+ # newer chi's index.
62
+ def sweep(ctx)
63
+ return if ctx.nil? || !ctx.turn_author.nil? || !@store.exists?
64
+
65
+ names = @catalog.sources.select { |source| source["kind"] == CHI_KIND && source["location"] == "sessions" }
66
+ .map { |source| source["name"] }
67
+ return if names.empty? || @store.newer?
68
+
69
+ present = ctx.sessions.present_ids.to_h { |id| [id, true] }
70
+ names.each do |name|
71
+ sweep_old_rule(name)
72
+ gone = @store.sigs(name).keys.reject { |id| present.key?(id) }
73
+ @catalog.lock { @store.delete(gone.map { |id| [name, id] }) } unless gone.empty?
74
+ end
75
+ end
76
+
77
+ private
78
+
79
+ def refresh_due(sources, budget_ms, force, cancel, ctx)
35
80
  now = @clock.call
36
81
  due = sources.select { |source| force.include?(source["name"]) || Catalog.stale?(source, now) }
37
82
  return {} if due.empty?
@@ -49,11 +94,21 @@ class Plugin
49
94
  due.to_h { |source| [source["name"], states.fetch(source["name"], :refreshing)] }
50
95
  end
51
96
 
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]
97
+ # The sessions source +name+'s rows of an older rule (a sig without
98
+ # RULE's prefix: indexed before a participant's turns were dropped) go,
99
+ # read and deleted under the catalog lock (a refresh's put is too), and
100
+ # its listed_at is cleared: the next listing is a full one, and stays
101
+ # full until one completes.
102
+ def sweep_old_rule(name)
103
+ old = @catalog.lock do
104
+ @store.sigs(name).reject { |_key, sig| SessionsAdapter.current?(sig) }.keys.tap do |keys|
105
+ @store.delete(keys.map { |key| [name, key] }) unless keys.empty?
106
+ end
107
+ end
108
+ return if old.empty?
55
109
 
56
- private
110
+ @catalog.update { |data| data["sources"].find { |entry| entry["name"] == name }&.delete("listed_at") }
111
+ end
57
112
 
58
113
  def one(source, cancel, ctx)
59
114
  name = source["name"]
@@ -79,23 +134,27 @@ class Plugin
79
134
  @catalog.lock { @store.ensure_schema! }
80
135
  adapter = @build.call(source, ctx)
81
136
  items = adapter.items
137
+ @catalog.lock { current!(source) }
82
138
  old = @store.sigs(name)
83
139
  changed = items.reject { |item| old[item.key] == item.sig }
84
140
  gone = adapter.respond_to?(:gone) ? adapter.gone(old.keys) : old.keys - items.map(&:key)
85
141
  changed.each_slice(GROUP).with_index do |group, index|
86
- return record(name, error: "cancelled") if cancel&.cancelled?
142
+ return record(source, error: "cancelled") if cancel&.cancelled?
87
143
 
88
144
  rows = group.filter_map do |item|
89
145
  row(name, item, adapter).tap { |made| listed_at = [listed_at, item.updated_at.to_i].min if made.nil? && item.updated_at }
90
146
  end
91
- @catalog.lock { @store.put(rows) }
147
+ @catalog.lock { current!(source) && @store.put(rows) }
92
148
  @progress[name] = ((index + 1) * GROUP.to_f / changed.size).clamp(0.0, 1.0)
93
149
  end
94
- @catalog.lock { @store.delete(gone.map { |key| [name, key] }) } unless gone.empty?
95
- record(name, skipped: adapter.skipped, listed_at: listed_at)
150
+ @catalog.lock { current!(source) && @store.delete(gone.map { |key| [name, key] }) } unless gone.empty?
151
+ record(source, skipped: adapter.skipped, listed_at: listed_at)
96
152
  :refreshed
153
+ rescue Dropped
154
+ @dropped.call(source)
155
+ :elsewhere
97
156
  rescue StandardError => e
98
- record(name, error: "#{e.class.name.split("::").last}: #{e.message}"[0, 300])
157
+ record(source, error: "#{e.class.name.split("::").last}: #{e.message}"[0, 300])
99
158
  :failed
100
159
  end
101
160
 
@@ -113,10 +172,26 @@ class Plugin
113
172
  updated_at: item.updated_at, sig: item.sig, chunks: chunks }
114
173
  end
115
174
 
116
- def record(name, error: nil, skipped: nil, listed_at: nil)
175
+ # Whether +source+ is still the catalog's at the gen it had when the
176
+ # refresh began (a source from before gens has none: nil == nil). Call
177
+ # under the index lock, which knowledge_add and knowledge_remove take.
178
+ # @raise [Dropped] removed, or added again
179
+ def current!(source)
180
+ now = @catalog.source(source["name"])
181
+ raise Dropped unless now && now["gen"] == source["gen"]
182
+
183
+ true
184
+ end
185
+
186
+ # Writes the refresh's outcome on the source, only when it is still the
187
+ # one refreshed (#current!): never on a source added again since.
188
+ def record(refreshed, error: nil, skipped: nil, listed_at: nil)
189
+ name = refreshed["name"]
117
190
  counts = @store.exists? ? @store.counts.fetch(name, { items: 0, chunks: 0 }) : { items: 0, chunks: 0 }
118
191
  @catalog.update do |data|
119
192
  source = data["sources"].find { |entry| entry["name"] == name } or next
193
+ next unless source["gen"] == refreshed["gen"]
194
+
120
195
  if error
121
196
  source.merge!("last_error" => error, "last_error_at" => @clock.call)
122
197
  else
@@ -29,6 +29,10 @@ class Plugin
29
29
  # A sqlite3 run failed: its first error line.
30
30
  class Error < StandardError; end
31
31
 
32
+ # The index was made by a newer chi (a higher SCHEMA_VERSION): this one
33
+ # leaves it as it is (#ensure_schema!).
34
+ class NewerSchema < Error; end
35
+
32
36
  SCHEMA_VERSION = "1"
33
37
  DB = "index.db"
34
38
  BASE_ARGS = ["-init", File::NULL, "-safe", "-bail", "-nofollow"].freeze
@@ -49,6 +53,8 @@ class Plugin
49
53
  insert or ignore into meta(k, v) values('schema', '#{SCHEMA_VERSION}');
50
54
  select v from meta where k = 'schema';
51
55
  SQL
56
+ # The schema version as it is, nothing written (no table made).
57
+ VERSION_READ = "pragma query_only=1;\nselect v from meta where k = 'schema';\n"
52
58
 
53
59
  # Upserts a batch of items (their old chunks gone) and inserts their
54
60
  # chunks: temp.batch holds the JSON array, one row per item.
@@ -106,11 +112,20 @@ class Plugin
106
112
  # finds nothing, without making it).
107
113
  def exists? = File.file?(@db) && !File.symlink?(@db)
108
114
 
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
115
+ # Make the db (0600) and its schema; an older schema version is dropped
116
+ # and made again (re-creatable data). A newer one (a newer chi's index,
117
+ # its workers sharing the catalog) is left as it is, read before
118
+ # anything is written: NewerSchema, logged. Call under the catalog's
111
119
  # index lock.
120
+ # @raise [NewerSchema]
112
121
  def ensure_schema!
113
122
  if exists?
123
+ if newer?
124
+ message = "#{@db} is a newer chi's index (schema #{schema_version}, this chi's is #{SCHEMA_VERSION}): " \
125
+ "left as it is, not refreshed here; restart this session on the newer chi"
126
+ Samagotchi::Log.warn(:plugins, "knowledge_newer_index", bundle: "knowledge", msg: message)
127
+ raise NewerSchema, message
128
+ end
114
129
  return if run(SCHEMA).lines.last.to_s.strip == SCHEMA_VERSION
115
130
 
116
131
  [@db, "#{@db}-wal", "#{@db}-shm"].each { |path| FileUtils.rm_f(path) }
@@ -118,6 +133,25 @@ class Plugin
118
133
  build!
119
134
  end
120
135
 
136
+ # The index's schema version, read only (nil with no db, no meta table
137
+ # or no version row).
138
+ def schema_version
139
+ return nil unless exists?
140
+
141
+ version = run(VERSION_READ).lines.last.to_s.strip
142
+ version.empty? ? nil : version
143
+ rescue Error
144
+ nil
145
+ end
146
+
147
+ # Whether the index was made by a newer chi: a schema version that is a
148
+ # number above SCHEMA_VERSION. Its rows are that chi's: this one writes
149
+ # none (ensure_schema!) and deletes none (Refresh#sweep, Plugin#remove).
150
+ def newer?
151
+ version = schema_version
152
+ version.to_s.match?(/\A\d+\z/) && version.to_i > SCHEMA_VERSION.to_i
153
+ end
154
+
121
155
  # One write transaction of +sql+ (constant text with hex values).
122
156
  def write(sql) = run("begin immediate;\n#{sql}\ncommit;\n")
123
157
 
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: schedules
3
- version: 0.1.1
3
+ version: 0.1.2
4
4
  scope: system
5
5
  description: "A Schedules page in chi web (#/p/schedules, chi page run schedules): every durable schedule, why one is off and how to turn it on, and the recent runs; read-only"
6
6
  trust_level: reviewed
7
7
  # runtime.schedules' condition (the If column) is new in the next chi (release:bump sets the floor)
8
8
  requires_chi: ">= 0.190.0"
9
9
  scripts:
10
- schedules.rb: sha256:ac1bf79cb3df54511c0263cd7dde7e671f853a66c932606c8e2a235835afb44d
10
+ schedules.rb: sha256:ac34444962c8f48edd87e6aac59b333299d34f798a895274211055ac903e00ad
11
11
  pages: [schedules.rb]