samagotchi 0.172.1 → 0.174.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 (143) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/docs/architecture.md +16 -5
  4. data/docs/cli.md +11 -3
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/background-tasks.md +16 -6
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -1
  9. data/docs/internals/participants.md +69 -9
  10. data/docs/internals/remote-sessions.md +9 -1
  11. data/docs/internals/web-frontend.md +34 -8
  12. data/docs/plugins.md +1 -1
  13. data/docs/scheduling.md +9 -3
  14. data/docs/sessions.md +5 -3
  15. data/docs/testing.md +32 -10
  16. data/lib/samagotchi/bridge.rb +4 -3
  17. data/lib/samagotchi/bundle_command/try/sandbox.rb +2 -2
  18. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  19. data/lib/samagotchi/bundles/slow-commands/manifest.yml +3 -3
  20. data/lib/samagotchi/bundles/slow-commands/plugin.rb +3 -3
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/child_move.rb +11 -4
  23. data/lib/samagotchi/continued_from.rb +51 -0
  24. data/lib/samagotchi/engine/participants.rb +2 -2
  25. data/lib/samagotchi/engine.rb +1 -2
  26. data/lib/samagotchi/file_ref.rb +3 -5
  27. data/lib/samagotchi/guardrails/participant_refusal.rb +1 -1
  28. data/lib/samagotchi/memory_usage.rb +2 -1
  29. data/lib/samagotchi/message_parts.rb +5 -3
  30. data/lib/samagotchi/note_move.rb +11 -4
  31. data/lib/samagotchi/objectives_backing.rb +6 -10
  32. data/lib/samagotchi/parent_report.rb +1 -1
  33. data/lib/samagotchi/participant_prompts.rb +101 -0
  34. data/lib/samagotchi/participant_turn_mode.rb +1 -1
  35. data/lib/samagotchi/project_env.rb +7 -5
  36. data/lib/samagotchi/prompt_history.rb +2 -2
  37. data/lib/samagotchi/schedules.rb +13 -16
  38. data/lib/samagotchi/send_command/parent_gate.rb +2 -2
  39. data/lib/samagotchi/send_command.rb +4 -4
  40. data/lib/samagotchi/session_access/contract.rb +1 -0
  41. data/lib/samagotchi/session_access/local.rb +9 -1
  42. data/lib/samagotchi/session_access/remote.rb +26 -3
  43. data/lib/samagotchi/session_chain/delete.rb +405 -0
  44. data/lib/samagotchi/session_chain/delete_preview.rb +96 -0
  45. data/lib/samagotchi/session_chain/links.rb +38 -0
  46. data/lib/samagotchi/session_command_catalog.rb +210 -0
  47. data/lib/samagotchi/session_commands.rb +6 -187
  48. data/lib/samagotchi/session_continue.rb +51 -13
  49. data/lib/samagotchi/session_delete_command.rb +82 -17
  50. data/lib/samagotchi/session_manager/lifecycle.rb +5 -4
  51. data/lib/samagotchi/session_manager/removal.rb +137 -31
  52. data/lib/samagotchi/session_manager.rb +2 -1
  53. data/lib/samagotchi/session_stores.rb +4 -0
  54. data/lib/samagotchi/spawn_env.rb +75 -0
  55. data/lib/samagotchi/task_files.rb +51 -0
  56. data/lib/samagotchi/task_transcript.rb +67 -0
  57. data/lib/samagotchi/task_watch.rb +8 -6
  58. data/lib/samagotchi/terminal_ui/attached_loop/composer.rb +3 -3
  59. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +2 -2
  60. data/lib/samagotchi/terminal_ui/attached_loop/questions.rb +2 -2
  61. data/lib/samagotchi/terminal_ui/attached_loop.rb +4 -4
  62. data/lib/samagotchi/terminal_ui/exit_lines.rb +16 -0
  63. data/lib/samagotchi/terminal_ui/input_support.rb +1 -1
  64. data/lib/samagotchi/terminal_ui/local_link.rb +7 -1
  65. data/lib/samagotchi/terminal_ui.rb +3 -3
  66. data/lib/samagotchi/testing/boundary.rb +2 -2
  67. data/lib/samagotchi/testing/bundle.rb +1 -1
  68. data/lib/samagotchi/tool_activity.rb +63 -79
  69. data/lib/samagotchi/tool_names.rb +179 -0
  70. data/lib/samagotchi/tool_view.rb +3 -5
  71. data/lib/samagotchi/tools/ask_user_question.rb +2 -1
  72. data/lib/samagotchi/tools/builtins.rb +1 -1
  73. data/lib/samagotchi/tools/cancel_reminder.rb +2 -1
  74. data/lib/samagotchi/tools/cancel_schedule.rb +3 -1
  75. data/lib/samagotchi/tools/context_read.rb +2 -1
  76. data/lib/samagotchi/tools/delegate.rb +2 -1
  77. data/lib/samagotchi/tools/delegate_result.rb +2 -1
  78. data/lib/samagotchi/tools/edit.rb +2 -1
  79. data/lib/samagotchi/tools/execute.rb +22 -28
  80. data/lib/samagotchi/tools/forget_outputs.rb +2 -1
  81. data/lib/samagotchi/tools/list_reminders.rb +2 -1
  82. data/lib/samagotchi/tools/list_schedules.rb +3 -1
  83. data/lib/samagotchi/tools/list_sessions.rb +2 -1
  84. data/lib/samagotchi/tools/memory.rb +3 -2
  85. data/lib/samagotchi/tools/objectives_tool.rb +5 -4
  86. data/lib/samagotchi/tools/read.rb +2 -1
  87. data/lib/samagotchi/tools/register_reminder.rb +2 -1
  88. data/lib/samagotchi/tools/schedule_task.rb +3 -1
  89. data/lib/samagotchi/tools/send_note.rb +2 -1
  90. data/lib/samagotchi/tools/task_create.rb +2 -1
  91. data/lib/samagotchi/tools/task_get.rb +2 -1
  92. data/lib/samagotchi/tools/task_list.rb +2 -1
  93. data/lib/samagotchi/tools/task_runtime.rb +29 -154
  94. data/lib/samagotchi/tools/task_stop.rb +2 -1
  95. data/lib/samagotchi/tools/task_wait.rb +3 -2
  96. data/lib/samagotchi/tools/web_fetch.rb +2 -1
  97. data/lib/samagotchi/tools/write.rb +2 -1
  98. data/lib/samagotchi/turn_checkpoint.rb +1 -1
  99. data/lib/samagotchi/version.rb +1 -1
  100. data/lib/samagotchi/web/app.rb +45 -37
  101. data/lib/samagotchi/web/message_display.rb +1 -7
  102. data/lib/samagotchi/web/participant_access.rb +12 -4
  103. data/lib/samagotchi/web/participant_history.rb +68 -0
  104. data/lib/samagotchi/web/participant_images.rb +2 -1
  105. data/lib/samagotchi/web/participant_show.rb +5 -5
  106. data/lib/samagotchi/web/participants_admin.rb +1 -1
  107. data/lib/samagotchi/web/public/app.js +24 -12
  108. data/lib/samagotchi/web/public/card_registry.js +248 -0
  109. data/lib/samagotchi/web/public/cards_offscreen.js +3 -3
  110. data/lib/samagotchi/web/public/cards_place.js +8 -2
  111. data/lib/samagotchi/web/public/chains.js +3 -3
  112. data/lib/samagotchi/web/public/data.js +12 -0
  113. data/lib/samagotchi/web/public/delete_sheet.js +344 -0
  114. data/lib/samagotchi/web/public/format.js +1 -1
  115. data/lib/samagotchi/web/public/history_shape.js +1 -2
  116. data/lib/samagotchi/web/public/index.html +27 -0
  117. data/lib/samagotchi/web/public/info_bar.js +3 -2
  118. data/lib/samagotchi/web/public/lists_view.js +2 -2
  119. data/lib/samagotchi/web/public/more_sheet.js +42 -5
  120. data/lib/samagotchi/web/public/participant_history.js +27 -0
  121. data/lib/samagotchi/web/public/question_cards.js +1 -15
  122. data/lib/samagotchi/web/public/reload_check.js +90 -72
  123. data/lib/samagotchi/web/public/session_actions.js +50 -6
  124. data/lib/samagotchi/web/public/session_view.js +6 -1
  125. data/lib/samagotchi/web/public/stage_asking.js +6 -20
  126. data/lib/samagotchi/web/public/stage_view.js +2 -2
  127. data/lib/samagotchi/web/public/stage_waiting.js +4 -10
  128. data/lib/samagotchi/web/public/task_stop.js +1 -1
  129. data/lib/samagotchi/web/push_routes.rb +1 -1
  130. data/lib/samagotchi/web/reload_check_route.rb +5 -2
  131. data/lib/samagotchi/web/request_body.rb +72 -0
  132. data/lib/samagotchi/web/server.rb +70 -0
  133. data/lib/samagotchi/web/session_access_routes.rb +13 -11
  134. data/lib/samagotchi/web/session_control.rb +79 -20
  135. data/lib/samagotchi/web/session_create.rb +2 -1
  136. data/lib/samagotchi/web/session_show.rb +8 -8
  137. data/lib/samagotchi/web/viewer.rb +7 -2
  138. data/lib/samagotchi/web/working_set_routes.rb +3 -3
  139. data/lib/samagotchi/worker.rb +49 -182
  140. data/lib/samagotchi/worker_exit_claim.rb +102 -0
  141. data/lib/samagotchi/worker_participant_gate.rb +156 -0
  142. data/lib/samagotchi/worker_task_wakes.rb +2 -2
  143. metadata +17 -1
