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
@@ -1,8 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "tools/read"
4
- require_relative "tools/write"
5
- require_relative "tools/edit"
3
+ require_relative "tool_names"
6
4
 
7
5
  module Samagotchi
8
6
  # A ref to the file a read/write/edit call touched, for a UI to trace it
@@ -20,7 +18,7 @@ module Samagotchi
20
18
  class FileRef
21
19
  KIND = "file"
22
20
 
23
- TOOLS = [Tools::Read::NAME, Tools::Write::NAME, Tools::Edit::NAME].freeze
21
+ TOOLS = [ToolNames::Read::NAME, ToolNames::Write::NAME, ToolNames::Edit::NAME].freeze
24
22
 
25
23
  # @param cwd [String, nil] the session's working directory; without one
26
24
  # a relative path gets no ref (an absolute or ~ path still does)
@@ -30,7 +28,7 @@ module Samagotchi
30
28
  def self.for(tool_name, call, cwd:)
31
29
  return nil unless TOOLS.include?(tool_name) && call.is_a?(Hash)
32
30
 
33
- path = absolute((tool_name == Tools::Read::NAME ? call[:content] : call[:path]).to_s.strip, cwd)
31
+ path = absolute((tool_name == ToolNames::Read::NAME ? call[:content] : call[:path]).to_s.strip, cwd)
34
32
  return nil unless path
35
33
 
36
34
  line = positive(call[:start_line])
@@ -8,7 +8,7 @@ module Samagotchi
8
8
  # participant's turn this chi doesn't run under the owner's rules: no
9
9
  # current invite (an older chi's read-only one, no grant at all), a
10
10
  # Verify fresh child saved for a read-only turn, or no session. The
11
- # worker refuses such a turn before it starts (Worker#participant_refusal);
11
+ # worker refuses such a turn before it starts (WorkerParticipantGate#refusal);
12
12
  # this is the fail-closed fallback should one start anyway: every call is
13
13
  # denied, nobody is asked. A no-op for the owner's turns.
14
14
  class ParticipantRefusal
@@ -11,6 +11,7 @@ require_relative "working_set"
11
11
  require_relative "file_ref"
12
12
  require_relative "tool_response"
13
13
  require_relative "tool_output_cut"
14
+ require_relative "tool_names"
14
15
  require_relative "model_overlay"
15
16
  require_relative "tools/memory"
16
17
 
@@ -38,7 +39,7 @@ module Samagotchi
38
39
  # The memory scopes, project first, as `chi memory ls` reports them.
39
40
  SCOPES = Tools::VALID_SCOPES
40
41
  MEMORY_READ = Tools::MemoryRead::NAME
41
- FILE_READ = Tools::Read::NAME
42
+ FILE_READ = ToolNames::Read::NAME
42
43
 
43
44
  # One memory read at least once in the sessions counted: its tokens (the
44
45
  # results' size) and reads, +cut_reads+ of them returned a cut result,
@@ -5,7 +5,8 @@ require_relative "tool_call_parser"
5
5
  require_relative "tool_activity"
6
6
  require_relative "tool_row_fields"
7
7
  require_relative "llm/native_tool_normalizer"
8
- require_relative "tools/builtins"
8
+ require_relative "tool_names"
9
+ require_relative "tools/builtin_calls"
9
10
  require_relative "image_store"
10
11
  require_relative "llm_context_edit"
11
12
  require_relative "token_usage"
@@ -65,14 +66,15 @@ module Samagotchi
65
66
 
66
67
  # @param message [Hash] a saved model message (symbol or string keys)
67
68
  # @param responses [Array<Hash>] the tool_response messages after it
68
- # @param registry [Tools::Registry] the session's tools
69
+ # @param registry [Tools::Registry, #[]] the session's tools; the
70
+ # built-ins' names alone by default (ToolNames::BuiltinRegistry)
69
71
  # @param cwd [String, nil] the session's working directory (a file
70
72
  # tool's title is relative to it)
71
73
  # @param marks [Hash{String => Hash}] the session's edit marks by
72
74
  # output id (.edit_marks)
73
75
  # @return [Hash, nil] { thinking:, tools: [{ tool:, params:, title:,
