samagotchi 0.162.0 → 0.164.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 (56) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +42 -1
  3. data/docs/architecture.md +2 -2
  4. data/docs/bundles.md +4 -2
  5. data/docs/cli.md +7 -2
  6. data/docs/configuration.md +1 -1
  7. data/docs/internals/block-renderers.md +3 -1
  8. data/docs/internals/bridge.md +37 -24
  9. data/docs/internals/inline-widgets.md +5 -2
  10. data/docs/internals/remote-sessions.md +7 -2
  11. data/docs/internals/web-frontend.md +1 -1
  12. data/docs/memory.md +8 -2
  13. data/docs/sessions.md +3 -2
  14. data/docs/sub-agent.md +11 -0
  15. data/docs/testing.md +8 -2
  16. data/lib/samagotchi/block_renderers.rb +14 -4
  17. data/lib/samagotchi/bridge/turn_drawings/synth.rb +7 -3
  18. data/lib/samagotchi/bridge/turn_drawings.rb +45 -30
  19. data/lib/samagotchi/bundles/inline-widgets/manifest.yml +2 -2
  20. data/lib/samagotchi/bundles/inline-widgets/plugin.rb +8 -4
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/cli/parent_wait.rb +5 -1
  23. data/lib/samagotchi/continue_intent.rb +48 -0
  24. data/lib/samagotchi/message_parts.rb +13 -0
  25. data/lib/samagotchi/note_command.rb +3 -6
  26. data/lib/samagotchi/parent_report.rb +3 -2
  27. data/lib/samagotchi/project_command.rb +74 -6
  28. data/lib/samagotchi/project_subfolders.rb +188 -0
  29. data/lib/samagotchi/send_command/parent_gate.rb +8 -5
  30. data/lib/samagotchi/send_command.rb +139 -34
  31. data/lib/samagotchi/session_access/local.rb +6 -0
  32. data/lib/samagotchi/session_access/remote.rb +25 -0
  33. data/lib/samagotchi/session_continue.rb +5 -3
  34. data/lib/samagotchi/session_inbox_delivery.rb +54 -7
  35. data/lib/samagotchi/session_manager/delivery.rb +3 -1
  36. data/lib/samagotchi/terminal_ui/join_replay.rb +2 -2
  37. data/lib/samagotchi/version.rb +1 -1
  38. data/lib/samagotchi/web/message_display.rb +45 -36
  39. data/lib/samagotchi/web/public/app.js +8 -7
  40. data/lib/samagotchi/web/public/apple-touch-icon.png +0 -0
  41. data/lib/samagotchi/web/public/data.js +4 -6
  42. data/lib/samagotchi/web/public/favicon.svg +1 -1
  43. data/lib/samagotchi/web/public/icons/chi-180.png +0 -0
  44. data/lib/samagotchi/web/public/icons/chi-192.png +0 -0
  45. data/lib/samagotchi/web/public/icons/chi-512.png +0 -0
  46. data/lib/samagotchi/web/public/inline_widgets.js +4 -1
  47. data/lib/samagotchi/web/public/reload_check.js +7 -4
  48. data/lib/samagotchi/web/public/time_gaps.js +1 -2
  49. data/lib/samagotchi/web/public/timing.js +49 -224
  50. data/lib/samagotchi/web/public/turn_block.js +40 -122
  51. data/lib/samagotchi/web/public/turn_html.js +3 -2
  52. data/lib/samagotchi/web/public/widget_walk.js +14 -4
  53. data/lib/samagotchi/web/reload_check_route.rb +6 -3
  54. data/lib/samagotchi/web/session_access_routes.rb +8 -1
  55. data/lib/samagotchi/web/session_show.rb +8 -24
  56. metadata +3 -1