@@ -14,15 +14,22 @@ module Samagotchi
14
14
  include CLI::Command
15
15
 
16
16
  USAGE = <<~TEXT
17
- Usage: chi sessions delete [--force] (ID|PREFIX)...
17
+ Usage: chi sessions delete [--force] [--chain] (ID|PREFIX)...
18
18
  Deletes each session: its history, notes, images and queued input.
19
- This can't be undone.
19
+ This can't be undone. Deleting a chain's newest link undoes its
20
+ continue: the previous link comes back to the lists (not started),
21
+ with the delegates and notes that had moved on.
20
22
  -f, --force stop a session's running worker first (without it,
21
23
  a live session is refused); a session in a one-turn
22
24
  chi run (chi --non-interactive) is always refused
25
+ --chain delete every link of the session's chain, with their
26
+ delegates; running delegates are left running
23
27
  TEXT
24
28
  PREVIEW_LIMIT = 60
25
- FLAGS = CLI::Flags.new(help: CLI::Command::HELP_WORDS) { |f| f.switch "-f", "--force" }
29
+ FLAGS = CLI::Flags.new(help: CLI::Command::HELP_WORDS) do |f|
30
+ f.switch "-f", "--force"
31
+ f.switch "--chain"
32
+ end
26
33
 
27
34
  # @param argv [Array<String>] the arguments after "sessions delete"
28
35
  # @param access [SessionAccess::Local, nil] where the sessions are;
@@ -41,7 +48,10 @@ module Samagotchi
41
48
  options = parse
42
49
  return options if options.is_a?(Integer)
43
50
 
44
- options[:ids].uniq.map { |given| delete(given, force: options[:force]) }.all? ? 0 : 1
51
+ gone = options[:ids].uniq.map do |given|
52
+ options[:chain] ? delete_chain(given, force: options[:force]) : delete(given, force: options[:force])
53
+ end
54
+ gone.all? ? 0 : 1
45
55
  end
