samagotchi 0.181.0 → 0.182.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 (67) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +26 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +30 -4
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/block-renderers.md +114 -0
  8. data/docs/internals/bridge.md +10 -0
  9. data/docs/internals/engine.md +11 -0
  10. data/docs/internals/inline-widgets.md +3 -1
  11. data/docs/internals/prompt-caching.md +9 -1
  12. data/docs/internals/remote-sessions.md +14 -2
  13. data/docs/internals/web-frontend.md +33 -3
  14. data/docs/sessions.md +7 -4
  15. data/lib/samagotchi/answer_display.rb +3 -2
  16. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  17. data/lib/samagotchi/block_fix.rb +220 -0
  18. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  19. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  20. data/lib/samagotchi/bridge.rb +11 -2
  21. data/lib/samagotchi/bridge_client.rb +9 -0
  22. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  23. data/lib/samagotchi/config.rb +3 -0
  24. data/lib/samagotchi/continue_intent.rb +8 -0
  25. data/lib/samagotchi/engine/block_fix.rb +332 -0
  26. data/lib/samagotchi/engine/side_requests.rb +7 -5
  27. data/lib/samagotchi/engine.rb +4 -0
  28. data/lib/samagotchi/events.rb +1 -0
  29. data/lib/samagotchi/idle_client.rb +10 -6
  30. data/lib/samagotchi/inline_widgets.rb +12 -0
  31. data/lib/samagotchi/kernel_loop.rb +7 -5
  32. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  33. data/lib/samagotchi/markdown_parser.rb +28 -0
  34. data/lib/samagotchi/session_access/contract.rb +3 -0
  35. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  36. data/lib/samagotchi/session_access/local.rb +13 -0
  37. data/lib/samagotchi/session_access/remote.rb +19 -1
  38. data/lib/samagotchi/session_access.rb +1 -0
  39. data/lib/samagotchi/session_chain/delete.rb +39 -81
  40. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  41. data/lib/samagotchi/session_delete_command.rb +129 -3
  42. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  43. data/lib/samagotchi/session_manager/listing.rb +4 -4
  44. data/lib/samagotchi/session_manager/removal.rb +38 -12
  45. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  46. data/lib/samagotchi/session_manager.rb +1 -0
  47. data/lib/samagotchi/version.rb +1 -1
  48. data/lib/samagotchi/web/app.rb +13 -1
  49. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  50. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  51. data/lib/samagotchi/web/message_display.rb +6 -1
  52. data/lib/samagotchi/web/participant_view.rb +1 -1
  53. data/lib/samagotchi/web/public/app.js +5 -5
  54. data/lib/samagotchi/web/public/block_fix.js +270 -0
  55. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  56. data/lib/samagotchi/web/public/block_frame.js +6 -3
  57. data/lib/samagotchi/web/public/block_host.js +1 -1
  58. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  59. data/lib/samagotchi/web/public/block_watch.js +16 -2
  60. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  61. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  62. data/lib/samagotchi/web/public/turn_block.js +5 -2
  63. data/lib/samagotchi/web/server.rb +6 -4
  64. data/lib/samagotchi/web/session_control.rb +53 -21
  65. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  66. data/lib/samagotchi/worker.rb +10 -3
  67. metadata +12 -1
@@ -320,6 +320,9 @@ module Samagotchi
320
320
  CHAIN_DELETE_FEATURE = "chain_delete"
321
321
  # Web::App::STOP_TASKS_FEATURE: delete and archive take stop_tasks.
322
322
  STOP_TASKS_FEATURE = "stop_tasks"
323
+ # Web::App::DELETE_PLAN_FEATURE: GET …/delete_plan answers for every
324
+ # session, with each choice's delegates, tasks and workers.
325
+ DELETE_PLAN_FEATURE = "delete_plan_all"
323
326
 
324
327
  # The header that chi web names the signed-in user in (GET
325
328
  # /api/info's proxy), nil when it has no such proxy, or is a chi
@@ -538,6 +541,19 @@ module Samagotchi
538
541
  **task_fields(json) }
539
542
  end
540
543
 
544
+ # GET …/delete_plan there: what a delete would do now (chi sessions
545
+ # delete --dry-run), nothing deleted.
546
+ # @return [DeletePlan::Plan]
547
+ # @raise [RemoteTooOld] a chi web without DELETE_PLAN_FEATURE (an
548
+ # older one answers a session in no chain without the plan)
549
+ def delete_plan(id)
550
+ require_feature!(DELETE_PLAN_FEATURE)
551
+ reply = request(:get, "#{session_path(id)}/delete_plan")
552
+ raise_refusal(reply) unless reply.status == 200
553
+
554
+ DeletePlan.read(reply.json)
555
+ end
556
+
541
557
  private def ids_of(value) = Array(value).select { |id| Session.valid_id?(id) }
542
558
 
543
559
  # --- context (a session's own sources: a project's are local only)
@@ -841,7 +857,9 @@ module Samagotchi
841
857
  # Whose worker was stopped (an older chi web sends only the Boolean).
