samagotchi 0.139.1 → 0.141.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 (65) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +56 -1
  3. data/README.md +2 -1
  4. data/docs/architecture.md +8 -6
  5. data/docs/cli.md +3 -1
  6. data/docs/configuration.md +33 -1
  7. data/docs/context.md +249 -46
  8. data/docs/guardrails.md +11 -0
  9. data/docs/internals/engine.md +7 -1
  10. data/docs/internals/prompt-caching.md +10 -1
  11. data/docs/internals/remote-sessions.md +4 -1
  12. data/docs/plugins.md +75 -18
  13. data/docs/sessions.md +3 -2
  14. data/lib/samagotchi/bridge/turn_accumulator.rb +4 -1
  15. data/lib/samagotchi/bundles/claude-peer/manifest.yml +2 -2
  16. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +14 -0
  17. data/lib/samagotchi/bundles/codex-peer/manifest.yml +2 -2
  18. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +15 -1
  19. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  20. data/lib/samagotchi/bundles/github-pr/manifest.yml +4 -4
  21. data/lib/samagotchi/bundles/github-pr/plugin.rb +72 -176
  22. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  23. data/lib/samagotchi/config.rb +8 -0
  24. data/lib/samagotchi/context_candidate_choice.rb +154 -0
  25. data/lib/samagotchi/context_candidates.rb +259 -0
  26. data/lib/samagotchi/context_candidates_log.rb +90 -0
  27. data/lib/samagotchi/context_command.rb +65 -17
  28. data/lib/samagotchi/context_judge.rb +194 -0
  29. data/lib/samagotchi/context_move.rb +31 -0
  30. data/lib/samagotchi/context_report_command.rb +161 -0
  31. data/lib/samagotchi/context_sources.rb +311 -29
  32. data/lib/samagotchi/engine.rb +189 -32
  33. data/lib/samagotchi/owner_prompt.rb +39 -0
  34. data/lib/samagotchi/plugin/api.rb +1 -0
  35. data/lib/samagotchi/plugin/attached_context.rb +105 -13
  36. data/lib/samagotchi/plugin/context.rb +12 -1
  37. data/lib/samagotchi/plugin/peer.rb +53 -0
  38. data/lib/samagotchi/plugin/sessions.rb +9 -2
  39. data/lib/samagotchi/prompt_warmup.rb +9 -1
  40. data/lib/samagotchi/send_command.rb +3 -1
  41. data/lib/samagotchi/session.rb +4 -0
  42. data/lib/samagotchi/session_access/contract.rb +4 -0
  43. data/lib/samagotchi/session_access/local.rb +34 -3
  44. data/lib/samagotchi/session_access/remote.rb +33 -8
  45. data/lib/samagotchi/session_access.rb +31 -6
  46. data/lib/samagotchi/session_commands.rb +28 -5
  47. data/lib/samagotchi/session_continue.rb +9 -2
  48. data/lib/samagotchi/side_judgments.rb +84 -0
  49. data/lib/samagotchi/terminal_ui.rb +15 -0
  50. data/lib/samagotchi/testing/boundary.rb +5 -1
  51. data/lib/samagotchi/testing/host.rb +4 -1
  52. data/lib/samagotchi/toolkit_report_command.rb +2 -1
  53. data/lib/samagotchi/toolkit_suggest.rb +3 -18
  54. data/lib/samagotchi/version.rb +1 -1
  55. data/lib/samagotchi/web/app.rb +24 -11
  56. data/lib/samagotchi/web/auto_update.rb +8 -1
  57. data/lib/samagotchi/web/public/app.js +8 -2
  58. data/lib/samagotchi/web/public/chains.js +10 -2
  59. data/lib/samagotchi/web/public/update_notice.js +21 -8
  60. data/lib/samagotchi/web/session_access_routes.rb +8 -3
  61. data/lib/samagotchi/web/session_create.rb +1 -0
  62. data/lib/samagotchi/web/session_hub.rb +5 -2
  63. data/lib/samagotchi/web/update_check.rb +14 -8
  64. data/lib/samagotchi/worker.rb +5 -0
  65. metadata +9 -1
@@ -7,6 +7,7 @@ require_relative "../worker_link"
7
7
  require_relative "../bridge/turn_accumulator"
8
8
  require_relative "../tools/delegate"
9
9
  require_relative "../children_status"
10
+ require_relative "../context_move"
10
11
  require_relative "../review_start"
11
12
  require_relative "../model_profile"
12
13
 
@@ -42,7 +43,8 @@ module Samagotchi
42
43
  # runs it as its first turn, and counts against session.max_children.
43
44
  # It keeps this session's own setup (SessionSetup: its llm_context values).
44
45
  # Each image a message names is copied into the child, or dropped with