46
56
 
47
57
  private
@@ -51,7 +61,7 @@ module Samagotchi
51
61
  # @return [Hash, Integer] the options, or the exit status after the
52
62
  # help or a usage error
53
63
  def parse
54
- parsed = parse_flags(FLAGS, @argv, force: false)
64
+ parsed = parse_flags(FLAGS, @argv, force: false, chain: false)
55
65
  return parsed if parsed.is_a?(Integer)
56
66
  return usage_error("give session ids") if parsed.args.empty?
57
67
 
@@ -64,19 +74,11 @@ module Samagotchi
64
74
  short = id[0, 8]
65
75
  preview = preview_of(id)
66
76
  result = @access.delete(id, force: force)
67
- @stdout.puts(["#{short} deleted#{" (stopped its worker)" if result[:stopped]}", preview].compact.join(" "))
77
+ @stdout.puts(["#{short} deleted#{" (stopped its worker)" if result[:stopped]}#{revived(result)}#{delegates(result, id)}",
78
+ preview].compact.join(" "))
68
79
  true
69
- rescue SessionManager::OwnedByTUI
70
- @stdout.puts("#{short} refused: it is #{OwnerLock::TUI_BUSY}; let it finish first")
71
- false
72
- rescue SessionManager::DeleteRefused => e
73
- line = case e.reason
74
- when :still_stopping then "its worker is still shutting down; try again in a moment"
75
- when :scheduled then e.message
76
- else "its worker is running (--force stops it first)"
77
- end
78
- @stdout.puts("#{short} refused: #{line}")
79
- false
80
+ rescue SessionManager::OwnedByTUI, SessionManager::DeleteRefused => e
81
+ refused(e.session_id && e.session_id != id ? e.session_id[0, 8] : short, e)
80
82
  rescue ArgumentError => e
81
83
  error_line("chi sessions delete: #{e.message}")
82
84
  false
@@ -85,6 +87,69 @@ module Samagotchi
85
87
  false
86
88
  end
87
89
 
90
+ # "; the previous link 1a2b3c4d is back in the lists" (D1), with the
91
+ # delegates that went back to it.
92
+ def revived(result)
93
+ back = Array(result[:unarchived]).first
94
+ return "" unless back
95
+
96
+ moved = Array(result[:moved_back]).size
97
+ "; the previous link #{back[0, 8]} is back in the lists" \
98
+ "#{" with #{moved} delegate#{"s" unless moved == 1}" if moved.positive?}"
99
+ end
100
+
101
+ # "; 2 delegates deleted with it; 1 left running: 9d0e1f2a" (D7, a
102
+ # chained link's own delegates).
103
+ def delegates(result, id)
104
+ gone = Array(result[:deleted]).size - (Array(result[:deleted]).include?(id) ? 1 : 0)
105
+ running = Array(result[:left_running])
106
+ words = []
107
+ words << "#{gone} delegate#{"s" unless gone == 1} deleted with it" if gone.positive?
108
+ words << "#{running.size} left running: #{running.map { |sid| sid[0, 8] }.join(", ")}" unless running.empty?
109
+ words.empty? ? "" : "; #{words.join("; ")}"
110
+ end
111
+
112
+ # --chain: one line per link deleted, then a summary.
113
+ # @return [Boolean] whether every link went
114
+ def delete_chain(given, force:)
115
+ id = @access.resolve_id(given)
116
+ result = @access.delete_chain(id, force: force)
117
+ result[:deleted].each { |sid| @stdout.puts("#{sid[0, 8]} deleted#{" (stopped its worker)" if result[:stopped].include?(sid)}") }
118
+ @stdout.puts(chain_summary(result))
119
+ result[:left].empty?
120
+ rescue SessionManager::OwnedByTUI, SessionManager::DeleteRefused => e
121
+ refused((e.session_id || id).to_s[0, 8], e)
122
+ rescue ArgumentError => e
123
+ error_line("chi sessions delete: #{e.message}")
124
+ false
125
+ end
126
+
127
+ def chain_summary(result)
128
+ parts = ["#{result[:deleted].size} deleted"]
129
+ parts << "#{result[:left].size} links kept: #{result[:refusal]}" unless result[:left].empty?
130
+ parts << "back in the lists: #{result[:unarchived].map { |sid| sid[0, 8] }.join(", ")}" unless result[:unarchived].empty?
131
+ unless result[:left_running].empty?
132
+ parts << "left running, without a parent: #{result[:left_running].map { |sid| sid[0, 8] }.join(", ")}"
133
+ end
134
+ parts << "earlier links, cut off by a deleted link, are kept (archived)" if result[:cut_off]
135
+ "chain: #{parts.join("; ")}"
136
+ end
137
+
138
+ # @return [false]
139
+ def refused(short, error)
140
+ line = case error
141
+ when SessionManager::OwnedByTUI then "it is #{OwnerLock::TUI_BUSY}; let it finish first"
142
+ else
143
+ case error.reason
144
+ when :still_stopping then "its worker is still shutting down; try again in a moment"
145
+ when :worker_running then "its worker is running (--force stops it first)"
146
+ else error.message
147
+ end
148
+ end
149
+ @stdout.puts("#{short} refused: #{line}")
150
+ false
151
+ end
152
+
88
153
  def preview_of(id)
89
154
  text = @access.show(id).display_title.gsub(/\s+/, " ").strip
90
155
  return nil if text.empty?
@@ -10,8 +10,9 @@ require_relative "../process_group"
10
10
  require_relative "../reminder_carry"
11
11
  require_relative "../session"
12
12
  require_relative "../session_inbox"
13
+ require_relative "../task_files"
13
14
  require_relative "../tools/task_record"
14
- require_relative "../tools/task_runtime"
15
+ require_relative "../task_transcript"
15
16
  require_relative "../worker_link"
