samagotchi 0.190.1 → 0.192.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 (106) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/docs/architecture.md +13 -11
  4. data/docs/bundles.md +1 -1
  5. data/docs/cli.md +17 -6
  6. data/docs/configuration.md +6 -1
  7. data/docs/context.md +8 -1
  8. data/docs/internals/attached-context.md +3 -1
  9. data/docs/internals/inline-widgets.md +2 -1
  10. data/docs/internals/participants.md +1 -5
  11. data/docs/internals/peers.md +15 -3
  12. data/docs/internals/remote-sessions.md +5 -2
  13. data/docs/internals/session-lifecycle.md +233 -18
  14. data/docs/internals/web-frontend.md +107 -9
  15. data/docs/peers.md +3 -1
  16. data/docs/plugins.md +2 -1
  17. data/docs/scheduling.md +31 -7
  18. data/docs/sessions.md +12 -12
  19. data/docs/sub-agent.md +1 -1
  20. data/docs/testing.md +1 -2
  21. data/docs/thin-clients.md +98 -12
  22. data/lib/samagotchi/bridge.rb +3 -4
  23. data/lib/samagotchi/bundles/mcp/manifest.yml +4 -2
  24. data/lib/samagotchi/bundles/mcp/plugin.rb +7 -398
  25. data/lib/samagotchi/bundles/mcp/server_config.rb +158 -0
  26. data/lib/samagotchi/bundles/mcp/sign_in.rb +261 -0
  27. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  28. data/lib/samagotchi/client_id.rb +2 -19
  29. data/lib/samagotchi/compat.rb +1 -7
  30. data/lib/samagotchi/config.rb +3 -0
  31. data/lib/samagotchi/context_command.rb +5 -1
  32. data/lib/samagotchi/context_sources.rb +28 -0
  33. data/lib/samagotchi/continue_intent.rb +23 -43
  34. data/lib/samagotchi/delivery.rb +1 -5
  35. data/lib/samagotchi/hold_stop.rb +5 -2
  36. data/lib/samagotchi/participants.rb +13 -5
  37. data/lib/samagotchi/peer_say.rb +29 -14
  38. data/lib/samagotchi/plugin/sessions.rb +9 -5
  39. data/lib/samagotchi/schedule_command.rb +6 -1
  40. data/lib/samagotchi/schedules/prune_part.rb +162 -41
  41. data/lib/samagotchi/schedules.rb +32 -15
  42. data/lib/samagotchi/send_command.rb +6 -6
  43. data/lib/samagotchi/session.rb +7 -0
  44. data/lib/samagotchi/session_access/ask.rb +9 -3
  45. data/lib/samagotchi/session_access/exchange.rb +6 -2
  46. data/lib/samagotchi/session_access/local.rb +103 -32
  47. data/lib/samagotchi/session_access/remote.rb +10 -9
  48. data/lib/samagotchi/session_access/remote_peers.rb +2 -2
  49. data/lib/samagotchi/session_access.rb +17 -7
  50. data/lib/samagotchi/session_chain/delete.rb +100 -47
  51. data/lib/samagotchi/session_chain/delete_preview.rb +9 -5
  52. data/lib/samagotchi/session_chain/successor.rb +78 -0
  53. data/lib/samagotchi/session_continue.rb +112 -42
  54. data/lib/samagotchi/session_inbox.rb +1 -1
  55. data/lib/samagotchi/session_inbox_delivery.rb +111 -25
  56. data/lib/samagotchi/session_lifecycle/allowed.rb +20 -1
  57. data/lib/samagotchi/session_lifecycle/reading.rb +9 -3
  58. data/lib/samagotchi/session_lifecycle.rb +17 -2
  59. data/lib/samagotchi/session_manager/delivery.rb +61 -29
  60. data/lib/samagotchi/session_manager/emptiness.rb +5 -2
  61. data/lib/samagotchi/session_manager/lifecycle.rb +68 -19
  62. data/lib/samagotchi/session_manager/listing.rb +2 -1
  63. data/lib/samagotchi/session_manager/removal.rb +67 -13
  64. data/lib/samagotchi/session_manager/spawn.rb +16 -9
  65. data/lib/samagotchi/session_manager.rb +4 -0
  66. data/lib/samagotchi/session_retention.rb +28 -7
  67. data/lib/samagotchi/session_row.rb +2 -0
  68. data/lib/samagotchi/session_transition.rb +361 -0
  69. data/lib/samagotchi/sessions_command.rb +1 -1
  70. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -0
  71. data/lib/samagotchi/tools/cancel_schedule.rb +10 -6
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/app.rb +13 -3
  74. data/lib/samagotchi/web/ask_create.rb +138 -0
  75. data/lib/samagotchi/web/ask_routes.rb +56 -9
  76. data/lib/samagotchi/web/last_ask.rb +78 -0
  77. data/lib/samagotchi/web/peer_routes.rb +5 -2
  78. data/lib/samagotchi/web/public/answer_refs.js +3 -9
  79. data/lib/samagotchi/web/public/answer_write.js +28 -0
  80. data/lib/samagotchi/web/public/app.js +72 -96
  81. data/lib/samagotchi/web/public/block_fix.js +30 -12
  82. data/lib/samagotchi/web/public/chains.js +3 -1
  83. data/lib/samagotchi/web/public/command_list.js +5 -3
  84. data/lib/samagotchi/web/public/composer.js +9 -6
  85. data/lib/samagotchi/web/public/composer_mount.js +18 -11
  86. data/lib/samagotchi/web/public/draft_keys.js +10 -0
  87. data/lib/samagotchi/web/public/drafts.js +278 -0
  88. data/lib/samagotchi/web/public/owner_claim.js +7 -12
  89. data/lib/samagotchi/web/public/prompt_history.js +6 -0
  90. data/lib/samagotchi/web/public/send_turn.js +51 -20
  91. data/lib/samagotchi/web/public/session_actions.js +80 -16
  92. data/lib/samagotchi/web/public/session_prefs.js +9 -3
  93. data/lib/samagotchi/web/public/session_view.js +7 -2
  94. data/lib/samagotchi/web/public/turn_events.js +0 -2
  95. data/lib/samagotchi/web/public/unqueue.js +22 -9
  96. data/lib/samagotchi/web/public/viewer_self.js +1 -6
  97. data/lib/samagotchi/web/public/views.js +12 -1
  98. data/lib/samagotchi/web/session_access_routes.rb +11 -5
  99. data/lib/samagotchi/web/session_control.rb +8 -1
  100. data/lib/samagotchi/web/session_create.rb +51 -34
  101. data/lib/samagotchi/web/session_hub.rb +52 -36
  102. data/lib/samagotchi/web/session_summary.rb +45 -7
  103. data/lib/samagotchi/web/start_dir.rb +6 -4
  104. data/lib/samagotchi/worker_boot.rb +28 -6
  105. data/lib/samagotchi/worker_presence.rb +22 -6
  106. metadata +10 -1
