samagotchi 0.107.0 → 0.108.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 (58) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -1
  3. data/docs/architecture.md +3 -2
  4. data/docs/internals/engine.md +17 -6
  5. data/docs/internals/participants.md +5 -2
  6. data/docs/internals/working-set.md +2 -1
  7. data/docs/memory.md +20 -0
  8. data/docs/plugins.md +9 -2
  9. data/docs/releasing.md +11 -6
  10. data/docs/sessions.md +3 -3
  11. data/docs/sub-agent.md +1 -1
  12. data/docs/testing.md +5 -1
  13. data/lib/samagotchi/bridge/turn_accumulator.rb +3 -2
  14. data/lib/samagotchi/bridge.rb +3 -2
  15. data/lib/samagotchi/bundles/cost-cap/manifest.yml +2 -2
  16. data/lib/samagotchi/bundles/cost-cap/plugin.rb +51 -9
  17. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  18. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  19. data/lib/samagotchi/bundles/work-cap/manifest.yml +2 -2
  20. data/lib/samagotchi/bundles/work-cap/plugin.rb +50 -14
  21. data/lib/samagotchi/child_reports.rb +2 -1
  22. data/lib/samagotchi/cli/parent_wait.rb +1 -1
  23. data/lib/samagotchi/context_sources.rb +1 -6
  24. data/lib/samagotchi/continue_offer.rb +8 -6
  25. data/lib/samagotchi/engine.rb +36 -25
  26. data/lib/samagotchi/guardrail_wiring.rb +9 -6
  27. data/lib/samagotchi/idle_scheduler.rb +17 -2
  28. data/lib/samagotchi/last_turn.rb +7 -0
  29. data/lib/samagotchi/log_subscriber.rb +2 -1
  30. data/lib/samagotchi/memory_orphans.rb +74 -0
  31. data/lib/samagotchi/memory_paths.rb +4 -4
  32. data/lib/samagotchi/parent_report.rb +11 -3
  33. data/lib/samagotchi/reply_wait.rb +7 -2
  34. data/lib/samagotchi/send_command/busy.rb +5 -2
  35. data/lib/samagotchi/send_command/wait_target.rb +16 -11
  36. data/lib/samagotchi/session_inbox.rb +12 -8
  37. data/lib/samagotchi/session_metrics.rb +7 -6
  38. data/lib/samagotchi/session_participants.rb +3 -1
  39. data/lib/samagotchi/steer.rb +11 -1
  40. data/lib/samagotchi/terminal_ui/attached_loop.rb +30 -26
  41. data/lib/samagotchi/terminal_ui/formatting.rb +2 -2
  42. data/lib/samagotchi/terminal_ui/one_shot_sink.rb +5 -1
  43. data/lib/samagotchi/tools/memory.rb +16 -9
  44. data/lib/samagotchi/turn_origin.rb +68 -0
  45. data/lib/samagotchi/version.rb +1 -1
  46. data/lib/samagotchi/web/app.rb +2 -0
  47. data/lib/samagotchi/web/grants.rb +2 -1
  48. data/lib/samagotchi/web/participant_access.rb +6 -116
  49. data/lib/samagotchi/web/participant_view.rb +7 -13
  50. data/lib/samagotchi/web/participants_admin.rb +129 -0
  51. data/lib/samagotchi/web/public/participant.js +2 -2
  52. data/lib/samagotchi/web/public/participant_model.js +5 -0
  53. data/lib/samagotchi/web/public/participant_names.js +2 -2
  54. data/lib/samagotchi/web/public/participants_panel.js +2 -2
  55. data/lib/samagotchi/worker.rb +30 -25
  56. data/lib/samagotchi/worker_inbound.rb +12 -9
  57. data/lib/samagotchi/working_set.rb +3 -2
  58. metadata +4 -1
@@ -63,6 +63,7 @@ class Plugin
63
63
  @resolved = nil # {session:, settings:, meters: {meter => {cap:, step:, key:}}, unreadable: {name => value}}
64
64
  @warned = {} # meter => [session id, cap] the share warning was given for
65
65
  @unread_warned = nil # the session id the "isn't a number" notice was given for
66
+ @corrupt_warned = nil # the session id the "state file doesn't read" notice was given for
66
67
  end
67
68
 
68
69
  def register(chi)
@@ -126,6 +127,7 @@ class Plugin
126
127
  def check(ctx)
127
128
  resolved = resolve(ctx)
128
129
  unreadable(ctx, resolved)
130
+ corrupt(ctx, resolved)
129
131
  capped = resolved[:meters].select { |_meter, meter_cap| meter_cap[:cap] }
130
132
  return if capped.empty?
131
133
 
@@ -161,11 +163,26 @@ class Plugin
161
163
  return if bad.empty? || !first_time?(:@unread_warned, resolved[:session])
162
164
 
163
165
  named = bad.map { |key, value| "#{key}: #{value.inspect}" }.join(" and ")