45
- # a note in its message when its file is gone.
46
+ # a note in its message when its file is gone. This session's movable
47
+ # attached context goes too (ContextMove), with a note naming it.
46
48
  # @param messages [Array<Hash>] the child's conversation to start with
47
49
  # @param title [String, nil] what the lists show for it (the prompt, or
48
50
  # the first user message, by default)
@@ -60,11 +62,16 @@ module Samagotchi
60
62
  prompt = prompt.to_s.strip.empty? ? nil : prompt.to_s
61
63
  check_children(parent_id, state_dir) if prompt
62
64
 
65
+ # The fork takes this session's movable attached context, its
66
+ # subscriptions as its seed last had them.
67
+ before_spawn = lambda do |forked|
68
+ ContextMove.call(from: parent_id, to: forked.id, mode: :fork, seed: forked.messages, state_dir: state_dir)
69
+ end
63
70
  child = SessionManager.spawn_session(
64
71
  prompt: prompt, working_directory: @host.cwd.call || Dir.pwd, model_name: @host.model_name&.call,
65
72
  parent_id: parent_id, messages: Array(messages).map { |message| unfrozen(message) }, preview: title,
66
73
  images_from: Session.session_dir(parent_id, state_dir: state_dir), state_dir: state_dir,
67
- setup: @host.setup&.call || SessionSetup.new
74
+ setup: @host.setup&.call || SessionSetup.new, before_spawn: before_spawn
68
75
  )
69
76
  child.id
70
77
  rescue *REFUSED => e
@@ -38,6 +38,10 @@ module Samagotchi
38
38
  DECIDE_TIMEOUT = 3
39
39
  # Seconds #stop waits for a killed warm-up's thread to end.
40
40
  STOP_JOIN_SECONDS = 1
41
+ # Seconds a warm-up waits for the side asks sent to the same server
42
+ # before it (#start's +after+: the candidate judge's, which evict the
43
+ # cached prefix the warm-up is there to restore).
44
+ AFTER_SECONDS = 5
41
45
 
42
46
  # Whether cache.warmup allows a warm-up (auto, the default; off, false,
43
47
  # no or 0 turn it off; on/true/1 (YAML's unquoted on) are auto; anything
@@ -67,8 +71,11 @@ module Samagotchi
67
71
  # Start a warm-up of +prompt+ on +client+ in its own thread.
68
72
  # @param slot [Integer, nil] the last request's slot (nil: unpinned, and
69
73
  # nothing to pin the next request to)
74
+ # @param after [Thread, nil] asks to the same server that go first: the
75
+ # warm-up waits for them (AFTER_SECONDS at most), so it re-warms what
76
+ # they evicted
70
77
  # @return [Thread, nil] nil once #stop ran
71
- def start(client:, prompt:, model:, slot:, images: [])
78
+ def start(client:, prompt:, model:, slot:, images: [], after: nil)
72
79
  return nil if @mutex.synchronize { @stopped }
73
80
 
74
81
  # Whether the warm-up went to its slot (true) or was skipped: the
@@ -76,6 +83,7 @@ module Samagotchi
76
83
  sent = Queue.new
77
84
  thread = Thread.new do
78
85
  Thread.current.report_on_exception = false
86
+ after&.join(AFTER_SECONDS)
79
87
  busy = slot.is_a?(Integer) && client.slot_status(slot, model: model) == :busy
80
88
  sent << !busy
81
89
  next skip(slot) if busy
@@ -571,7 +571,9 @@ module Samagotchi
571
571
  return "" unless session.continues
572
572
 
573
573
  moved = Array(session.moved_children).size
574
- " (continues #{session.continues[0, 8]}#{"; #{moved} delegate#{"s" if moved != 1} moved" if moved.positive?})"
574
+ context = session.moved_context&.words
575
+ " (continues #{session.continues[0, 8]}#{"; #{moved} delegate#{"s" if moved != 1} moved" if moved.positive?}" \
576
+ "#{"; #{context}" if context})"
575
577
  end
576
578
 
577
579
  # One existing session, then its next reply. The cursor and baseline
@@ -347,6 +347,10 @@ module Samagotchi
347
347
  # SessionManager.continue_session sets it); not saved.
348
348
  attr_accessor :moved_children
349
349
 
350
+ # The attached context a continue took to this new link
351
+ # (ContextSources::Moved; SessionContinue sets it); not saved.
352
+ attr_accessor :moved_context
353
+
350
354
  # The text web `continue →` prefills in this new link
351
355
  # (SessionChain.opener_for; SessionManager.continue_session sets it); not
352
356
  # saved.
@@ -78,6 +78,8 @@ module Samagotchi
78
78
  "context add --every" => SUPPORTED,
79
79
  "context add --why" => SUPPORTED,
80
80
  "context add --hint" => SUPPORTED,
81
+ "context add --movable" => SUPPORTED,
82
+ "context add --no-movable" => SUPPORTED,
81
83
  "context add --project" => LOCAL_ONLY,