842
858
  stopped = Session.valid_id?(json["stopped_worker"]) ? json["stopped_worker"] : json["worker_stopped"] == true
843
859
  if json["op"] == "archive"
844
- SessionManager::ArchiveRefused.new(sid, :tasks_running, tasks: tasks, worker_stopped: stopped)
860
+ stopped_workers = Array(json["stopped_workers"]).select { |id| id.is_a?(String) && Session.valid_id?(id) }
861
+ SessionManager::ArchiveRefused.new(sid, :tasks_running, tasks: tasks, worker_stopped: stopped,
862
+ sessions: json["sessions"], stopped_workers: stopped_workers)
845
863
  else
846
864
  SessionManager::DeleteRefused.new(sid, :tasks_running, tasks: tasks, worker_stopped: stopped,
847
865
  links: ids_of(json["links"]))
@@ -18,6 +18,7 @@ module Samagotchi
18
18
  autoload :Contract, File.expand_path("session_access/contract", __dir__)
19
19
  autoload :Remote, File.expand_path("session_access/remote", __dir__)
20
20
  autoload :Dispatch, File.expand_path("session_access/dispatch", __dir__)
21
+ autoload :DeletePlan, File.expand_path("session_access/delete_plan", __dir__)
21
22
 
22
23
  # A remote's chi web could not be asked, or answered what this chi can't
23
24
  # use: the message names the remote and what failed ("remote studio
@@ -21,13 +21,14 @@ module Samagotchi
21
21
  autoload :Schedules, File.expand_path("../schedules", __dir__)
22
22
 
23
23
  module SessionChain
24
- # A user's delete of a link of a session chain (the CLI, the web, the
25
- # TUI's /exit --delete: SessionManager.delete_session's revive_previous:
26
- # and refuse_continuing:), and of the whole chain (.chain:
27
- # SessionManager.delete_chain). A session in no chain is deleted as
28
- # before (SessionManager.delete_resolved). The scratch cleanup, the
29
- # empty-session discard, the failed-continue rollback and the prune
30
- # never come here.
24
+ # A user's delete of a session (the CLI, the web, the TUI's /exit
25
+ # --delete: SessionManager.delete_session's revive_previous: and
26
+ # refuse_continuing:), a link of a chain or a session in no chain alike
27
+ # (a link with nothing before it to undo), and of the whole chain
28
+ # (.chain: SessionManager.delete_chain). The scratch cleanup, the
29
+ # empty-session discard, the failed-continue rollback, the prune and
30
+ # retention never come here (SessionManager.delete_resolved and
31
+ # remove_files): they take no delegates.
31
32
  #
32
33
  # - The chain's newest link (not archived itself, its previous link
33
34
  # archived, nobody continuing it) is undone (D2/D5): the delegates its
@@ -36,85 +37,41 @@ module Samagotchi
36
37
  # come back to the lists (ContinuedFrom's record; without one, the
37
38
  # previous link alone). The previous link is not started.
38
39
  # - Any other link (a middle one splits the chain) is deleted alone.
39
- # - Either way the link's own delegates follow DELEGATES (D7).
40
+ # - Either way the link's own delegates follow SessionManager::DELEGATES
41
+ # (D7).
40
42
  module Delete
41
- # What DELEGATES does with a link's delegates: +delete+ (deepest
42
- # first, before the link) and +leave+ (running, with their whole
43
- # subtrees: they go on without a parent, their files untouched).
44
- Plan = Data.define(:delete, :leave)
45
-
46
- # D7, hard-coded for the chain deletes for now (one place, so that a
47
- # policy for every delete can move it into SessionManager later): a
48
- # delegate is running when a worker owns it or is being started for
49
- # it (a one-turn chi run too, which can't be stopped from here). A
50
- # saved status running with no worker is a crashed run: it goes. A running one is left with its whole subtree;
51
- # every other node under the link (no running node between it and the
52
- # link) is deleted.
53
- class DelegateRule
54
- # @param except [Array<String>] the link's children left out with
55
- # their subtrees (the ones the undo gives back)
56
- # @return [Plan]
57
- def plan(link, state_dir:, except: [])
58
- delete = []
59
- leave = []
60
- queue = [link]
61
- until queue.empty?
62
- SessionManager.children_of(queue.shift, state_dir: state_dir).each do |row|
63
- next if row.id == link || except.include?(row.id) || delete.include?(row.id) || leave.include?(row.id)
64
-
65
- if running?(row, state_dir)
66
- leave.concat([row.id, *SessionManager.descendant_ids(row.id, state_dir)] - leave)
67
- else
68
- delete << row.id
69
- queue << row.id
70
- end
71
- end
72
- end
73
- Plan.new(delete: delete.reverse, leave: leave)
74
- end
75
-
76
- private
77
-
78
- def running?(row, state_dir)
79
- presence = WorkerPresence.read(row.id, state_dir: state_dir,
80
- owner: SessionManager.session_owner(row.id, state_dir: state_dir))
81
- presence.owned? || presence.starting?
82
- end
83
- end
84
-
85
- DELEGATES = DelegateRule.new.freeze
86
-
87
43
  module_function