16
17
 
17
18
  module Samagotchi
@@ -199,10 +200,10 @@ module Samagotchi
199
200
  root = session.working_directory.to_s
200
201
  return false if root.empty?
201
202
 
202
- Tools::TaskRuntime.created_ids_in(session.messages).any? do |id|
203
- next false unless Tools::TaskRuntime::TASK_ID.match?(id)
203
+ TaskTranscript.created_ids_in(session.messages).any? do |id|
204
+ next false unless TaskFiles::TASK_ID.match?(id)
204
205
 
205
- path = File.join(root, Tools::TaskRuntime::TASKS_DIR, id, Tools::TaskRuntime::METADATA_FILENAME)
206
+ path = File.join(root, TaskFiles::TASKS_DIR, id, TaskFiles::METADATA_FILENAME)
206
207
  next false unless File.file?(path)
207
208
 
208
209
  Tools::TaskRecord.from_file(JSON.parse(File.read(path)))&.running?
@@ -4,26 +4,44 @@ require_relative "../session_stores"
4
4
 
5
5
  module Samagotchi
6
6
  class SessionManager
7
- # A delete that would pull the session from under its live worker.
8
- # reason: :worker_running (not asked to stop it), :still_stopping
9
- # (stopped, but the worker outlived the wait) or :changed (the caller's
10
- # +still:+ check, read again under the owner lock, no longer holds).
7
+ # A delete that can't happen now, one message per reason:
8
+ # :worker_running (not asked to stop it), :still_stopping (stopped, but
9
+ # the worker outlived the wait), :changed (the caller's +still:+ check,
10
+ # read again under the owner lock, no longer holds), :scheduled (an
11
+ # enabled schedule's target, anchor or head: +schedule_id+),
12
+ # :continuing (a continue of +session_id+ is in flight: this link, or
13
+ # the previous one a delete would bring back), :delegate_unmovable (a
14
+ # delegate the deleted link's continue moved can't go back: +ids+,
15
+ # +detail+ says why), :chain_scheduled (a schedule is on the chain a
16
+ # chain delete would take: +schedule_id+).
11
17
  class DeleteRefused < StandardError
12
- attr_reader :session_id, :reason, :schedule_id
18
+ attr_reader :session_id, :reason, :schedule_id, :ids
13
19
 
14
- def initialize(session_id, reason, message: nil, schedule_id: nil)
20
+ def initialize(session_id, reason, message: nil, schedule_id: nil, ids: [], detail: nil)
15
21
  @session_id = session_id
16
22
  @reason = reason
17
23
  @schedule_id = schedule_id
18
- message ||= case reason
19
- when :still_stopping then "session #{session_id}'s worker is still shutting down"
20
- when :changed then "session #{session_id} changed since it was checked"
21
- when :scheduled
22
- "this session is the target of an enabled schedule" \
23
- "#{"; cancel it with chi schedule cancel #{schedule_id}" if schedule_id}"
24
- else "session #{session_id}'s worker is running"
25
- end
26
- super(message)
24
+ @ids = ids
25
+ super(message || refused_message(detail))
26
+ end
27
+
28
+ private
29
+
30
+ def refused_message(detail)
31
+ short = @session_id.to_s[0, 8]
32
+ cancel = "; cancel it with chi schedule cancel #{@schedule_id}" if @schedule_id
33
+ case @reason
34
+ when :worker_running then "session #{@session_id}'s worker is running"
35
+ when :still_stopping then "session #{@session_id}'s worker is still shutting down"
36
+ when :changed then "session #{@session_id} changed since it was checked"
37
+ when :scheduled then "this session is the target of an enabled schedule#{cancel}"
38
+ when :continuing then "a continue of #{short} is under way; try again in a moment"
39
+ when :delegate_unmovable
40
+ "#{@ids.map { |id| id[0, 8] }.join(", ")}, moved here by the continue, can't go back to the previous link" \
41
+ "#{": #{detail}" if detail}"
42
+ when :chain_scheduled then "an enabled schedule runs on this chain#{cancel}"
43
+ else "session #{@session_id} can't be deleted now (#{@reason})"
44
+ end
27
45
  end
28
46
  end
29
47
 
@@ -165,8 +183,18 @@ module Samagotchi
165
183
  # its candidate-log lines; a session a worker left empty has none worth
166
184
  # the read
167
185
  # @param allow_scheduled [Boolean] internal rollback of a failed continue
186
+ # @param revive_previous [Boolean] a user's delete (CLI, web, TUI) of a
187
+ # chain's newest link brings the previous one back to the lists and
188
+ # undoes the continue (SessionChain::Delete.link, D2/D5); any chained
189
+ # link's own delegates follow SessionChain::Delete::DELEGATES. The
190
+ # result then also has unarchived:, moved_back:, deleted: and
191
+ # left_running: (ids)
192
+ # @param refuse_continuing [Boolean] a user's delete refuses
193
+ # (:continuing) while a continue of the session is in flight
194
+ # @raise [DeleteRefused] also :scheduled for a schedule's anchor or
195
+ # head, and with the keywords :continuing and :delegate_unmovable
168
196
  def delete_session(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT, purge_runs: true,
169
- allow_scheduled: false)
197
+ allow_scheduled: false, revive_previous: false, refuse_continuing: false)
170
198
  sd = state_dir || Session.default_state_dir
171
199
  given = id_or_prefix.to_s
172
200
  # Only a plain id: anything else could name a path outside the state dir.
@@ -178,25 +206,101 @@ module Samagotchi
178
206
  # A folder with no file left is still deleted (not resolve!).
179
207
  raise Session::NotFound, given unless File.exist?(path) || Dir.exist?(dir)
180
208
 
