samagotchi 0.177.0 → 0.178.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 (88) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -1
  3. data/docs/architecture.md +5 -4
  4. data/docs/cli.md +31 -6
  5. data/docs/guardrails.md +1 -1
  6. data/docs/internals/background-tasks.md +23 -2
  7. data/docs/internals/bridge.md +17 -6
  8. data/docs/internals/bundles.md +4 -3
  9. data/docs/internals/participants.md +8 -5
  10. data/docs/internals/remote-sessions.md +6 -1
  11. data/docs/internals/session-lifecycle.md +176 -0
  12. data/docs/internals/web-frontend.md +14 -6
  13. data/docs/internals/working-set.md +33 -6
  14. data/docs/plugins.md +1 -1
  15. data/docs/releasing.md +3 -2
  16. data/docs/scheduling.md +8 -1
  17. data/docs/sessions.md +15 -9
  18. data/docs/testing.md +4 -2
  19. data/lib/samagotchi/bridge/card_store.rb +2 -19
  20. data/lib/samagotchi/bridge.rb +38 -6
  21. data/lib/samagotchi/bundle_command/check.rb +1 -1
  22. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  23. data/lib/samagotchi/compat.rb +0 -7
  24. data/lib/samagotchi/engine/events.rb +43 -0
  25. data/lib/samagotchi/engine/session.rb +7 -0
  26. data/lib/samagotchi/engine.rb +9 -3
  27. data/lib/samagotchi/event_fanout.rb +56 -0
  28. data/lib/samagotchi/guardrails/approvals.rb +0 -4
  29. data/lib/samagotchi/memory_bundle/shipped_update.rb +1 -1
  30. data/lib/samagotchi/note_delivery.rb +9 -4
  31. data/lib/samagotchi/plugin/sessions.rb +2 -1
  32. data/lib/samagotchi/revise_anchor.rb +2 -0
  33. data/lib/samagotchi/schedules.rb +12 -5
  34. data/lib/samagotchi/session_access/contract.rb +4 -0
  35. data/lib/samagotchi/session_access/local.rb +16 -4
  36. data/lib/samagotchi/session_access/remote.rb +42 -9
  37. data/lib/samagotchi/session_archive_command.rb +38 -10
  38. data/lib/samagotchi/session_chain/delete.rb +98 -25
  39. data/lib/samagotchi/session_chain/delete_preview.rb +2 -2
  40. data/lib/samagotchi/session_delete_command.rb +33 -10
  41. data/lib/samagotchi/session_inbox.rb +29 -0
  42. data/lib/samagotchi/session_inbox_delivery.rb +13 -5
  43. data/lib/samagotchi/session_lifecycle/allowed.rb +69 -0
  44. data/lib/samagotchi/session_lifecycle/canonical.rb +49 -0
  45. data/lib/samagotchi/session_lifecycle/reading.rb +65 -0
  46. data/lib/samagotchi/session_lifecycle.rb +59 -0
  47. data/lib/samagotchi/session_manager/delivery.rb +29 -6
  48. data/lib/samagotchi/session_manager/lifecycle.rb +33 -39
  49. data/lib/samagotchi/session_manager/removal.rb +117 -25
  50. data/lib/samagotchi/session_manager/running_tasks.rb +334 -0
  51. data/lib/samagotchi/session_manager/spawn.rb +2 -2
  52. data/lib/samagotchi/sessions_command.rb +1 -1
  53. data/lib/samagotchi/system_prompt.rb +22 -2
  54. data/lib/samagotchi/task_files.rb +37 -4
  55. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +7 -1
  56. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  57. data/lib/samagotchi/terminal_ui/local_link.rb +11 -3
  58. data/lib/samagotchi/tool_names.rb +1 -1
  59. data/lib/samagotchi/tools/memory.rb +29 -0
  60. data/lib/samagotchi/tools/task_runtime.rb +25 -6
  61. data/lib/samagotchi/turn_anchors.rb +5 -0
  62. data/lib/samagotchi/verify_anchor.rb +2 -0
  63. data/lib/samagotchi/version.rb +1 -1
  64. data/lib/samagotchi/web/app.rb +5 -1
  65. data/lib/samagotchi/web/participant_show.rb +3 -4
  66. data/lib/samagotchi/web/participant_view.rb +4 -6
  67. data/lib/samagotchi/web/public/data.js +19 -3
  68. data/lib/samagotchi/web/public/delete_sheet.js +67 -11
  69. data/lib/samagotchi/web/public/running_tasks.js +73 -0
  70. data/lib/samagotchi/web/public/session_actions.js +57 -8
  71. data/lib/samagotchi/web/public/stop_sheet.js +3 -2
  72. data/lib/samagotchi/web/public/working_set.js +3 -28
  73. data/lib/samagotchi/web/public/working_set_view.js +5 -2
  74. data/lib/samagotchi/web/public/ws_item_sig.js +51 -0
  75. data/lib/samagotchi/web/public/ws_peek.js +23 -13
  76. data/lib/samagotchi/web/public/ws_reader.js +22 -12
  77. data/lib/samagotchi/web/public/ws_sections.js +1 -0
  78. data/lib/samagotchi/web/public/ws_timeline.js +9 -6
  79. data/lib/samagotchi/web/session_control.rb +66 -16
  80. data/lib/samagotchi/web/session_summary.rb +7 -0
  81. data/lib/samagotchi/web/working_set_routes.rb +29 -8
  82. data/lib/samagotchi/worker_boot.rb +9 -6
  83. data/lib/samagotchi/worker_link.rb +9 -1
  84. data/lib/samagotchi/worker_presence.rb +4 -0
  85. data/lib/samagotchi/working_set.rb +26 -0
  86. data/lib/samagotchi/working_set_command.rb +10 -7
  87. data/lib/samagotchi/working_set_steer.rb +3 -10
  88. metadata +9 -1