88
44
 
89
45
  # What deleting the link +id+ alone does, read from one listing: the
90
46
  # one plan the delete runs (.link) and the web's sheet shows (.preview).
91
47
  # +previous+: the link whose continue is undone (D2/D5), nil when
92
48
  # none is; +revive+: what comes back to the lists; +moved+: the
93
- # delegates that go back to it; +delegates+: DELEGATES' Plan for the
94
- # rest of its delegates; +notes+: the waiting notes that go back.
49
+ # delegates that go back to it; +delegates+: SessionManager::DELEGATES'
50
+ # Plan for the rest of its delegates; +notes+: the waiting notes that go back.
95
51
  LinkPlan = Data.define(:id, :previous, :revive, :moved, :delegates, :notes)
96
52
 
97
53
  # @param undo [Boolean] the caller undoes a newest link's continue
98
54
  # (revive_previous)
99
55
  # @return [LinkPlan]
100
- def link_plan(id, state_dir:, links:, undo: true)
56
+ def link_plan(id, state_dir:, links:, undo: true, rows: nil)
101
57
  previous = links.continues(id)
102
58
  previous = nil unless undo && previous && revivable?(id, previous, links)
103
- moved = previous ? moved_ids(id, previous, state_dir) : []
59
+ moved = previous ? moved_ids(id, previous, state_dir, rows: rows) : []
104
60
  LinkPlan.new(id: id, previous: previous, revive: previous ? revive_ids(id, previous, state_dir) : [],
105
- moved: moved, delegates: DELEGATES.plan(id, state_dir: state_dir, except: moved),
61
+ moved: moved, delegates: SessionManager::DELEGATES.plan(id, state_dir: state_dir, except: moved, rows: rows),
106
62
  notes: previous ? NoteMove.returnable(from: id, moved: [], state_dir: state_dir).size : 0)
107
63
  end
108
64
 
109
65
  # What deleting every link of +id+'s chain does: the links on its
110
66
  # branch (root to end, past a gap only the part after it), each
111
- # link's DELEGATES plan, and whether a gap cut earlier links off.
67
+ # link's SessionManager::DELEGATES plan, and whether a gap cut earlier links off.
112
68
  ChainPlan = Data.define(:id, :links, :delegates, :cut_off)
113
69
 
114
70
  # @return [ChainPlan]
115
- def chain_plan(id, state_dir:, links:)
71
+ def chain_plan(id, state_dir:, links:, rows: nil)
116
72
  ids = links.live_links(id)