@@ -0,0 +1,188 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require_relative "guardrails/path_resolve"
5
+ require_relative "memory_paths"
6
+ require_relative "paths"
7
+
8
+ module Samagotchi
9
+ # Memories saved from a subfolder of a marked project before
10
+ # `chi project init`: a session there keyed them by its own path
11
+ # (MemoryPaths.lookup was :none, the root its cwd), and after init the
12
+ # subfolder resolves to the project, so that folder is out of reach.
13
+ #
14
+ # A path key can't be reversed, so the candidates come only from this
15
+ # machine's session rows (each stores the root it keyed by: a project-less
16
+ # session's is its cwd); memories older than the sessions kept are not
17
+ # found (docs/memory.md: move them by hand). No directory walk: one
18
+ # listing of the sessions, one stat per row. Memories only: a subfolder's
19
+ # project context sources and skills history stay where they are.
20
+ #
21
+ # The one text for the condition is #message (`chi project init`'s report
22
+ # and `chi project`'s note); #merge (`chi project init --merge-subfolders`)
23
+ # moves them, #running_message refuses while a session could write.
24
+ module ProjectSubfolders
25
+ # +path+: the subfolder a session keyed its memories by; +dir+: that
26
+ # memories folder; +count+: the memories in it.
27
+ Found = Data.define(:path, :dir, :count)
28
+
29
+ FLAG = "--merge-subfolders"
30
+ INDEX = "index.md"
31
+ # What an emptied folder may still hold, none of it moved: the index
32
+ # (removed only when #hand_written? says it holds nothing of the user's),
33
+ # IndexUpdater's lock, and .root: ProjectIdClash's claim, written only in
34
+ # an id folder, so in a path-keyed one it is a copy's stray (a copied
35
+ # id folder renamed by hand) that names no folder this key belongs to.
36
+ LEFTOVERS = [INDEX, ".index.lock", ".root"].freeze
37
+
38
+ module_function
39
+
40
+ # The subfolders of +root+ (a marked project's realpath) whose
41
+ # path-keyed memories folder exists: a row's stored root under +root+
42
+ # that resolves to +root+ now (a nested git repository or marked folder
43
+ # is its own project; a symlink out of +root+ resolves elsewhere).
44
+ # @param sessions [Array<SessionRow>] this machine's sessions (+project+, +cwd+)
45
+ # @return [Array<Found>] sorted by path
46
+ def find(root, sessions:, env: ENV, home: MemoryPaths.default_home)
47
+ projects = MemoryPaths.projects_dir(env: env)
48
+ seen = {}
49
+ Array(sessions).each do |row|
50
+ path = (row.project || row.cwd).to_s
51
+ next if path.empty? || seen.key?(path)
52
+
53
+ seen[path] = nil
54
+ real = Guardrails::PathResolve.real(path)
55
+ next if real == root || !Guardrails::PathResolve.under?(real, root)
56
+ next unless MemoryPaths.lookup(path, home: home).root == root
57
+
58
+ dir = File.join(projects, MemoryPaths.key_for_root(path))
59
+ next unless File.directory?(dir) && !File.symlink?(dir)
60
+
61
+ count = entries(dir).size
62
+ seen[path] = Found.new(path: path, dir: dir, count: count) if count.positive?
63
+ end
64
+ seen.values.compact.uniq(&:dir).sort_by(&:path)
65
+ end
66
+
67
+ # The one text for found subfolder memories, or nil for none.
68
+ def message(found)
69
+ return nil if found.empty?
70
+
71
+ list = found.map { |item| "#{Paths.tilde(item.path)} (#{item.count} #{item.count == 1 ? "memory" : "memories"})" }
72
+ "memories saved from subfolders before init: #{list.join(", ")}; move them into the project with " \
73
+ "chi project init #{FLAG}"
74
+ end
75
+
76
+ # The running sessions that refuse a merge: under +root+ by the root
77
+ # they stored or by their folder (a live pre-init session stored its cwd).
78
+ def running(root, sessions:, home: MemoryPaths.default_home)
79
+ Array(sessions).select do |row|
80
+ next false unless row.live
81
+
82
+ [row.project, row.cwd].compact.map(&:to_s).reject(&:empty?).any? do |path|
83
+ Guardrails::PathResolve.under?(Guardrails::PathResolve.real(path), root) ||
84
+ MemoryPaths.lookup(path, home: home).root == root
85
+ end
86
+ end
87
+ end
88
+
89
+ def running_message(root, rows)
90
+ "#{Paths.tilde(root)} has running sessions (#{rows.map { |row| row.id[0, 8] }.join(", ")}): stop them " \
91
+ "(chi sessions stop ID) and rerun chi project init #{FLAG}, which moves the subfolders' memories while " \
92
+ "no session can write to them"
93
+ end
94
+
95
+ # Moves each found folder's memories (the file, its model overlays,
96
+ # its index line) into +target+ (the project's memories folder). One
97
+ # the project has by that name, or a bundle owns, stays and is named;
98
+ # an emptied folder is removed, with no link: every chi that knows
99
+ # markers resolves the subfolder to the project, and a link would hide
100
+ # a folder made there again from #find.
101
+ # @return [Array<String>] the report's lines
102
+ def merge(found, target:, env: ENV)
103
+ require_relative "memory_bundle/index_updater"
104
+ require_relative "memory_bundle/provenance"
105
+ require_relative "tools/memory"
106
+ lines = []
107
+ found.each { |item| lines.concat(merge_one(item, target, env)) }
108
+ lines << "no memories saved from subfolders before init to move" if lines.empty?
109
+ lines
110
+ end
111
+
112
+ # The entries of a memories folder: each <name>.md but the index and
113
+ # the model overlays of another entry (Tools::MemoryWrite.overlay_files),
114
+ # with its managed index line (or nil).
115
+ # @return [Hash{String => String, nil}] name → line
116
+ def entries(dir)
117
+ index_text = index_text(dir)
118
+ names = Dir.children(dir).select { |name| name.end_with?(".md") && name != INDEX && File.file?(File.join(dir, name)) }
119
+ .map { |name| name.delete_suffix(".md") }.sort
120
+ require_relative "tools/memory"
121
+ overlays = names.flat_map { |name| Tools::MemoryWrite.overlay_files(dir, name, index_text) }
122
+ .map { |path| File.basename(path, ".md") }
123
+ (names - overlays).to_h { |name| [name, index_text[Tools::MemoryWrite.managed_pattern(name)]&.chomp] }
124
+ end
125
+
126
+ def index_text(dir)
127
+ path = File.join(dir, INDEX)
128
+ File.file?(path) ? File.read(path, encoding: "UTF-8") : ""
129
+ end
130
+
131
+ def merge_one(item, target, env)
132
+ from = item.dir
133
+ index_text = index_text(from)
134
+ moved = []
135
+ kept = []
136
+ entries(from).each do |name, line|
137
+ files = [File.join(from, "#{name}.md")] + Tools::MemoryWrite.overlay_files(from, name, index_text)
138
+ owner = MemoryBundle::Provenance.claimants("#{name}.md", scope: "project",
139
+ dir: MemoryPaths.bundles_dir(env: env)).first ||
140
+ (line && MemoryBundle::IndexUpdater.extract_source(line))
141
+ next kept << "#{name} (from bundle #{owner})" if owner
142
+ next kept << "#{name} (the project has one by that name)" if files.any? { |path| File.exist?(File.join(target, File.basename(path))) }
143
+
144
+ FileUtils.mkdir_p(target)
145
+ bytes = File.size(files.first)
146
+ files.each { |path| File.rename(path, File.join(target, File.basename(path))) }
147
+ description = line && MemoryBundle::IndexUpdater.extract_description(line)
148
+ MemoryBundle::IndexUpdater.update_index("project", name, bytes, description, target_dir: target)
149
+ MemoryBundle::IndexUpdater.remove_index("project", name, target_dir: from)
150
+ moved << name
151
+ end
152
+
153
+ lines = []
154
+ unless moved.empty?
155
+ lines << "moved #{moved.size} #{moved.size == 1 ? "memory" : "memories"} saved from " \
156
+ "#{Paths.tilde(item.path)} into #{Paths.tilde(target)}: #{moved.join(", ")}"
157
+ end
158
+ lines << "kept in #{Paths.tilde(from)}: #{kept.join(", ")}" unless kept.empty?
159
+ rest = Dir.children(from) - LEFTOVERS
160
+ if rest.empty? && hand_written?(index_text(from))
161
+ lines << "#{Paths.tilde(from)} keeps its index.md: it has lines written by hand"
162
+ elsif rest.empty?
163
+ FileUtils.rm_rf(from)
164
+ lines << "removed the emptied #{Paths.tilde(from)}"
165
+ else
166
+ left = index_text(from)
167
+ memory_files = entries(from).keys.flat_map do |name|
168
+ ["#{name}.md"] + Tools::MemoryWrite.overlay_files(from, name, left).map { |path| File.basename(path) }
169
+ end
170
+ others = (rest - memory_files).sort
171
+ lines << "#{Paths.tilde(from)} keeps files that aren't memories: #{others.join(", ")}" unless others.empty?
172
+ end
173
+ lines
174
+ end
175
+
176
+ # Whether an index holds a line that isn't the auto header, blank or a
177
+ # managed line (memory_write keeps every other line byte for byte; a
178
+ # dangling managed line, its file gone, may go with the folder).
179
+ def hand_written?(text)
180
+ header = MemoryBundle::IndexUpdater.auto_index_header.lines.map(&:strip)
181
+ text.each_line.any? do |line|
182
+ line = line.strip
183
+ !(line.empty? || header.include?(line) || line.match?(/\A- \*\*[^*]+\*\*[ \t]*(?:[·•].*|:.*)?\z/))
184
+ end
185
+ end
186
+ private_class_method :index_text, :merge_one, :hand_written?
187
+ end
188
+ end
@@ -24,10 +24,13 @@ module Samagotchi
24
24
  # goes.
