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
@@ -35,8 +35,11 @@ module Samagotchi
35
35
  REFUSED = [ModelProfile::MissingModel, Toolkit::Refused, ArgumentError].freeze
36
36
 
37
37
  # @param host [Host] session_id, cwd, model_name and state_dir
38
- def initialize(host)
38
+ # @param project [#call, nil] → ctx.project (Project), the project
39
+ # #list reads; nil: the host's folder's
40
+ def initialize(host, project: nil)
39
41
  @host = host
42
+ @project = project
40
43
  end
41
44
 
42
45
  # Start a child session from +messages+ (usually ctx.messages plus
@@ -158,6 +161,31 @@ module Samagotchi
158
161
  running: running, messages: without_system_head(messages) }
159
162
  end
160
163
 
164
+ # This project's saved sessions (ctx.project's root; a session in no
165
+ # project lists the sessions in none), newest updated first, archived
166
+ # ones included, no test_run or scratch session (SessionStats.summaries:
167
+ # the listing reflect's counts read too). Each file is parsed, so call
168
+ # it from a background part; +changed_since+ (a Time) parses only the
169
+ # files written after it.
170
+ # @return [Array<Hash>] frozen {id:, title:, updated_at:, archived:}
171
+ def list(changed_since: nil)
172
+ require_relative "../session_stats"
173
+ root = project_root
174
+ SessionStats.summaries(project: root || :none, changed_since: changed_since, state_dir: state_dir).map do |summary|
175
+ { id: summary.id, title: summary.display_title, updated_at: summary.updated_at,
176
+ archived: summary.archived ? true : false }.freeze
177
+ end
178
+ end
179
+
180
+ # Every saved session's id (file names only, nothing parsed): what an
181
+ # index of sessions keeps rows for; a deleted or pruned session's id
182
+ # is gone from it.
183
+ # @return [Array<String>]
184
+ def present_ids
185
+ require_relative "../session_stats"
186
+ SessionStats.present_ids(state_dir: state_dir)
187
+ end
188
+
161
189
  # This session's children, newest first (ChildrenStatus.of): delegates
162
190
  # and forks (delegate: false), archived ones only with +all+. It reads
163
191
  # every session's file, so call it on demand, not in a loop.
@@ -196,6 +224,13 @@ module Samagotchi
196
224
 
197
225
  def state_dir = @host.state_dir&.call || Session.default_state_dir
198
226
 
227
+ def project_root
228
+ return @project.call.root if @project
229
+
230
+ require_relative "project"
231
+ Project.for(@host.cwd.call || Dir.pwd).root
232
+ end
233
+
199
234
  # A session file that won't load (corrupt) is an Error, not a crash
200
235
  # of the command that called stop.
201
236
  def child_of?(sid, parent_id, state_dir)
@@ -10,16 +10,25 @@ module Samagotchi
10
10
  # ToolSpec.build make, and what Tools::Registry#register gets
11
11
  # (#entry_fields). +schema+ is what reaches the prompt ({name:,
12
12
  # description:, parameters:}); the block, preview:, targets: and refs:
13
- # never do.
14
- class ToolSpec < Data.define(:name, :schema, :label, :preview, :targets, :refs, :block)
13
+ # never do. +declare+ is which toolkits declare it (DECLARE: nil, as a
14
+ # built-in is; :kit, only a kit that adds it; :always, every kit that
15
+ # doesn't remove it: Toolkit::Resolved#declares?). +participant+ is
16
+ # whether a participant's pair turn may call it (PARTICIPANT: :allow,
17
+ # the default; :deny, Guardrails::PairBoundary refuses it before any
18
+ # check or ask).
19
+ class ToolSpec < Data.define(:name, :schema, :label, :preview, :targets, :refs, :block, :declare, :participant)
15
20
  TOOL_NAME = /\A[a-z][a-z0-9_]{0,47}\z/
16
21
  PARAM_NAME = /\A[a-z_][a-z0-9_]*\z/i
22
+ # chi.tool(declare:)'s values; nil (omitted) is a built-in's rule.
23
+ DECLARE = %i[kit always].freeze
24
+ # chi.tool(participant:)'s values (default :allow).
25
+ PARTICIPANT = %i[allow deny].freeze
17
26
 
18
27
  # A checked tool declaration from #tool's arguments (Api#tool and
19
28
  # ToolSet#tool pass theirs on, so a new keyword is added here).