@@ -2,6 +2,8 @@
2
2
 
3
3
  require_relative "peer_mailbox"
4
4
  require_relative "peer_receipts"
5
+ require_relative "session_chain/successor"
6
+ require_relative "session_transition"
5
7
 
6
8
  module Samagotchi
7
9
  # What chi peer say tells the peer, in chi's own words: the message's
@@ -12,7 +14,9 @@ module Samagotchi
12
14
  # #line, so a --remote say prints the remote's line.
13
15
  #
14
16
  # +status+: :received, or a refusal (nothing written): :gone (no such
15
- # session), :deleting, :continued (+next_id+), :not_paired, :old_worker
17
+ # session), :deleting, :continued (+next_id+; +in_flight+ while its
18
+ # continue runs: the new link is not saved yet), :busy (another change
19
+ # of the session holds its transition lock), :not_paired, :old_worker
16
20
  # (a live worker without the peer mail), :full (UNTAKEN_MAX unread).
17
21
  # +serial+: the message's. +wake+: what the say saw at once, when it
18
22
  # didn't wait: :running (a turn runs), :starting, :stopped, :archived,
@@ -22,14 +26,15 @@ module Samagotchi
22
26
  # without one. +earlier+: [[serial, reason]…] of the peer's other held
23
27
  # messages. +turns+: the wakes in a row that a held receipt's reason
24
28
  # names (peer turns or max wakes), as configured where the say ran.
25
- PeerSay = Data.define(:status, :serial, :wake, :receipt, :earlier, :next_id, :turns) do
26
- def initialize(status:, serial: nil, wake: nil, receipt: nil, earlier: [], next_id: nil, turns: nil) = super
29
+ PeerSay = Data.define(:status, :serial, :wake, :receipt, :earlier, :next_id, :turns, :in_flight) do
30
+ def initialize(status:, serial: nil, wake: nil, receipt: nil, earlier: [], next_id: nil, turns: nil,
31
+ in_flight: false) = super
27
32
 
28
33
  def received? = status == :received
29
34
 
30
35
  # The line for +peer+ (its name): "#12 received · woke chi".
31
36
  def line(peer)
32
- return PeerSay.refusal(status, peer, next_id) unless received?
37
+ return PeerSay.refusal(status, peer, next_id, in_flight: in_flight) unless received?
33
38
 
34
39
  parts = ["##{serial} received", tail(peer)]
35
40
  parts << "also held: #{PeerSay.held_list(earlier)}" unless earlier.empty?
@@ -38,7 +43,7 @@ module Samagotchi
38
43
 
39
44
  def to_h
40
45
  { "status" => status.to_s, "serial" => serial, "wake" => wake&.to_s, "receipt" => receipt&.to_h,
41
- "earlier" => earlier, "next_id" => next_id, "turns" => turns }.compact
46
+ "earlier" => earlier, "next_id" => next_id, "turns" => turns, "in_flight" => (true if in_flight) }.compact
42
47
  end
43
48
 
44
49
  # The JSON a chi web answered (#to_h); nil for another shape.
@@ -50,15 +55,17 @@ module Samagotchi
50
55
  new(status: data["status"].to_sym, serial: (data["serial"] if data["serial"].is_a?(Integer)),
51
56
  wake: (data["wake"].to_sym if PeerSay::WAKES.include?(data["wake"].to_s)),
52
57
  receipt: PeerReceipts::Receipt.from_h(data["receipt"]), earlier: earlier,
53
- next_id: data["next_id"]&.to_s, turns: (data["turns"] if data["turns"].is_a?(Integer)))
58
+ next_id: data["next_id"]&.to_s, turns: (data["turns"] if data["turns"].is_a?(Integer)),
59
+ in_flight: data["in_flight"] == true)
54
60
  end
55
61
 
56
62
  # The words of a refused say, nothing written.
57
- def self.refusal(status, peer, next_id)
63
+ def self.refusal(status, peer, next_id, in_flight: false)
58
64
  case status
59
65
  when :gone then "no such session"