25
25
  class ParentGate
26
26
  # @param options [Hash] chi send's parsed options (:new, :continues,
27
- # :parent_answers, :ids)
28
- def initialize(options, state_dir:)
27
+ # :parent_answers)
28
+ # @param ids [Array<String>, nil] the sessions the ids name, as chi send
29
+ # sends to them (a continued one's newest link); nil with --new
30
+ def initialize(options, state_dir:, ids: nil)
29
31
  @options = options
30
32
  @state_dir = state_dir
33
+ @ids = ids
31
34
  end
32
35
 
33
36
  # A /continue yes (or bare /continue) from a parent agent's process.
@@ -69,8 +72,8 @@ module Samagotchi
69
72
  private
70
73
 
71
74
  # The targets' own parent_answers values. An id that doesn't resolve
72
- # is skipped (SendCommand#resolve reports it later); none left is
73
- # config.yml's alone ([nil]).
75
+ # is skipped (SendCommand reports it later); none left is config.yml's
76
+ # alone ([nil]).
74
77
  def target_values
75
78
  @target_values ||= if @options[:new] && !@options[:continues]
76
79
  [@options[:parent_answers]]
@@ -78,7 +81,7 @@ module Samagotchi
78
81
  sessions = if @options[:new]
79
82
  [target_session { SessionChain.resolve(@options[:continues], state_dir: @state_dir) }]