82
84
  "context push" => SUPPORTED,
83
85
  "context push --message" => SUPPORTED,
@@ -93,6 +95,8 @@ module Samagotchi
93
95
  "context refresh" => LOCAL_ONLY,
94
96
  "context mute" => LOCAL_ONLY,
95
97
  "context unmute" => LOCAL_ONLY,
98
+ # This machine's candidates log (ContextReportCommand).
99
+ "context report" => LOCAL_ONLY,
96
100
 
97
101
  "sessions" => SUPPORTED,
98
102
  "sessions list" => SUPPORTED,
@@ -10,7 +10,10 @@ require_relative "../owner_lock"
10
10
  require_relative "../parent_report"
11
11
  require_relative "../note_delivery"
12
12
  require_relative "../image_store"
13
+ require_relative "../context_candidates"
13
14
  require_relative "../context_sources"
15
+ require_relative "../archive_store"
16
+ require_relative "../session_chain"
14
17
  require_relative "../send_command/busy"
15
18
  require_relative "../chi_invocation"
16
19
  require_relative "../worker_sidecar"
@@ -284,17 +287,26 @@ module Samagotchi
284
287
  # project's when session_id is nil).
285
288
 
286
289
  # Attaches +source+ to the target's own sources.
290
+ # @return [ContextAdded]
287
291
  def context_add(target, source)
288
292
  location = context_location(target)
289
293
  location.add(source.with(scope: location.scope))
290
- nil
294
+ ContextAdded.new(name: source.name)
291
295
  end
292
296
 
293
- # New text for the target's --push source +name+.
297
+ # New text for the target's --push source +name+. Refused, nothing
298
+ # written, when the session was continued (its writer holds a stale
299
+ # id): a source of its own, or none of the name. A project's source
300
+ # takes it (the next link sees it too).
294
301
  # @param fetched [ContextSources::Fetched]
295
302
  # @return [ContextPush]
296
303
  def context_push(target, name, fetched)
297
- attached = context_attached(target, name) or return ContextPush.new(status: :missing)
304
+ attached = context_attached(target, name)
305
+ if !target.project? && (attached.nil? || attached.location.session?) &&
306
+ (next_id = continued_as(target.session_id))
307
+ return ContextPush.new(status: :continued, next_id: next_id)
308
+ end
309
+ return ContextPush.new(status: :missing) unless attached
298
310
  return ContextPush.new(status: :not_push) unless attached.source.push?
299
311
 
300
312
  before, written = attached.location.locked(name) do
@@ -322,6 +334,15 @@ module Samagotchi
322
334
  end
323
335
  end
324
336
 
337
+ # A session's candidates with their status; none for a project.
338
+ # @return [Array<ContextCandidate>]
339
+ def context_candidates(target)
340
+ return [] if target.project?
341
+
342
+ ContextCandidates.with_status(target.session_id, project_root: target.project_root, state_dir: @state_dir)
343
+ .map { |candidate, status| ContextCandidate.new(candidate: candidate, status: status) }
344
+ end
345
+
325
346
  # The source +name+ as the target sees it, with its snapshot.
326
347
  # @return [ContextEntry, nil]
327
348
  def context_entry(target, name)
@@ -481,6 +502,16 @@ module Samagotchi
481
502
  end
482
503
 
483
504
  def dir = @state_dir ? { state_dir: @state_dir } : {}
505
+
506
+ # The session that continues +id+, or nil. The archive check first: a
507
+ # continued link is always archived, and SessionChain.next_of loads
508
+ # every session.
509
+ def continued_as(id)
510
+ return nil unless ArchiveStore.archived?(session_dir(id))
511
+
512
+ SessionChain.next_of(id, state_dir: state_dir!)
513
+ end
514
+
484
515
  def state_dir! = @state_dir || Session.default_state_dir
485
516
  def session_dir(id) = Session.session_dir(id, state_dir: state_dir!)
486
517
 
@@ -181,7 +181,8 @@ module Samagotchi
181
181
  json = reply.json
182
182
  Created.new(id: json.fetch("id"), model_warning: json["model_warning"], continues: json["continues"],
183
183
  moved_children: json["moved"] || [], parent_answers_warning: json["parent_answers_warning"],
184
- first_turn_id: json["first_turn_id"])
184
+ first_turn_id: json["first_turn_id"],
185
+ moved_context: ContextSources::Moved.from_h(json["moved_context"]))
185
186
  end
186
187
 
187
188
  # Whether a just-created session's worker came up within +timeout+
@@ -458,21 +459,23 @@ module Samagotchi
458
459
 
459
460
  # --- context (a session's own sources: a project's are local only)
460
461
 
462
+ # @return [ContextAdded]
461
463
  # @raise [ContextSources::Invalid] refused (a name taken, a bad one)