60
66
  when :deleting then "this session is being deleted"
61
- when :continued then "this session was continued as #{next_id}: say it there"
67
+ when :continued then PeerSay.continued(next_id, in_flight, "say it there")
68
+ when :busy then SessionTransition::Busy.new(nil).message
62
69
  when :not_paired then "not paired: run the pair script"
63
70
  when :old_worker then "this session's chi is older than chi peer: restart the session (chi sessions restart)"
64
71
  when :full then "chi has #{PeerMailbox::UNTAKEN_MAX} unread messages from #{peer}"
@@ -66,6 +73,13 @@ module Samagotchi
66
73
  end
67
74
  end
68
75
 
76
+ # A continued link's refusal (SessionChain::Continued, "this session"),
77
+ # then what to do: +what+ there, once the new link is saved when its
78
+ # continue still runs.
79
+ def self.continued(next_id, in_flight, what)
80
+ "#{SessionChain::Continued.new(nil, next_id, in_flight: in_flight).message}: #{what}#{" in a moment" if in_flight}"
81
+ end
82
+
69
83
  # "#10, #11 (paused)", a run of one reason at a time.
70
84
  def self.held_list(earlier)
71
85
  earlier.chunk_while { |a, b| a[1] == b[1] }.map do |run|
@@ -111,20 +125,21 @@ module Samagotchi
111
125
  PeerSay::POLL_SECONDS = 0.25
112
126
 
113
127
  # What chi peer pair did: :paired (+link+), or a refusal (nothing
114
- # written): :continued (+next_id+), :old_worker (a live worker without
115
- # the peer mail).
116
- PeerPaired = Data.define(:status, :link, :next_id) do
117
- def initialize(status:, link: nil, next_id: nil) = super
128
+ # written): :continued (+next_id+, +in_flight+ as PeerSay's), :busy,
129
+ # :old_worker (a live worker without the peer mail).
130
+ PeerPaired = Data.define(:status, :link, :next_id, :in_flight) do
131
+ def initialize(status:, link: nil, next_id: nil, in_flight: false) = super
118
132
 
119
133
  def refusal
120
134
  case status
121
- when :continued then "this session was continued as #{next_id}: pair with it"
135
+ when :continued then PeerSay.continued(next_id, in_flight, "pair with it")
136
+ when :busy then SessionTransition::Busy.new(nil).message
122
137
  when :old_worker then PeerSay.refusal(:old_worker, nil, nil)
123
138
  end
124
139
  end
125
140
  end
126
141
 
127
- PeerSay::STATUSES = %w[received gone deleting continued not_paired old_worker full].freeze
142
+ PeerSay::STATUSES = %w[received gone deleting continued busy not_paired old_worker full].freeze
128
143
  PeerSay::WAKES = %w[running starting stopped archived owned start_failed no_turn not_running deleting].freeze
129
144
  # The setting a peer_turns hold names (WorkerWakes::PEER_TURNS_KEY: the
130
145
  # CLI loads no worker).
@@ -100,7 +100,8 @@ module Samagotchi
100
100
  # @raise [Error] no such session, a one-shot owns it, it wasn't taken
101
101
  # (a worker older than queueing refuses a queue; a stopped or
102
102
  # archived session: session_stopped / session_archived; one being
103
- # deleted: session_deleting), or delivery is
103
+ # deleted: session_deleting; one a transition holds: link_continued,
104
+ # transition_busy), or delivery is
104
105
  # :cut or unknown
105
106
  def send(id, text, delivery: nil)
106
107
  raise Error, "nothing to send" if text.to_s.strip.empty?
@@ -170,10 +171,11 @@ module Samagotchi
170
171
 
171
172
  # Stop one of this session's own children as `chi sessions stop` does
172
173
  # (by session id; no pid is read here), waiting up to STOP_WAIT s for
173
- # its worker to let go.
174
+ # its worker to let go. Its transition lock is one try (this worker
175
+ # holds its own owner.lock, so it never waits for one).
174
176
  # @return [String] the child's id
175
- # @raise [Error] not a child of this session, no such session, or a
176
- # one-shot owns it
177
+ # @raise [Error] not a child of this session, no such session, a
178
+ # one-shot owns it, or another change holds it (Busy's words)
177
179
  def stop(id)
178
180
  state_dir = self.state_dir
179
181
  sid = resolve(id, state_dir)
@@ -182,10 +184,12 @@ module Samagotchi
182
184
  raise Error, "session #{sid[0, 8]} is not a child of this session"
183
185
  end
184
186
 
185
- SessionManager.stop_session(sid, state_dir: state_dir, wait: STOP_WAIT)
187
+ SessionManager.stop_session(sid, state_dir: state_dir, wait: STOP_WAIT, lock_wait: 0)
186
188
  sid
187
189
  rescue SessionManager::OwnedByTUI
188
190
  raise Error, "session #{sid[0, 8]} is #{OwnerLock::TUI_BUSY}; let it finish"
191
+ rescue SessionTransition::Busy => e
192
+ raise Error, e.message
189
193
  end
190
194
 
191
195
  private
@@ -252,6 +252,8 @@ module Samagotchi
252
252
  @stdout.puts(" last fired: #{clock(entry.last_fired)} last result: #{entry.last_result || "-"}")
253
253
  @stdout.puts(" skips: #{entry.skips} of #{entry.max_skips} failures: #{entry.failures} of #{entry.max_failures}")
254
254
  @stdout.puts(" keep_links: #{entry.keep_links} enabled: #{entry.enabled}")