80
83
  else
81
- @options[:ids].map { |given| target_session { Session.resolve_id(given, state_dir: @state_dir) } }
84
+ Array(@ids).map { |id| target_session { id } }
82
85
  end
83
86
  values = sessions.compact.map(&:parent_answers)
84
87
  values.empty? ? [nil] : values
@@ -46,6 +46,14 @@ module Samagotchi
46
46
  MAX_IMAGES = ImageStore::MAX_TURN_REFS
47
47
  # A cut's outcomes in the Bridge's ack (SteerCut#cut_for_steer).
48
48
  CUT_OUTCOMES = %w[now waits off].freeze
49
+ # How long a send to a link being continued waits for the new link to
50
+ # be saved (SessionInbox::Head's :continuing; the spawn is quick), and
51
+ # how often it asks again; then it is refused.
52
+ CONTINUING_WAIT = 10.0
53
+ CONTINUING_POLL = 0.2
54
+
55
+ # The pause between two looks at a continue in flight (a seam for specs).
56
+ def self.pause(seconds) = sleep(seconds)
49
57
 
50
58
  USAGE = <<~TEXT
51
59
  Usage: chi send [-m TEXT] [--image PATH]... [--cut | --queue] (ID|PREFIX)...
@@ -56,7 +64,10 @@ module Samagotchi
56
64
  chi send --wait [--timeout S] [--format json] [--turn T] ID
57
65
  Sends a message to each session, as if typed in it: a turn starts,
58
66
  or a running one takes it at its next step. A stopped session's
59
- worker starts.
67
+ worker starts. A session that was continued: the newest link of its
68
+ chain gets it (OLD → NEW (continued)), and the old link stays
69
+ archived; one being continued right now waits a moment for its new
70
+ link. A chain's first id is a stable address for it.
60
71
  A session command (/model x, !cmd) runs as the command; --wait
61
72
  then has no reply to wait for (exit 0, status command).
62
73
  -m TEXT the message; stdin, when piped too, goes above it as a
@@ -295,7 +306,7 @@ module Samagotchi
295
306
  # check the line chi send's client_id marks; the worker checks a
296
307
  # CLI_ANSWER /continue again).
297
308
  unless @access.remote?