166
+ ctx.notify("work-cap: #{named} #{bad.size == 1 ? "isn't" : "aren't"} a number or off; #{using(resolved)}",
167
+ level: :warn)
168
+ end
169
+
170
+ # Once per session: a state file that is there but doesn't read (not
171
+ # JSON, or not a mapping) holds no /workcap caps, so the settings' are
172
+ # used; said rather than a /workcap cap silently gone.
173
+ def corrupt(ctx, resolved)
174
+ path = resolved[:corrupt]
175
+ return unless path && first_time?(:@corrupt_warned, resolved[:session])
176
+
177
+ ctx.notify("work-cap: #{path} doesn't read, its /workcap caps are ignored; #{using(resolved)}", level: :warn)
178
+ end
179
+
180
+ # "using tool_calls: (400), minutes: (60)", or "no cap".
181
+ def using(resolved)
164
182
  used = resolved[:meters].values.filter_map do |meter_cap|
165
183
  "#{meter_cap[:key]}: (#{count(meter_cap[:cap])})" if meter_cap[:cap]
166
184
  end
167
- using = used.empty? ? "no cap" : "using #{used.join(", ")}"
168
- ctx.notify("work-cap: #{named} #{bad.size == 1 ? "isn't" : "aren't"} a number or off; #{using}", level: :warn)
185
+ used.empty? ? "no cap" : "using #{used.join(", ")}"
169
186
  end
170
187
 
171
188
  def at_cap(ctx, resolved, reached, usage, used)
@@ -280,29 +297,37 @@ class Plugin
280
297
  cached = @mutex.synchronize { @resolved }
281
298
  return cached if cached && cached[:session] == session && cached[:settings] == settings
282
299
 
283
- saved = state(ctx, session)
300
+ saved, corrupt = state(ctx, session)
284
301
  configured = configured(ctx)
285
302
  meters = METERS.to_h { |meter| [meter, saved[meter] || configured[:meters][meter]] }
286
- resolved = { session: session, settings: settings, meters: meters, unreadable: configured[:unreadable] }
303
+ resolved = { session: session, settings: settings, meters: meters, unreadable: configured[:unreadable],
304
+ corrupt: corrupt }
287
305
  @mutex.synchronize { @resolved = resolved }
288
306
  end
289
307
 
290
- # The state file's meters ({meter => {cap:, step:}}), {} without one.
308
+ # The state file's meters ({meter => {cap:, step:}}), {} without one,
309
+ # and the file's path when it is there but doesn't read (logged; the
310
+ # user is told by #corrupt), else nil.
291
311
  def state(ctx, session)
292
- return {} unless session
312
+ return [{}, nil] unless session
293
313
 
294
- saved = JSON.parse(File.read(state_path(ctx, session)))
295
- return {} unless saved.is_a?(Hash)
314
+ path = state_path(ctx, session)
315
+ saved = JSON.parse(File.read(path))
316
+ raise JSON::ParserError, "not a JSON object" unless saved.is_a?(Hash)
296
317
 
297
- METERS.each_with_object({}) do |meter, meters|
318
+ meters = METERS.each_with_object({}) do |meter, found|
298
319
  entry = saved[meter]
299
320
  next unless entry.is_a?(Hash) && entry.key?("cap")
300
321
 
301
322
  cap = self.class.amount(entry["cap"], meter)
302
- meters[meter] = { cap: cap, step: self.class.amount(entry["step"], meter) || cap, key: "/workcap" }
323
+ found[meter] = { cap: cap, step: self.class.amount(entry["step"], meter) || cap, key: "/workcap" }
303
324
  end
304
- rescue Errno::ENOENT, JSON::ParserError
305
- {}
325
+ [meters, nil]
326
+ rescue Errno::ENOENT
327
+ [{}, nil]
328
+ rescue JSON::ParserError => e
329
+ ctx.log.warn(:workcap_state_unreadable, path: path, error: e.message.to_s[0, 200])
330
+ [{}, path]
306
331
  end
307
332
 
308
333
  # Per meter the first of its own value, child:'s (a delegate's) and
@@ -358,21 +383,32 @@ class Plugin
358
383
  end
359
384
 
360
385
  # Write one meter's cap into the session's state file (the other kept).
386
+ # One there that doesn't read (#state) is written over: logged and said,
387
+ # never a silent replace.
361
388
  def save_meter(ctx, session, meter, data)
362
389
  path = state_path(ctx, session)
363
390
  FileUtils.mkdir_p(File.dirname(path))
364
391
  saved = begin
365
392
  JSON.parse(File.read(path))
366
- rescue Errno::ENOENT, JSON::ParserError
393
+ rescue Errno::ENOENT
367
394
  {}
395
+ rescue JSON::ParserError
396
+ nil
368
397
  end
369
- saved = {} unless saved.is_a?(Hash)
398
+ replacing = !saved.is_a?(Hash)
399
+ saved = {} if replacing
370
400
  saved[meter] = data.transform_values { |value| whole(value) }
371
401
  Samagotchi::AtomicFile.write(path, "#{JSON.generate(saved)}\n")
402
+ replaced(ctx, path) if replacing
372
403
  # Resolved again at the next use, from the file now holding the meter.
373
404
  @mutex.synchronize { @resolved = nil }
374
405
  end
375
406
 