@@ -61,8 +61,8 @@ module Samagotchi
61
61
  # new worker's turn). A card shown between turns (github-pr's offer,
62
62
  # btw, coordinator) keeps its buttons.
63
63
  #
64
- # A file from before the log (version 1) keeps its places: each entry's
65
- # count becomes +base_since+, and new openings add to it (#seed_v1).
64
+ # A file from before the log (version 1) is no longer read; its earlier
65
+ # cards do not show. Version 2 files saved since can still include readable +base_since+ places.
66
66
  class CardStore
67
67
  CAPACITY = 20
68
68
  FORMAT_VERSION = 2
@@ -256,8 +256,6 @@ module Samagotchi
256
256
  @turn_log = data[:turn_log].grep(String)
257
257
  @failed_turn = data[:failed_turn] if data[:failed_turn].is_a?(String)
258
258
  @entries = seeded(document.entries.map { |entry| entry.to_h.transform_keys(&:to_sym) })
259
- elsif data[:turns].is_a?(Integer)
260
- seed_v1(data)
261
259
  end
262
260
  rescue StateFormat::InvalidDocument => e
263
261
  @format_read_only = true
@@ -269,21 +267,6 @@ module Samagotchi
269
267
  @entries = []
270
268
  end
271
269
 
272
- # A file from before the turn log: each entry's place by the count it was
273
- # saved with, killed turn included (nothing in it can say where a drifted
274
- # card was). New openings add to it. The next save keeps +base_since+.
275
- # Can go a retention period after the release that wrote version 2
276
- # (compat shim cards_v1_seed: Compat::SHIMS).
277
- def seed_v1(data)
278
- killed_in_turn = data[:running] == true
279
- turns_done = data[:turns] + (killed_in_turn ? 1 : 0)
280
- olds = data[:entries].select { |entry| entry.is_a?(Hash) && entry[:turns].is_a?(Integer) }
281
- @entries = seeded(olds.map do |entry|
282
- turns = entry[:during] && killed_in_turn ? turns_done : entry[:turns]
283
- entry.except(:turns).merge(base_since: [turns_done - turns - (entry[:in_turn] ? 1 : 0), 0].max)
284
- end)
285
- end
286
-
287
270
  def seeded(entries)
288
271
  entries.filter_map do |entry|
289
272
  next unless entry.is_a?(Hash) && entry[:type].is_a?(String) && sound_place?(entry)
@@ -39,6 +39,7 @@ require_relative "proxy_trace"
39
39
  require_relative "version"
40
40
  require_relative "worker_sidecar"
41
41
  require_relative "worker_link"
42
+ require_relative "working_set"
42
43
  require_relative "relay_verifier"
43
44
  require_relative "relay_watcher"
44
45
  require_relative "reply_wait"
@@ -92,6 +93,7 @@ module Samagotchi
92
93
  request_recap: "idle-recap monitor",
93
94
  reserve_enqueued_id: "turn-state monitor",
94
95
  working_set_snapshot: "idle working-set snapshot under event lock",
96
+ working_set_item: "turn view under its mutex, else session messages under event lock",
95
97
  "running_turn_messages=": "callback writer; Bridge lifecycle",
96
98
  saved_recap: "recap mutex; replace-only session messages",
97
99
  session: "session reference; messages are replace-only",
@@ -803,11 +805,15 @@ module Samagotchi
803
805
  # participant_client_id: it reads a participant's client id as