74
76
  # output:, output_truncated:, images:, tool_id:, edit: }] } with only what it found; nil for nothing
75
- def for_message(message, responses, registry: Tools::Builtins.default, cwd: nil, marks: {})
77
+ def for_message(message, responses, registry: ToolNames::BuiltinRegistry, cwd: nil, marks: {})
76
78
  return nil unless something?(message)
77
79
 
78
80
  content = field(message, :content).to_s
@@ -57,15 +57,22 @@ module Samagotchi
57
57
  # meanwhile, never one the continue wrote itself (CONTINUE_SOURCES).
58
58
  # @return [Array<String>] the file names given back
59
59
  def give_back(from:, to:, moved:, state_dir:)
60
- files = unclaimed(notes_dir(from, state_dir)).select do |file|
60
+ rename(returnable(from: from, moved: moved, state_dir: state_dir), notes_dir(to, state_dir)).tap do |back|
61
+ Log.info(:worker, "notes_given_back", from: from[0, 8], to: to[0, 8], count: back.size) unless back.empty?
62
+ end
63
+ end
64
+
65
+ # The note files #give_back takes from +from+: those in +moved+ and
66
+ # every other unclaimed one but an objectives list and the continue's
67
+ # own (CONTINUE_SOURCES). A chain delete's plan counts them.
68
+ # @return [Array<String>] paths, oldest first
69
+ def returnable(from:, moved:, state_dir:)
70
+ unclaimed(notes_dir(from, state_dir)).select do |file|
61
71
  next true if moved.include?(File.basename(file))
62
72
 
63
73
  data = read(file)
64
74
  data && !objectives?(data) && !CONTINUE_SOURCES.include?(data["source"])
65
75
  end
66
- rename(files, notes_dir(to, state_dir)).tap do |back|
67
- Log.info(:worker, "notes_given_back", from: from[0, 8], to: to[0, 8], count: back.size) unless back.empty?
68
- end
69
76
  end
70
77
 
71
78
  # How far back along the chain a worker adopts (Adoption): the links
@@ -3,11 +3,7 @@
3
3
  require_relative "steer"
4
4
  require_relative "tool_activity"
5
5
  require_relative "tool_response"
6
- require_relative "tools/edit"
7
- require_relative "tools/execute"
8
- require_relative "tools/objectives_tool"
9
- require_relative "tools/task_wait"
10
- require_relative "tools/write"
6
+ require_relative "tool_names"
11
7
 
12
8
  module Samagotchi
13
9
  module Objectives
@@ -37,7 +33,7 @@ module Samagotchi
37
33
  class Backing
38
34
  OK = "ok"
39
35
  FAILED = "failed"
40
- CHANGES = [Tools::Edit::NAME, Tools::Write::NAME].freeze
36
+ CHANGES = [ToolNames::Edit::NAME, ToolNames::Write::NAME].freeze
41
37
 
42
38
  # +runs+ the move's turn's paired runs before it (LLMContextStale.paired_runs'),
43
39
  # in order; +state+ the move's.
@@ -58,7 +54,7 @@ module Samagotchi
58
54
  edited_after = false
59
55
  end
60
56
  end
61
- unbacked = state == Tools::ObjectivesTool::DONE && !command.nil? && (command == FAILED || edited_after)
57
+ unbacked = state == ToolNames::ObjectivesTool::DONE && !command.nil? && (command == FAILED || edited_after)
62
58
  new(edits: edits, command: command, edited_after_command: edited_after, unbacked: unbacked)
63
59
  end
64
60
 
@@ -79,7 +75,7 @@ module Samagotchi
79
75
  # an execute that finished ok (a failed, denied, stopped one isn't; one
80
76
  # handed over as a task still runs, and isn't either).
81
77
  def self.work?(run)
82
- edit?(run) || (run.call[:name].to_s == Tools::Execute::NAME && command_status(run) == OK)
78
+ edit?(run) || (run.call[:name].to_s == ToolNames::Execute::NAME && command_status(run) == OK)
83
79
  end
84
80
 
85
81
  def self.edit?(run)
@@ -95,12 +91,12 @@ module Samagotchi
95
91
  # a waiting message) or that waited on nothing (an Error:).
96
92
  def self.command_status(run)