298
- gate = ParentGate.new(options, state_dir: @state_dir)
309
+ gate = ParentGate.new(options, state_dir: @state_dir, ids: (resolved_ids(options) unless options[:new]))
299
310
  if prompt && (refusal = gate.continue_refusal(prompt))
300
311
  @stderr.puts("chi send: #{refusal}")
301
312
  return CLI::Exit::FAILED
@@ -313,15 +324,16 @@ module Samagotchi
313
324
  return run_new(prompt, options) if options[:new]
314
325
  return run_wait(prompt, options) if options[:wait]
315
326
 
316
- # One id at a time, so each line follows the order of the ids given.
327
+ # One id at a time, so each line follows the order of the ids given;
328
+ # two that reach the same link (an old id and its newest link) send
329
+ # once.
317
330
  seen = {}
318
- results = options[:ids].uniq.map do |given|
319
- id = resolve(given)
320
- next false unless id
321
- next true if seen[id]
331
+ results = targets(options).map do |target|
332
+ next unsent(target) unless target.is_a?(SessionInbox::Resolved)
333
+ next true if seen[target.id]
322
334
 
323
- seen[id] = true
324
- deliver(id, prompt)
335
+ seen[target.id] = true
336
+ deliver(target, prompt)
325
337
  end
326
338
  results.all? ? 0 : 1
327
339
  ensure
@@ -583,20 +595,21 @@ module Samagotchi
583
595
  # enqueued_id), whatever runs before it.
584
596
  # @return [Integer] the exit status
585
597
  def run_wait(prompt, options)
586
- id = resolve(options[:ids].first) or return 1
587
- return run_participant_wait(id, prompt, options) if @access.participant?
598
+ target = wait_target(options) or return 1
599
+ id = target.id
600
+ return run_participant_wait(target, prompt, options) if @access.participant?
588
601
 
589
602
  # Local: one read for the check and the baseline; remotely the
590
603
  # server's wait prepare route reads both (Busy's words).
591
604
  session = @access.show(id) unless @access.remote?
592
605
  if (busy = @access.busy(id, queue: @queue, session: session))
593
- error_line("#{id[0, 8]} #{busy.message(via: @access.invocation)}")
606
+ error_line("#{target.label} #{busy.message(via: @access.invocation)}")
594
607
  return 1
595
608
  end
596
609
 
597
610
  start = @access.prepare_wait(id, session: session)
598
- return 1 unless deliver(id, prompt)
599
- return report_command(id) if @sent_command
611
+ return 1 unless deliver(target, prompt)
612
+ return report_command(id, label: target.label) if @sent_command
600
613
 
601
614
  target = ReplyWait::Target.message(start, @delivered, queue: @queue)
602
615
  wait_for_reply(id, target: target, timeout: options[:timeout])
@@ -609,12 +622,13 @@ module Samagotchi
609
622
  # wait routes take only a turn of theirs: the wait is on the one just
610
623
  # queued, as --wait --turn T.
611
624
  # @return [Integer] the exit status
612
- def run_participant_wait(id, prompt, options)
613
- return 1 unless deliver(id, prompt)
625
+ def run_participant_wait(target, prompt, options)
626
+ id = target.id
627
+ return 1 unless deliver(target, prompt)
614
628
 
615
629
  turn = @delivered.enqueued_id.to_s
616
630
  if turn.empty?
617
- error_line("chi send: #{id[0, 8]}: the review turn's id didn't come back; chi --remote … send --wait --turn T waits once you have it")
631
+ error_line("chi send: #{target.label}: the review turn's id didn't come back; chi --remote … send --wait --turn T waits once you have it")
618
632
  return 1
619
633
  end
620
634
  start = @access.prepare_wait(id, turn: turn)
@@ -634,10 +648,17 @@ module Samagotchi
634
648
  # idle in the gap between waits: that turn's end is the answer — its
635
649
  # reply, or its no-reply outcome — so the wait returns it at once
636
650
  # (ReplyWait's ended_before:) instead of timing out "running" again.
651
+ # A continued session's wait is on its newest link, but --turn T of the
652
+ # old link (from before the continue) waits on the old one.
637
653
  # @return [Integer] the exit status
638
654
  def run_wait_only(options)
639
- id = resolve(options[:ids].first) or return 1
655
+ target = wait_target(options) or return 1
640
656
  requested_turn = options[:turn]&.to_s