407
+ def replaced(ctx, path)
408
+ ctx.log.warn(:workcap_state_replaced, path: path)
409
+ ctx.notify("work-cap: #{path} didn't read; replaced with the new cap", level: :warn)
410
+ end
411
+
376
412
  # 800.0 as 800 (a whole cap is saved as an Integer), 2.5 as it is.
377
413
  def whole(value) = value.is_a?(Float) && value.finite? && value == value.to_i ? value.to_i : value
378
414
 
@@ -7,6 +7,7 @@ require_relative "session"
7
7
  require_relative "session_inbox"
8
8
  require_relative "reply_wait"
9
9
  require_relative "steer"
10
+ require_relative "turn_origin"
10
11
  require_relative "log"
11
12
  require_relative "config"
12
13
  require_relative "tools/delegate_wait"
@@ -138,7 +139,7 @@ module Samagotchi
138
139
  def initialize(relay: nil, **) = super
139
140
 
140
141
  def line(mark: nil) = Steer::Line.new(text: text, source: ChildReports::SOURCE, mark: mark)
141
- def origin = { client_id: "#{ClientId::CHILD_PREFIX}#{child_id[0, 8]}" }
142
+ def origin = TurnOrigin.new(client_id: "#{ClientId::CHILD_PREFIX}#{child_id[0, 8]}")
142
143
  end
143
144
 
144
145
  # @param predecessor [String, nil] the link this session continues
@@ -96,7 +96,7 @@ module Samagotchi
96
96
  @stdout.flush
97
97
  @reported = true
98
98
  end
99
- error_line("#{command_name}: still running: #{@access.invocation.shows(id)}")
99
+ error_line("#{command_name}: still running: #{ParentReport.still_running_hint(id, report_turn_id, via: @access.invocation)}")
100
100
  Exit::INTERRUPTED
101
101
  rescue ArgumentError
102
102
  error_line("#{command_name}: the session is gone (deleted while waiting)")
@@ -359,12 +359,7 @@ module Samagotchi
359
359
  def project_location_for(project_root, state_dir: nil)
360
360
  return nil if project_root.to_s.empty?
361
361
 
362
- project_location(project_key_of(project_root), state_dir: state_dir)
363
- end
364
-
365
- # MemoryPaths.project_key for a root already resolved.
366
- def project_key_of(root)
367
- "#{File.basename(root)}_#{Digest::MD5.hexdigest(root)[0..7]}"
362
+ project_location(MemoryPaths.key_for_root(project_root), state_dir: state_dir)
368
363
  end
369
364
 
370
365
  # A session's sources: its own, then the project's it doesn't shadow
@@ -4,6 +4,7 @@ require "time"
4
4
  require_relative "last_turn"
5
5
  require_relative "log"
6
6
  require_relative "steer"
7
+ require_relative "turn_origin"
7
8
 
8
9
  module Samagotchi
9
10
  # A session worker's continue offer: what it announces when a turn runs out
@@ -71,6 +72,7 @@ module Samagotchi
71
72
 
72
73
  # A prompt (or a reminder turn) taken while a continue is offered
73
74
  # replaces the answer (D2): the offer goes, the partial turn stays.
75
+ # @param origin [TurnOrigin] the taken turn's
74
76
  def drop(origin)
75
77
  return unless awaiting?
76
78
 
@@ -78,7 +80,7 @@ module Samagotchi
78
80
  close("dropped")
79
81
  @engine.synchronize_events do
80
82
  @turn_flow.drop_offer!
81
- @engine.announce(type: :continue_resolved, decision: "dropped", client_id: origin&.dig(:client_id))
83
+ @engine.announce(type: :continue_resolved, decision: "dropped", client_id: origin.client_id)
82
84
  end
83
85
  @engine.record_activity
84
86
  end
@@ -149,7 +151,7 @@ module Samagotchi
149
151
  offer = @turn_flow.offer
150
152
  resume_from = @turn_flow.resume_from
151
153
  enqueued_id = offer_turn_id
152
- author = Steer.sender_author(@engine.session&.last_turn&.author)
154
+ author = @engine.session&.last_turn&.participant_author
153
155
  close("answered")
154
156
  if author && (reason = @participant_refused.call(author))
155
157
  @continue_steer = nil
@@ -166,7 +168,7 @@ module Samagotchi
166
168
  Log.warn(:worker, "turn_not_begun", continue: true, error: e.class.name, msg: e.message)
167
169
  return announce_offer(offer)
168
170
  end
169
- origin = { client_id: command.client_id, enqueued_id: enqueued_id, author: author }.compact
171
+ origin = TurnOrigin.new(client_id: command.client_id, enqueued_id: enqueued_id, author: author)
170
172
  @run_turn.call(nil, continue: true, origin: origin, resumed: true, resume_from: resume_from,
171
173
  max_iterations: @max_iterations.call(offer[:no_interrupt])) do |result, error|
172
174
  if error
@@ -192,7 +194,7 @@ module Samagotchi
192
194
  private
193
195
 
194
196
  def refusal_of_offer_author