97
93
  name = run.call[:name].to_s
98
- return nil unless [Tools::Execute::NAME, Tools::TaskWait::NAME].include?(name)
94
+ return nil unless [ToolNames::Execute::NAME, ToolNames::TaskWait::NAME].include?(name)
99
95
  return nil if ToolResponse.interrupted_text?(run.text)
100
96
 
101
97
  text = ToolActivity.saved_result_text(run.text)
102
98
  return nil if ToolActivity.guardrail_denied?(text)
103
- return task_status(text) if name == Tools::TaskWait::NAME
99
+ return task_status(text) if name == ToolNames::TaskWait::NAME
104
100
  return nil if ToolActivity.handed_over?(name, text)
105
101
 
106
102
  case ToolActivity.tool_activity_status(text, name, command: run.call[:content])
@@ -76,7 +76,7 @@ module Samagotchi
76
76
  end
77
77
 
78
78
  # The reasons a worker refuses a participant's queued turn
79
- # (Worker#participant_refusal), as its settled record's cancel_reason.
79
+ # (WorkerParticipantGate#refusal), as its settled record's cancel_reason.
80
80
  REFUSED_LINES = { "revoked" => ParticipantMessages::TOKEN_ENDED,
81
81
  "outdated" => ParticipantMessages::TOKEN_OUTDATED,
82
82
  "cap_reached" => ParticipantMessages::CAP_REACHED }.freeze
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "atomic_file"
5
+ require_relative "grants"
6
+ require_relative "log"
7
+ require_relative "prompt_history"
8
+
9
+ module Samagotchi
10
+ # Each participant's own prompts in one session, the list their
11
+ # composer's ↑/↓ walks (chi web's ParticipantHistory serves it, redacted,
12
+ # to that grant only). Written by chi web when it accepts a participant's
13
+ # turn, never derived from a message, a body field or an author the page
14
+ # sends; the owner's PromptHistory (the machine-wide file) is never
15
+ # written or read for a participant.
16
+ #
17
+ # participant_prompts.json in the session folder (beside
18
+ # participants.json, not in images/), 0600, written whole (AtomicFile):
19
+ # {prompts: {<grant id>: [text, …]}}, oldest first. At most LIMIT per
20
+ # grant; a text over MAX_ENTRY_BYTES isn't recorded (a cut prompt
21
+ # recalled and re-sent would be another message). Keys are grant ids
22
+ # (Grants::ID_RE) still known to the grants store: an append drops the
23
+ # others. A file that doesn't read is never written over (Log.warn) and
24
+ # reads as no entries; the owner can delete it. Callers serialize
25
+ # read-then-write themselves (chi web's @participant_prompts_mutex).
26
+ # See docs/internals/participants.md.
27
+ module ParticipantPrompts
28
+ FILE = "participant_prompts.json"
29
+ LIMIT = PromptHistory::LIMIT
30
+ MAX_ENTRY_BYTES = 16 * 1024
31
+
32
+ # What the file holds: +prompts+ grant id => [String] (only ID_RE keys,
33
+ # only String entries); +broken+ when it doesn't read.
34
+ State = Data.define(:prompts, :broken)
35
+ BROKEN = State.new(prompts: {}.freeze, broken: true)
36
+
37
+ module_function
38
+
39
+ # @return [State]
40
+ def read(dir)
41
+ path = File.join(dir, FILE)
42
+ return State.new(prompts: {}, broken: false) unless File.exist?(path)
43
+
44
+ data = JSON.parse(File.read(path))
45
+ raise TypeError, "not an object" unless data.is_a?(Hash)
46
+
47
+ prompts = data.fetch("prompts", {})
48
+ raise TypeError, "prompts not an object" unless prompts.is_a?(Hash)
49
+
50
+ kept = prompts.each_with_object({}) do |(grant_id, list), out|
51
+ next unless grant_id?(grant_id)
52
+
53
+ out[grant_id] = list.is_a?(Array) ? list.grep(String) : []
54
+ end
55
+ State.new(prompts: kept, broken: false)
56
+ rescue JSON::ParserError, SystemCallError, TypeError => e
57
+ Log.warn(:web, "participant_prompts_unreadable", file: path, msg: e.message)
58
+ BROKEN
59
+ end
60
+
61
+ # +grant_id+'s prompts, oldest first: a new array of theirs only; []
62
+ # for an unknown grant, a bad id or a broken file.
63
+ # @return [Array<String>]
64
+ def entries(dir, grant_id)
65
+ return [] unless grant_id?(grant_id)
66
+
67
+ read(dir).prompts.fetch(grant_id, []).dup
68
+ end
69
+
70
+ # The text as it would be kept (PromptHistory.normalize's), nil when it
71
+ # isn't kept: empty, or over MAX_ENTRY_BYTES.
72
+ # @return [String, nil]
73
+ def recordable(text)
74
+ line = PromptHistory.normalize([text]).first
75
+ line if line && line.bytesize <= MAX_ENTRY_BYTES
76
+ end
77
+
78
+ # Records +text+ as +grant_id+'s newest prompt, keeping its last LIMIT;
79
+ # the lists of grants not in +live_grant_ids+ are dropped. A broken
80
+ # file, a bad grant id or a text #recordable refuses writes nothing.
81
+ # @param live_grant_ids [Array<String>] the session's grants the grants
82
+ # store still knows (active or not yet swept)
83
+ # @return [Boolean] whether it was recorded
84
+ def append(dir, grant_id:, text:, live_grant_ids:)
85
+ return false unless grant_id?(grant_id)
86
+
87
+ line = recordable(text) or return false
88
+ state = read(dir)
89
+ return false if state.broken
90
+
91
+ live = Array(live_grant_ids) | [grant_id]
92
+ prompts = state.prompts.slice(*live)
93
+ prompts[grant_id] = (prompts.fetch(grant_id, []) + [line]).last(LIMIT)
94
+ body = { "prompts" => prompts }
95
+ AtomicFile.write(File.join(dir, FILE), "#{JSON.pretty_generate(body)}\n", perm: 0o600)
96
+ true
97
+ end
98
+
99
+ def grant_id?(grant_id) = grant_id.is_a?(String) && Grants::ID_RE.match?(grant_id)
100
+ end
101
+ end
@@ -2,7 +2,7 @@
2
2
 