657
+ id = target.id
658
+ if requested_turn && target.asked != id && @access.prepare_wait(target.asked, turn: requested_turn).known_turn
659
+ @wait_target = target = SessionInbox::Resolved.new(id: target.asked, asked: target.asked, via: :same)
660
+ @session_id = id = target.id
661
+ end
641
662
  start = @access.prepare_wait(id, turn: requested_turn)
642
663
  if requested_turn && !start.known_turn
643
664
  error_line("chi send: turn #{requested_turn} is not a running, queued, or last ended turn")
@@ -708,12 +729,13 @@ module Samagotchi
708
729
  elsif options[:wait]
709
730
  # --wait: the JSON line goes to stdout, @info is stderr; an unknown
710
731
  # or ambiguous id gets resolve's own error line.
711
- id = resolve(options[:ids].first) or return CLI::Exit::FAILED
712
- @stderr.puts("#{id[0, 8]} refused: #{local_refusal(entry.name, id)}")
732
+ target = wait_target(options) or return CLI::Exit::FAILED
733
+ @stderr.puts("#{target.label} refused: #{local_refusal(entry.name, target.id)}")
713
734
  else
714
- options[:ids].uniq.each do |given|
715
- id = resolve(given) or next
716
- @info.puts("#{id[0, 8]} refused: #{local_refusal(entry.name, id)}")
735
+ targets(options).each do |target|
736
+ next unsent(target) unless target.is_a?(SessionInbox::Resolved)
737
+
738
+ @info.puts("#{target.label} refused: #{local_refusal(entry.name, target.id)}")
717
739
  end
718
740
  end
719
741
  CLI::Exit::FAILED
@@ -723,22 +745,25 @@ module Samagotchi
723
745
 
724
746
  # --wait after a message that ran as a session command: no reply comes
725
747
  # for it. Its output shows where the session is open.
748
+ # @param label [String] how the line names it (a chain's label, #target)
726
749
  # @return [Integer] 0
727
- def report_command(id)
750
+ def report_command(id, label: id[0, 8])
728
751
  detail = "#{SENT_COMMAND}: no reply to wait for (its output shows in #{@access.invocation.open_it(id)})"
729
752
  if @json
730
- @stdout.puts(JSON.generate({ status: "command", session_id: id, detail: detail }))
753
+ @stdout.puts(JSON.generate({ status: "command", session_id: id, **asked_extra, detail: detail }))
731
754
  @stdout.flush
732
755
  @reported = true
733
756
  else
734
- @stderr.puts("#{id[0, 8]} #{detail}")
757
+ @stderr.puts("#{label} #{detail}")
735
758
  end
736
759
  CLI::Exit::OK
737
760
  end
738
761
 
762
+ # @param target [SessionInbox::Resolved] the session (#target)
739
763
  # @return [Boolean] whether the message was queued
740
- def deliver(id, prompt)
741
- short = id[0, 8]
764
+ def deliver(target, prompt)
765
+ id = target.id
766
+ short = target.label
742
767
  session = @access.show(id)
743
768
  # Machine-local (this machine's model registry): remotely the
744
769
  # server's (P2), as for --new.
@@ -776,7 +801,7 @@ module Samagotchi
776
801
  @sent_delivery = result.delivery || delivery
777
802
  @sent_cut = result.cut
778
803
  note = if @access.participant? then participant_note(id, result)
779
- else delivery_note(result, delivery: delivery, running: running, owner: owner)
804
+ else delivery_note(id, result, delivery: delivery, running: running, owner: owner)
780
805
  end
781
806
  @info.puts("#{short} sent#{with_images}#{note}")
782
807
  true
@@ -795,12 +820,14 @@ module Samagotchi
795
820
  # running turn's next step (nothing cuts by default); a --cut one names
796
821
  # the outcome from the ack (now, waits, off); a --queue one runs after
797
822
  # the turn (or now, when the turn ended before it went in); images keep
798
- # their own wording; an idle session's turn simply runs.
823
+ # their own wording; an idle session's turn simply runs. A link reached
824
+ # after waiting on its continue (#target) has the continue's own spawn
825
+ # starting its worker: no worker yet doesn't mean this send started it.
799
826
  # @param result [SessionManager::DeliverResult] the accepted delivery
800
827
  # (its ack is {} for the input file)
801
828
  # @return [String] "" or " (...)"