195
- author = Steer.sender_author(@engine.session&.last_turn&.author)
197
+ author = @engine.session&.last_turn&.participant_author
196
198
  author && @participant_refused.call(author)
197
199
  end
198
200
 
@@ -204,11 +206,11 @@ module Samagotchi
204
206
  # participant turns go on). The question goes with the next close.
205
207
  # Called with the event log held.
206
208
  def refuse_continue(reason, command)
207
- author = @engine.session&.last_turn&.author
209
+ author = @engine.session&.last_turn&.participant_author
208
210
  enqueued_id = offer_turn_id
209
211
  @engine.announce(type: :continue_resolved, decision: "refused", reason: reason.to_s, client_id: command.client_id)
210
212
  @engine.announce(type: :hook_notice, hook: "participants", level: :warn, between_turns: true,
211
- text: format(REFUSED_NOTICE, who: author.to_s.delete_prefix("p:"), reason: REFUSED_WHY.fetch(reason.to_s, reason.to_s)))
213
+ text: format(REFUSED_NOTICE, who: Steer.participant_id(author), reason: REFUSED_WHY.fetch(reason.to_s, reason.to_s)))
212
214
  @turn_flow.abort_continue!
213
215
  session = @engine.session
214
216
  session.last_turn = LastTurn.new(outcome: NOT_CONTINUED, ended_at: Time.now.iso8601(3), enqueued_id: enqueued_id) if session
@@ -13,6 +13,7 @@ require_relative "context_note"
13
13
  require_relative "context_status"
14
14
  require_relative "steer"
15
15
  require_relative "turn_note"
16
+ require_relative "turn_origin"
16
17
  require_relative "model_profile"
17
18
  require_relative "effective_model"
18
19
  require_relative "session_setting"
@@ -57,6 +58,7 @@ require_relative "hook_routes"
57
58
  require_relative "guardrails"
58
59
  require_relative "reminder_store"
59
60
  require_relative "reminder_queue"
61
+ require_relative "memory_orphans"
60
62
  require_relative "tools/memory"
61
63
  require_relative "muted_memories"
62
64
  require_relative "used_memories"
@@ -623,7 +625,7 @@ module Samagotchi
623
625
  def side_author(kind)
624
626
  return nil unless turn_running? || kind.to_s == RECAP_SIDE_KIND
625
627
 
626
- Steer.sender_author(@guardrail_wiring.turn_author)
628
+ @guardrail_wiring.turn_author
627
629
  end
628
630
 
629
631
  RECAP_SIDE_KIND = "recap"
@@ -631,7 +633,7 @@ module Samagotchi
631
633
  # The running turn's author when a participant wrote it, else nil
632
634
  # (ctx.turn_author, the hooks' author).
633
635
  # @return [String, nil]
634
- def turn_author = turn_running? ? Steer.sender_author(@guardrail_wiring.turn_author) : nil
636
+ def turn_author = turn_running? ? @guardrail_wiring.turn_author : nil
635
637
 
636
638
  # @return [SessionMetrics] the per-session analytics collector
637
639
  attr_reader :metrics
@@ -984,7 +986,8 @@ module Samagotchi
984
986
 
985
987
  # Announce what failed to load and what plugins showed while loading,
986
988
  # once, as soon as the owner can show it (the worker's Bridge is up, the
987
- # REPL renders events): the guardrail and plugin warnings, then the
989
+ # REPL renders events): the guardrail and plugin warnings, an orphaned
990
+ # project memory folder (label: "memory", MemoryOrphans), then the
988
991
  # held notices (between_turns) and cards (in_turn: false, so late
989
992
  # joiners get them). Without this call the first turn announces them
990
993
  # (#announce_guardrail_failures).
@@ -997,6 +1000,8 @@ module Samagotchi
997
1000
  announce({ type: :guardrail_warning, message: message }) if message
998
1001
  plugins = @plugin_failures.message
999
1002
  announce({ type: :guardrail_warning, message: plugins, label: "plugins" }) if plugins
1003
+ memory = MemoryOrphans.message
1004
+ announce({ type: :guardrail_warning, message: memory, label: "memory" }) if memory
1000
1005
  @extension_load.held_events.each do |event|
1001
1006
  announce(event[:type] == :card ? event.merge(in_turn: false) : event.merge(between_turns: true))
1002
1007
  end
@@ -1448,8 +1453,8 @@ module Samagotchi
1448
1453
 
1449
1454
  # Once per Engine, on its first turn: what failed to load, so every UI
1450
1455
  # (REPL, attached TUI, web) shows it: the guardrails, then the plugins
1451
- # (label: "plugins"; the UIs say guardrails without one), then the
1452
- # notices and cards plugins showed as they loaded.
1456
+ # (label: "plugins"; the UIs say guardrails without one), an orphaned
1457
+ # project memory folder (label: "memory"), then the notices and cards plugins showed as they loaded.
1453
1458
  def announce_guardrail_failures(on_event)
1454
1459
  return if @guardrail_failures_announced
1455
1460
 
@@ -1458,6 +1463,8 @@ module Samagotchi
1458
1463
  emit_event(on_event, { type: :guardrail_warning, message: message }) if message
1459
1464
  plugins = @plugin_failures.message