3
3
  module Samagotchi
4
4
  # Whether a participant's turn runs here, and why not: the one decision
5
- # the worker (Worker#participant_refusal, before the turn starts and
5
+ # the worker (WorkerParticipantGate#refusal, before the turn starts and
6
6
  # before each of its generations) and the guardrails
7
7
  # (GuardrailWiring#participant_turn_mode, the turn's mode) both take.
8
8
  # :pair — it runs, under the owner's guardrails (PairBoundary);
@@ -63,7 +63,7 @@ module Samagotchi
63
63
  # would trust, and remember, an untrusted repo's mise.toml); CI too.
64
64
  MISE_UNSET = %w[MISE_YES CI].freeze
65
65
  TIMEOUT = 5
66
- # What execute and tasks set themselves (Tools::TaskRuntime's
66
+ # What execute and tasks set themselves (SpawnEnv's
67
67
  # sanitized env): never taken from the project's.
68
68
  TOOLS_DROP = BundlerEnv::CHILD_RUBY
69
69
 
@@ -111,20 +111,22 @@ module Samagotchi
111
111
  def install!(overlay) = @current = overlay
112
112
 
113
113
  # #current's env for a tool's spawn, less what every tool runs without
114
- # (Tools::TaskRuntime::SANITIZED_ENV_KEYS: RUBYOPT, RUBYLIB, Bundler's).
114
+ # (SpawnEnv::SANITIZED_ENV_KEYS: RUBYOPT, RUBYLIB, Bundler's).
115
115
  # @return [Hash{String=>String, nil}]
116
116
  def tools_env = current.env.except(*TOOLS_DROP)
117
117
 
118
118
  # The whole env change for a command chi starts for the session outside
119
119
  # execute (MCP servers, context sources): what execute spawns over
120
- # (Tools::TaskRuntime.sanitized_spawn_env: chi's own RUBYOPT without
120
+ # (SpawnEnv.sanitized_spawn_env: chi's own RUBYOPT without
121
121
  # bundler/setup, no RUBYLIB or Bundler variables), then #tools_env. One