20
29
  # @return [ToolSpec]
21
30
  def self.build(name, description, params: {}, schema: nil, label: nil, preview: nil, targets: nil, refs: nil,
22
- &block)
31
+ declare: nil, participant: :allow, &block)
23
32
  raise ArgumentError, "tool #{name.inspect} needs a block" unless block
24
33
 
25
34
  name = name.to_s
@@ -27,18 +36,27 @@ module Samagotchi
27
36
  raise ArgumentError, "tool #{name}: preview must respond to #call" if preview && !preview.respond_to?(:call)
28
37
  raise ArgumentError, "tool #{name}: targets must respond to #call" if targets && !targets.respond_to?(:call)
29
38
  raise ArgumentError, "tool #{name}: refs must respond to #call" if refs && !refs.respond_to?(:call)
39
+ unless declare.nil? || DECLARE.include?(declare)
40
+ raise ArgumentError, "tool #{name}: declare must be :kit or :always (got #{declare.inspect})"
41
+ end
42
+ unless PARTICIPANT.include?(participant)
43
+ raise ArgumentError, "tool #{name}: participant must be :allow or :deny (got #{participant.inspect})"
44
+ end
30
45
 
31
46
  parameters = schema ? schema_parameters(name, schema) : params_schema(name, params)
32
47
  new(name: name, schema: { name: name, description: description.to_s, parameters: parameters },
33
- label: label&.to_s, preview: preview, targets: targets, refs: refs, block: block)
48
+ label: label&.to_s, preview: preview, targets: targets, refs: refs, block: block, declare: declare,
49
+ participant: participant)
34
50
  end
35
51
 
36
52
  # Make +bundle+'s tools in +registry+ the +specs+: its tools not in
37
53
  # them go; a new one, or one whose schema or label changed, is
38
54
  # registered (a changed one again, in its place: Tools::Registry
39
55
  # orders bundle tools by bundle and name); an unchanged one is kept
40
- # as it is, but for its block, preview:, targets: and refs:, swapped
41
- # in place: none of them reaches the prompt, so not a change (that
56
+ # as it is, but for its block, preview:, targets:, refs: and
57
+ # participant:, swapped in place, so the next call reads them (a
58
+ # changed declare: is a change: it moves the tool between declared and
59
+ # not): none of them reaches the prompt, so not a change (that
42
60
  # would build the prompts again). A name
43
61
  # another source has is left out. Called on the turn thread
44
62
  # (Engine#apply_staged_tools!).
@@ -47,8 +65,9 @@ module Samagotchi
47
65
  wanted = specs.to_h { |spec| [spec.name, spec] }
48
66
  changed = false
49
67
  registry.by_source(bundle).each do |entry|
50
- if (spec = wanted[entry.name]) && spec.schema == entry.schema && spec.label == entry.label
51
- spec.entry_fields(context).slice(:handler, :preview, :targets, :refs).each { |key, value| entry[key] = value }
68
+ if (spec = wanted[entry.name]) && spec.schema == entry.schema && spec.label == entry.label &&
69
+ spec.declare == entry.declare
70
+ spec.entry_fields(context).slice(:handler, :preview, :targets, :refs, :participant).each { |key, value| entry[key] = value }
52
71
  next
53
72
  end
54
73
 
@@ -146,7 +165,7 @@ module Samagotchi
146
165
  preview = per_call(self.preview, parameters)
147
166
  targets = per_call(self.targets, parameters)