1460
1465
  emit_event(on_event, { type: :guardrail_warning, message: plugins, label: "plugins" }) if plugins
1466
+ memory = MemoryOrphans.message
1467
+ emit_event(on_event, { type: :guardrail_warning, message: memory, label: "memory" }) if memory
1461
1468
  @extension_load.held_events.each { |event| emit_event(on_event, event) }
1462
1469
  end
1463
1470
  private :announce_guardrail_failures
@@ -1494,14 +1501,14 @@ module Samagotchi
1494
1501
  # @param limit [Integer, nil] the turn ran out of iterations at this
1495
1502
  # limit: "exhausted" => true, "limit" => N, so a wait with nobody to
1496
1503
  # answer the continue offer says so (ReplyWait, ParentReport "limit")
1504
+ # @param origin [TurnOrigin] the turn's (TurnOrigin::NONE for no sender)
1497
1505
  # @param event [Hash] the turn's end event (#stop_facts)
1498
1506
  def record_last_turn(session, outcome, seconds, origin, event, limit: nil)
1499
- source = ClientId.origin(origin.is_a?(Hash) ? origin[:client_id] : nil)
1500
- enqueued_id = origin.is_a?(Hash) ? origin[:enqueued_id] : nil
1507
+ enqueued_id = origin.enqueued_id
1501
1508
  session.last_turn = LastTurn.new(outcome: outcome, ended_at: Time.now.iso8601(3), seconds: seconds.round(1),
1502
- origin: source, exhausted: limit ? true : nil, limit: limit,
1509
+ origin: origin.source, exhausted: limit ? true : nil, limit: limit,
1503
1510
  enqueued_id: enqueued_id.to_s.empty? ? nil : enqueued_id.to_s,
1504
- author: Steer.sender_author(origin.is_a?(Hash) ? origin[:author] : nil),
1511
+ author: origin.participant_author,
1505
1512
  **stop_facts(event))
1506
1513
  end
1507
1514
 
@@ -1532,10 +1539,9 @@ module Samagotchi
1532
1539
  # author:, and author_name: from participants.json), {} for the owner.
1533
1540
  # The worker's drain names a participant's merged lines with it, and
1534
1541
  # its running save a participant's prompt.
1535
- # @param origin [Hash, String, nil] a turn's origin, or an author
1542
+ # @param author [String, nil] a turn's or a line's author (TurnOrigin#author)
1536
1543
  # @param session [Session, nil] the session it is for (the turn's)
1537
- def author_fields(origin, session: @session)
1538
- author = origin.is_a?(Hash) ? origin[:author] : origin
1544
+ def author_fields(author, session: @session)
1539
1545
  return {} unless Steer.participant_author?(author)
1540
1546
 
1541
1547
  Steer.author_fields(author, @participants.name_for(author, session: session))
@@ -1995,9 +2001,11 @@ module Samagotchi
1995
2001
  :settings, :id, :limit, :resumed, :resume_from) do
1996
2002
  def resumed? = resumed ? true : false
1997
2003
 
1998
- # The turn's boundary events carry the origin only when there is one,
1999
- # so payloads stay unchanged for callers that don't pass it.
2000
- def tag(event) = origin ? event.merge(origin: origin) : event
2004
+ # The turn's boundary events carry the origin only when it names a
2005
+ # sender (not TurnOrigin::NONE), so payloads stay unchanged for callers
2006
+ # that don't pass one; as its wire Hash (TurnOrigin#to_h), which the
2007
+ # Bridge and the UIs read.
2008
+ def tag(event) = origin.empty? ? event : event.merge(origin: origin.to_h)
2001
2009
 
2002
2010
  # Seconds since the turn started (the cancel note says how long it ran).
2003
2011
  def elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at
@@ -2032,11 +2040,13 @@ module Samagotchi
2032
2040
  # run it resumes started (ModelResult#run_start, kept in the offer by
2033
2041
  # TurnFlow), so it keeps that run's reasoning; nil starts cold (a
2034
2042
  # model change while the offer stood, every other turn).
2035
- # @param origin [Hash, nil] who queued the turn ({client_id:, enqueued_id:},
2036
- # and author: when someone other than the session's owner wrote it, from
2037
- # its input file; absent for the owner); when given, the turn's boundary
2038
- # events (:turn_started, :turn_completed, :turn_canceled, :turn_failed)
2039
- # carry it as `origin:`, and GuardrailWiring#begin_turn gets it
2043
+ # @param origin [TurnOrigin, Hash, nil] who queued the turn (client_id,
2044
+ # enqueued_id, and author when someone other than the session's owner
2045
+ # wrote it, from its input file; none for the owner; a Hash is read as
2046
+ # one, TurnOrigin.of; TurnOrigin::NONE, the default, names no sender
2047
+ # and so does nil or {}); when it names one, the turn's boundary events
2048
+ # (:turn_started, :turn_completed, :turn_canceled, :turn_failed) carry
2049
+ # it as `origin:` (its wire Hash), and GuardrailWiring#begin_turn gets it
2040
2050
  # @param images [Array<Hash>] the prompt's images: {path:} (a file on this