122
122
  # env for every command, so a worker run from a checkout under `bundle
123
123
  # exec` hands none of them its Gemfile.
124
124
  # @return [Hash{String=>String, nil}]
125
125
  def spawn_env
126
- require_relative "tools/task_runtime" # lazily: bin/chi loads this file for #take_orig!
127
- Tools::TaskRuntime.sanitized_spawn_env.merge(tools_env)
126
+ # Lazily: bin/chi loads this file for #take_orig!, and spawn_env's
127
+ # child_env requires this file.
128
+ require_relative "spawn_env"
129
+ SpawnEnv.sanitized_spawn_env.merge(tools_env)
128
130
  end
129
131
 
130
132
  # Specs: back to NONE.
@@ -6,7 +6,7 @@ require "fileutils"
6
6
  require_relative "atomic_file"
7
7
  require_relative "config"
8
8
  require_relative "paths"
9
- require_relative "session_commands"
9
+ require_relative "session_command_catalog"
10
10
 
11
11
  module Samagotchi
12
12
  # The prompts typed at a chi prompt, kept for ↑ across launches: one
@@ -81,7 +81,7 @@ module Samagotchi
81
81
 
82
82
  # A `!command` worth recalling; `!rollback` isn't one.
83
83
  def shell_line?(line)
84
- line.to_s.start_with?(SessionCommands::SHELL_BANG_PREFIX) && line.to_s.strip != SessionCommands::ROLLBACK_COMMAND
84
+ line.to_s.start_with?(SessionCommandCatalog::SHELL_BANG_PREFIX) && line.to_s.strip != SessionCommandCatalog::ROLLBACK_COMMAND
85
85
  end
86
86
 
87
87
  def normalize(list)
@@ -209,6 +209,14 @@ module Samagotchi
209
209
  entries.find { |entry| target_of(entry, links).first == session_id }
210
210
  end
211
211
 
212
+ # The enabled schedule a delete of +session_id+ would break: one whose
213
+ # target (#protecting), anchor or head it is. A head deleted would make
214
+ # the schedule fall back to its anchor (an archived link) and fail.
215
+ # @return [Entry, nil]
216
+ def protecting_link(session_id)
217
+ entries.find { |entry| entry.anchor == session_id || entry.head == session_id } || protecting(session_id)
218
+ end
219
+
212
220
  # @param id_or_name [String] an id, a unique prefix of one, or a title
213
221
  # @return [Entry, nil]
214
222
  # @raise [Usage] the prefix or the title names more than one schedule
@@ -303,17 +311,7 @@ module Samagotchi
303
311
  # chain and each link back to its root. A schedule belongs to a chain when
304
312
  # its anchor or its head is one of them.
305
313
  # @return [Array<String>]
306
- def chain_of(session_id)
307
- links = links_now
308
- head = links.latest(session_id)
309
- ids = [head]
310
- id = head
311
- while (previous = links.continues(id)) && !ids.include?(previous)
312
- ids << previous
313
- id = previous
314
- end
315
- ids
316
- end
314
+ def chain_of(session_id) = links_now.chain(session_id).reverse
317
315
 
318
316
  # The schedules of this session's chain — the ones the tools may touch
319
317
  # without `all: true`.
@@ -1230,11 +1228,12 @@ module Samagotchi
1230
1228
  next if link == entry.anchor
1231
1229
  break unless ArchiveStore.archived?(Session.session_dir(link, state_dir: @state_dir))
1232
1230
 
1233
- descendants = SessionManager.descendant_ids(link, @state_dir)
1231
+ tree = SessionManager.delete_tree_ids(link, @state_dir)
1232
+ descendants = tree[0...-1]
1234
1233
  # The whole subtree must be ready: a live worker anywhere in it, or a
1235
1234
  # link's descendant that is not archived, stops the walk here rather
1236
1235
  # than half-deleting a tree.
1237
- owned = [link, *descendants].select { |sid| SessionManager.session_owner(sid, state_dir: @state_dir) }
1236
+ owned = tree.select { |sid| SessionManager.session_owner(sid, state_dir: @state_dir) }
1238
1237
  unless owned.empty?