462
464
  def context_add(target, source)
463
- body = { name: source.name, why: source.why, hint: source.hint, added_by: source.added_by }
465
+ body = { name: source.name, why: source.why, hint: source.hint, added_by: source.added_by, movable: source.movable }
464
466
  source.push? ? body[:push] = true : body.merge!(cmd: source.cmd, every: source.every_seconds)
465
- context_added(request(:post, "#{session_path(target.session_id)}/context", body: body.compact))
466
- nil
467
+ reply = request(:post, "#{session_path(target.session_id)}/context", body: body.compact)
468
+ context_added(reply)
469
+ ContextAdded.new(name: source.name, movable_dropped: movable_dropped?(reply, source.movable))
467
470
  end
468
471
 
469
472
  # A URL through the remote's installed bundles' providers (chi web's
470
473
  # {url} body: the page's own).
471
- # @return [String] the source's name
474
+ # @return [ContextAdded] the source's name
472
475
  # @raise [ContextProviders::Invalid] no bundle there resolves it
473
- def context_add_url(target, url, why:, hint:, added_by:)
476
+ def context_add_url(target, url, why:, hint:, added_by:, movable: nil)
474
477
  reply = request(:post, "#{session_path(target.session_id)}/context",
475
- body: { url: url, why: why, hint: hint, added_by: added_by }.compact)
478
+ body: { url: url, why: why, hint: hint, added_by: added_by, movable: movable }.compact)
476
479
  if reply.status == 422 && no_provider?(reply)
477
480
  require_relative "../context_providers"
478
481
  detail = "no installed bundle on #{name} resolves #{url} (chi bundle install github-pr there for GitHub PRs)"
@@ -482,9 +485,13 @@ module Samagotchi
482
485
  raise ContextProviders::Invalid, "#{reply.json["detail"]} (on #{name})"
483
486
  end
484
487
  context_added(reply)
485
- reply.json.fetch("name")
488
+ ContextAdded.new(name: reply.json.fetch("name"), movable_dropped: movable_dropped?(reply, movable))
486
489
  end
487
490
 
491
+ # A movable flag sent that the 201 doesn't echo: an older chi web
492
+ # dropped it.
493
+ def movable_dropped?(reply, movable) = !movable.nil? && !reply.json.key?("movable")
494
+
488
495
  # @param fetched [ContextSources::Fetched]
489
496
  # @return [ContextPush]
490
497
  def context_push(target, name, fetched)
@@ -498,6 +505,10 @@ module Samagotchi
498
505
 
499
506
  raise_refusal(reply)
500
507
  when 409 then ContextPush.new(status: :not_push)
508
+ when 410
509
+ raise_refusal(reply) unless reply.error == "context_continued"
510
+
511
+ ContextPush.new(status: :continued, next_id: reply.json["next_id"].to_s)
501
512
  when 400 then raise ContextSources::Invalid, reply.json["detail"].to_s
502
513
  else raise_refusal(reply)
503
514
  end
@@ -511,6 +522,20 @@ module Samagotchi
511
522
  Array(reply.json["sources"]).map { |row| context_entry_of(row) }
512
523
  end
513
524
 
525
+ # The session's candidates (chi web's list, ?full=1); none from a
526
+ # chi web before them.
527
+ # @return [Array<ContextCandidate>]
528
+ def context_candidates(target)
529
+ reply = request(:get, "#{session_path(target.session_id)}/context", query: { full: 1 })
530
+ raise_refusal(reply) unless reply.status == 200
531
+
532
+ Array(reply.json["candidates"]).filter_map do |row|
533
+ next unless row.is_a?(Hash) && row["name"].is_a?(String)
534
+
535
+ ContextCandidate.new(candidate: ContextSources::Candidate.from_h(row["name"], row), status: row["status"].to_s)
536
+ end
537
+ end
538
+
514
539
  # @return [ContextEntry, nil]
515
540
  def context_entry(target, name)
516
541
  ContextSources.check_name!(name)
@@ -173,9 +173,12 @@ module Samagotchi
173
173
  # over, the server's word on a --parent-answers looser than its
174
174
  # config.yml's (capped), and the id the prompt it started with gets for
175
175
  # its first turn (nil for one created idle).
176
- Created = Data.define(:id, :model_warning, :continues, :moved_children, :parent_answers_warning, :first_turn_id) do
176
+ # +moved_context+: the attached context a continue took
177
+ # (ContextSources::Moved; nil from an older chi web).
178
+ Created = Data.define(:id, :model_warning, :continues, :moved_children, :parent_answers_warning, :first_turn_id,
179
+ :moved_context) do
177
180
  def initialize(id:, model_warning: nil, continues: nil, moved_children: [], parent_answers_warning: nil,
178
- first_turn_id: nil) = super
181
+ first_turn_id: nil, moved_context: nil) = super
179
182
  end