802
- def delivery_note(result, delivery:, running:, owner:)
803
- return " (started its worker)" if owner.nil?
829
+ def delivery_note(id, result, delivery:, running:, owner:)
830
+ return " (started its worker)" if owner.nil? && !@continued_here&.key?(id)
804
831
  return queue_note(result, running: running) if Delivery.queue?(delivery)
805
832
  return "" unless running
806
833
  # A participant's review turn was running: the worker queued it.
@@ -844,14 +871,92 @@ module Samagotchi
844
871
  # unchanged otherwise): the delivery the worker applied (next_step to
845
872
  # an idle session) and a cut's outcome (now, waits, off). --cut --wait
846
873
  # is refused for a running turn, so its json line says next_step.
874
+ # A continued session's names the id asked too (asked_extra).
847
875
  def report_extra
848
- return {} unless @cut || @queue
876
+ return asked_extra unless @cut || @queue
849
877
 
850
- extra = { delivery: @sent_delivery || Delivery::NEXT_STEP }
878
+ extra = asked_extra.merge(delivery: @sent_delivery || Delivery::NEXT_STEP)
851
879
  extra[:cut] = @sent_cut if @sent_cut
852
880
  extra
853
881
  end
854
882
 
883
+ # The sessions the ids name, each once and in the order given, resolved
884
+ # once up front (#target): what ParentGate checks, what the message
885
+ # goes to, what --wait waits on.
886
+ # @return [Array<SessionInbox::Resolved, Unsent>]
887
+ def targets(options)
888
+ @targets ||= options[:ids].uniq.map { |given| target(given) }
889
+ end
890
+
891
+ # The targets' ids, for ParentGate (one that names none is skipped:
892
+ # its line comes where it is sent).
893
+ def resolved_ids(options) = targets(options).grep(SessionInbox::Resolved).map(&:id)
894
+
895
+ # --wait's one target, kept for the JSON lines (@session_id: its id;
896
+ # asked_extra); nil after its line (an Unsent is kept too: a continue
897
+ # in flight's refusal names the id asked).
898
+ # @return [SessionInbox::Resolved, nil]
899
+ def wait_target(options)
900
+ target = targets(options).first
901
+ @wait_target = target
902
+ unless target.is_a?(SessionInbox::Resolved)
903
+ unsent(target)
904
+ return nil
905
+ end
906
+
907
+ @session_id = target.id
908
+ @wait_target = target
909
+ end
910
+
911
+ # The --format json line's asked, whatever the end once the id given
912
+ # resolved (an answer, a refusal, an error): that id, when it is not
913
+ # the line's session_id (the wait is on a later link of its chain, or a
914
+ # continue in flight refused it before there was one); {} otherwise.
915
+ def asked_extra
916
+ asked = @wait_target&.asked
917
+ asked && asked != @session_id ? { asked: asked } : {}
918
+ end
919
+
920
+ # ParentWait's error line: asked too (asked_extra).
921
+ def error_extra = asked_extra
922
+
923
+ # An id given that names no session to send to, and the line that says
924
+ # why: an error line (no such session, a prefix of several) or a
925
+ # refusal on the info stream (a continue in flight: +asked+ the full id
926
+ # given, nil for the others).
927
+ Unsent = Data.define(:line, :error, :asked) do
928
+ def initialize(line:, error:, asked: nil) = super
929
+ end
930
+
931
+ # +given+'s session (an id or a prefix), then where input for it goes
932
+ # (SessionAccess#head): a continued session's chain's newest link. A
933
+ # continue of it in flight (:continuing: the new link not saved yet)
934
+ # is asked again for up to CONTINUING_WAIT, then refused; the old link
935
+ # is never sent to (a send would un-archive it beside the new one).
936
+ # @return [SessionInbox::Resolved, Unsent]
937
+ def target(given)
938
+ id = @access.resolve(given)
939
+ head = @access.head(id)
940
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + self.class::CONTINUING_WAIT
941
+ waited = head.continuing?
942
+ while head.continuing? && Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
943
+ self.class.pause(self.class::CONTINUING_POLL)
944
+ head = @access.head(id)
945
+ end
946
+ return Unsent.new(line: "#{id[0, 8]} refused: #{head.continuing_refusal}", error: false, asked: id) if head.continuing?
947
+
948
+ (@continued_here ||= {})[head.id] = true if waited
949
+ head
950
+ rescue ArgumentError => e
951
+ Unsent.new(line: "#{command_name}: #{e.message}", error: true)
952
+ end
953
+
954
+ # Prints +unsent+'s line. @return [false]
955
+ def unsent(unsent)
956
+ unsent.error ? error_line(unsent.line) : @info.puts(unsent.line)
957
+ false
958
+ end
959
+
855
960
  # What to say when +model_name+ is known not to take images, or nil