117
- ChainPlan.new(id: id, links: ids, delegates: ids.to_h { |link| [link, DELEGATES.plan(link, state_dir: state_dir)] },
73
+ ChainPlan.new(id: id, links: ids,
74
+ delegates: ids.to_h { |link| [link, SessionManager::DELEGATES.plan(link, state_dir: state_dir, rows: rows)] },
118
75
  cut_off: links.gone?(links.chain(id).first))
119
76
  end
120
77
 
@@ -135,11 +92,12 @@ module Samagotchi
135
92
  end
136
93
 
137
94
  # Whether +id+ is in a chain of 2 or more links that still exist (D1):
138
- # a link alone past a gap (its predecessor deleted) is deleted as a
139
- # session in no chain is.
95
+ # a link alone past a gap (its predecessor deleted) is no chain (the
96
+ # preview's chained: false, the sheet's one choice).
140
97
  def chained?(id, links) = links.live_links(id).size > 1
141
98
 
142
- # Delete the link +id+ (a full id that exists), inside a shared hold
99
+ # Delete the link +id+ (a full id with a file or a folder; a session
100
+ # in no chain is a link with no previous one), inside a shared hold
143
101
  # of its continue lock (and the previous link's when it would come
144
102
  # back), so no continue of either starts meanwhile.
145
103
  # @return [Hash] {id:, removed:, stopped:, unarchived:, moved_back:,
@@ -155,15 +113,7 @@ module Samagotchi
155
113
  ContinueIntent.hold(id, state_dir: state_dir) do |held|
156
114
  raise SessionManager::DeleteRefused.new(id, :continuing) if refuse_continuing && !held
157
115
 
158
- links = Links.new(state_dir: state_dir)
159
- unless chained?(id, links)
160
- raise SessionManager::DeleteRefused.new(id, :plan_changed) unless expect.nil?
161
-
162
- return plain(SessionManager.delete_resolved(id, state_dir: state_dir, stop: stop, wait: wait,
163
- running_tasks: running_tasks))
164
- end
165
-
166
- plan = link_plan(id, state_dir: state_dir, links: links, undo: revive_previous)
116
+ plan = link_plan(id, state_dir: state_dir, links: Links.new(state_dir: state_dir), undo: revive_previous)
167
117
  unless plan.previous
168
118
  return delete_link(plan, state_dir: state_dir, stop: stop, wait: wait, expect: expect,
169
119
  running_tasks: running_tasks)
@@ -188,8 +138,6 @@ module Samagotchi
188
138
  !links.gone?(previous) && links.next_of(id).nil? && !links.archived?(id) && links.archived?(previous)
189
139
  end
190
140
 
191
- def plain(result) = result.merge(unarchived: [], moved_back: [], deleted: [result[:id]], left_running: [])
192
-
193
141
  # The refusals a link's delete makes before anything changes (the
194
142
  # sheet's too): a schedule's target, anchor or head, on the link or a
195
143
  # delegate that would go; a moved delegate that can't go back; a
@@ -246,8 +194,10 @@ module Samagotchi
246
194
 
247
195
  # The worker stopped was the link's, whichever id refused.
248
196
  raise e.with_worker_stopped(id)
197
+ ensure
198
+ # What went, also before a refusal part-way (as delete_links does).
199
+ SessionManager.purge_removal_stores(doomed.reject { |sid| on_disk?(sid, state_dir) }, state_dir: state_dir)
249
200
  end
250
- SessionManager.purge_removal_stores(doomed, state_dir: state_dir)
251
201
  unarchived = plan.revive.select { |sid| ArchiveStore.unarchive(sid, state_dir: state_dir) }
252
202
  { id: id, removed: removed, stopped: stopped, unarchived: unarchived, moved_back: plan.moved,
253
203
  deleted: doomed, left_running: plan.delegates.leave, **running_tasks.result_fields }
@@ -318,8 +268,8 @@ module Samagotchi
318
268
  # one rewrote parent.json's from), else +id+'s children whose
319
269
  # parent.json says they came from +previous+.
320
270
  # @return [Array<String>]
321
- def moved_ids(id, previous, state_dir)
322
- children = SessionManager.children_of(id, state_dir: state_dir).map(&:id)
271
+ def moved_ids(id, previous, state_dir, rows: nil)
272
+ children = SessionManager.children_of(id, state_dir: state_dir, rows: rows).map(&:id)
323
273
  record = ContinuedFrom.read(id, state_dir: state_dir)
324
274
  return record.moved_ids & children if record&.previous_id == previous
325
275
 
@@ -386,8 +336,16 @@ module Samagotchi
386
336
  stopped = plan.links.select do |link|
387
337
  SessionManager.release_for_delete!(link, state_dir: state_dir, stop: stop, wait: wait)
388
338
  end
389
- delete_links(plan, links, state_dir, running_tasks: running_tasks)
390
- .merge(stopped: stopped, cut_off: plan.cut_off, **running_tasks.result_fields)
339
+ begin
340
+ delete_links(plan, links, state_dir, running_tasks: running_tasks)
341
+ .merge(stopped: stopped, cut_off: plan.cut_off, **running_tasks.result_fields)
342
+ rescue SessionManager::DeleteRefused => e
343
+ raise e unless e.reason == :tasks_running && !stopped.empty?
344
+
345
+ # Nothing went (a part-way refusal is in the result): say whose
346
+ # worker was stopped, the refused link's own when it was.
347
+ raise e.with_worker_stopped(stopped.include?(e.session_id) ? e.session_id : stopped.first)
348
+ end
391
349
  end
392
350
  end
393
351
 
@@ -5,51 +5,88 @@ require_relative "delete"
5
5
  module Samagotchi
6
6
  module SessionChain
7
7
  module Delete
8
- # What the web's delete sheet shows for a chained session (GET
8
+ # What the web's delete sheet shows for any session (GET
9
9
  # /api/sessions/:id/delete_plan): the same LinkPlan and ChainPlan the
10
10
  # delete runs, and the refusals the delete's own checks raise now
11
- # (check_link!, check_chain!, the continue holds, a one-turn run). Made
12
- # from one listing each time the sheet opens. It takes and releases
13
- # each link's continue lock (shared, as the delete does), creating its
14
- # empty file where there was none; it writes nothing else. A stale preview is fine:
15
- # the delete builds its plan again and refuses as it does.
11
+ # (check_link!, check_chain!, the continue holds, a one-turn run), with
12
+ # each choice's delegates, running tasks and workers. Made from one
13
+ # shared session listing each time the sheet opens. It read-only checks
14
+ # each link's continue lock (a session in no chain too); besides that,
15
+ # only the listing's own repair of an interrupted continue writes. A
16
+ # stale preview is fine: the delete builds its plan again and refuses as
17
+ # it does.
16
18
  module Preview
17
19
  module_function
18
20
 
19
- # @return [Hash] {chained: false} for a session in no chain, else
21
+ # @return [Hash] {chained: false, session_id, link: {...}} for a
22
+ # session in no chain (an older page reads only chained), else
20
23
  # {chained: true, session_id, position, size, cut_off, link: {...},
21
24
  # chain: {...}}; each refusal {reason, message, schedule_id, ids,
22
- # stoppable} or nil
25
+ # stoppable} or nil. Each choice also has +delegates+ ({delete:
26
+ # [ids], leave: [{id, running}]}: +running+ false for a stopped
27
+ # session left under a running delegate), +tasks+ (RunningTasks.of
28
+ # the ids it deletes, the wire form) and +worker+ (#link_worker; a
29
+ # chain's {idle: n, turn: n} over its links). No titles: the page
30
+ # names each id from its own list.
23
31
  # @param state_dir [String, nil] nil: Session.default_state_dir (chi
24
32
  # web's, as SessionManager's methods take it)
25
33
  def call(id, state_dir:)
26
34
  state_dir ||= Session.default_state_dir
27
35
  links = Links.new(state_dir: state_dir)
28
- return { chained: false, session_id: id } unless Delete.chained?(id, links)
36
+ rows = SessionManager.session_rows(state_dir: state_dir, include_tests: true, include_archived: true)
37
+ this = Delete.link_plan(id, state_dir: state_dir, links: links, rows: rows)
38
+ return { chained: false, session_id: id, link: link_json(this, links, nil, 0, state_dir, rows: rows) } unless Delete.chained?(id, links)
29
39
 
30
- this = Delete.link_plan(id, state_dir: state_dir, links: links)
31
- whole = Delete.chain_plan(id, state_dir: state_dir, links: links)
40
+ whole = Delete.chain_plan(id, state_dir: state_dir, links: links, rows: rows)
32
41
  at = whole.links.index(id) || 0
33
42
  { chained: true, session_id: id, position: at + 1, size: whole.links.size, cut_off: whole.cut_off,
34
- link: link_json(this, links, whole, at, state_dir), chain: chain_json(whole, state_dir) }
43
+ link: link_json(this, links, whole, at, state_dir, rows: rows), chain: chain_json(whole, state_dir) }
35
44
  end