804
806
  # participant:<id>; chi web sends a worker without it review:<id>
805
807
  # (Delivery::PARTICIPANT_ID_FEATURE).
808
+ # working_set_item: GET working_set/item answers one item's timeline,
809
+ # the running turn's mid-turn (WorkingSet::ITEM_FEATURE); chi web asks
810
+ # an older worker for its whole snapshot instead.
806
811
  FEATURES = ["restart", "task_stop", "reparent", Delivery::QUEUE_FEATURE, ReplyWait::TURN_IDS_FEATURE,
807
812
  VerifyAnchor::FEATURE, ReviseAnchor::FEATURE,
808
813
  SessionInbox::UNQUEUE_FEATURE, Delivery::REVIEW_FEATURE, Delivery::PAIR_FEATURE, TurnDrawings::FEATURE,
809
814
  WorkerLink::ACTIVITY_FEATURE, ObjectivesTrack::FEATURE, Delivery::OWN_TURN_STEER_FEATURE,
810
- Delivery::CANCEL_TURN_ID_FEATURE, ReviseAnchor::PARTICIPANT_FEATURE, Delivery::PARTICIPANT_ID_FEATURE].freeze
815
+ Delivery::CANCEL_TURN_ID_FEATURE, ReviseAnchor::PARTICIPANT_FEATURE, Delivery::PARTICIPANT_ID_FEATURE,
816
+ WorkingSet::ITEM_FEATURE].freeze
811
817
 
812
818
  # The routes, by method and what follows /session/:id/: a handler takes
813
819
  # the session id and the request body and returns [headers, status, body].
@@ -832,9 +838,13 @@ module Samagotchi
832
838
  %w[GET state] => :handle_state,
833
839
  %w[GET stats] => :handle_stats,
834
840
  %w[GET snapshot] => :handle_snapshot,
835
- %w[GET tail] => :handle_tail
841
+ %w[GET tail] => :handle_tail,
842
+ %w[GET working_set/item] => :handle_working_set_item
836
843
  }.freeze
837
844
  ROUTE_PATH = %r{\A/session/([^/]+)/(.+)\z}u
845
+ # The handlers that take the request's query string as a third
846
+ # argument (#dispatch); every other one gets the id and the body only.
847
+ QUERY_HANDLERS = %i[handle_tail handle_working_set_item].freeze
838
848
 
839
849
  # @return [Array(Symbol, String), nil] the handler and the session id, or
840
850
  # nil when no route takes this method and path
@@ -848,10 +858,10 @@ module Samagotchi
848
858
  # #own_session?), and a handler that raises answers 500 bridge_error,
849
859
  # logged (the connection thread doesn't report).
850
860
  # @return [Array(Hash, Integer, Hash)] headers, status, body
851
- # Only GET tail takes the request's +query+.
861
+ # Only a QUERY_HANDLERS handler takes the request's +query+.
852
862
  def dispatch(handler, session_id, body, query = nil)
853
863
  return [{}, 404, { error: "unknown_session" }] unless own_session?(session_id)
854
- return handle_tail(session_id, body, query) if handler == :handle_tail
864
+ return send(handler, session_id, body, query) if QUERY_HANDLERS.include?(handler)
855
865
 
856
866
  send(handler, session_id, body)
857
867
  rescue StandardError => e
@@ -1538,8 +1548,8 @@ module Samagotchi
1538
1548
  end
1539
1549
 
1540
1550
  # The page's light re-read (#tail_frame): no message list. `?turn_id=`:
1541
- # that turn's answer (a queued turn's page re-reads late). The one
1542
- # handler that gets the query (#dispatch); an older worker's route
1551
+ # that turn's answer (a queued turn's page re-reads late). A handler
1552
+ # that gets the query (QUERY_HANDLERS); an older worker's route
1543
1553
  # ignores it and sends the newest answer.
1544
1554
  def handle_tail(_session_id, _body = nil, query = nil)
1545
1555
  turn_id = query && URI.decode_www_form(query).to_h["turn_id"].to_s
@@ -1548,6 +1558,28 @@ module Samagotchi
1548
1558
  [{}, 200, tail_frame]
1549
1559
  end
1550
1560
 