181
- unless allow_scheduled
182
- require_relative "../schedules"
183
- schedule = Schedules.new(state_dir: sd).protecting(id)
184
- if schedule
185
- raise DeleteRefused.new(id, :scheduled, schedule_id: schedule.id)
186
- end
209
+ if revive_previous || refuse_continuing
210
+ require_relative "../session_chain/delete"
211
+ return SessionChain::Delete.link(id, state_dir: sd, stop: stop, wait: wait, revive_previous: revive_previous,
212
+ refuse_continuing: refuse_continuing)
187
213
  end
188
214
 
189
- presence = WorkerPresence.read(id, state_dir: sd, owner: session_owner(id, state_dir: sd))
215
+ delete_resolved(id, state_dir: sd, stop: stop, wait: wait, purge_runs: purge_runs, allow_scheduled: allow_scheduled)
216
+ end
217
+
218
+ # Delete every link of +id+'s chain with their delegates
219
+ # (SessionChain::Delete.chain, D4/D7): all or nothing for the
220
+ # refusals, newest link first.
221
+ # @param stop [Boolean] stop the links' live workers first (the web
222
+ # always does; the CLI's --force)
223
+ # @return [Hash] SessionChain::Delete.chain's
224
+ # @raise [ArgumentError] unknown id (Session::AmbiguousId for a prefix of several)
225
+ # @raise [DeleteRefused, OwnedByTUI] nothing was deleted
226
+ def delete_chain(id_or_prefix, state_dir: nil, stop: false, wait: STOP_WAIT)
227
+ sd = state_dir || Session.default_state_dir
228
+ given = id_or_prefix.to_s
229
+ raise Session::NotFound, given unless Session.valid_id?(given)
230
+
231
+ id = Session.resolve_id(given, state_dir: sd)
232
+ raise Session::NotFound, given unless Session.exist?(id, state_dir: sd)
233
+
234
+ require_relative "../session_chain/delete"
235
+ SessionChain::Delete.chain(id, state_dir: sd, stop: stop, wait: wait)
236
+ end
237
+
238
+ # #delete_session's checks and removal for a full id that exists:
239
+ # the schedule refusal, the one-turn run, the worker (stopped with
240
+ # +stop+), then #remove_files. SessionChain::Delete's last step.
241
+ # @return [Hash] {id:, removed:, stopped:}
242
+ def delete_resolved(id, state_dir:, stop: false, wait: STOP_WAIT, purge_runs: true, allow_scheduled: false)
243
+ sd = state_dir
244
+ path = Session.session_file(id, state_dir: sd)
245
+ dir = Session.session_dir(id, state_dir: sd)
246
+ refuse_scheduled!(id, sd) unless allow_scheduled
247
+
248
+ held = release_for_delete!(id, state_dir: sd, stop: stop, wait: wait)
249
+ removed = remove_files(id, path, dir, state_dir: sd, purge_runs: purge_runs)
250
+ { id: id, removed: removed, stopped: held }
251
+ end
252
+
253
+ # +id+ free for a delete: a one-turn run refuses, a worker that owns it
254
+ # or is being started for it is stopped with +stop+ (else refused).
255
+ # @return [Boolean] whether there was one to stop
256
+ # @raise [OwnedByTUI, DeleteRefused] :worker_running, :still_stopping
257
+ def release_for_delete!(id, state_dir:, stop:, wait:)
258
+ presence = WorkerPresence.read(id, state_dir: state_dir, owner: session_owner(id, state_dir: state_dir))
190
259
  raise OwnedByTUI, id if presence.tui_owned?
191
260
 
192
261
  held = presence.owned? || presence.starting?
193
262
  if held
194
263
  raise DeleteRefused.new(id, :worker_running) unless stop
195
- raise DeleteRefused.new(id, :still_stopping) unless stop_held(id, state_dir: sd, wait: wait)
264
+ raise DeleteRefused.new(id, :still_stopping) unless stop_held(id, state_dir: state_dir, wait: wait)
196
265
  end
266
+ held
267
+ end
197
268
 
198
- removed = remove_files(id, path, dir, state_dir: sd, purge_runs: purge_runs)
199
- { id: id, removed: removed, stopped: held }
269
+ # Delete these ids safely, in this order: #delete_session for each (it
270
+ # re-checks the one-turn run, the starting marker and the owner lock),
271
+ # and the expensive session-scoped logs (#purge_removal_stores) once
272
+ # for the batch, for the ids deleted even when a later one is refused.
273
+ # No eligibility policy: each caller (Schedules#prune, the chain
274
+ # delete) decides which ids, and keeps its own checks and log tags.
275
+ # @param ids [Array<String>] full ids, in the order to delete them
276
+ # @return [Array<Hash>] #delete_session's result for each
277
+ # @raise [DeleteRefused, OwnedByTUI, Session::NotFound] the first
278
+ # refusal; the ids before it are deleted
279
+ def delete_ids(ids, state_dir: nil, stop: false, wait: STOP_WAIT)
280
+ sd = state_dir || Session.default_state_dir
281
+ results = []
282
+ # Not a map: the ids deleted before a refusal must reach the ensure's purge.
283
+ ids.each do |id| # rubocop:disable Style/MapIntoArray
284
+ results << delete_session(id, state_dir: sd, stop: stop, wait: wait, purge_runs: false)
285
+ end
286
+ results
287
+ ensure
288
+ purge_removal_stores(results.map { |result| result[:id] }, state_dir: sd) if results
289
+ end
290
+
291
+ # +id+'s delegate subtree and +id+, in the order a delete takes them:
292
+ # the descendants deepest first, +id+ last. A delete refused part-way
293
+ # leaves nothing above what it took, so a retry finds the same tree.
294
+ # @return [Array<String>]
295
+ def delete_tree_ids(id, state_dir) = [*descendant_ids(id, state_dir).reverse, id]
296
+
297
+ # DeleteRefused :scheduled when an enabled schedule's target, anchor
298
+ # or head is +id+: deleting a head would make the schedule fall back to
299
+ # an archived link and lose the links after it.
300
+ def refuse_scheduled!(id, state_dir)
301
+ require_relative "../schedules"
302
+ schedule = Schedules.new(state_dir: state_dir).protecting_link(id)
303
+ raise DeleteRefused.new(id, :scheduled, schedule_id: schedule.id) if schedule
200
304
  end