1239
1238
  Log.warn(:worker, "prune_waiting", sid: link, id: entry.id, owned: owned.map { |sid| sid[0, 8] })
1240
1239
  break
@@ -1250,9 +1249,7 @@ module Samagotchi
1250
1249
  # refused partway, nothing above it has gone, so the next firing
1251
1250
  # retries the same set instead of leaving children under a link that
1252
1251
  # is already deleted.
1253
- (descendants.reverse + [link]).each do |sid|
1254
- SessionManager.delete_session(sid, state_dir: @state_dir)
1255
- end
1252
+ SessionManager.delete_ids(tree, state_dir: @state_dir)
1256
1253
  Log.info(:worker, "pruned_link", sid: link, id: entry.id, links: descendants.size + 1)
1257
1254
  end
1258
1255
  rescue SessionManager::DeleteRefused => e
@@ -2,7 +2,7 @@
2
2
 
3
3
  require_relative "../session"
4
4
  require_relative "../session_chain"
5
- require_relative "../session_commands"
5
+ require_relative "../session_command_catalog"
6
6
  require_relative "../parent_answers_command"
7
7
  require_relative "../turn_flow"
8
8
  require_relative "../guardrails/parent_approvals"
@@ -49,7 +49,7 @@ module Samagotchi
49
49
  end
50
50
 
51
51
  # Whether +prompt+ is a /parent-answers line.
52
- def self.parent_answers_line?(prompt) = SessionCommands.builtin_registry.lookup(prompt)&.id == :parent_answers
52
+ def self.parent_answers_line?(prompt) = SessionCommandCatalog.builtin_registry.lookup(prompt)&.id == :parent_answers
53
53
 
54
54
  # Whether +prompt+ is a /parent-answers line that loosens one of
55
55
  # +values+ (targets' own parent_answers).
@@ -5,7 +5,7 @@ require_relative "delivery"
5
5
  require_relative "terminal_ui/formatting"
6
6
  require_relative "session"
7
7
  require_relative "worker_link"
8
- require_relative "session_commands"
8
+ require_relative "session_command_catalog"
9
9
  require_relative "parent_answers_command"
10
10
  require_relative "session_inbox"
11
11
  require_relative "session_manager"
@@ -734,8 +734,8 @@ module Samagotchi
734
734
  # (a bundle's too).
735
735
  def command_like?(text) = text.to_s.lstrip.start_with?("/", "!")
736
736
 
737
- # @return [Commands::Registry::Entry, nil] SessionCommands.ui_only_entry
738
- def local_command(text) = SessionCommands.ui_only_entry(text)
737
+ # @return [Commands::Registry::Entry, nil] SessionCommandCatalog.ui_only_entry
738
+ def local_command(text) = SessionCommandCatalog.ui_only_entry(text)
739
739
 
740
740
  # A UI-only command: nothing is sent (with --new, no session is created
741
741
  # either). /stats points at its model-free reader and names the session;
@@ -761,7 +761,7 @@ module Samagotchi
761
761
  CLI::Exit::FAILED
762
762
  end
763
763
 
764
- def local_refusal(name, id) = SessionCommands.ui_only_refusal(name, id, runner: "chi send", remote: @access.invocation.remote)
764
+ def local_refusal(name, id) = SessionCommandCatalog.ui_only_refusal(name, id, runner: "chi send", remote: @access.invocation.remote)
765
765
 
766
766
  # --wait after a message that ran as a session command: no reply comes
767
767
  # for it. Its output shows where the session is open.
@@ -116,6 +116,7 @@ module Samagotchi
116
116
  "sessions unarchive" => SUPPORTED,
117
117
  "sessions delete" => SUPPORTED,
118
118
  "sessions delete --force" => SUPPORTED,
119
+ "sessions delete --chain" => SUPPORTED,
119
120
  "sessions prune" => LOCAL_ONLY,
120
121
  "sessions clean" => LOCAL_ONLY,
121
122
  "sessions stats" => LOCAL_ONLY,
@@ -293,7 +293,15 @@ module Samagotchi
293
293
 
294
294
  # @param force [Boolean] stop a live worker first (else refused)
295
295
  # @return [Hash] SessionManager.delete_session's