255
+ waiting = Schedules::PrunePart.waiting(entry)
256
+ @stdout.puts(" pruning held at #{waiting.link[0, 8]}: #{waiting.reason} (since #{clock(waiting.at)})") if waiting
255
257
  @stdout.puts(" if: #{condition_show(entry)}") unless entry.condition.nil?
256
258
  @stdout.puts(" prompt: #{entry.prompt}")
257
259
  print_history(entry)
@@ -317,6 +319,7 @@ module Samagotchi
317
319
  end
318
320
 
319
321
  @stdout.puts("#{id} #{@argv[0]}: ok")
322
+ @stdout.puts(result.warning) if result.is_a?(Schedules::Cancelled) && result.warning
320
323
  CLI::Exit::OK
321
324
  rescue Schedules::Usage => e
322
325
  usage_error(e.message)
@@ -336,7 +339,8 @@ module Samagotchi
336
339
  end
337
340
 
338
341
  # One `list` row: id, name, mode, recurrence, next due, target head, and the
339
- # notes (skips, why it is disabled, the last result). +name_width+ is the
342
+ # notes (skips, why it is disabled, the last result, the link its prune
343
+ # waits at: Schedules::PrunePart.waiting). +name_width+ is the
340
344
  # widest name among the rows printed; without it the name column is just
341
345
  # the name. "disabled after N" only when that budget is spent: a one-off
342
346
  # whose firing failed (ScheduleDisplay.off_reason "failures") reads
@@ -347,6 +351,7 @@ module Samagotchi
347
351
  note += off_note(entry) unless entry.enabled
348
352
  note += " if: #{ScheduleDisplay.condition_words(entry, chars: ScheduleDisplay::PROMPT_CHARS)}" unless entry.condition.nil?
349
353
  note += " last: #{entry.last_result}" if entry.last_result
354
+ note += " pruning held at #{Schedules::PrunePart.waiting(entry).link[0, 8]}" if Schedules::PrunePart.waiting(entry)
350
355
  "#{entry.id} #{ScheduleDisplay.name(entry, width: name_width)} #{entry.mode} #{entry.recurrence_words} " \
351
356
  "#{clock(entry.next_due)} #{entry.head[0, 8]}#{note}"
352
357
  end
@@ -1,36 +1,91 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "time"
3
4
  require_relative "../archive_store"
4
5
  require_relative "../log"
5
6
  require_relative "../session"
6
7
  require_relative "../session_manager"
8
+ require_relative "../session_transition"
7
9
 
8
10
  module Samagotchi
9
11
  class Schedules
12
+ # What #cancel removed: +entry+ (an Entry, or the raw Hash of one that
13
+ # doesn't read) and +newest+, the chain's newest link, set only
14
+ # when this cancel took away the last bridge over a pruned anchor's gap
15
+ # (PrunePart#cancel_strands). It owns the line that says so; callers only
16
+ # add context.
17
+ Cancelled = Data.define(:entry, :newest) do
18
+ def initialize(entry:, newest: nil) = super
19
+
20
+ def id = entry.is_a?(Hash) ? entry["id"] : entry.id
21
+
22
+ def warning
23
+ newest && "#{entry.anchor[0, 8]}'s chain was pruned; its newest link is #{newest[0, 8]} — send there from now on."
24
+ end
25
+ end
26
+
10
27
  # The chain prune after a firing (docs/scheduling.md, "Keeping the chain
11
- # short"): the links behind a chain entry's keep_links window go.
28
+ # short"): the links behind a chain entry's keep_links window go, oldest
29
+ # first, each under the transition locks of it and the link after it.
30
+ # A link that can't go now holds the prune there (never skipped past:
31
+ # the chain is not deleted around it); the entry records where and why
32
+ # (PRUNE_WAITING, shown by chi schedule list/show), and every tick
33
+ # tries again until it goes.
12
34
  module PrunePart
35
+ # The entry's extra key for where its prune waits: {"link", "reason",
36
+ # "at"} (since when it waits at that link). No history row: it is
37
+ # state, cleared once the prune gets past it.
38
+ PRUNE_WAITING = "prune_waiting"
39
+
40
+ # Where an entry's prune waits.
41
+ Waiting = Data.define(:link, :reason, :at)
42
+
43
+ # @return [Waiting, nil]
44
+ def self.waiting(entry)
45
+ value = entry.extra[PRUNE_WAITING]
46
+ return nil unless value.is_a?(Hash) && Session.valid_id?(value["link"])
47
+
48
+ Waiting.new(link: value["link"], reason: value["reason"].to_s, at: value["at"])
49
+ end
50
+
13
51
  private
14
52
 
53
+ # The entries a tick prunes: the chain entries it fired, then every
54
+ # enabled one whose prune waits at a link (#prune tries it again).
55
+ def prunes_due(fired, listed)
56
+ waiting = listed.select do |entry|
57
+ entry.enabled && entry.mode == CHAIN && entry.keep_links.positive? && PrunePart.waiting(entry) &&
58
+ fired.none? { |done| done.id == entry.id }
59
+ end
60
+ fired + waiting
61
+ end
62
+
15
63
  # The links behind the kept window, with the delegates that hung under
16
64
  # them: archiving a link archives its descendants, and archived sessions
17
65
  # are outside the retention sweep, so the delegate pile is the bulk of the
18
66
  # archived count. Oldest link first, and within a link its children first