201
305
 
202
306
  # Remove every store with state scoped to +id+. The file and sidecar
@@ -206,12 +310,14 @@ module Samagotchi
206
310
  # a refusal leaves every store as it was).
207
311
  # @return [Array<String>] the session file, sidecar and context paths removed
208
312
  # @raise [DeleteRefused] see #remove_session_files
209
- def remove_files(id, path, dir, state_dir:, purge_runs: true, still: nil)
313
+ # @param locked [Boolean] the caller holds +id+'s owner lock (kind
314
+ # deleting) already: SessionChain::Delete, across its undo
315
+ def remove_files(id, path, dir, state_dir:, purge_runs: true, still: nil, locked: false)
210
316
  removed = []
211
317
  SESSION_STATE_STORES.each do |store|
212
318
  case store
213
319
  when :session_files
214
- removed.concat(remove_session_files(id, path, dir, state_dir: state_dir, still: still))
320
+ removed.concat(remove_session_files(id, path, dir, state_dir: state_dir, still: still, locked: locked))
215
321
  when :plugin_session_state
216
322
  PluginSessionState.remove(id)
217
323
  when :context_sources
@@ -251,9 +357,9 @@ module Samagotchi
251
357
  # @return [Array<String>] the paths removed
252
358
  # @raise [DeleteRefused] a worker took the lock, or a start was
253
359
  # claimed, after the caller's check, or +still+ no longer holds
254
- def remove_session_files(id, path, dir, state_dir:, still: nil)
255
- lock = Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0) : nil
256
- raise DeleteRefused.new(id, :worker_running) if Dir.exist?(dir) && lock.nil?
360
+ def remove_session_files(id, path, dir, state_dir:, still: nil, locked: false)
361
+ lock = !locked && Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0) : nil
362
+ raise DeleteRefused.new(id, :worker_running) if !locked && Dir.exist?(dir) && lock.nil?
257
363
  raise DeleteRefused.new(id, :worker_running) if StartingMarker.fresh?(id, state_dir: state_dir)
258
364
  raise DeleteRefused.new(id, :changed) if still && !still.call
259
365
 
@@ -61,7 +61,8 @@ require_relative "session_chain"
61
61
  require_relative "child_move"
62
62
  require_relative "starting_marker"
63
63
  require_relative "worker_presence"
64
- require_relative "tools/task_runtime"
64
+ require_relative "task_files"
65
+ require_relative "task_transcript"
65
66
 
66
67
  module Samagotchi
67
68
  # SessionManager coordinates background session processes.
@@ -29,6 +29,8 @@ module Samagotchi
29
29
  continue: "a continue ends the previous link's participants", corpus_dir: SIDE_CAR),
30
30
  Store.new(file: "participant_images.json", owner: "ParticipantUploads", removal: :session_files, cross_version: true,
31
31
  continue: "a continue ends the previous link's participants", corpus_dir: SIDE_CAR),
32
+ Store.new(file: "participant_prompts.json", owner: "ParticipantPrompts", removal: :session_files, cross_version: true,
33
+ continue: "a continue ends the previous link's participants", corpus_dir: SIDE_CAR),
32
34
  Store.new(file: "judgments.jsonl", owner: "SystemOne::RunsStore", removal: :system_one_runs, cross_version: false,
33
35
  continue: "saved judgments belong to the previous link", corpus_dir: nil),
34
36
  Store.new(file: "context_candidates.jsonl", owner: "ContextCandidatesLog", removal: :context_candidates_log,
@@ -43,6 +45,8 @@ module Samagotchi
43
45
  continue: "drawings describe turns in the previous link", corpus_dir: "sessions/compat-drawn"),
44
46
  Store.new(file: "move.json", owner: "ChildMove", removal: :session_files, cross_version: true,
45
47
  continue: "an interrupted move belongs to the previous continue", corpus_dir: SIDE_CAR),
48
+ Store.new(file: "continued_from.json", owner: "ContinuedFrom", removal: :session_files, cross_version: true,
49
+ continue: "the record names the continue that made this link", corpus_dir: SIDE_CAR),
46
50
  Store.new(file: "continue.json", owner: "ContinueIntent", removal: :session_files, cross_version: true,
47
51
  continue: "the intent records the previous link's continue", corpus_dir: SIDE_CAR),