296
- def delete(id, force:) = SessionManager.delete_session(id, stop: force, **dir)
296
+ # A user's delete: SessionManager.delete_session's revive_previous: and
297
+ # refuse_continuing: (D2/D5), on unless told otherwise.
298
+ def delete(id, force:, revive_previous: true, refuse_continuing: true)
299
+ SessionManager.delete_session(id, stop: force, revive_previous: revive_previous,
300
+ refuse_continuing: refuse_continuing, **dir)
301
+ end
302
+
303
+ # Every link of the chain (SessionManager.delete_chain).
304
+ def delete_chain(id, force:) = SessionManager.delete_chain(id, stop: force, **dir)
297
305
 
298
306
  # --- context (a session's sources, or a project's: local only)
299
307
  #
@@ -316,6 +316,8 @@ module Samagotchi
316
316
 
317
317
  # Web::App::BOUND_FEATURE: POST …/participants takes an identity.
318
318
  BOUND_FEATURE = "bound_grants"
319
+ # Web::App::CHAIN_DELETE_FEATURE: DELETE …/chain.
320
+ CHAIN_DELETE_FEATURE = "chain_delete"
319
321
 
320
322
  # The header that chi web names the signed-in user in (GET
321
323
  # /api/info's proxy), nil when it has no such proxy, or is a chi
@@ -493,13 +495,33 @@ module Samagotchi
493
495
  end
494
496
 
495
497
  # @return [Hash] {id:, stopped:}
498
+ # A chi web before chain_delete answers without unarchived,
499
+ # moved_back, deleted and left_running (no revive, no undo, no D7
500
+ # there): each reads as [].
496
501
  def delete(id, force:)
497
502
  reply = request(:delete, session_path(id), query: { force: (true if force) })
498
503
  raise_refusal(reply) unless reply.status == 200
499
504
 
500
- { id: reply.json["session_id"] || id, stopped: reply.json["stopped"] == true }
505
+ { id: reply.json["session_id"] || id, stopped: reply.json["stopped"] == true,
506
+ unarchived: ids_of(reply.json["unarchived"]), moved_back: ids_of(reply.json["moved_back"]),
507
+ deleted: ids_of(reply.json["deleted"]), left_running: ids_of(reply.json["left_running"]) }
501
508
  end
502
509
 
510
+ # DELETE …/chain there (SessionManager.delete_chain's result).
511
+ # @raise [RemoteTooOld] a chi web without it (an older one would answer 404)
512
+ def delete_chain(id, force:)
513
+ require_feature!(CHAIN_DELETE_FEATURE)
514
+ reply = request(:delete, "#{session_path(id)}/chain", query: { force: (true if force) })
515
+ raise_refusal(reply) unless reply.status == 200
516
+
517
+ json = reply.json
518
+ { id: json["session_id"] || id, deleted: ids_of(json["deleted"]), left: ids_of(json["left"]),
519
+ left_running: ids_of(json["left_running"]), unarchived: ids_of(json["unarchived"]),
520
+ stopped: ids_of(json["stopped"]), cut_off: json["cut_off"] == true, refusal: json["refusal"] }
521
+ end
522
+
523
+ private def ids_of(value) = Array(value).select { |id| Session.valid_id?(id) }
524
+
503
525
  # --- context (a session's own sources: a project's are local only)
504
526
 
505
527
  # @return [ContextAdded]
@@ -761,8 +783,9 @@ module Samagotchi
761
783
  raise SessionManager::ScratchSession, sid if json["scratch"] == true
762
784
 
763
785
  raise SessionManager::OwnedByTUI, sid
764
- when "worker_running", "still_stopping", "scheduled"
765
- raise SessionManager::DeleteRefused.new(sid, reason, message: message)
786
+ when "worker_running", "still_stopping", "scheduled", "continuing", "delegate_unmovable", "chain_scheduled"
787
+ raise SessionManager::DeleteRefused.new(sid, reason || error.to_sym, message: message, ids: ids_of(json["ids"]),
788
+ schedule_id: json["schedule_id"])
766
789
  when "busy", "scratch"
767
790
  raise SessionManager::ArchiveRefused.new(sid, reason, busy_id: json["busy_id"]) if reason
768
791
  when "continued", "open_children", "folder_gone"