2041
2051
  # machine; in-process and attached-TUI callers only) or {file:, name:}
2042
2052
  # (already in the session's images/, e.g. a web upload). They are
@@ -2056,8 +2066,8 @@ module Samagotchi
2056
2066
  # other error (e.g. an LLM::ProviderError) emits :turn_failed and
2057
2067
  # re-raises; a provider error adds error_kind:, retryable:, host: and a
2058
2068
  # one-line summary:.
2059
- def run_turn(session, prompt, on_event: nil, max_iterations: nil, cancel_controller: nil, max_tool_output_chars: nil, pending_input: nil, continue: false, origin: nil,
2060
- images: [], id: nil, resumed: false, resume_from: nil)
2069
+ def run_turn(session, prompt, on_event: nil, max_iterations: nil, cancel_controller: nil, max_tool_output_chars: nil, pending_input: nil, continue: false,
2070
+ origin: TurnOrigin::NONE, images: [], id: nil, resumed: false, resume_from: nil)
2061
2071
  turn = begin_turn(session, prompt, on_event: on_event, cancel_controller: cancel_controller, origin: origin,
2062
2072
  continue: continue, id: id)
2063
2073
  if continue
@@ -2108,6 +2118,7 @@ module Samagotchi
2108
2118
  # the turn flag, its cancel controller and sink. The cross-thread state
2109
2119
  # is set here and cleared in #release_turn only.
2110
2120
  def begin_turn(session, prompt, on_event:, cancel_controller:, origin:, continue:, id: nil)
2121
+ origin = TurnOrigin.of(origin)
2111
2122
  # Track the active session for recap and status snapshot.
2112
2123
  @session = session
2113
2124
  # status is turn state: running now, idle again before the turn's end
@@ -2151,7 +2162,7 @@ module Samagotchi
2151
2162
  turn_started[:cut_after] = steer_cut_after
2152
2163
  # A participant's turn names them (author, author_name) for the UIs'
2153
2164
  # badge; the owner's turn_started stays as it was.
2154
- turn_started.merge!(author_fields(turn.origin, session: session))
2165
+ turn_started.merge!(author_fields(turn.origin.author, session: session))
2155
2166
  emit_event(turn.on_event, turn.tag(turn_started))
2156
2167
  raise image_error if image_error
2157
2168
 
@@ -2305,7 +2316,7 @@ module Samagotchi
2305
2316
  # system prompt invalidates cache for the entire prefix.
2306
2317
  # Not into a participant's turn: the owner's reminders are the owner's,
2307
2318
  # and would be used up there under the review boundary.
2308
- due_reminders = Steer.participant_author?(turn.origin&.dig(:author)) ? [] : @reminder_queue.inject!(turn.messages)
2319
+ due_reminders = turn.origin.participant? ? [] : @reminder_queue.inject!(turn.messages)
2309
2320
  if due_reminders.any?