19
- # (deepest first) and the link last. The walk stops at a link that is not
20
- # archived, one whose subtree has a live worker, or one with a descendant
21
- # still unarchived: nothing is deleted in that case, and the next firing
22
- # retries (a schedule failure it is not). A link already gone (the one
23
- # an earlier prune deleted: the walk back from the head ends on its id)
24
- # is skipped, not a stop, or every prune after the first would stall
67
+ # (deepest first) and the link last. A link already gone (the one an
68
+ # earlier prune deleted: the walk back from the head ends on its id) is
69
+ # skipped, not a stop, or every prune after the first would stall
25
70
  # there. The anchor is never pruned: `last:<anchor>` must keep resolving
26
71
  # (SessionChain::Links forwards it over the gap to the head), and it is
27
- # the id the user remembers.
72
+ # the id the user remembers. Any other link that can't go now
73
+ # (#prune_hold, or its or the next link's transition lock held) stops
74
+ # the prune below it, recorded (#note_waiting); a schedule failure it
75
+ # is not.
28
76
  def prune(entry, links)
77
+ chain = chain_back(entry, links)
78
+ older = chain[entry.keep_links..] || []
79
+ note_waiting(entry, older.empty? ? nil : prune_links(entry, chain, older))
80
+ rescue Session::NotFound => e
81
+ Log.warn(:worker, "prune_missing", id: entry.id, msg: e.message)
82
+ end
83
+
84
+ # The chain from the head back to the anchor, head first.
85
+ def chain_back(entry, links)
29
86
  chain = []
30
87
  id = entry.head
31
- seen = []
32
- while id && !seen.include?(id)
33
- seen << id
88
+ while id && !chain.include?(id)
34
89
  chain << id
35
90
  # The walk stops at the anchor: the links before it are the user's own
36
91
  # history, made before this schedule existed, and the anchor itself is
@@ -42,42 +97,108 @@ module Samagotchi
42
97
  session = links.session(id) || (File.exist?(Session.session_file(id, state_dir: @state_dir)) ? Session.load(id, state_dir: @state_dir) : nil)
43
98
  id = session&.continues
44
99
  end
45
- older = chain[entry.keep_links..] || []
46
- return if older.empty?
100
+ chain
101
+ end
47
102
 
103
+ # +older+ deleted oldest first, each link under the exclusive
104
+ # transition locks (kind :delete, one try) of it and the link after
105
+ # it, its hold checked again under them.
106
+ # @return [Array(String, String), nil] the link the prune stopped at
107
+ # and why, nil when it got through
108
+ def prune_links(entry, chain, older)
48
109
  older.reverse_each do |link|
49
- next if link == entry.anchor
50
- next if link_gone?(link)
51
- break unless ArchiveStore.archived?(Session.session_dir(link, state_dir: @state_dir))
52
-
53
- tree = SessionManager.delete_tree_ids(link, @state_dir)
54
- descendants = tree[0...-1]
55
- # The whole subtree must be ready: a live worker anywhere in it, or a
56
- # link's descendant that is not archived, stops the walk here rather
57
- # than half-deleting a tree.
58
- owned = tree.select { |sid| SessionManager.session_owner(sid, state_dir: @state_dir) }
59
- unless owned.empty?
60
- Log.warn(:worker, "prune_waiting", sid: link, id: entry.id, owned: owned.map { |sid| sid[0, 8] })
61
- break
62
- end
110
+ next if link == entry.anchor || link_gone?(link)
111
+
112
+ reason = prune_hold(link)
113
+ return [link, reason] if reason
114
+
115
+ following = chain[chain.index(link) - 1]
116
+ stopped = SessionTransition.exclusive([link, following], kind: :delete, state_dir: @state_dir, deadline: 0) do
117
+ reason = prune_hold(link)
118
+ next [link, reason] if reason
63
119
 
64
- open = descendants.reject { |sid| ArchiveStore.archived?(Session.session_dir(sid, state_dir: @state_dir)) }
65
- unless open.empty?
66
- Log.warn(:worker, "prune_open_children", sid: link, id: entry.id, open: open.map { |sid| sid[0, 8] })
67
- break
120
+ tree = SessionManager.delete_tree_ids(link, @state_dir)
121
+ # Children first (deepest first), the link last: if a delete is
122
+ # refused partway, nothing above it has gone, so the next try
123
+ # finds the same set instead of children under a deleted link.
124
+ SessionManager.delete_ids(tree, state_dir: @state_dir)
125
+ Log.info(:worker, "pruned_link", sid: link, id: entry.id, links: tree.size)
126
+ nil
68
127
  end
128
+ return stopped if stopped
129
+ rescue SessionTransition::Busy => e
130
+ return [link, e.message]
131
+ rescue SessionManager::DeleteRefused => e
132
+ return [link, e.session_id == link ? e.message : "#{e.session_id.to_s[0, 8]}: #{e.message}"]
133
+ end
134
+ nil
135
+ end
69
136
 
70
- # Children first (deepest first), the link last: if a delete is
71
- # refused partway, nothing above it has gone, so the next firing
72
- # retries the same set instead of leaving children under a link that
73
- # is already deleted.
74
- SessionManager.delete_ids(tree, state_dir: @state_dir)
75
- Log.info(:worker, "pruned_link", sid: link, id: entry.id, links: descendants.size + 1)
137
+ # Why +link+ (behind the window) can't go now, nil when it can: not
138
+ # archived (a user brought it back), a schedule's anchor, head or
139
+ # target in its subtree (another entry anchored inside the chain), a
140
+ # live worker in it, or a descendant not archived. The whole subtree
141
+ # must be ready: never half a tree.
142
+ def prune_hold(link)
143
+ return "it is not archived" unless ArchiveStore.archived?(Session.session_dir(link, state_dir: @state_dir))
144
+
145
+ tree = SessionManager.delete_tree_ids(link, @state_dir)
146
+ tree.reverse_each do |sid|
147
+ SessionManager.refuse_protected!(sid, @state_dir)
148
+ rescue SessionManager::DeleteRefused => e
149
+ return sid == link ? e.message : "its delegate #{sid[0, 8]}: #{e.message}"
76
150
  end