180
183
 
181
184
  # A session's worker as an attach finds it (Local#worker, chi web's GET
@@ -250,16 +253,38 @@ module Samagotchi
250
253
  def initialize(source:, snapshot:, muted: nil, shadowed: nil, unread: nil) = super
251
254
  end
252
255
 
256
+ # A session's candidate source (ContextSources::Candidate) and its
257
+ # derived status (ContextCandidates.status): "proposed", "attached" or
258
+ # "declined".
259
+ ContextCandidate = Data.define(:candidate, :status)
260
+
261
+ # chi context add's outcome: the source's +name+, and
262
+ # +movable_dropped+ when a movable flag was given and the remote's chi
263
+ # web didn't keep it (its answer has no movable: older than the flag).
264
+ ContextAdded = Data.define(:name, :movable_dropped) do
265
+ def initialize(name:, movable_dropped: false) = super
266
+ end
267
+
253
268
  # chi context push's outcome: :pushed (+before+ the revision it had,
254
- # +revision+ the new one), :missing (no such source) or :not_push (a
255
- # command source, whose text is its command's).
256
- ContextPush = Data.define(:status, :before, :revision) do
257
- def initialize(status:, before: nil, revision: nil) = super
269
+ # +revision+ the new one), :missing (no such source), :not_push (a
270
+ # command source, whose text is its command's) or :continued (the
271
+ # session was continued, as +next_id+: nothing was written).
272
+ ContextPush = Data.define(:status, :before, :revision, :next_id) do
273
+ def initialize(status:, before: nil, revision: nil, next_id: nil) = super
258
274
 
259
275
  # Why a push to +name+ was refused as :not_push: a command source's
260
276
  # text is its command's, and a push between two fetches would read
261
277
  # as a change and then vanish.
262
278
  def self.not_push_message(name) = "#{name} runs a command, which writes its text: push goes to a --push source"
279
+
280
+ # Why a push to +name+ in session +id+ was refused as :continued: its
281
+ # writer holds the old id, and nothing reads a continued session.
282
+ # Generic (the CLI and chi web load no plugins): a peer's skill owns
283
+ # its re-pair.
284
+ def self.continued_message(name, id, next_id)
285
+ "#{id.to_s[0, 8]} was continued as #{next_id}: #{name} stays with the session it was attached to; " \
286
+ "attach it to #{next_id} (or pair again with #{next_id}) and push there"
287
+ end
263
288
  end
264
289
  end
265
290
  end
@@ -8,6 +8,8 @@ require_relative "turn_flow"
8
8
  require_relative "cache_confirm"
9
9
  require_relative "tools/execute"
10
10
  require_relative "tools/builtins"
11
+ require_relative "context_candidate_choice"
12
+ require_relative "context_candidates"
11
13
  require_relative "tools/context_read"
12
14
  require_relative "tools/peers"
13
15
  require_relative "commands/registry"
@@ -98,10 +100,12 @@ module Samagotchi
98
100
  mid_turn: show_mid_turn(GUARDRAILS_COMMAND)) do |text|
99
101
  guardrails(text.delete_prefix(GUARDRAILS_COMMAND).strip)
100
102
  end
101
- # It only reads the store: mid-turn too.
102
- registry.register(CONTEXT_COMMAND, "list the attached context (chi context)", anytime: true,
103
- match: ->(text) { text.casecmp?(CONTEXT_COMMAND) }) do |_text|
104
- reply(context_listing)
103
+ # The list only reads the store; attach and decline only write it (the
104
+ # note waits for the next between-turn delivery): mid-turn too.
105
+ registry.register(CONTEXT_COMMAND, "list the attached context and its candidates (chi context); attach NAME, " \
106
+ "decline NAME: a candidate", anytime: true,
107
+ match: ->(text) { text.match?(%r{\A/context(?:\s+.*)?\z}i) }) do |text|
108
+ context_command(text.strip.sub(%r{\A/context}i, "").strip)
105
109
  end
106
110
  registry.register(MODEL_COMMAND, "show or switch the model", mid_turn: show_mid_turn(MODEL_COMMAND),
107
111
  match: ->(text) { text.match?(%r{\A/model(?:\s+.*)?\z}) }) { |text| model(text) }
@@ -428,13 +432,32 @@ module Samagotchi
428
432
 
429
433
  # /guardrails: the rules (by source), what failed to load, the stored
430
434
  # approvals, numbered; /guardrails revoke N removes approval N.