1561
+ # What the model has of one item now (Engine#working_set_item: the
1562
+ # running turn's view as of its last request, else the session's),
1563
+ # chi web's item route's answer. `?kind=&key=[&now=1][&latest=1]`
1564
+ # (latest: the peek's events and counts only); 400 for a
1565
+ # kind not in WorkingSet::KINDS or a blank key, in chi web's words.
1566
+ # Owner-only stays chi web's: the Bridge's gate is its secret.
1567
+ def handle_working_set_item(_session_id, _body = nil, query = nil)
1568
+ params = begin
1569
+ URI.decode_www_form(query.to_s).to_h
1570
+ rescue ArgumentError
1571
+ {}
1572
+ end
1573
+ kind = params["kind"].to_s
1574
+ key = params["key"].to_s
1575
+ unless WorkingSet::KINDS.include?(kind) && !key.strip.empty?
1576
+ return [{}, 400, { error: "invalid_item", detail: WorkingSet::INVALID_ITEM }]
1577
+ end
1578
+
1579
+ item = @engine.working_set_item(kind: kind, key: key, now: params["now"] == "1", latest: params["latest"] == "1")
1580
+ item ? [{}, 200, item] : [{}, 409, { error: "no_session" }]
1581
+ end
1582
+
1551
1583
  # The stream cursor for +seq+ in this worker.
1552
1584
  def event_id(seq)
1553
1585
  EventId.format(seq.to_i, @epoch)
@@ -147,7 +147,7 @@ module Samagotchi
147
147
  end
148
148
 
149
149
  # A source with hooks/*.rb (listed or not) can't be installed: the run
150
- # stops there, as after a manifest error (Installer#refuse_hooks).
150
+ # stops there, as after a manifest error (Manifest::HooksRetired.refuse_source_files).
151
151
  def hooks_retired?
152
152
  files = MemoryBundle::Manifest::HooksRetired.files_in(@dir)
153
153
  return false if files.empty?
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.177.0
3
+ version: 0.178.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -18,13 +18,6 @@ module Samagotchi
18
18
  MIN_AGE_DAYS = 14
19
19
 