77
- rescue SessionManager::DeleteRefused => e
78
- Log.warn(:worker, "prune_stopped", sid: e.session_id, id: entry.id, msg: e.message)
79
- rescue Session::NotFound => e
80
- Log.warn(:worker, "prune_missing", id: entry.id, msg: e.message)
151
+ owned = tree.select { |sid| SessionManager.session_owner(sid, state_dir: @state_dir) }
152
+ return "a worker runs in it: #{owned.map { |sid| sid[0, 8] }.join(", ")}" unless owned.empty?
153
+
154
+ open = tree[0...-1].reject { |sid| ArchiveStore.archived?(Session.session_dir(sid, state_dir: @state_dir)) }
155
+ "its delegates are not archived: #{open.map { |sid| sid[0, 8] }.join(", ")}" unless open.empty?
156
+ end
157
+
158
+ # Record where +entry+'s prune waits (+waiting+: [link, reason]) or
159
+ # that it waits nowhere (nil), under the file's lock, on the stored
160
+ # entry; logged (prune_waiting) once per link it waits at, not every
161
+ # tick. Nothing is written when the entry's record (read with it)
162
+ # says the same.
163
+ def note_waiting(entry, waiting)
164
+ link, reason = waiting
165
+ was = PrunePart.waiting(entry)
166
+ return if was.nil? && link.nil?
167
+ return if was && was.link == link && was.reason == reason
168
+
169
+ logged = false
170
+ write_under_lock do |file|
171
+ position = file.entries.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
172
+ next unless position
173
+
174
+ stored = file.entries[position]
175
+ before = PrunePart.waiting(stored)
176
+ extra = stored.extra.except(PRUNE_WAITING)
177
+ if link
178
+ at = before&.link == link ? before.at : @clock.call.utc.iso8601
179
+ extra = extra.merge(PRUNE_WAITING => { "link" => link, "reason" => reason, "at" => at })
180
+ logged = before&.link != link
181
+ end
182
+ file.entries[position] = stored.with(extra: extra)
183
+ end
184
+ Log.warn(:worker, "prune_waiting", sid: link, id: entry.id, msg: reason) if logged
185
+ end
186
+
187
+ # The chain's newest link when removing +removed+ from +entries+ (the
188
+ # file's list, under its lock) takes away the last bridge over its
189
+ # anchor's gap (SessionChain::Links#anchor_forward), else nil. A disabled
190
+ # entry still bridges, so only a cancel ends one. The heads are given,
191
+ # not read: the file still holds the entry.
192
+ # @return [String, nil]
193
+ def cancel_strands(entries, removed)
194
+ return nil if removed.head == removed.anchor
195
+
196
+ before = SessionChain::Links.new(state_dir: @state_dir, anchor_heads: heads_by_anchor(entries))
197
+ return nil unless before.anchor_forward(removed.anchor)
198
+
199
+ rest = entries.reject { |entry| entry.equal?(removed) }
200
+ after = SessionChain::Links.new(state_dir: @state_dir, anchor_heads: heads_by_anchor(rest))
201
+ after.anchor_forward(removed.anchor) ? nil : before.latest(removed.anchor)
81
202
  end
82
203
 
83
204
  # Neither a session file nor a folder: nothing left to delete.
@@ -18,6 +18,7 @@ require_relative "delivery"
18
18
  require_relative "log"
19
19
  require_relative "session"
20
20
  require_relative "session_chain"
21
+ require_relative "session_chain/successor"
21
22
  require_relative "session_inbox"
22
23
  require_relative "session_manager"
23
24
  require_relative "session_row"
@@ -80,9 +81,12 @@ module Samagotchi
80
81
  # A schedule prompt is a chain link's first message or a turn's prompt: the
81
82
  # same limit the note inbox uses.
82
83
  PROMPT_MAX_BYTES = SessionInbox::NOTE_MAX_BYTES
83
- # A chain firing can wait 30 s for a recap and 5 s for an archive; 5 s
84
- # more leaves margin before an unfinished turn is called interrupted.
85
- FIRING_TIMEOUT = 40
84
+ # A chain firing can wait 30 s for a recap (SessionContinue::RECAP_WAIT),
85
+ # 10 s for the transition locks on each of its 3 tries (LOCK_WAIT,
86
+ # TRIES: a last: continue that meets another's lock follows it) and 5 s
87
+ # for an archive; 5 s more leaves margin before an unfinished turn is
88
+ # called interrupted.
89
+ FIRING_TIMEOUT = 70
86
90
  PENDING_MIN_SECONDS = 10 * 60
87
91
  PENDING_MAX_SECONDS = 6 * 60 * 60
88
92
  # A disabled notice older than this is dropped, not pushed: a chi web that
@@ -91,8 +95,11 @@ module Samagotchi
91
95
  # Refusals that mean "not now" rather than "this schedule is broken".
92
96
  # (starting: the link's worker holds no lock yet, e.g. another ticker's
93
97
  # firing just continued the chain.)