148
167
  {
149
- schema: schema, label: label,
168
+ schema: schema, label: label, declare: declare, participant: participant,
150
169
  handler: lambda { |call, _kctx|
151
170
  result = block.call(ToolSpec.args_of(call, parameters), context)
152
171
  ToolSpec.result_text(result)
@@ -247,15 +247,21 @@ module Samagotchi
247
247
  end
248
248
 
249
249
  # @param id_or_name [String] an id, a unique prefix of one, or a title
250
- # @return [Entry, nil]
250
+ # @return [Entry, nil] nil too for the exact id of an entry that doesn't
251
+ # read: an exact id wins over another schedule's prefix or title, so
252
+ # chi schedule cancel ID reaches that entry (#cancel_unreadable) and
253
+ # show, edit, enable and disable say "no schedule" rather than take a
254
+ # different one
251
255
  # @raise [Usage] the prefix or the title names more than one schedule
252
256
  def lookup(id_or_name)
253
257
  given = id_or_name.to_s.strip
254
258
  return nil if given.empty?
255
259
 
256
- list = read.entries.grep(Entry)
260
+ records = read.entries
261
+ list = records.grep(Entry)
257
262
  exact = list.find { |entry| entry.id == given }
258
263
  return exact if exact
264
+ return nil if records.any? { |record| !record.is_a?(Entry) && record.raw.is_a?(Hash) && record.raw["id"] == given }
259
265
 
260
266
  matches = ambiguous(list.select { |entry| entry.id.start_with?(given) }, given)
261
267
  return matches.first unless matches.empty?
@@ -282,13 +282,14 @@ module Samagotchi
282
282
  # chi web's create) can name it (`--wait --turn T ID`). nil for a
283
283
  # session created idle, and for one saved before the field existed.
284
284
  SessionField.plain("first_turn_id", nil, optional: true),
285
- # Who sent that prompt when no person did (a ClientId: a delegating
286
- # parent's delegate:<parent8>, a schedule's chain link
287
- # system:schedule:<id>): the first turn's origin, so the command
288
- # intake treats it as theirs (CommandIntake) and last_turn names
289
- # them. nil for a person's prompt (chi send --new, the web, a TUI, a
290
- # continue) and an idle session. Set once, by spawn_session; a
291
- # continue and a fork don't carry it.
285
+ # Who sent that prompt (a ClientId): any sender that is no human's
286
+ # (a delegating parent's delegate:<parent8>, a schedule's chain link
287
+ # system:schedule:<id>, an agent's agent:<name>) and an interactive
288
+ # one (a web tab's web:…, a TUI's tui:…): the first turn's origin, so
289
+ # the command intake treats it as theirs (CommandIntake) and
290
+ # last_turn names them. nil for chi send --new, a continue, an idle
291
+ # session and a file saved before interactive ids were kept. Set
292
+ # once, by spawn_session; a continue and a fork don't carry it.
292
293
  SessionField.plain("first_turn_client_id", nil, optional: true),
293
294
  # The agent that drives this session (agent:<name>, a ClientId): the
294
295
  # one that created it (spawn_session, a prompt or none), or the one
@@ -743,14 +744,18 @@ module Samagotchi
743
744
  # Archived sessions (ArchiveStore) are left out unless +include_archived+;
744
745
  # everything built on .list follows (the lists, the summaries, the
745
746
  # retention prune, which then neither deletes nor counts them).
747
+ # +changed_since+ (a Time) skips a file whose mtime is not newer before
748
+ # it is parsed (an incremental reader's listing: SessionStats.summaries).
746
749
  def self.list(state_dir: default_state_dir, sort: "updated_at", order: "desc", limit: nil, offset: 0,
747
- project_root: nil, include_archived: false)
750
+ project_root: nil, include_archived: false, changed_since: nil)
748
751
  return [] unless Dir.exist?(state_dir)
749
752
 
750
753
  sort_key = SORT_KEYS.include?(sort.to_s) ? sort.to_s : "updated_at"
751
754
  sort_order = SORT_ORDERS.include?(order.to_s) ? order.to_s : "desc"
752
755
 
753
- sessions = Dir.glob(File.join(state_dir, "*#{SessionPaths::FILE_EXT}")).filter_map { |path| summary_from_file(path) }
756
+ paths = Dir.glob(File.join(state_dir, "*#{SessionPaths::FILE_EXT}"))
757
+ paths = paths.select { |path| changed_after?(path, changed_since) } if changed_since
758
+ sessions = paths.filter_map { |path| summary_from_file(path) }
754
759
  sessions.each { |s| s.archived = ArchiveStore.archived?(session_dir(s.id, state_dir: state_dir)) }
755
760
  sessions.reject!(&:archived) unless include_archived
756
761
  if project_root
@@ -776,6 +781,14 @@ module Samagotchi
776
781
  sorted
777
782
  end
778
783
 
784
+ # Whether +path+ was written after +time+ (a file gone since the glob: no).
785
+ def self.changed_after?(path, time)
786
+ File.mtime(path) > time
787
+ rescue SystemCallError
788
+ false
789
+ end
790
+ private_class_method :changed_after?
791
+
779
792
  # One session file as .list reads it: the session without its messages
780
793
  # (the list is lightweight). The session hub reads files the same way,
781
794
  # so both agree on which files count.
@@ -13,6 +13,7 @@ require_relative "../note_delivery"
13
13
  require_relative "../image_store"
14
14
  require_relative "../context_candidates"
15
15
  require_relative "../worker_inbound"
16
+ require_relative "../context_change"
16
17
  require_relative "../context_sources"
17
18
  require_relative "../peer_exchanges"
18
19
  require_relative "../peer_mailbox"
@@ -23,7 +24,7 @@ require_relative "../peer_say"
23
24
  require_relative "../archive_store"
24
25
  require_relative "../session_chain"
25
26
  require_relative "../session_chain/successor"
26
- require_relative "../session_transition"
27
+ require_relative "../session_chain/sharing"
27
28
  require_relative "../send_command/busy"
28
29
  require_relative "../chi_invocation"
29
30
  require_relative "../worker_sidecar"
@@ -368,7 +369,7 @@ module Samagotchi
368
369
 
369
370
  # Attaches +source+ to the target's own sources.
370
371
  # @return [ContextAdded]
371
- # A session's own: under its transition lock (ContextSources.changing).
372
+ # A session's own: under its transition lock (ContextChange.under).
372
373
  # @raise [ContextSources::Held] a transition holds the session's lock
373
374
  def context_add(target, source)
374
375
  location = context_location(target)
@@ -381,9 +382,10 @@ module Samagotchi
381
382
  # id): a source of its own, or none of the name. A project's source
382
383
  # takes it (the next link sees it too). The session's own source is
383
384
  # checked again and written under a shared hold of its transition lock
384
- # (SessionTransition.shared), so a continue (which moves its sources)
385
- # can't start in between; one holding the lock now refuses it, naming
386
- # its new link (:continued, in flight) or :busy.
385
+ # (SessionChain::Sharing.under), so a continue (which moves its
386
+ # sources) can't start in between; a transition holding the lock now
387
+ # refuses it, naming who continues the session (:continued: a
388
+ # continue's new link in flight, else a saved successor) or :busy.
387
389
  # @param fetched [ContextSources::Fetched]
388
390
  # @return [ContextPush]
389
391
  def context_push(target, name, fetched)
@@ -398,11 +400,11 @@ module Samagotchi
398
400
  # Its file is gone: no hold (it would make the folder again).
399
401
  return context_push_to(target, name, fetched, attached) unless Session.exist?(sid, **dir)
400
402
 
401
- SessionTransition.shared(sid, state_dir: state_dir!) do |free|
402
- case (moved = moved_on(sid, free))
403
- when :busy then next ContextPush.new(status: :busy)
404
- when SessionChain::Successor
405
- next ContextPush.new(status: :continued, next_id: moved.id, in_flight: moved.in_flight?)
403
+ SessionChain::Sharing.under(sid, state_dir: state_dir!) do |sharing|
404
+ case (moved = moved_on(sid, sharing))
405
+ when SessionChain::Sharing::Held then next ContextPush.new(status: :busy)
406
+ when nil then nil
407
+ else next ContextPush.new(status: :continued, next_id: moved.id, in_flight: moved.in_flight?)
406
408
  end
407
409
 
408
410
  context_push_to(target, name, fetched, attached)
@@ -698,11 +700,11 @@ module Samagotchi
698
700
  end
699
701
  return PeerPaired.new(status: :old_worker) if old_peer_worker?(id)
700
702
 
701
- SessionTransition.shared(id, state_dir: state_dir!) do |free|
702
- case (moved = moved_on(id, free))
703
- when :busy then next PeerPaired.new(status: :busy)
704
- when SessionChain::Successor
705
- next PeerPaired.new(status: :continued, next_id: moved.id, in_flight: moved.in_flight?)
703
+ SessionChain::Sharing.under(id, state_dir: state_dir!) do |sharing|
704
+ case (moved = moved_on(id, sharing))
705
+ when SessionChain::Sharing::Held then next PeerPaired.new(status: :busy)
706
+ when nil then nil
707
+ else next PeerPaired.new(status: :continued, next_id: moved.id, in_flight: moved.in_flight?)
706
708
  end
707
709
 
708
710
  link = PeerMailbox.pair(id, peer, address: address, from: from, peer_session: peer_session, state_dir: state_dir!)
@@ -735,11 +737,11 @@ module Samagotchi
735
737
  message = nil
736
738
  start_failed = false
737
739
  delivered = begin
738
- SessionTransition.shared(id, state_dir: state_dir!) do |free|
739
- case (moved = moved_on(id, free))
740
- when :busy then return PeerSay.new(status: :busy)
741
- when SessionChain::Successor
742
- return PeerSay.new(status: :continued, next_id: moved.id, in_flight: moved.in_flight?)
740
+ SessionChain::Sharing.under(id, state_dir: state_dir!) do |sharing|
741
+ case (moved = moved_on(id, sharing))
742
+ when SessionChain::Sharing::Held then return PeerSay.new(status: :busy)
743
+ when nil then nil
744
+ else return PeerSay.new(status: :continued, next_id: moved.id, in_flight: moved.in_flight?)
743
745
  end
744
746
  return unpaired unless PeerMailbox.link(id, peer, state_dir: state_dir!)
745
747
 
@@ -922,24 +924,23 @@ module Samagotchi
922
924
  SessionChain::Successor.of(id, state_dir: state_dir!)
923
925
  end
924
926
 
925
- # Inside SessionTransition.shared(+id+) (+free+: the shared hold was
926
- # taken): why an arrival can't be written now — a Successor (a saved
927
- # one; or, when a continue holds the lock, the one its intent names)
928
- # or :busy (held, nobody named: another change, or a continue before
929
- # its intent or after its undo). nil: it goes in.
930
- # @return [SessionChain::Successor, :busy, nil]
931
- def moved_on(id, free)
932
- return continued_as(id) if free
933
-
934
- SessionChain::Successor.of(id, state_dir: state_dir!, in_flight: true) || :busy
935
- end
927
+ # Inside SessionChain::Sharing.under(+id+) (+sharing+ its value, nil
928
+ # when the shared hold was taken): why an arrival can't be written
929
+ # now. Held: the lock is held and nobody is named (another change, a
930
+ # continue before its intent or after its undo, a delete with no saved
931
+ # successor). A Sharing::Moved (a continue's new link in flight, else
932
+ # a saved successor, under any holder's kind) or, the hold taken, a
933
+ # Successor (#continued_as: archived, with its anchor's head): both
934
+ # answer #id and #in_flight?. nil: it goes in.
935
+ # @return [SessionChain::Sharing::Moved, SessionChain::Sharing::Held, SessionChain::Successor, nil]
936
+ def moved_on(id, sharing) = sharing || continued_as(id)
936
937
 
937
938
  # The block, for a session target under its transition lock
938
- # (ContextSources.changing); a project's as is.
939
+ # (ContextChange.under); a project's as is.
939
940
  def own_change(target, &)
940
941
  return yield if target.project?
941
942
 
942
- ContextSources.changing(target.session_id, state_dir: state_dir!, &)
943
+ ContextChange.under(target.session_id, state_dir: state_dir!, &)
943
944
  end
944
945
 
945
946
  def state_dir! = @state_dir || Session.default_state_dir
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../session"
4
+ require_relative "../session_transition"
5
+ require_relative "successor"
6
+
7
+ module Samagotchi
8
+ module SessionChain
9
+ # The one answer an arrival gets when it takes a session's transition
10
+ # lock shared (SessionTransition.shared) and another holds it
11
+ # exclusively: moved (Moved: who continues the session, and the kind of
12
+ # the hold) or held (Held: nobody to name). Each caller decides what it
13
+ # does with it: the inbox names nobody under a delete, a stop or an
14
+ # archive, a context change says Busy's words there, a peer say, pair or
15
+ # push names the saved successor whatever the kind.
16
+ #
17
+ # The rule (docs/internals/session-lifecycle.md, The transition lock),
18
+ # on SessionTransition::Busy.held's read of the holder:
19
+ # 1. a continue in flight that names its new link (Busy#successor_id:
20
+ # never under a delete, a stop or an archive, whatever a crashed
21
+ # continue left) → Moved(kind: :continue, in flight);
22
+ # 2. a saved successor (Successor.of without the anchor), under every
23
+ # kind → Moved(kind: the holder's, saved);
24
+ # 3. else Held(kind: the holder's).
25
+ # The saved lookup lists the sessions (Links): one Session.list per
26
+ # refused arrival with no continue in flight, only while a transition
27
+ # holds the lock.
28
+ module Sharing
29
+ # +busy+ is the holder's Busy (Busy.held), +successor+ a Successor.
30
+ Moved = Data.define(:kind, :successor, :busy) do
31
+ def id = successor.id
32
+ def in_flight? = successor.in_flight?
33
+
34
+ # The refusal naming the new link ("is being continued as Y", "was
35
+ # continued as S"): callers add what to do next as a tail.
36
+ # @return [Continued]
37
+ def refusal = Continued.for(busy.session_id, successor)
38
+ end
39
+
40
+ # +busy+ is the holder's Busy (Busy.held): its words name the holder.
41
+ Held = Data.define(:kind, :busy) do
42
+ # @return [SessionTransition::Busy]
43
+ def refusal = busy
44
+ end
45
+
46
+ module_function
47
+
48
+ # The block under a shared hold of +id+'s transition lock, its
49
+ # argument nil when the hold was taken (or this thread holds it
50
+ # exclusively), else a Moved or a Held by the rule above. An id that
51
+ # is no session id fails closed, as SessionTransition.shared's false:
52
+ # Held, nobody named, Busy's plain words (callers check the id first).
53
+ # Nothing is held while a Moved or a Held is yielded.
54
+ # @yieldparam sharing [Moved, Held, nil]
55
+ # @return the block's value
56
+ def under(id, state_dir:)
57
+ return yield(Held.new(kind: nil, busy: SessionTransition::Busy.new(id))) unless Session.valid_id?(id)
58
+
59
+ SessionTransition.shared(id, state_dir: state_dir) do |free|
60
+ next yield(nil) if free
61
+
62
+ yield answer(id, state_dir: state_dir)
63
+ end
64
+ end
65
+
66
+ # What a held lock of +id+ answers (the rule).
67
+ # @return [Moved, Held]
68
+ def answer(id, state_dir:)
69
+ busy = SessionTransition::Busy.held(id, state_dir: state_dir)
70
+ if busy.successor_id
71
+ return Moved.new(kind: :continue, successor: Successor.new(id: busy.successor_id, via: :in_flight), busy: busy)
72
+ end
73
+
74
+ successor = Successor.of(id, state_dir: state_dir, anchor: false)
75
+ successor ? Moved.new(kind: busy.kind, successor: successor, busy: busy) : Held.new(kind: busy.kind, busy: busy)
76
+ end
77
+ end
78
+ end
79
+ end
@@ -13,8 +13,10 @@ module Samagotchi
13
13
  # or just saved: ContinueIntent.in_flight).
14
14
  #
15
15
  # Who asks what: SessionAccess::Local#continued_as (peer say/pair, a
16
- # context push: .of, in flight only while the lock is held),
17
- # SessionContinue's check (.of, no in-flight: it holds the lock itself),
16
+ # context push, the hold taken: .of), SessionChain::Sharing (a shared
17
+ # hold that met a transition: Busy.held's in-flight read, then .of
18
+ # without the anchor), SessionContinue's check (.of, no in-flight: it
19
+ # holds the lock itself),
18
20
  # follow_guard (.of without the anchor while it holds the lock, as it
19
21
  # always asked; .in_flight when it can't), SessionInbox::Head#continuing
20
22
  # and Schedules#continuing_reason (.in_flight alone: their walk already
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "fileutils"
5
+ require "monitor"
6
+ require "time"
7
+ require_relative "atomic_file"
8
+ require_relative "session_paths"
9
+
10
+ module Samagotchi
11
+ # The chips bundles draw in a session's bar (ctx.chips, docs/plugins.md,
12
+ # Chips): chips.json in the session's own folder (beside cards.json), so
13
+ # chi web serves them with no worker running. Written whole through
14
+ # AtomicFile: {"<bundle>" => {"<name>" => {"label", "state", "dot", "title",
15
+ # "at", "body", "actions", "set_at"}}}. Checked chips only: Plugin::Chips
16
+ # builds them. A continue or a fork copies nothing (the bundle sets its
17
+ # chips again); a delete removes the folder. The file doesn't make a
18
+ # session count as used (SessionManager's emptiness).
19
+ class SessionChips
20
+ FILE = "chips.json"
21
+ # A chip's key a write doesn't compare: the same content again writes
22
+ # nothing and announces nothing.
23
+ STAMP = "set_at"
24
+ # Every write in the process, every session's: they are rare (a bundle's
25
+ # change), and one lock keeps a read-change-write whole.
26
+ LOCK = Monitor.new
27
+
28
+ # @return [String] the session's chips.json
29
+ def self.path(session_id, state_dir:) = File.join(SessionPaths.session_dir(session_id, state_dir: state_dir), FILE)
30
+
31
+ # A session's chips, every bundle's: {} for none, or a file that doesn't
32
+ # read (or isn't a mapping of mappings).
33
+ # @return [Hash{String => Hash{String => Hash}}]
34
+ def self.read(session_id, state_dir:)
35
+ from_file(path(session_id, state_dir: state_dir))
36
+ end
37
+
38
+ def self.from_file(path)
39
+ data = JSON.parse(File.read(path))
40
+ return {} unless data.is_a?(Hash)
41
+
42
+ data.select { |bundle, chips| bundle.is_a?(String) && chips.is_a?(Hash) && chips.values.all?(Hash) }
43
+ rescue JSON::ParserError, SystemCallError
44
+ {}
45
+ end
46
+
47
+ # Whether two chip lists of a bundle show the same (their stamps aside).
48
+ def self.same?(one, other)
49
+ strip = ->(chips) { chips.transform_values { |chip| chip.except(STAMP) } }
50
+ strip.call(one) == strip.call(other)
51
+ end
52
+
53
+ # +fresh+ with each chip that didn't change keeping its stamp from
54
+ # +old+, the others stamped +now+.
55
+ def self.stamped(old, fresh, now)
56
+ fresh.to_h do |name, chip|
57
+ was = old[name]
58
+ stamp = was && was.except(STAMP) == chip.except(STAMP) ? was[STAMP] : now
59
+ [name, chip.merge(STAMP => stamp)]
60
+ end
61
+ end
62
+
63
+ # @param session_id [String]
64
+ # @param state_dir [String] the sessions dir
65
+ # @param on_change [#call, nil] called after a write that changed
66
+ # something (the Engine's :chips_updated), outside the lock
67
+ def initialize(session_id, state_dir:, on_change: nil)
68
+ @path = self.class.path(session_id, state_dir: state_dir)
69
+ @on_change = on_change
70
+ end
71
+
72
+ # @return [Hash{String => Hash{String => Hash}}] every bundle's chips now
73
+ def all = self.class.from_file(@path)
74
+
75
+ # Read +bundle+'s chips, change them, write the file when they changed.
76
+ # @yieldparam mine [Hash{String => Hash}] the bundle's chips now (a copy)
77
+ # @yieldreturn [Hash{String => Hash}] what they are after
78
+ # @return [Boolean] whether anything was written (and announced)
79
+ def update(bundle)
80
+ changed = LOCK.synchronize do
81
+ chips = all
82
+ old = chips[bundle] || {}
83
+ fresh = yield(old.transform_values(&:dup))
84
+ next false if self.class.same?(old, fresh)
85
+
86
+ fresh = self.class.stamped(old, fresh, Time.now.utc.iso8601)
87
+ fresh.empty? ? chips.delete(bundle) : chips[bundle] = fresh
88
+ write(chips)
89
+ true
90
+ end
91
+ @on_change&.call if changed
92
+ changed
93
+ end
94
+
95
+ private
96
+
97
+ def write(chips)
98
+ if chips.empty?
99
+ FileUtils.rm_f(@path)
100
+ else
101
+ FileUtils.mkdir_p(File.dirname(@path))
102
+ AtomicFile.write(@path, "#{JSON.generate(chips)}\n")
103
+ end
104
+ end
105
+
106
+ # The bundle test kit's store (Testing::Recorder#chips): the same
107
+ # update, in memory; #writes counts the changes.
108
+ class Memory
109
+ attr_reader :writes
110
+
111
+ def initialize
112
+ @chips = {}
113
+ @writes = 0
114
+ @mutex = Monitor.new
115
+ end
116
+
117
+ def all = @mutex.synchronize { @chips.transform_values(&:dup) }
118
+
119
+ def update(bundle)
120
+ @mutex.synchronize do
121
+ old = @chips[bundle] || {}
122
+ fresh = yield(old.transform_values(&:dup))
123
+ next false if SessionChips.same?(old, fresh)
124
+
125
+ fresh = SessionChips.stamped(old, fresh, Time.now.utc.iso8601)
126
+ fresh.empty? ? @chips.delete(bundle) : @chips[bundle] = fresh
127
+ @writes += 1
128
+ true
129
+ end
130
+ end
131
+ end
132
+ end
133
+ end
@@ -7,6 +7,7 @@ require_relative "client_id"
7
7
  require_relative "worker_presence"
8
8
  require_relative "continue_intent"
9
9
  require_relative "session_chain/links"
10
+ require_relative "session_chain/sharing"
10
11
  require_relative "session_chain/successor"
11
12
  require_relative "session_transition"
12
13
 
@@ -286,9 +287,9 @@ module Samagotchi
286
287
 
287
288
  # The block under +policy+'s hold of +id+, or, when a transition
288
289
  # holds the lock now (not waited for), +refused+ called with who
289
- # continues +id+ (the holding continue's new link, in flight, else a
290
- # saved successor: SessionChain::Successor) or nil (busy: Busy's
291
- # words). A :none row,
290
+ # continues +id+ (SessionChain::Sharing's Moved: the holding
291
+ # continue's new link, in flight, else a saved successor, its
292
+ # SessionChain::Successor) or nil (busy: Busy's words). A :none row,
292
293
  # or an id that is no session id (the caller's own refusal follows),
293
294
  # is the block alone.
294
295
  # @param refused [#call] (successor) the refusal's value
@@ -296,17 +297,16 @@ module Samagotchi
296
297
  def under(policy, id, state_dir, refused:)
297
298
  return yield unless policy.shared? && Session.valid_id?(id)
298
299
 
299
- SessionTransition.shared(id, state_dir: state_dir) do |free|
300
- next yield if free
300
+ SessionChain::Sharing.under(id, state_dir: state_dir) do |sharing|
301
+ next yield if sharing.nil?
301
302
 
302
303
  # A delete, a stop or an archive holding it names nobody (Busy's
303
304
  # "being deleted": a link being deleted or pruned is not
304
- # continued anywhere new); else the holder's in-flight continue
305
- # first (its new link may be saved already), then a saved one.
306
- next refused.call(nil) if SessionTransition.other_than_continue?(SessionTransition.holder(id, state_dir: state_dir))
307
-
308
- refused.call(SessionChain::Successor.in_flight(id, state_dir: state_dir) ||
309
- SessionChain::Successor.of(id, state_dir: state_dir, anchor: false))
305
+ # continued anywhere new), on purpose, even with a saved
306
+ # successor; a holder that names no kind (an older chi's
307
+ # continue) still names it.
308
+ moved = sharing.is_a?(SessionChain::Sharing::Moved) && !SessionTransition.other_than_continue?(sharing.kind)
309
+ refused.call(moved ? sharing.successor : nil)
310
310
  end
311
311
  end
312
312
  end
@@ -5,6 +5,7 @@ require_relative "../session_inbox"
5
5
  require_relative "../worker_link"
6
6
  require_relative "../starting_marker"
7
7
  require_relative "../session_transition"
8
+ require_relative "../session_chips"
8
9
 
9
10
  module Samagotchi
10
11
  class SessionManager
@@ -17,8 +18,10 @@ module Samagotchi
17
18
  # The starting marker is one too: a start left one behind; a fresh one
18
19
  # keeps the session from the deleters itself. So is the transition lock
19
20
  # (a send's shared hold leaves it: SessionInbox::Hold).
21
+ # A bundle's chips (SessionChips) are its own, not the user's: a bundle
22
+ # that sets one at session start leaves an untouched session discardable.
20
23
  EMPTY_SKELETON_FILES = ["pid", "owner.lock", WorkerLink::FILE, AnalyticsFile::NAME, StartingMarker::FILE,
21
- SessionTransition::LOCK].freeze
24
+ SessionTransition::LOCK, SessionChips::FILE].freeze
22
25
  EMPTY_DIRS = [SessionInbox::INPUT_DIR, SessionInbox::NOTES_DIR, "images"].freeze
23
26
  EMPTY_SKELETON_DIRS = (EMPTY_DIRS + [SessionInbox::OUTPUT_DIR]).freeze
24
27
 
@@ -33,7 +33,7 @@ module Samagotchi
33
33
  ANNOUNCEABLE_EVENTS = %i[turn_enqueued turn_dequeued input_merged prompt_restored continue_offered continue_resolved
34
34
  command_queued command_ran context_added card hook_notice guardrail_warning
35
35
  plugin_init_started plugin_init_finished working_set_updated participants_changed
36
- verdict_recorded objectives_updated].freeze
36
+ verdict_recorded objectives_updated chips_updated].freeze
37
37
 
38
38
  # Handle returned by #subscribe. Holds the observer reference and carries
39
39
  # #unsubscribe so a caller can deregister without keeping the registry.