20
20
  SHIMS = [
21
- Shim.new(id: :cards_v1_seed, added_in: "0.151.0", added_on: "2026-11-05", remove_after: "0.170.0",
22
- files: ["lib/samagotchi/bridge/card_store.rb"],
23
- what: "CardStore#seed_v1 reads a cards.json from before the turn log; its comment says a retention " \
24
- "period after the release that wrote version 2 (0.151.0, 2026-11-05)"),
25
- Shim.new(id: :approvals_bare_list, added_in: "0.169.0", added_on: "2026-11-12", remove_after: "0.172.0",
26
- files: ["lib/samagotchi/guardrails/approvals.rb"],
27
- what: "Approvals reads the bare list written by chi 0.166 and before, converting it on write"),
28
21
  Shim.new(id: :review_client_id, added_in: "0.172.0", added_on: "2026-11-14", remove_after: "0.173.0",
29
22
  files: ["lib/samagotchi/client_id.rb", "lib/samagotchi/session_manager/delivery.rb",
30
23
  "lib/samagotchi/web/public/turn_events.js", "lib/samagotchi/web/public/viewer_self.js"],
@@ -2,6 +2,8 @@
2
2
 
3
3
  require_relative "../memory_orphans"
4
4
  require_relative "../project_id_clash"
5
+ require_relative "../event_fanout"
6
+ require_relative "../memory_paths"
5
7
  require_relative "../working_set"
6
8
 
7
9
  module Samagotchi
@@ -86,6 +88,47 @@ module Samagotchi
86
88
  pins: session.working_set_pins)
87
89
  end
88
90
 
91
+ # The conversation the working set is built from now: the running
92
+ # turn's view as of its last request (EventFanout#turn_view), else a
93
+ # copy of the session's messages (a starting turn shares their entries
94
+ # and writes them in place: Engine#turn_messages), taken under the
95
+ # event lock as #working_set_snapshot's callers read them. nil with no
96
+ # session.
97
+ # @return [EventFanout::TurnView, nil]
98
+ def working_set_view
99
+ @event_fanout.turn_view || synchronize_events do
100
+ session = @session
101
+ if session
102
+ messages = clone_messages(session.messages)
103
+ EventFanout::TurnView.new(turn_id: nil, conversation: messages, at: messages.size,
104
+ strategy: working_set_strategy, cwd: session.working_directory)
105
+ end
106
+ end
107
+ end
108
+
109
+ # What the model has of one item (WorkingSet.timeline_of's to_h), from
110
+ # #working_set_view: the Bridge's GET working_set/item. +now+ (a
111
+ # memory): its text now (WorkingSet.memory_now). +latest+: only what
112
+ # the peek draws (Timeline#peek_h). +at+ is the view's size, +running+
113
+ # whether it is a running turn's (+turn_id+ then names it). nil with
114
+ # no session.
115
+ # @return [Hash, nil]
116
+ def working_set_item(kind:, key:, now: false, latest: false)
117
+ view = working_set_view or return nil
118
+
119
+ conversation = view.conversation
120
+ strategy = view.strategy
121
+ cwd = view.cwd
122
+ timeline = WorkingSet.timeline_of(conversation, kind: kind, key: key, strategy: strategy, cwd: cwd)
123
+ body = latest ? timeline.peek_h : timeline.to_h
124
+ if now && kind == WorkingSet::MEMORY
125
+ body[:now] = WorkingSet.memory_now(conversation, key: key, strategy: strategy, cwd: cwd,
126
+ root: MemoryPaths.system_dir)&.to_h
127
+ end
128
+ body[:turn_id] = view.turn_id if view.turn_id
129
+ body.merge(at: view.at, running: view.turn_id ? true : turn_running?)
130
+ end
131
+
89
132
  # ── Load events ───────────────────────────────────────────────────────
90
133
 
91
134
  # Announce what failed to load and what plugins showed while loading,
@@ -29,6 +29,13 @@ module Samagotchi
29
29
  names.map { |name| name.to_s.strip }.reject(&:empty?).uniq.sort
30
30
  end
31
31
 
32
+ # @return [Array<Array(String, String, nil)>] prompt memory names and scopes
33
+ def prompt_memories
34
+ memories = Array(@prompt_builder.prompt_memories) + Array(prompt_notes).map { |note| [note.name, note.scope] }
35
+ memories.map { |name, scope| [name.to_s.strip, scope] }.reject { |name, _| name.empty? }.uniq
36
+ .sort_by { |name, scope| [name, scope.to_s] }
37
+ end
38
+
32
39
  # @return [Array<String>] the names the session preloads (config baseline
33
40
  # + --memory, minus mutes), known before the prompt is built, unlike
34
41
  # #activated_memory_names
@@ -29,6 +29,7 @@ require_relative "context_window"
29
29
  require_relative "kernel_loop"
30
30
  require_relative "reprefill_meter"
31
31
  require_relative "tools/builtins"
32
+ require_relative "tools/task_runtime"
32
33
  require_relative "tools/tool_index"
33
34
  require_relative "tools/tool_surface"
34
35
  require_relative "peer_sources"
@@ -674,8 +675,9 @@ module Samagotchi
674
675
  # The session's worker (or a one-shot run) is leaving (/exit, an idle
675
676
  # exit, a crash, TERM): stop the idle jobs, give the running anytime commands
676
677
  # up to +join_timeout+ seconds to finish (their command_ran is
677
- # announced), then stop the plugins' services, newest first. Once;
678
- # later calls do nothing.
678
+ # announced), and settle already-reaped tasks under a shared deadline
679
+ # of at least TaskRuntime::SETTLE_ON_EXIT_SECONDS. Then stop the plugins'
680
+ # services, newest first. Once; later calls do nothing.
679
681
  # @return [self]
680
682
  def shutdown(join_timeout: SHUTDOWN_JOIN_SECONDS)
681
683
  threads = @lifecycle_mutex.synchronize do
@@ -689,12 +691,15 @@ module Samagotchi
689
691
  # callers haven't stopped it already.
690
692
  @idle_scheduler&.stop
691
693
  @prompt_warmup.stop
692
- deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + join_timeout
694
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
695
+ deadline = started + join_timeout
693
696
  threads.each do |thread|
694
697
  next if thread == Thread.current
695
698
 
696
699
  thread.join([deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max)
697
700
  end
701
+ settle_deadline = started + [join_timeout, Tools::TaskRuntime::SETTLE_ON_EXIT_SECONDS].max
702
+ Tools::TaskRuntime.settle_pending!(timeout: [settle_deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max)
698
703
  @side_judgments.join(SIDE_JUDGMENTS_JOIN_SECONDS)
699
704
  # The warm-up's answer is dropped anyway.
700
705
  @toolkit_suggestion.stop_warmup
@@ -735,6 +740,7 @@ module Samagotchi
735
740
  revises = @verify_anchors.stamp_opening(kept, turn, outcome)
736
741
  kept_range!(event, turn, kept)
737
742
  replace_session_messages(turn.session, kept) if kept
743
+ @event_fanout.drop_turn_view
738
744
  verdict = @verify_anchors.record_verdict(turn, outcome)
739
745
  event[:verdict] = verdict if verdict
740
746
  event[:revises] = revises.to_h if revises
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "hooks"
4
+ require_relative "llm_context_view"
4
5
  require_relative "log"
5
6
  require_relative "steer_cut"
6
7
 
@@ -18,6 +19,14 @@ module Samagotchi
18
19
  # notify takes the event lock, as before. #announce_or_hold stays the
19
20
  # Engine's: its thread-local is keyed on the Engine.
20
21
  class EventFanout
22
+ # What the running turn's model has, as of its last request: a shallow
23
+ # copy of the turn's +conversation+ (#keep_turn_view), its size (+at+,
24
+ # the :working_set_updated's), the set's +strategy+ and the session's
25
+ # folder (+cwd+). +turn_id+ is the turn it was taken in: a reader
26
+ # takes it only while that turn runs (#turn_view). Built from the
27
+ # session's messages, turn_id is nil (Engine#working_set_view).
28
+ TurnView = Data.define(:turn_id, :conversation, :at, :strategy, :cwd)
29
+
21
30
  # @param observer [#call] → SessionObserver
22
31
  # @param used_memories [#call] → UsedMemories
23
32
  # @param muted [#call] → Array<String>, the muted memory names
@@ -60,6 +69,26 @@ module Samagotchi
60
69
  @announce_or_hold = announce_or_hold
61
70
  @keep_context_status = keep_context_status
62
71
  @working_set_emitted = nil
72
+ @turn_view = nil
73
+ @turn_view_lock = Mutex.new
74
+ end
75
+
76
+ # The running turn's TurnView, nil between turns, before its first
77
+ # request and once another turn runs: the same guard as
78
+ # Engine#live_conversation (the turn id), so a turn's end, cancel or
79
+ # failure needs no clear. Any thread.
80
+ # @return [TurnView, nil]
81
+ def turn_view
82
+ view = @turn_view_lock.synchronize { @turn_view }
83
+ running = turn_context
84
+ view if view && running && view.turn_id == running.id
85
+ end
86
+
87
+ # The turn's end (Engine#end_turn, under the event lock, before its
88
+ # :working_set_updated): the session's kept messages are the truth from
89
+ # then on, though the turn still reads as running until it has ended.
90
+ def drop_turn_view
91
+ @turn_view_lock.synchronize { @turn_view = nil }
63
92
  end
64
93
 
65
94
  # Always return a handler so raw kernel loop events reach the persistent
@@ -91,6 +120,7 @@ module Samagotchi
91
120
  steer_cut.observe(event, progress)
92
121
  case event[:type]
93
122
  when :generation_started
123
+ keep_turn_view
94
124
  event = event.merge(model_ref: model_ref) if model_ref
95
125
  thinking_notices.generation_started
96
126
  watch&.started(event[:iteration])
@@ -153,6 +183,32 @@ module Samagotchi
153
183
  Log.warn(:turn, "working_set_failed", error: e.class.name, msg: e.message.to_s[0, 200])
154
184
  end
155
185
 
186
+ # A TurnView of what this request sends (the loops start a generation
187
+ # after their apply_llm_context!), on the turn's thread, at every
188
+ # request: an edit or a forget can change what the model has without
189
+ # changing the set's rows, so it never waits for #emit_working_set's
190
+ # dedupe. Before the event goes out, so a client that reads the item
191
+ # on it finds this step. A copy, not the live Array: the turn's thread
192
+ # writes its entries in place (LLMContextEdit.store's :edits) while a
193
+ # Bridge thread reads. Shallow is enough: in-turn writers change only
194
+ # top-level keys (LLMContextEdit.store/.remove replace :edits, the
195
+ # forget store, ChatLoop's :interrupted; KernelLoop appends or pops).
196
+ def keep_turn_view
197
+ running = turn_context
198
+ conversation = live_conversation
199
+ current = session
200
+ return unless running && conversation && current
201
+
202
+ copy = conversation.map(&:dup)
203
+ view = TurnView.new(turn_id: running.id, conversation: copy, at: copy.size,
204
+ strategy: working_set_llm_context&.strategy || LLMContextView::NONE,
205
+ cwd: current.working_directory)
206
+ @turn_view_lock.synchronize { @turn_view = view }
207
+ rescue StandardError => e
208
+ Log.warn(:turn, "turn_view_failed", error: e.class.name, msg: e.message.to_s[0, 200])
209
+ end
210
+ private :keep_turn_view
211
+
156
212
  # The strategy the set is built under: the running turn's
157
213
  # (TurnSettings#llm_context: what its requests send), the last turn's
158
214
  # while the running one has no settings yet (before Engine#generate);
@@ -190,10 +190,6 @@ module Samagotchi
190
190
  def parse(text)
191
191
  data = JSON.parse(text)
192
192
  case data
193
- when Array
194
- # compat shim approvals_bare_list
195
- document = FORMAT.read({ COLLECTION => data }, collection: COLLECTION)
196
- [document.entries.map(&:raw).select { |e| e.is_a?(Hash) }, document]
197
193
  when Hash
198
194
  raise JSON::ParserError, "#{COLLECTION} is not a list" unless data.fetch(COLLECTION, []).is_a?(Array)
199
195
 
@@ -203,7 +203,7 @@ module Samagotchi
203
203
  return skip(row, "needs chi #{manifest.requires_chi}", keep_to: true)
204
204
  end
205
205
 
206
- # The upgrade would refuse it (Installer#refuse_hooks).
206
+ # The upgrade would refuse it (Manifest::HooksRetired.refuse_source_files).
207
207
  hooks = Manifest::HooksRetired.files_in(row.source_dir)
208
208
  return skip(row, Manifest::HooksRetired.for_files(hooks).message, keep_to: true) unless hooks.empty?
209
209
  return skip(row, "project scope: chi bundle upgrade #{ship.source} in the project") if row.scope == "project"
@@ -48,16 +48,21 @@ module Samagotchi
48
48
  # resolved already (SessionInbox::Head.resolve(:note, id)): no second walk
49
49
  # @return [Result]
50
50
  # @raise [SessionInbox::NoteRejected] an empty note or one over 16 KiB
51
- # @raise [Session::NotFound] no such session
51
+ # @raise [Session::NotFound] no such session, or one being deleted
52
52
  def deliver(id, text:, source:, state_dir:, from_session: nil, from_cwd: nil, objectives: nil, pin: false,
53
53
  resolved: nil)
54
54
  body = SessionInbox.checked_text(text)
55
+ path = nil
55
56
  delivered = SessionInbox.deliver(:note, id, state_dir: state_dir, pin: pin, resolved: resolved) do |at|
56
- SessionInbox.write_note(at, text: body, source: source, from_session: from_session, from_cwd: from_cwd,
57
- objectives: objectives, state_dir: state_dir)
57
+ path = SessionInbox.write_note(at, text: body, source: source, from_session: from_session, from_cwd: from_cwd,
58
+ objectives: objectives, state_dir: state_dir)
58
59
  false
59
60
  end
60
- raise Session::NotFound, id if delivered.wake == :gone
61
+ # A session being deleted is a gone one; a delete that took its lock
62
+ # after the write gets the note back (unless a worker read it already).
63
+ raise Session::NotFound, id if delivered.wake == :gone ||
64
+ (delivered.wake == :deleting &&
65
+ (path.nil? || SessionInbox.withdraw(path, delivered.id, state_dir: state_dir)))
61
66
 
62
67
  Result.new(id: delivered.id, asked: delivered.asked, status: delivered.status, queued: delivered.queued || 0,
63
68
  scratch: delivered.refused? && delivered.wake == :scratch)
@@ -99,7 +99,8 @@ module Samagotchi
99
99
  # @return [String] the id of the session it went to
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
- # archived session: session_stopped / session_archived), or delivery is
102
+ # archived session: session_stopped / session_archived; one being
103
+ # deleted: session_deleting), or delivery is
103
104
  # :cut or unknown
104
105
  def send(id, text, delivery: nil)
105
106
  raise Error, "nothing to send" if text.to_s.strip.empty?
@@ -24,6 +24,8 @@ module Samagotchi
24
24
  def to_h = { turn_id: }
25
25
 
26
26
  def to_file = { "turn_id" => turn_id }
27
+
28
+ def participant_view = { "turn_id" => turn_id }
27
29
  end
28
30
 
29
31
  ReviseAnchor::FEATURE = "revise"
@@ -964,19 +964,24 @@ module Samagotchi
964
964
  end
965
965
 
966
966
  # Two paths (FR7): a live worker is asked through its Bridge; with no
967
- # worker the files say what the tick can know. A session its owner
968
- # stopped is a skip first, in both modes: a schedule restarts nothing
969
- # the owner stopped (deliver_turn would refuse a same-mode firing too,
970
- # SessionManager::DeliverResult::STOPPED, in the same words).
967
+ # worker the files say what the tick can know. A session being deleted
968
+ # is a skip first, then one its owner stopped, in both modes: a schedule
969
+ # restarts nothing the owner stopped (deliver_turn would refuse a same-mode
970
+ # firing too, SessionManager::DeliverResult::STOPPED, in the same words).
971
971
  def busy_reason(entry, links, target)
972
972
  dir = Session.session_dir(target, state_dir: @state_dir)
973
973
  owner = SessionManager.session_owner(target, state_dir: @state_dir)
974
974
  presence = WorkerPresence.read(target, state_dir: @state_dir, owner: owner, link: :look)
975
+ return [:skip, SessionManager::DeliverResult::DELETING["detail"]] if presence.deleting?
975
976
  return [:skip, SessionManager::DeliverResult::STOPPED["detail"]] if presence.stop_marked?
976
977
 
977
978
  link = presence.link
978
979
 
979
980
  if presence.worker_owned?
981
+ # A newer worker's Bridge cannot be asked; updating chi or restarting
982
+ # chi web fixes it, and max_skips still bounds a stuck schedule.
983
+ return [:skip, link.short_message] if link.is_a?(WorkerLink::Skew)
984
+
980
985
  # A worker that has not published its Bridge yet (or is closing it):
981
986
  # nothing can be read from it, and firing now would race with it.
982
987
  return [:skip, "its worker is starting or leaving"] unless presence.live?
@@ -1002,7 +1007,9 @@ module Samagotchi
1002
1007
  # an open session is fine, so same mode does not count streams.
1003
1008
  return [:skip, "a terminal or a web tab is open on it"] if entry.mode == CHAIN && activity[:open_streams].to_i.positive?
1004
1009
 
1005
- nil
1010
+ # An idle live worker: free, whatever a starting marker its own
1011
+ # start left (Worker#start clears it just after the lock).
1012
+ return nil
1006
1013
  end
1007
1014
  # A worker being started for it holds no lock yet (another ticker's
1008
1015
  # firing just continued the chain to it, a resume): a chain firing
@@ -113,10 +113,14 @@ module Samagotchi
113
113
  "sessions stop" => SUPPORTED,
114
114
  "sessions restart" => SUPPORTED,
115
115
  "sessions archive" => SUPPORTED,
116
+ # A chi web without stop_tasks (Remote#archive and #delete check its
117
+ # feature) refuses with RemoteTooOld.
118
+ "sessions archive --stop-tasks" => SUPPORTED,
116
119
  "sessions unarchive" => SUPPORTED,
117
120
  "sessions delete" => SUPPORTED,
118
121
  "sessions delete --force" => SUPPORTED,
119
122
  "sessions delete --chain" => SUPPORTED,
123
+ "sessions delete --stop-tasks" => SUPPORTED,
120
124
  "sessions prune" => LOCAL_ONLY,
121
125
  "sessions clean" => LOCAL_ONLY,
122
126
  "sessions stats" => LOCAL_ONLY,
@@ -286,7 +286,9 @@ module Samagotchi
286
286
  def restart(id) = SessionManager.restart_session(id, **dir)
287
287
 
288
288
  # @return [SessionManager::ArchiveResult]
289
- def archive(id) = SessionManager.archive_session(id, **dir)
289
+ # @param stop_tasks [Boolean] stop the background tasks it or a
290
+ # delegate started that still run (else ArchiveRefused :tasks_running)
291
+ def archive(id, stop_tasks: false) = SessionManager.archive_session(id, running_tasks: tasks_policy(stop_tasks), **dir)
290
292
 
291
293
  # @return [Hash] SessionManager.unarchive_session's
292
294
  def unarchive(id) = SessionManager.unarchive_session(id, **dir)
@@ -295,13 +297,23 @@ module Samagotchi
295
297
  # @return [Hash] SessionManager.delete_session's
296
298
  # A user's delete: SessionManager.delete_session's revive_previous: and
297
299
  # refuse_continuing: (D2/D5), on unless told otherwise.
298
- def delete(id, force:, revive_previous: true, refuse_continuing: true)
300
+ # @param stop_tasks [Boolean] stop the background tasks the deleted
301
+ # sessions started that still run (else DeleteRefused :tasks_running)
302
+ def delete(id, force:, stop_tasks: false, revive_previous: true, refuse_continuing: true)
299
303
  SessionManager.delete_session(id, stop: force, revive_previous: revive_previous,
300
- refuse_continuing: refuse_continuing, **dir)
304
+ refuse_continuing: refuse_continuing, running_tasks: tasks_policy(stop_tasks), **dir)
301
305
  end
302
306
 
303
307
  # Every link of the chain (SessionManager.delete_chain).
304
- def delete_chain(id, force:) = SessionManager.delete_chain(id, stop: force, **dir)
308
+ def delete_chain(id, force:, stop_tasks: false)
309
+ SessionManager.delete_chain(id, stop: force, running_tasks: tasks_policy(stop_tasks), **dir)
310
+ end
311
+
312
+ # A user's delete or archive: REFUSE, or a stop by "user".
313
+ private def tasks_policy(stop_tasks)
314
+ policies = SessionManager::RunningTasks::Policy
315
+ stop_tasks ? policies.stop(by: "user") : policies::REFUSE
316
+ end
305
317
 
306
318
  # --- context (a session's sources, or a project's: local only)
307
319
  #