856
961
  # (it does, or it is unknown: sent as before). Asked once per model.
857
962
  def vision_refusal(model_name, typed: nil)
@@ -81,6 +81,12 @@ module Samagotchi
81
81
  # @raise [ArgumentError] no such session
82
82
  def show(id) = Session.load(id, **dir)
83
83
 
84
+ # Where input for +id+ goes: its chain's newest link when it was
85
+ # continued (SessionInbox::Head's send walk; :continuing while a
86
+ # continue of it is in flight), else +id+.
87
+ # @return [SessionInbox::Resolved]
88
+ def head(id) = SessionInbox::Head.resolve(:send, id, state_dir: state_dir!)
89
+
84
90
  # @return [OwnerLock::Owner, nil] the worker or one-turn chi run that owns it
85
91
  def owner(id) = SessionManager.session_owner(id, **dir)
86
92
 
@@ -7,6 +7,7 @@ require_relative "../remotes"
7
7
  require_relative "../reply_wait"
8
8
  require_relative "../pending_question"
9
9
  require_relative "../note_delivery"
10
+ require_relative "../session_inbox"
10
11
  require_relative "../owner_lock"
11
12
  require_relative "../context_sources"
12
13
  require_relative "../bridge_client"
@@ -147,6 +148,30 @@ module Samagotchi
147
148
  id
148
149
  end
149
150
 
151
+ # Where input for +id+ goes, as chi web resolves it there
152
+ # (Local#head): GET /api/sessions/resolve?id=X&head=1. An older chi
153
+ # web ignores head=1 and answers {id}, and a refusal (the session
154
+ # gone since) is the send's to report: +id+ itself (:same, as before
155
+ # it followed). A participant never
156
+ # asks: their grant is for one session (:pinned).
157
+ # @return [SessionInbox::Resolved]
158
+ def head(id)
159
+ return SessionInbox::Resolved.new(id: id, asked: id, via: :pinned) if participant?
160
+
161
+ same = SessionInbox::Resolved.new(id: id, asked: id, via: :same)
162
+ reply = request(:get, "/api/sessions/resolve", query: { id: id.to_s, head: 1 })
163
+ return same unless reply.status == 200
164
+
165
+ json = reply.json
166
+ via = HEAD_VIAS[json["via"]] if json.is_a?(Hash)
167
+ return same unless via && Session.valid_id?(json["id"])
168
+
169
+ SessionInbox::Resolved.new(id: json["id"], asked: id, via: via)
170
+ end
171
+
172
+ # The ways resolve?head=1 answers (SessionInbox::Resolved#via).
173
+ HEAD_VIAS = { "same" => :same, "head" => :head, "continuing" => :continuing }.freeze
174
+
150
175
  # @return [SessionView]
151
176
  # @raise [ArgumentError] no such session
152
177
  def show(id)
@@ -14,6 +14,7 @@ require_relative "starting_marker"
14
14
  require_relative "context_move"
15
15
  require_relative "note_move"
16
16
  require_relative "archive_store"
17
+ require_relative "continue_intent"
17
18
  require_relative "recap_store"
18
19
  require_relative "bridge_client"
19
20
  require_relative "worker_link"
@@ -59,9 +60,10 @@ module Samagotchi
59
60
  # recap (IdleRecap's own request timeout).
60
61
  RECAP_WAIT = 30.0
61
62
  # In the previous link's folder: one continue of a session at a time.
62
- LOCK = "continue.lock"
63
- # A durable record in the previous link's folder, written before archive.
64
- CONTINUE_INTENT = "continue.json"
63
+ LOCK = ContinueIntent::LOCK
64
+ # A durable record in the previous link's folder, written before archive
65
+ # (a send in flight reads it: ContinueIntent.in_flight).
66
+ CONTINUE_INTENT = ContinueIntent::FILE
65
67
  # How often a last:<id> continue looks again when another continue
66
68
  # moved the chain's end while it waited for the lock.
67
69
  TRIES = 3