36
45
 
37
- def link_json(plan, links, whole, at, state_dir)
38
- { digest: Delete.digest(plan), previous_id: plan.previous, moved: moved_count(plan, state_dir), notes: plan.notes, unarchived: plan.revive.size,
46
+ # +whole+ nil: a session in no chain (no link before or after it).
47
+ def link_json(plan, links, whole, at, state_dir, rows:)
48
+ { digest: Delete.digest(plan), previous_id: plan.previous, moved: moved_count(plan, state_dir, rows: rows), notes: plan.notes, unarchived: plan.revive.size,
39
49
  deletes: plan.delegates.delete.size, left_running: plan.delegates.leave.size,
40
- earlier: at, next_id: links.next_of(plan.id), later: whole.links.size - at - 1,
50
+ earlier: at, next_id: whole && links.next_of(plan.id), later: whole ? whole.links.size - at - 1 : 0,
51
+ delegates: delegates_json(plan.delegates.delete, plan.delegates.leave, state_dir),
52
+ tasks: tasks_json([*plan.delegates.delete, plan.id], state_dir), worker: link_worker(plan.id, state_dir),
41
53
  refusal: refusal(state_dir) { link_checks(plan, state_dir) } }
42
54
  end
43
55
 
56
+ # The ids that go, and each one left with whether it runs itself (a
57
+ # left running delegate's stopped descendants stay with it).
58
+ def delegates_json(delete, leave, state_dir)
59
+ { delete: delete, leave: leave.map { |sid| { id: sid, running: SessionManager::DELEGATES.running?(sid, state_dir) } } }
60
+ end
61
+
62
+ def tasks_json(ids, state_dir) = SessionManager::RunningTasks.of(ids, state_dir: state_dir).to_wire
63
+
64
+ # "turn" when a worker owns +id+ and its saved status is running,
65
+ # "idle" when a worker owns it or is being started for it, else nil.
66
+ def link_worker(id, state_dir)
67
+ presence = WorkerPresence.read(id, state_dir: state_dir, owner: SessionManager.session_owner(id, state_dir: state_dir))
68
+ return nil unless presence.owned? || presence.starting?
69
+ return "idle" unless presence.owned?
70
+
71
+ Session.load(id, state_dir: state_dir).status == Session::STATUS_RUNNING ? "turn" : "idle"
72
+ rescue Session::NotFound, ArgumentError, SystemCallError
73
+ "idle"
74
+ end
75
+
44
76
  # The sessions that go back with the undo: each moved delegate and
45
77
  # its own subtree (they come back with it).
46
- def moved_count(plan, state_dir)
47
- plan.moved.sum { |child| 1 + SessionManager.descendant_ids(child, state_dir).size }
78
+ def moved_count(plan, state_dir, rows:)
79
+ plan.moved.sum { |child| 1 + SessionManager.descendant_ids(child, state_dir, rows: rows).size }
48
80
  end
49
81
 
50
82
  def chain_json(plan, state_dir)
83
+ delete = plan.delegates.values.flat_map(&:delete)
84
+ leave = plan.delegates.values.flat_map(&:leave).uniq
85
+ workers = plan.links.map { |link| link_worker(link, state_dir) }
51
86
  { digest: Delete.digest(plan), links: plan.links.size, deletes: plan.delegates.values.sum { |d| d.delete.size },
52
87
  left_running: plan.delegates.values.sum { |d| d.leave.size },
88
+ delegates: delegates_json(delete, leave, state_dir), tasks: tasks_json([*plan.links, *delete], state_dir),
89
+ worker: { idle: workers.count("idle"), turn: workers.count("turn") },
53
90
  refusal: refusal(state_dir) { chain_checks(plan, state_dir) } }
54
91
  end
55
92
 
@@ -69,8 +106,7 @@ module Samagotchi
69
106
  end
70
107
 
71
108
  def refuse_continuing!(id, state_dir)
72
- free = ContinueIntent.hold(id, state_dir: state_dir) { |held| held }
73
- raise SessionManager::DeleteRefused.new(id, :continuing) unless free
109
+ raise SessionManager::DeleteRefused.new(id, :continuing) if ContinueIntent.lock_held?(id, state_dir: state_dir)
74
110
  end
75
111
 
76
112
  def tui!(id, state_dir)
@@ -14,7 +14,7 @@ module Samagotchi
14
14
  include CLI::Command
15
15
 
16
16
  USAGE = <<~TEXT
17
- Usage: chi sessions delete [--force] [--chain] [--stop-tasks] (ID|PREFIX)...
17
+ Usage: chi sessions delete [--force] [--chain] [--stop-tasks] [--dry-run] (ID|PREFIX)...
18
18
  Deletes each session: its history, notes, images and queued input.
19
19
  This can't be undone. Deleting a chain's newest link undoes its
20
20
  continue: the previous link comes back to the lists (not started),
@@ -28,13 +28,20 @@ module Samagotchi
28
28
  (TERM, then KILL), then delete; without it a session
29
29
  whose tasks still run is refused. Not --force: a live
30
30
  worker is still refused without it
31
+ --dry-run print what the delete would do (what goes, what is
32
+ stopped first, what stays, and which of --force and
33
+ --stop-tasks it needs) and delete nothing; exits 1
34
+ when it would be refused
31
35
  TEXT
32
36
  PREVIEW_LIMIT = 60
33
37
  FLAGS = CLI::Flags.new(help: CLI::Command::HELP_WORDS) do |f|
34
38
  f.switch "-f", "--force"
35
39
  f.switch "--chain"
36
40
  f.switch "--stop-tasks"
41
+ f.switch "--dry-run"
37
42
  end
43
+ # The width of a --dry-run row's key ("stopped first: ").
44
+ ROW_KEY = 15
38
45
 
39
46
  # @param argv [Array<String>] the arguments after "sessions delete"
40
47
  # @param access [SessionAccess::Local, nil] where the sessions are;
@@ -48,10 +55,12 @@ module Samagotchi
48
55
  end
49
56
 
50
57
  # @return [Integer] exit status: 0 all deleted, 1 any refused or
51
- # unknown, 2 usage
58
+ # unknown, 2 usage; with --dry-run 0 when each would go, 1 when any
59
+ # would be refused or is unknown
52
60
  def run
53
61
  options = parse
54
62
  return options if options.is_a?(Integer)
63
+ return options[:ids].uniq.map { |given| dry_run(given, chain: options[:chain]) }.all? ? 0 : 1 if options[:dry_run]
55
64
 
56
65
  gone = options[:ids].uniq.map do |given|
57
66
  how = { force: options[:force], stop_tasks: options[:stop_tasks] }
@@ -67,7 +76,7 @@ module Samagotchi
67
76
  # @return [Hash, Integer] the options, or the exit status after the
68
77
  # help or a usage error
69
78
  def parse
70
- parsed = parse_flags(FLAGS, @argv, force: false, chain: false, stop_tasks: false)
79
+ parsed = parse_flags(FLAGS, @argv, force: false, chain: false, stop_tasks: false, dry_run: false)
71
80
  return parsed if parsed.is_a?(Integer)
72
81
  return usage_error("give session ids") if parsed.args.empty?
73
82
 
@@ -173,6 +182,123 @@ module Samagotchi
173
182
  false
174
183
  end
175
184
 
185
+ # --dry-run: the plan the delete (+chain+: of the whole chain) would
186
+ # follow now, as the web's sheet says it; nothing is deleted.
187
+ # @return [Boolean] whether it would go (no refusal)
188
+ def dry_run(given, chain:)
189
+ id = @access.resolve_id(given)
190
+ plan = @access.delete_plan(id)
191
+ choice = chain && plan.chain ? plan.chain : plan.link
192
+ short = id[0, 8]
193
+ title = preview_of(id)
194
+ if choice.refusal
195
+ @stdout.puts(["#{short} would be refused: #{refusal_words(choice.refusal, short)}", title && "\"#{title}\""].compact.join(" "))
196
+ return false
197
+ end
198
+
199
+ head = "would delete#{plan_scope(plan, choice)}"
200
+ @stdout.puts(["#{short} #{head}", title && "\"#{title}\""].compact.join(" "))
201
+ plan_rows(choice, id).each { |key, words| @stdout.puts("#{" " * 10}#{"#{key}:".ljust(ROW_KEY)}#{words}") }
202
+ true
203
+ rescue ArgumentError => e
204
+ error_line("chi sessions delete: #{e.message}")
205
+ false
206
+ end
207
+
208
+ # " its chain (3 links)", " link 2 of 3", or "" for a session in no chain.
209
+ def plan_scope(plan, choice)
210
+ return "" unless plan.chained
211
+ return " its chain (#{choice.links} links)" if choice.equal?(plan.chain)
212
+
213
+ " link #{plan.position} of #{plan.size}"
214
+ end
215
+
216
+ # The rows that apply, in the sheet's order: back (the undo), goes,
217
+ # stopped first, stays; the flags the delete needs end the stopped
218
+ # first row (or the stays row: a task chi can't verify still needs
219
+ # --stop-tasks, which never signals it).
220
+ # @return [Array(String, String)] key, words
221
+ def plan_rows(choice, id)
222
+ rows = [["back", back_words(choice)], ["goes", goes_words(choice)], ["stopped first", stopped_words(choice, id)],
223
+ ["stays", stays_words(choice, id)]].reject { |_, words| words.empty? }
224
+ needs = []
225
+ needs << "--force" if choice.workers.positive?
226
+ needs << "--stop-tasks" unless choice.tasks.empty?
227
+ return rows if needs.empty?
228
+
229
+ at = rows.index { |key, _| key == "stopped first" } || rows.index { |key, _| key == "stays" }
230
+ rows[at][1] = "#{rows[at][1]} — needs #{needs.join(", ")}"
231
+ rows
232
+ end
233
+
234
+ def back_words(choice)
235
+ return "" unless choice.previous_id
236
+
237
+ "the previous link #{choice.previous_id[0, 8]} comes back to the lists (not started)" \
238
+ "#{", with #{counted(choice.moved, "delegate")}" if choice.moved.positive?}"
239
+ end
240
+
241
+ def goes_words(choice)
242
+ parts = []
243
+ parts << "all #{choice.links} links" if choice.links > 1
244
+ parts << "#{counted(choice.delete.size, "stopped delegate")} (#{short_ids(choice.delete)})" unless choice.delete.empty?
245
+ parts.join("; ")
246
+ end
247
+
248
+ def stopped_words(choice, id)
249
+ parts = []
250
+ parts << worker_words(choice) if choice.workers.positive?
251
+ running = choice.tasks.running
252
+ parts << "#{counted(running.size, "background task")} (#{task_names(running, id)})" unless running.empty?
253
+ parts.join("; ")
254
+ end
255
+
256
+ def worker_words(choice)
257
+ if choice.links == 1 then choice.turns.positive? ? "its running turn" : "its worker"
258
+ else
259
+ "#{counted(choice.workers, "worker")}#{" (#{choice.turns} running a turn)" if choice.turns.positive?}"
260
+ end
261
+ end
262
+
263
+ def stays_words(choice, id)
264
+ parts = []
265
+ running, under = choice.leave.partition(&:running)
266
+ unless running.empty?
267
+ with = " with #{running.size == 1 ? "its" : "their"} #{counted(under.size, "delegate")}" unless under.empty?
268
+ parts << "#{counted(running.size, "running delegate")} (#{short_ids(running.map(&:id))})#{with}, without a parent"
269
+ end
270
+ doubtful = choice.tasks.unverified + choice.tasks.unreadable
271
+ unless doubtful.empty?
272
+ parts << "#{counted(doubtful.size, "task")} chi can't verify (#{task_names(doubtful, id, short: true)}), left as it is"
273
+ end
274
+ parts.join("; ")
275
+ end
276
+
277
+ # Each task by its command (+short+: by its id), "9d0e1f2a: rspec" for
278
+ # another session's, cut to three, then "+N more".
279
+ def task_names(tasks, id, short: false)
280
+ tasks_module = SessionManager::RunningTasks
281
+ names = tasks.map do |task|
282
+ name = short ? "task #{tasks_module.short_task(task.id)}" : tasks_module.command_name(task)
283
+ task.session_id == id ? name : "#{task.session_id[0, 8]}: #{name}"
284
+ end
285
+ tasks_module.cut(names)
286
+ end
287
+
288
+ def short_ids(ids) = SessionManager::RunningTasks.cut(ids.map { |sid| sid[0, 8] })
289
+
290
+ def counted(count, noun) = "#{count} #{noun}#{"s" unless count == 1}"
291
+
292
+ # The refusal the plan carries, in the words the delete's own
293
+ # refusal line uses.
294
+ def refusal_words(refusal, short)
295
+ case refusal.reason
296
+ when "owned_by_tui" then "it is #{OwnerLock::TUI_BUSY}; let it finish first"
297
+ when "tasks_running" then "#{refusal.message} (#{SessionManager::RunningTasks.hint(nil, "delete", short)})"
298
+ else refusal.message
299
+ end
300
+ end
301
+
176
302
  def preview_of(id)
177
303
  text = @access.show(id).display_title.gsub(/\s+/, " ").strip
178
304
  return nil if text.empty?
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../worker_presence"
4
+
5
+ module Samagotchi
6
+ class SessionManager
7
+ # D7, the rule a user's delete applies to every session's delegates
8
+ # (SessionChain::Delete.link_plan and .chain_plan): a
9
+ # delegate is running when a worker owns it or is being started for it
10
+ # (a one-turn chi run too, which can't be stopped from here). A saved
11
+ # status running with no worker is a crashed run: it goes. A running one
12
+ # is left with its whole subtree; every other node under the session (no
13
+ # running node between it and the session) is deleted.
14
+ #
15
+ # One listing per plan: the rows are read once (.session_rows, archived
16
+ # and test runs too) and the tree is walked in memory. A caller with a
17
+ # shared snapshot can pass +rows+ to reuse it across plans.
18
+ class DelegateRule
19
+ # What the rule does with a session's delegates: +delete+ (deepest
20
+ # first, before the session) and +leave+ (running, with their whole
21
+ # subtrees: they go on without a parent, their files untouched).
22
+ Plan = Data.define(:delete, :leave)
23
+
24
+ # @param except [Array<String>] the session's children left out with
25
+ # their subtrees (the ones a chain link's undo gives back)
26
+ # @return [Plan]
27
+ def plan(id, state_dir:, except: [], rows: nil)
28
+ children = children_by_parent(state_dir, rows)
29
+ delete = []
30
+ leave = []
31
+ queue = [id]
32
+ until queue.empty?
33
+ children.fetch(queue.shift, []).each do |child|
34
+ next if child == id || except.include?(child) || delete.include?(child) || leave.include?(child)
35
+
36
+ if running?(child, state_dir)
37
+ leave.concat([child, *descendants(child, children)] - leave)
38
+ else
39
+ delete << child
40
+ queue << child
41
+ end
42
+ end
43
+ end
44
+ Plan.new(delete: delete.reverse, leave: leave)
45
+ end
46
+
47
+ # Whether the rule counts +id+ as running: a worker owns it or is being
48
+ # started for it. The delete sheet's preview reads it per left node.
49
+ def running?(id, state_dir)
50
+ presence = WorkerPresence.read(id, state_dir: state_dir,
51
+ owner: SessionManager.session_owner(id, state_dir: state_dir))
52
+ presence.owned? || presence.starting?
53
+ end
54
+
55
+ private
56
+
57
+ # Every session's children ids, newest first (.children_of's order),
58
+ # from one .session_rows.
59
+ # @return [Hash{String => Array<String>}]
60
+ def children_by_parent(state_dir, rows)
61
+ (rows || SessionManager.session_rows(state_dir: state_dir, include_tests: true, include_archived: true))
62
+ .each_with_object({}) do |row, by_parent|
63
+ (by_parent[row.parent_id] ||= []) << row.id unless row.parent_id.to_s.empty?
64
+ end
65
+ end
66
+
67
+ # .descendant_ids over the same rows.
68
+ def descendants(id, children)
69
+ seen = [id]
70
+ queue = [id]
71
+ until queue.empty?
72
+ children.fetch(queue.shift, []).each do |child|
73
+ next if seen.include?(child)
74
+
75
+ seen << child
76
+ queue << child
77
+ end
78
+ end
79
+ seen.drop(1)
80
+ end
81
+ end
82
+
83
+ # The one DelegateRule every user's delete uses.
84
+ DELEGATES = DelegateRule.new.freeze
85
+ end
86
+ end
@@ -72,20 +72,20 @@ module Samagotchi
72
72
  # first, as .session_rows. A running one (busy) counts against
73
73
  # session.max_children. Archived ones too.
74
74
  # @return [Array<SessionRow>]
75
- def children_of(parent_id, state_dir: nil)
75
+ def children_of(parent_id, state_dir: nil, rows: nil)
76
76
  return [] if parent_id.to_s.empty?
77
77
 
78
- session_rows(state_dir: state_dir, include_tests: true, include_archived: true)
78
+ (rows || session_rows(state_dir: state_dir, include_tests: true, include_archived: true))
79
79
  .select { |s| s.parent_id == parent_id.to_s }
80
80
  end
81
81
 
82
82
  # Children, their children, …: a delegated session doesn't delegate
83
83
  # further today, a plugin's fork may. The walk doesn't enter +except+.
84
- def descendant_ids(id, state_dir, except: [])
84
+ def descendant_ids(id, state_dir, except: [], rows: nil)
85
85
  seen = [id]
86
86
  queue = [id]
87
87
  until queue.empty?
88
- children_of(queue.shift, state_dir: state_dir).each do |child|
88
+ children_of(queue.shift, state_dir: state_dir, rows: rows).each do |child|
89
89
  next if seen.include?(child.id) || except.include?(child.id)
90
90
 
91
91
  seen << child.id