435
+ # /context, /context attach NAME, /context decline NAME
436
+ # (ContextCandidateChoice.choose: the owner's own; a participant can't
437
+ # send a / line, and a review session refuses them).
438
+ def context_command(args)
439
+ return reply(context_listing) if args.empty?
440
+
441
+ action, name, extra = args.split(/\s+/, 3)
442
+ action = action.downcase.to_sym
443
+ unless %i[attach decline].include?(action) && name && extra.nil?
444
+ return reply(ContextCandidateChoice::USAGE, status: :error)
445
+ end
446
+
447
+ status, output = ContextCandidateChoice.choose(action, name, session: @engine.session, state_dir: @engine.peer_state_dir,
448
+ show_card: ->(**card) { @engine.show_card(**card) })
449
+ reply(output, status: status)
450
+ end
451
+
431
452
  # /context: what context_read without a name gives the model.
432
453
  def context_listing
433
454
  session = @engine.session
434
455
  return "no session yet" unless session
435
456
 
436
457
  peers = Tools::Peers.new(session_id: session.id, cwd: session.working_directory, state_dir: @engine.peer_state_dir)
437
- Tools::ContextRead.call("", peers: peers)
458
+ listing = Tools::ContextRead.call("", peers: peers)
459
+ candidates = ContextCandidates.listing(session.id, project_root: session.project_root, state_dir: @engine.peer_state_dir)
460
+ candidates ? "#{listing}\n\n#{candidates}" : listing
438
461
  end
439
462
 
440
463
  def guardrails(args)
@@ -6,6 +6,7 @@ require_relative "session_setup"
6
6
  require_relative "session_inbox"
7
7
  require_relative "session_chain"
8
8
  require_relative "child_move"
9
+ require_relative "context_move"
9
10
  require_relative "archive_store"
10
11
  require_relative "recap_store"
11
12
  require_relative "bridge_client"
@@ -76,7 +77,8 @@ module Samagotchi
76
77
  # running, a prompt queued or the step-limit question refuse; an idle
77
78
  # worker is stopped), so a refusal starts nothing. Its open delegates
78
79
  # (running, waiting, live, an unreported reply, at any depth below them)
79
- # move to the new link instead (ChildMove): their reports reach it.
80
+ # move to the new link instead (ChildMove): their reports reach it. So
81
+ # does its movable attached context (ContextMove).
80
82
  # Before that its live worker is asked for a recap and given up to
81
83
  # +recap_wait+ seconds to write it.
82
84
  # One continue of a session at a time (a lock in its folder): a double
@@ -87,7 +89,8 @@ module Samagotchi
87
89
  # @param preview [String, nil] what the lists show before the first turn;
88
90
  # by default the prompt, else the previous link's preview
89
91
  # @return [Session] the new link (#model_warning as spawn_session's,
90
- # #moved_children: the delegates it took over, #opener:
92
+ # #moved_children: the delegates it took over, #moved_context: the
93
+ # attached context it took (ContextMove), #opener:
91
94
  # SessionChain.opener_for the previous link)
92
95
  # @raise [ArgumentError] no such session (Session::AmbiguousId for a prefix of several)
93
96
  # @raise [Refused] continued already, delegates open that can't
@@ -199,9 +202,12 @@ module Samagotchi
199
202
  recap = RecapStore.read(Session.session_dir(previous.id, state_dir: state_dir))
200
203
  start = prompt.to_s.strip.empty? ? nil : prompt
201
204
  preview = previous.first_preview if preview.to_s.strip.empty? && start.nil?
205
+ moved_context = nil
202
206
  before_spawn = lambda do |link|
203
207
  ChildMove.mark_starting(link.id, state_dir: state_dir)
204
208
  ChildMove.apply(move, from: previous.id, to: link.id, state_dir: state_dir)
209
+ # Its movable context too, with a note saying what moved and stayed.
210
+ moved_context = ContextMove.call(from: previous.id, to: link.id, mode: :continue, state_dir: state_dir)
205
211
  end
206
212
  link = SessionManager.spawn_session(
207
213
  prompt: start, preview: preview, title: previous.title, working_directory: previous.working_directory,
@@ -210,6 +216,7 @@ module Samagotchi
210
216
  note_source: SessionChain::NOTE_SOURCE, state_dir: state_dir, before_spawn: before_spawn
211
217
  )
212
218
  link.moved_children = move
219
+ link.moved_context = moved_context
213
220
  link.opener = SessionChain.opener_for(previous)
214
221
  # The fallback's warning first: spawn_session set its own.