98
+ # (transition_busy: a continue of the chain's end held its transition
99
+ # lock past SessionContinue::LOCK_WAIT, or a same-mode turn met a
100
+ # transition holding its target's lock: DeliverResult::BUSY.)
94
101
  SKIP_REASONS = %w[busy queued offer busy_child queued_child offer_child starting starting_child continued
95
- open_children].freeze
102
+ open_children transition_busy].freeze
96
103
 
97
104
  # The add itself is wrong (no prompt, two recurrence kinds, a scratch
98
105
  # target): a usage error, exit 2.
@@ -261,11 +268,7 @@ module Samagotchi
261
268
  # anchor's gap: a paused schedule's chain is still one chain). Lenient and
262
269
  # quiet: a file that doesn't read forwards nothing.
263
270
  # @return [Hash{String => Array<String>}]
264
- def anchor_heads
265
- read(quiet: true).entries.grep(Entry).each_with_object({}) do |entry, heads|
266
- (heads[entry.anchor] ||= []) << entry.head
267
- end
268
- end
271
+ def anchor_heads = heads_by_anchor(read(quiet: true).entries)
269
272
 
270
273
  # One match is the answer; several are a usage error naming them, the way
271
274
  # Session::AmbiguousId does for session prefixes.
@@ -329,8 +332,11 @@ module Samagotchi
329
332
  entry
330
333
  end
331
334
 
332
- # @return [Entry, nil] nil when no schedule matches
333
- def cancel(id_or_name) = change(id_or_name, delete: true) || cancel_unreadable(id_or_name)
335
+ # @return [Cancelled, nil] nil when no schedule matches
336
+ def cancel(id_or_name)
337
+ change(id_or_name, delete: true) || cancel_unreadable(id_or_name)&.then { |record| Cancelled.new(entry: record.raw) }
338
+ end
339
+
334
340
  def enable(id_or_name) = change(id_or_name, enabled: true)
335
341
  def disable(id_or_name) = change(id_or_name, enabled: false)
336
342
 
@@ -493,6 +499,7 @@ module Samagotchi
493
499
  outcomes << outcome
494
500
  prune_after << outcome.entry if outcome.status == "fired" && entry.mode == CHAIN && entry.keep_links.positive?
495
501
  end
502
+ prune_after = prunes_due(prune_after, started) unless dry_run
496
503
  links ||= links_now unless prune_after.empty?
497
504
  prune_after.each { |entry| prune(entry, links) }
498
505
  Tick.new(locked: false, outcomes: dry_run ? outcomes : mark_disabled(outcomes, started, links: links))
@@ -566,6 +573,11 @@ module Samagotchi
566
573
  # one-firing-per-chain guard and the firing see the same chain.
567
574
  def links_now = SessionChain::Links.new(state_dir: @state_dir)
568
575
 
576
+ # #anchor_heads of +entries+ (the readable ones), for PrunePart#cancel_strands too.
577
+ def heads_by_anchor(entries)
578
+ entries.grep(Entry).each_with_object({}) { |entry, heads| (heads[entry.anchor] ||= []) << entry.head }
579
+ end
580
+
569
581
  # @param strict [Boolean] a file that is not readable JSON raises rather
570
582
  # than reading as empty: a write starting from an empty list would rewrite
571
583
  # the file and lose every schedule on it. #entries stays lenient.
@@ -617,7 +629,7 @@ module Samagotchi
617
629
  # an ambiguous one raises Usage rather than taking the first match. nil
618
630
  # too when the entry is gone by the time the lock is held (another cancel
619
631
  # landed in between): the caller says "no schedule", not "ok".
620
- # @return [Entry, nil] the entry as changed (as removed, for a delete)
632
+ # @return [Entry, Cancelled, nil] the entry as changed (Cancelled, for a delete)
621
633
  def change(id_or_name, enabled: nil, delete: false)
622
634
  entry = lookup(id_or_name)
623
635
  return nil if entry.nil?
@@ -628,7 +640,8 @@ module Samagotchi
628
640
  next if position.nil?
629
641
 
630
642
  if delete
631
- result = file.entries[position]
643
+ removed = file.entries[position]
644
+ result = Cancelled.new(entry: removed, newest: cancel_strands(file.entries, removed))
632
645
  file.entries[position] = nil
633
646
  file.entries.compact!
634
647
  else
@@ -924,8 +937,8 @@ module Samagotchi
924
937
  # listing doesn't have yet; the next tick's walk reaches it. Else nil. A
925
938
  # stale intent (no continue holds the lock) is nil: archived it stays.
926
939
  def continuing_reason(link)
927
- successor = ContinueIntent.in_flight(link, state_dir: @state_dir)
928
- successor && "being continued as #{successor[0, 8]}; retry at the next tick"
940
+ successor = SessionChain::Successor.in_flight(link, state_dir: @state_dir)
941
+ successor && "#{SessionChain::Continued.for(link, successor).message}; retry at the next tick"
929
942
  end
930
943
 
931
944
  # Which chain an entry belongs to, for the one-firing-per-chain-per-tick
@@ -1026,6 +1039,10 @@ module Samagotchi
1026
1039
  elsif result.wake_refused?
1027
1040
  # Stopped (or archived) since the tick's check: a skip, as the check's.
1028
1041
  Outcome.new(id: entry.id, title: entry.title, status: "skipped", detail: result.detail, entry: entry)