48
52
  Store.new(file: "objectives.lock", owner: "Objectives", removal: :session_files, cross_version: false,
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "bundler_env"
5
+ require_relative "child_env"
6
+
7
+ module Samagotchi
8
+ # The env a command chi spawns for the model gets: chi's own Ruby/Bundler
9
+ # setup kept out (execute, task_create, and through ProjectEnv.spawn_env
10
+ # the MCP servers and context sources), and the checks on task_create's
11
+ # +env+ argument. No process code: Tools::TaskRuntime runs the task.
12
+ #
13
+ # ProjectEnv.spawn_env requires this file when it is called, never as it
14
+ # loads: child_env requires project_env.
15
+ module SpawnEnv
16
+ SANITIZED_ENV_KEYS = BundlerEnv::CHILD_RUBY
17
+ # Set by chi (Builtins.parent_env); the model's env can't change it.
18
+ MARKER_ENV_KEYS = ChildEnv::SESSION_MARKERS
19
+
20
+ module_function
21
+
22
+ # chi's own Ruby/Bundler setup, kept out of a command's environment
23
+ # (execute and task_create both spawn with it): run under `bundle
24
+ # exec`, chi would otherwise hand a project's `ruby -e` or
25
+ # `bundle exec` its Gemfile (RUBYOPT=-rbundler/setup, BUNDLE_GEMFILE,
26
+ # BUNDLER_SETUP) and lockfile.
27
+ def sanitized_spawn_env
28
+ SANITIZED_ENV_KEYS.to_h { |key| [key, nil] }.merge("RUBYOPT" => sanitized_rubyopt)
29
+ end
30
+
31
+ # The model's way out: a Ruby or Bundler variable it does want, for one command.
32
+ def sanitized_key_error(key)
33
+ "Error: env key is reserved: #{key} (chi clears it for every command; to set it for this one, " \
34
+ "put it in the command: #{key}=value cmd)"
35
+ end
36
+
37
+ # task_create's env: the scrub, then the model's +overrides+ (a Hash or
38
+ # a JSON object string), refused when they name a key chi sets.
39
+ # @return [Array(Hash, nil), Array(nil, String)] the env, or an error
40
+ def spawn_env_for(overrides)
41
+ return [sanitized_spawn_env, nil] if overrides.nil? || overrides.to_s.empty?
42
+
43
+ overrides = JSON.parse(overrides) if overrides.is_a?(String)
44
+ return [nil, "Error: env must be an object"] unless overrides.is_a?(Hash)
45
+
46
+ normalized = {}
47
+ overrides.each do |key, value|
48
+ return [nil, "Error: env keys and values must be strings"] unless key.is_a?(String) && value.is_a?(String)
49
+ return [nil, "Error: env keys and values cannot contain NUL bytes"] if key.include?("\0") || value.include?("\0")
50
+ return [nil, "Error: env key is reserved: #{key}"] if MARKER_ENV_KEYS.include?(key)
51
+ return [nil, sanitized_key_error(key)] if SANITIZED_ENV_KEYS.include?(key)
52
+
53
+ normalized[key] = value
54
+ end
55
+
56
+ [sanitized_spawn_env.merge(normalized), nil]
57
+ rescue JSON::ParserError
58
+ [nil, "Error: env must be a JSON object"]
59
+ end
60
+
61
+ def sanitized_rubyopt
62
+ rubyopt = ENV["RUBYOPT"].to_s
63
+ return nil if rubyopt.empty?
64
+
65
+ filtered = rubyopt.split(/\s+/).reject do |arg|
66
+ arg == "-rbundler/setup" || arg.match?(%r{\A-r.*bundler/setup\z})
67
+ end
68
+ return nil if filtered.empty?
69
+
70
+ filtered.join(" ")
71
+ end
72
+
73
+ private_class_method :sanitized_key_error, :sanitized_rubyopt
74
+ end
75
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "tools/task_record"
5
+
6
+ module Samagotchi
7
+ # Where a background task's files are: tmp/tasks/<id>/ in the worker's
8
+ # cwd, its task.json (a Tools::TaskRecord), output.log and exit_code. The
9
+ # layout only, and the one cheap read a UI row makes (command_of); no
10
+ # process code: Tools::TaskRuntime starts, refreshes and stops the tasks.
11
+ #
12
+ # TASKS_DIR and EXIT_CODE_FILENAME are on the bundle boundary's stable
13
+ # list (lib/samagotchi/testing/boundary.rb): the slow-commands bundle
14
+ # reads tmp/tasks/*/task.json and the exit_code beside it.
15
+ module TaskFiles
16
+ TASKS_DIR = File.join("tmp", "tasks")
17
+ METADATA_FILENAME = "task.json"
18
+ OUTPUT_FILENAME = "output.log"
19
+ EXIT_CODE_FILENAME = "exit_code"
20
+ # A task id as task_create makes them: no path parts.
21
+ TASK_ID = /\A[A-Za-z0-9_-]+\z/
22
+
23
+ module_function
24
+
25
+ def metadata_path(task_id)
26
+ File.join(task_dir_for(task_id), METADATA_FILENAME)
27
+ end
28
+
29
+ def task_dir_for(task_id)
30
+ File.join(TASKS_DIR, task_id.to_s)
31
+ end
32
+
33
+ # The command of the task +task_id+ under +root+ (a session's working
34
+ # directory) as its record has it, for a UI row's title; nil for no
35
+ # such task or an unreadable record. Reads the record only (no
36
+ # refresh), so it is cheap and never fails.
37
+ # @return [String, nil]
38
+ def command_of(task_id, root: Dir.pwd)
39
+ id = task_id.to_s.strip
40
+ return nil unless id.match?(TASK_ID)
41
+
42
+ path = File.join(root || Dir.pwd, TASKS_DIR, id, METADATA_FILENAME)
43
+ return nil unless File.file?(path)
44
+
45
+ command = Tools::TaskRecord.from_file(JSON.parse(File.read(path)))&.command
46
+ command.is_a?(String) && !command.strip.empty? ? command : nil
47
+ rescue StandardError # degrade-ok: a row's title; an unreadable record has none (moved from TaskRuntime)
48
+ nil
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "tool_names"
4
+
5
+ module Samagotchi
6
+ # Which background tasks a conversation started, read from its tool
7
+ # results: a task_create's "task_id:" and an execute's hand-over at its
8
+ # limit (or early, for a message). Text only: no record is read and no
9
+ # process looked at (Tools::TaskRuntime.running_created_in adds the
10
+ # refresh). The worker's finish wake (TaskWatch, WorkerTaskWakes), the
11
+ # Bridge's stop-task check, a turn's cancel note and SessionManager's
12
+ # running-task check read it. web/public/task_stop.js has the JS twin of
13
+ # handed_over_id (handedOverId).
14
+ module TaskTranscript
15
+ # A task_create result as the model gets it: its "[task_create]" lead,
16
+ # after the one "ran as: …" line a gate-corrected call has.
17
+ RAN_AS_LINE = "(?:ran as: [^\n]*\n)?"
18
+ CREATED_BLOCK = /\A#{RAN_AS_LINE}\[task_create\]\ntask_id: (\S+)/
19
+ CREATED_OUTPUT = /\A#{RAN_AS_LINE}(?:\[task_create\]\n)?task_id: (\S+)/
20
+
21
+ module_function
22
+
23
+ # The ids of every task this conversation started (task_create, a
24
+ # handed-over execute), whatever their status now, oldest first.
25
+ # A native tool_response joins its calls' results with "---".
26
+ # @return [Array<String>]
27
+ def created_ids_in(messages)
28
+ Array(messages).flat_map do |message|
29
+ next [] unless (message[:role] || message["role"]).to_s == "tool_response"
30
+
31
+ (message[:content] || message["content"]).to_s.split("\n\n---\n\n").filter_map do |block|
32
+ block[CREATED_BLOCK, 1] || handed_over_id(block)
33
+ end
34
+ end.uniq
35
+ end
36
+
37
+ # The task id of a tool output that started a task, the "[tool]" lead
38
+ # optional (a UI's row has it or not): a task_create's, or an execute's
39
+ # handed_over_id. nil for any other tool or output.
40
+ # @return [String, nil]
41
+ def created_id(tool, text)
42
+ case tool
43
+ when "task_create" then text.to_s[CREATED_OUTPUT, 1]
44
+ when ToolNames::Execute::NAME then handed_over_id(text)
45
+ end
46
+ end
47
+
48
+ # The task id an execute's hand-over result names: anchored on its
49
+ # first line (ToolNames::Execute::HANDED_OVER), never a "task_id:" line
50
+ # anywhere, which the command's own output can print. The "[execute]"
51
+ # lead and a "ran as: …" line before it are optional.
52
+ # web/public/task_stop.js has the JS twin (handedOverId).
53
+ # @return [String, nil]
54
+ def handed_over_id(text)
55
+ text = text.to_s
56
+ # A regexp raises on bytes that aren't UTF-8 (a command's raw output).
57
+ text = text.scrub unless text.valid_encoding?
58
+ text[handed_over_pattern, 1]
59
+ end
60
+
61
+ def handed_over_pattern
62
+ @handed_over_pattern ||= /\A#{RAN_AS_LINE}(?:\[#{ToolNames::Execute::NAME}\]\n)?#{Regexp.escape(ToolNames::Execute::HANDED_OVER)} #{ToolNames::Execute::HANDED_OVER_AFTER}[^\n]*\ntask_id: (\S+)/
63
+ end
64
+
65
+ private_class_method :handed_over_pattern
66
+ end
67
+ end
@@ -4,6 +4,8 @@ require "time"
4
4
 
5
5
  require_relative "config"
6
6
  require_relative "log"
7
+ require_relative "task_transcript"
8
+ require_relative "tool_names"
7
9
  require_relative "tools/task_runtime"
8
10
 
9
11
  module Samagotchi
@@ -40,10 +42,10 @@ module Samagotchi
40
42
 
41
43
  # The first line of a task tool's result, after a gate-corrected call's
42
44
  # "ran as: …" line and the optional "[tool]" lead.
43
- TASK_LINE = /\A#{Tools::TaskRuntime::RAN_AS_LINE}(?:\[task_(?:wait|get|stop)\]\n)?task_id: (\S+)/
45
+ TASK_LINE = /\A#{TaskTranscript::RAN_AS_LINE}(?:\[task_(?:wait|get|stop)\]\n)?task_id: (\S+)/
44
46
  LOOK_TOOLS = %w[task_wait task_get task_stop].freeze
45
- HANDED_OVER_LIMIT = /#{Regexp.escape(Tools::Execute::HANDED_OVER)} (\d+)s limit/
46
- HANDED_OVER_EARLY = /#{Regexp.escape(Tools::Execute::HANDED_OVER)} (\d+)s mark/
47
+ HANDED_OVER_LIMIT = /#{Regexp.escape(ToolNames::Execute::HANDED_OVER)} (\d+)s limit/
48
+ HANDED_OVER_EARLY = /#{Regexp.escape(ToolNames::Execute::HANDED_OVER)} (\d+)s mark/
47
49
 
48
50
  MODE_KEY = "session.task_wakes"
49
51
  MODES = %w[wake queue off].freeze
@@ -77,8 +79,8 @@ module Samagotchi
77
79
  tool = event[:tool].to_s
78
80
  output = event[:output].to_s
79
81
  output = output.scrub unless output.valid_encoding?
80
- if (id = Tools::TaskRuntime.created_id(tool, output))
81
- executed = tool == Tools::Execute::NAME
82
+ if (id = TaskTranscript.created_id(tool, output))
83
+ executed = tool == ToolNames::Execute::NAME
82
84
  add(id, limit_sec: executed ? output[HANDED_OVER_LIMIT, 1]&.to_i : nil,
83
85
  early_sec: executed ? output[HANDED_OVER_EARLY, 1]&.to_i : nil)
84
86
  elsif LOOK_TOOLS.include?(tool) && (id = output[TASK_LINE, 1])
@@ -125,7 +127,7 @@ module Samagotchi
125
127
  # records ([Entry, TaskRecord], oldest first). One the user stopped (the
126
128
  # web's stop-task button) or whose record is gone is dropped, not
127
129
  # returned. +keep+: the ids the conversation still holds
128
- # (TaskRuntime.created_ids_in): a !rollback or a restored turn may have
130
+ # (TaskTranscript.created_ids_in): a !rollback or a restored turn may have
129
131
  # dropped the result that added one, which is dropped too. One `ps` per
130
132
  # running task (TaskRuntime.get_record); nothing with an empty watch.
131
133
  # @return [Array<Array(Entry, Tools::TaskRecord)>]