215
222
  warnings = [choice.warning, link.model_warning].compact
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "llm/errors"
4
+ require_relative "log"
5
+ require_relative "system_one/log"
6
+
7
+ module Samagotchi
8
+ # The Engine's System 1 side judgments: a question about the session
9
+ # asked off the turn thread, whose answer is logged (and, for some
10
+ # kinds, joined by the turn: ToolkitSuggest::Pending). One per kind is in
11
+ # flight at a time; an ask that raises is one warn, never the turn's
12
+ # failure; shutdown waits a short while for the asks still running.
13
+ #
14
+ # The caller prepares the ask's snapshot on its own thread: the block
15
+ # sees only what it closes over.
16
+ class SideJudgments
17
+ def initialize
18
+ @threads = {}
19
+ @mutex = Mutex.new
20
+ end
21
+
22
+ # Whether +kind+'s last ask still runs.
23
+ def in_flight?(kind)
24
+ @mutex.synchronize { @threads[kind.to_sym]&.alive? || false }
25
+ end
26
+
27
+ # +kind+'s last ask's thread (specs join it), nil before the first.
28
+ # @return [Thread, nil]
29
+ def thread(kind) = @mutex.synchronize { @threads[kind.to_sym] }
30
+
31
+ # Run the block on its own thread as +kind+'s ask. A cancelled request
32
+ # (LLM::RequestCancelled) is no answer; any other StandardError goes
33
+ # to +warn+ (error) and is no answer. +finish+ (result) is called on
34
+ # the ask's thread whatever happened, with the block's value or nil.
35
+ # @return [Thread, nil] nil (nothing started) while +kind+'s last ask
36
+ # still runs: the caller checks #in_flight? first to say so
37
+ def start(kind, warn:, finish: nil, &block)
38
+ @mutex.synchronize do
39
+ return nil if @threads[kind.to_sym]&.alive?
40
+
41
+ @threads[kind.to_sym] = Thread.new { run(warn, finish, &block) }
42
+ end
43
+ end
44
+
45
+ # Wait for every running ask, up to +seconds+ in all.
46
+ def join(seconds)
47
+ threads = @mutex.synchronize { @threads.values }
48
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
49
+ threads.each do |thread|
50
+ next if thread == Thread.current
51
+
52
+ thread.join([deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max)
53
+ end
54
+ self
55
+ end
56
+
57
+ # A side judgment's append-only JSONL log (SystemOne::Log: 0600, one
58
+ # line under an exclusive flock): a failed write is one warn under
59
+ # +tag+ as +event+, never a raise.
60
+ # @return [SystemOne::Log]
61
+ def self.log(path, tag:, event:)
62
+ SystemOne::Log.new(dir: File.dirname(path), file: File.basename(path),
63
+ warn: lambda { |reason|
64
+ Samagotchi::Log.warn(tag, event, echo: "[samagotchi:#{tag}] #{reason}")
65
+ })
66
+ end
67
+
68
+ private
69
+
70
+ def run(warn, finish)
71
+ result = nil
72
+ begin
73
+ result = yield
74
+ rescue LLM::RequestCancelled
75
+ result = nil
76
+ rescue StandardError => e
77
+ result = nil
78
+ warn.call(e)
79
+ ensure
80
+ finish&.call(result)
81
+ end
82
+ end
83
+ end
84
+ end
@@ -11,6 +11,7 @@ require_relative "model_profile"
11
11
  require_relative "turn_note"
12
12
  require_relative "turn_checkpoint"
13
13
  require_relative "config"
14
+ require_relative "context_candidates"
14
15
  require_relative "context_note"
15
16
  require_relative "cancellation_controller"
16
17
  require_relative "llm/errors"
@@ -339,6 +340,7 @@ module Samagotchi
339
340
  # Retry lines and hook notices on stderr; stdout gets the answer below.
340
341
  sink = OneShotSink.new
341
342
  save_before_first_turn(session)
343
+ attach_mentioned_context(session, one_shot_prompt)
342
344
  max_iterations = IterationLimit.for(no_interrupt: true)
343
345
  begin
344
346
  result = @engine.run_turn(
@@ -708,6 +710,7 @@ module Samagotchi
708
710
  # A prompt the user typed brings an archived session back to the lists.
709
711
  ArchiveStore.user_input(session.id, state_dir: Session.default_state_dir) if prompt && !continue
710
712
  save_before_first_turn(session)
713
+ attach_mentioned_context(session, prompt) if prompt && !continue
711
714
  with_steering do
712
715
  @engine.run_turn(
713
716
  session,
@@ -1014,6 +1017,18 @@ module Samagotchi
1014
1017
  session.save unless Session.exist?(session.id)
1015
1018
  end
1016
1019
 
1020
+ # A candidate the prompt mentions (ContextCandidates) is attached and
1021
+ # fetched, and its note added before the turn, as a worker does. Ctrl-C
1022
+ # stops the wait, not the turn.
1023
+ def attach_mentioned_context(session, prompt)
1024
+ ContextCandidates.before_turn(session: session, prompt: prompt, author: nil, state_dir: Session.default_state_dir)
1025
+ ContextCandidates.deliver_notes(@engine, session, state_dir: Session.default_state_dir)
1026
+ rescue Interrupt
1027
+ nil
1028
+ rescue StandardError => e
1029
+ Log.warn(:context, "candidates_repl_failed", error: e.class.name, msg: e.message.to_s[0, 200])
1030
+ end
1031
+
1017
1032
  # A !cmd shows its own output; everything else is the model> line. A
1018
1033
  # change that asks first (CacheConfirm) puts its --yes line in the next
1019
1034
  # input: Enter applies it.
@@ -69,7 +69,11 @@ module Samagotchi
69
69
  'require "samagotchi/guardrails/context"' => "for GitInfo: a ctx helper for the checkout's files could replace it",
70
70
  "Samagotchi::Guardrails::GitInfo.new" => "the work tree's top for the AGENTS.md chain (ctx.repo_root covers the top only)"
71
71
  },
72
- "claude-peer" => PEER_SPEC,
72
+ # Both bundles' goldens live in claude-peer's spec/.
73
+ "claude-peer" => PEER_SPEC.merge(
74
+ "Samagotchi::ContextSources.move" => "spec: a continue leaving the pairing behind, as SessionContinue " \
75
+ "moves it: needs a kit helper that continues a session"
76
+ ),
73
77
  "codex-peer" => PEER_SPEC,
74
78
  "coordinator" => {
75
79
  "Samagotchi::MemoryPaths.scope_dir" => "where the coordinator's memories live: needs a ctx memory-path API",
@@ -66,7 +66,10 @@ module Samagotchi
66
66
  cache_confirm: lambda { |line, changed|
67
67
  CacheConfirm.ask(line: line, cost: :full, changed: changed,
68
68
  engine: CacheEngine.new(recorder[:history], recorder[:context_tokens]))
69
- }
69
+ },
70
+ # The candidate judge isn't the bundle's to test: a late proposal
71
+ # goes nowhere.
72
+ candidate_proposed: ->(_candidate) {}
70
73
  )
71
74
  end
72
75
 
@@ -11,6 +11,7 @@ require_relative "session"
11
11
  require_relative "system_one/log"
12
12
  require_relative "toolkit"
13
13
  require_relative "tool_response"
14
+ require_relative "owner_prompt"
14
15
  require_relative "toolkit_suggest"
15
16
 
16
17
  module Samagotchi
@@ -165,7 +166,7 @@ module Samagotchi
165
166
  Array(messages).each do |message|
166
167
  case field(message, :role).to_s
167
168
  when "user"
168
- if ToolkitSuggest.owner_prompt?(message)
169
+ if OwnerPrompt.message?(message)
169
170
  number += 1
170
171
  current = number
171
172
  uses[current]
@@ -4,8 +4,7 @@ require "json"
4
4
 
5
5
  require_relative "cancellation_controller"
6
6
  require_relative "log"
7
- require_relative "message_time"
8
- require_relative "steer"
7
+ require_relative "owner_prompt"
9
8
  require_relative "system_one/question"
10
9
  require_relative "toolkit"
11
10
 
@@ -73,8 +72,7 @@ module Samagotchi
73
72
  # path, when the session already has a model reply.
74
73
  def self.eligible?(session:, prompt:, author:, candidate_count:, last_suggestion:, defer_turns:, defer_tokens:)
75
74
  return false unless session&.toolkit_origin == "default"
76
- return false if session.delegate? || session.review?
77
- return false if Steer.participant_author?(author)
75
+ return false if session.delegate? || !OwnerPrompt.turn?(session: session, author: author)
78
76
  return false unless prompt.is_a?(String) && !prompt.strip.empty?
79
77
  return false if value(candidate_count).to_i < 2
80
78
 
@@ -96,19 +94,6 @@ module Samagotchi
96
94
 
97
95
  def self.turn_number(messages) = user_prompt_count(Array(messages)) + 1
98
96
 
99
- # The owner's own prompt: a user line the Engine kept for a turn (it
100
- # carries the turn's id), or TurnCheckpoint's line for a turn killed
101
- # before its first boundary (stamped, no id). A !command's output, a
102
- # declined continue's reason and KernelLoop's recovery prompt are
103
- # neither; steers, notes and reminders carry their kind.
104
- def self.owner_prompt?(message)
105
- field(message, :role).to_s == "user" &&
106
- !Steer.participant_author?(field(message, :author)) &&
107
- !%w[input steer note reminder].include?(field(message, :kind).to_s) &&
108
- !field(message, :preserve_literals) &&
109
- !(field(message, :turn_id) || field(message, MessageTime::KEY)).nil?
110
- end
111
-
112
97
  # The prior logged suggestion for this session; the log, not process
113
98
  # memory, keeps a deferred choice alive across a worker respawn.
114
99
  def self.last_suggestion(log, session_id)
@@ -360,7 +345,7 @@ module Samagotchi
360
345
 
361
346
  def user_prompt_count(messages)
362
347
  prompts = messages.filter_map do |message|
363
- next unless owner_prompt?(message)
348
+ next unless OwnerPrompt.message?(message)
364
349
 
365
350
  field(message, :turn_id) || message.object_id
366
351
  end