1042
+ elsif result.busy? || result.continued?
1043
+ # A transition held the target's lock (a continue naming its new
1044
+ # link, or another change): not now, the next tick tries again.
1045
+ classify(entry, result.continued? ? "continued" : SessionManager::DeliverResult::BUSY, result.detail)
1029
1046
  else
1030
1047
  Outcome.new(id: entry.id, title: entry.title, status: "failed",
1031
1048
  detail: "the turn was not accepted (#{result.status}: #{result.error || result.detail})", entry: entry)
@@ -820,7 +820,7 @@ module Samagotchi
820
820
  # A followed send (a head #target resolved) is refused when a continue
821
821
  # took its link since (DeliverResult#continued?): it resolves again
822
822
  # (#follow_again) and goes to the new link, until CONTINUING_WAIT after
823
- # the first refusal; the old link is never sent to.
823
+ # the first refusal; never to the old link. A busy one goes again, the same link too.
824
824
  # @param target [SessionInbox::Resolved] the session (#target)
825
825
  # @yieldparam at [SessionInbox::Resolved] each link about to be sent to
826
826
  # @yieldreturn [Boolean] false: nothing is sent (its line printed)
@@ -849,11 +849,11 @@ module Samagotchi
849
849
  refs = pass.refs
850
850
  delivery = pass.delivery
851
851
  result = pass.result
852
- if result.continued?
852
+ if result.continued? || result.busy?
853
853
  # Copied in before the refusal: not the old link's to keep.
854
854
  @access.discard_images(id, refs)
855
855
  deadline ||= monotonic + self.class::CONTINUING_WAIT
856
- again = follow_again(target, deadline)
856
+ again = follow_again(target, deadline, busy: result.busy?)
857
857
  return unsent(again) if again.is_a?(Unsent)
858
858
  return deliver(again, prompt, deadline: deadline, &before) if again
859
859
  end
@@ -1030,12 +1030,12 @@ module Samagotchi
1030
1030
  # (#deliver): Exchange#relocate, until +deadline+. The new link's
1031
1031
  # worker is the continue's spawn to start (#delivery_note).
1032
1032
  # @return [SessionInbox::Resolved, Unsent, nil] nil: out of time
1033
- def follow_again(refused, deadline)
1034
- again = exchange.relocate(refused, deadline) { |look| (@continued_here ||= {})[look.target.id] = true }
1033
+ def follow_again(refused, deadline, busy: false)
1034
+ again = exchange.relocate(refused, deadline, busy: busy) { |look| (@continued_here ||= {})[look.target.id] = true }
1035
1035
  return nil unless again
1036
1036
  return unsent_of(again) if again.is_a?(SessionAccess::Exchange::Unsent)
1037
1037
 
1038
- (@continued_here ||= {})[again.target.id] = true
1038
+ (@continued_here ||= {})[again.target.id] = true unless busy && again.target.id == refused.id
1039
1039
  again.target
1040
1040
  end
1041
1041
 
@@ -465,6 +465,11 @@ module Samagotchi
465
465
  # not saved.
466
466
  attr_accessor :model_warning
467
467
 
468
+ # The status the session file held when loaded, before the stop marker's
469
+ # overlay (Session.load and .summary_from_file set it; nil for a session
470
+ # built in memory); not saved.
471
+ attr_accessor :loaded_status
472
+
468
473
  # The delegates a continue moved to this new link (ChildMove;
469
474
  # SessionContinue.run sets it); not saved.
470
475
  attr_accessor :moved_children
@@ -653,6 +658,7 @@ module Samagotchi
653
658
 
654
659
  session = from_h(JSON.parse(File.read(path)))
655
660
  session.persisted!
661
+ session.loaded_status = session.status
656
662
  session.status = STATUS_STOPPED if stopped_marker?(session.id, state_dir: state_dir)
657
663
  session.parent_id = parent_override(session.id, state_dir: state_dir) || session.parent_id
658
664
  session
@@ -782,6 +788,7 @@ module Samagotchi
782
788
 
783
789
  session = from_h(data, messages: false)
784
790
  session.persisted!
791
+ session.loaded_status = session.status
785
792
  session.status = STATUS_STOPPED if stopped_marker?(session.id, state_dir: File.dirname(path))
786
793
  session.parent_id = parent_override(session.id, state_dir: File.dirname(path)) || session.parent_id
787
794
  session
@@ -132,11 +132,17 @@ module Samagotchi
132
132
  start ||= @access.prepare_wait(at.id, session: session)
133
133
  more = { enqueued_id: enqueued_id, anchors: anchors }.compact
134
134
  result = @exchange.attempt(at, prompt, client_id: client_id, queue: queue, **more).result
135
- if result.continued?
135
+ if result.continued? || result.busy?
136
136
  follow_until ||= [@clock.call + continuing_wait, ready_by].min
137
- again = @exchange.relocate(at, follow_until, bounded: true)
137
+ again = @exchange.relocate(at, follow_until, bounded: true, busy: result.busy?)
138
138
  return Refused.new(kind: :canceled, session_id: at.id) if cancelled&.call
139
- return Refused.new(kind: :continuing, session_id: at.id, message: result.refusal_text) unless again
139
+
140
+ unless again
141
+ # Still busy at the deadline: the busy refusal as it came.
142
+ return Refused.new(kind: :undelivered, session_id: at.id, result: result) if result.busy?
143
+
144
+ return Refused.new(kind: :continuing, session_id: at.id, message: result.refusal_text)
145
+ end
140
146
  return unsent(again, at.id) if again.is_a?(Exchange::Unsent)
141
147
 
142
148
  at = again.target