2310
2321
  emit_event(turn.on_event, {
2311
2322
  type: :reminder_injected,
@@ -2314,7 +2325,7 @@ module Samagotchi
2314
2325
  end
2315
2326
 
2316
2327
  unless turn.continue
2317
- user_message = { role: "user", content: turn.prompt, turn_id: turn.id, **author_fields(turn.origin) }
2328
+ user_message = { role: "user", content: turn.prompt, turn_id: turn.id, **author_fields(turn.origin.author) }
2318
2329
  user_message[:images] = image_refs unless image_refs.empty?
2319
2330
  turn.messages << user_message
2320
2331
  session.last_prompt = turn.prompt
@@ -11,6 +11,7 @@ require_relative "version"
11
11
  require_relative "hooks"
12
12
  require_relative "edit_preview"
13
13
  require_relative "tool_activity"
14
+ require_relative "turn_origin"
14
15
 
15
16
  module Samagotchi
16
17
  # An Engine's tool guardrails: who can approve (the interface), the YAML
@@ -55,6 +56,7 @@ module Samagotchi
55
56
  @failures = Guardrails::LoadFailures.new
56
57
  @rules_mutex = Mutex.new
57
58
  @git = Guardrails::GitInfo.new
59
+ @origin = TurnOrigin::NONE
58
60
  end
59
61
 
60
62
  # Who can answer an approval: :repl, :worker or :non_interactive (the
@@ -83,17 +85,18 @@ module Samagotchi
83
85
  @protected = nil
84
86
  end
85
87
 
86
- # A turn starts: its origin (Engine#run_turn's: {client_id:,
87
- # enqueued_id:, author:}, each optional), and the git facts read afresh.
88
+ # A turn starts: its origin (Engine#run_turn's TurnOrigin; nil or a
89
+ # Hash is read as one, TurnOrigin.of), and the git facts read afresh.
88
90
  def begin_turn(origin)
89
- @origin = origin
91
+ @origin = TurnOrigin.of(origin)
90
92
  @git = Guardrails::GitInfo.new
91
93
  end
92
94
 
93
95
  # Who wrote the running turn when it isn't the session's owner (its
94
- # origin's author); nil for the owner's turns and every other origin.
96
+ # origin's participant author); nil for the owner's turns and every
97
+ # other origin.
95
98
  # @return [String, nil]
96
- def turn_author = @origin.is_a?(Hash) ? @origin[:author] : nil
99
+ def turn_author = @origin.participant_author
97
100
 
98
101
  # The gate every tool call asks first.
99
102
  # @return [Guardrails::Gate]
@@ -229,7 +232,7 @@ module Samagotchi
229
232
  # @return [Guardrails::Context]
230
233
  def context
231
234
  Guardrails::Context.new(cwd: Dir.pwd, session_id: @session_lookup.call&.id, interface: interface,
232
- origin: @origin, git: @git)
235
+ origin: @origin.wire, git: @git)
233
236
  end
234
237
 
235
238
  # Ask the user to approve a call the gate voted `ask` on, through the
@@ -63,7 +63,10 @@ module Samagotchi
63
63
  # takes) passes join: false: the thread finishes its tick and exits by
64
64
  # itself, and a later joining stop (Engine#shutdown, the worker's
65
65
  # teardown) still joins it. From the scheduler's own thread (a job's
66
- # tick) it never joins.
66
+ # tick) it never joins. A thread that died of an error #run_loop doesn't
67
+ # rescue (a SystemStackError, a job's `exit`) is logged here, not raised
68
+ # again by the join into the caller (Engine#shutdown would skip the rest
69
+ # of its teardown: plugin tasks, MCP servers).
67
70
  def stop(join: true)
68
71
  @stopped = true
69
72
  @wake << :stop
@@ -72,7 +75,7 @@ module Samagotchi
72
75
  @unjoined = join ? nil : thread
73
76
  return if thread.nil? || !join || thread == Thread.current
74
77
 
75
- thread.kill unless thread.join(STOP_JOIN_SECONDS)
78
+ thread.kill unless join_thread(thread)
76
79
  nil
77
80
  end
78
81
 
@@ -104,6 +107,18 @@ module Samagotchi
104
107
 
105
108
  private
106
109
 
110
+ # The thread joined within STOP_JOIN_SECONDS (truthy) or not (nil).
111
+ def join_thread(thread)
112
+ thread.join(STOP_JOIN_SECONDS)
113
+ rescue Exception => e # rubocop:disable Lint/RescueException -- the thread's own death, re-raised by join
114
+ # A status of nil: the thread ended with this exception. Anything else
115
+ # (an interrupt of the caller's own while it waited) is the caller's.
116
+ raise unless thread.status.nil?
117
+
118
+ Log.exception(:idle, "scheduler_died", e, echo: "[IdleScheduler] scheduler thread died: #{e.class}: #{e.message}")
119
+ thread
120
+ end
121
+
107
122
  def run_loop
108
123
  until @stopped
109
124
  tick
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "steer"
4
+
3
5
  module Samagotchi
4
6
  # How a session's last turn ended (Session#last_turn), saved as
5
7
  # session.json's "last_turn" and sent in the web's session summary.
@@ -44,6 +46,11 @@ module Samagotchi
44
46
  # The stop facts this turn has (LastTurn::STOP_FACTS), symbol keys.
45
47
  # @return [Hash{Symbol => Object}]
46
48
  def stop_facts = to_h.slice(*self.class::STOP_FACTS).compact
49
+
50
+ # The turn's author when a participant's (Steer.sender_author, as
51
+ # TurnOrigin#participant_author reads a running turn's), else nil.
52
+ # @return [String, nil]
53
+ def participant_author = Steer.sender_author(author)
47
54
  end
48
55
 
49
56
  # Why a turn stopped, for a parent agent's wait (ReplyWait::Result takes
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "log"
4
+ require_relative "turn_origin"
4
5
 
5
6
  module Samagotchi
6
7
  # The event trail: a SessionObserver subscriber (next to SessionMetrics)
@@ -181,7 +182,7 @@ module Samagotchi
181
182
  end
182
183
 
183
184
  def origin(event)
184
- client = event.dig(:origin, :client_id) if event[:origin].is_a?(Hash)
185
+ client = TurnOrigin.from(event[:origin])&.client_id
185
186
  client ? { client_id: client } : {}
186
187
  end
187
188
 
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "memory_paths"
4
+
5
+ module Samagotchi
6
+ # A project memory folder left behind by a move: memories copied to a
7
+ # machine (or a path) where the project root differs, so its key
8
+ # (MemoryPaths.project_key: basename + MD5 of the root) differs too, and
9
+ # chi finds no project memories without a word about why.
10
+ #
11
+ # Pure: one listing of the projects dir, no git subprocess. Said at
12
+ # session start (Engine#announce_load_events!, label "memory") and under a
13
+ # memory_read miss (Tools::MemoryRead); never in the system prompt.
14
+ module MemoryOrphans
15
+ # @!attribute computed [String] the folder chi reads (this project's key)
16
+ # @!attribute candidates [Array<String>] same-basename folders, other hashes
17
+ # @!attribute computed_exists [Boolean] whether +computed+ is a folder (empty of memories)
18
+ Found = Data.define(:computed, :candidates, :computed_exists)
19
+
20
+ module_function
21
+
22
+ # The orphan candidates for +cwd+'s project, or nil: only inside a git
23
+ # repository (outside one the root is cwd, and every src/ or tmp/ would
24
+ # match), and only while the computed folder holds no *.md (a
25
+ # memory_write's mkdir_p or a project-scope bundle install alone must
26
+ # not silence it).
27
+ # @return [Found, nil]
28
+ def find(env: ENV, cwd: Dir.pwd)
29
+ return nil unless MemoryPaths.in_repo?(cwd)
30
+
31
+ projects = MemoryPaths.projects_dir(env: env)
32
+ computed = MemoryPaths.project_dir(env: env, cwd: cwd)
33
+ return nil if File.directory?(computed) && Dir.children(computed).any? { |name| name.end_with?(".md") }
34
+
35
+ key = File.basename(computed)
36
+ # The root's basename, never a split of a key on "_" (a basename may hold one).
37
+ pattern = /\A#{Regexp.escape(File.basename(MemoryPaths.project_root(cwd)))}_\h{8}\z/
38
+ names = Dir.children(projects).select { |name| name != key && name.match?(pattern) }
39
+ candidates = names.sort.map { |name| File.join(projects, name) }.select { |path| File.directory?(path) }
40
+ return nil if candidates.empty?
41
+
42
+ Found.new(computed: computed, candidates: candidates, computed_exists: File.directory?(computed))
43
+ rescue SystemCallError
44
+ nil
45
+ end
46
+
47
+ # The one text for the condition (the startup warning and the
48
+ # memory_read hint both say it), or nil when there is none.
49
+ def message(env: ENV, cwd: Dir.pwd)
50
+ found = find(env: env, cwd: cwd)
51
+ found && text(found)
52
+ end
53
+
54
+ def text(found)
55
+ computed = found.computed
56
+ lead = "no project memories in #{computed}"
57
+ if found.candidates.size == 1
58
+ candidate = found.candidates.first
59
+ fix = if found.computed_exists
60
+ "move its files into #{computed} (e.g. `mv #{candidate}/* #{computed}/`)"
61
+ else
62
+ "`mv #{candidate} #{computed}`"
63
+ end
64
+ "#{lead}, but #{candidate} has the same project name with another path's hash (memories moved from " \
65
+ "another machine or path?). A name match can't prove it's this project; if it is, #{fix}."
66
+ else
67
+ fix = found.computed_exists ? "move its files into #{computed}" : "`mv <that folder> #{computed}`"
68
+ "#{lead}, but these have the same project name with another path's hash (memories moved from another " \
69
+ "machine or path?): #{found.candidates.join(", ")}. A name match can't prove one is this project; if one " \
70
+ "is, #{fix}."
71
+ end
72
+ end
73
+ end
74
+ end
@@ -23,10 +23,10 @@ module Samagotchi
23
23
  end
24
24
 
25
25
  # One folder per project root: basename + 8 hex chars of MD5(full root path).
26
- def project_key(cwd = Dir.pwd)
27
- root = project_root(cwd)
28
- "#{File.basename(root)}_#{Digest::MD5.hexdigest(root)[0..7]}"
29
- end
26
+ def project_key(cwd = Dir.pwd) = key_for_root(project_root(cwd))
27
+
28
+ # #project_key for a root already resolved (a session's project_root).
29
+ def key_for_root(root) = "#{File.basename(root)}_#{Digest::MD5.hexdigest(root)[0..7]}"
30
30
 
31
31
  # The repository's common git directory identifies the project; every linked
32
32
  # worktree shares it. Returns the checkout holding it when it is named .git,
@@ -335,13 +335,21 @@ module Samagotchi
335
335
  turn = turn_id || result.turn_id
336
336
  turn.to_s.empty? ? WAITING_FOR_OWNER : "#{WAITING_FOR_OWNER}: #{via.command("send --wait --turn #{turn} #{session_id}")}"
337
337
  else
338
- turn = turn_id || result.turn_id
339
- wait_again = via.command("send --wait --turn #{turn} #{session_id}") unless turn.to_s.empty?
340
- hint = wait_again || shows
338
+ hint = still_running_hint(session_id, turn_id || result.turn_id, via: via)
341
339
  timeout ? "still running after #{format("%g", timeout)} s: #{hint}" : "still running: #{hint}"
342
340
  end
343
341
  end
344
342
 
343
+ # What a wait that left the turn running (a --timeout, a Ctrl-C) offers
344
+ # next: the wait for that turn when its id is known, else the wait for
345
+ # the session's running turn, with the attach that shows it.
346
+ # @param turn [String, nil] the waited turn's id
347
+ def still_running_hint(session_id, turn, via: ChiInvocation::HERE)
348
+ return via.command("send --wait --turn #{turn} #{session_id}") unless turn.to_s.empty?
349
+
350
+ "#{via.command("send --wait #{session_id}")} waits again; #{via.shows(session_id)} shows it"
351
+ end
352
+
345
353
  # The whole question for stderr: header, text, numbered options, what
346
354
  # else it takes, and the commands that answer it.
347
355
  # @return [String] lines, newline-terminated