samagotchi 0.161.0 → 0.163.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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +41 -1
  3. data/docs/architecture.md +2 -2
  4. data/docs/cli.md +1 -1
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/block-renderers.md +3 -2
  7. data/docs/internals/bridge.md +85 -22
  8. data/docs/internals/inline-widgets.md +6 -3
  9. data/docs/internals/web-frontend.md +1 -1
  10. data/docs/memory.md +8 -2
  11. data/docs/sessions.md +1 -1
  12. data/docs/testing.md +13 -1
  13. data/lib/samagotchi/bridge/card_store.rb +23 -13
  14. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -1
  15. data/lib/samagotchi/bridge/turn_drawings/synth.rb +559 -0
  16. data/lib/samagotchi/bridge/turn_drawings.rb +118 -7
  17. data/lib/samagotchi/bridge/turn_ranges.rb +175 -0
  18. data/lib/samagotchi/bridge.rb +35 -12
  19. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  20. data/lib/samagotchi/plugin/sessions.rb +8 -1
  21. data/lib/samagotchi/project_command.rb +74 -6
  22. data/lib/samagotchi/project_id_clash.rb +1 -1
  23. data/lib/samagotchi/project_subfolders.rb +188 -0
  24. data/lib/samagotchi/terminal_ui/join_replay.rb +36 -130
  25. data/lib/samagotchi/terminal_ui.rb +12 -1
  26. data/lib/samagotchi/version.rb +1 -1
  27. data/lib/samagotchi/web/message_display.rb +58 -37
  28. data/lib/samagotchi/web/public/app.js +8 -7
  29. data/lib/samagotchi/web/public/block_frame.js +5 -1
  30. data/lib/samagotchi/web/public/data.js +4 -6
  31. data/lib/samagotchi/web/public/reload_check.js +7 -4
  32. data/lib/samagotchi/web/public/time_gaps.js +1 -2
  33. data/lib/samagotchi/web/public/timing.js +52 -216
  34. data/lib/samagotchi/web/public/turn_block.js +46 -124
  35. data/lib/samagotchi/web/public/turn_html.js +3 -2
  36. data/lib/samagotchi/web/public/widget_walk.js +4 -2
  37. data/lib/samagotchi/web/reload_check_route.rb +6 -3
  38. data/lib/samagotchi/web/session_show.rb +23 -28
  39. metadata +4 -1
@@ -5,6 +5,8 @@ require "fileutils"
5
5
  require "json"
6
6
  require_relative "../log"
7
7
  require_relative "../message_time"
8
+ require_relative "../context_note"
9
+ require_relative "../degrade"
8
10
  require_relative "../steer"
9
11
 
10
12
  module Samagotchi
@@ -31,17 +33,18 @@ module Samagotchi
31
33
  # SessionObserver's delivery: the line is on disk before any stream gets
32
34
  # the end frame. That departs from SessionObserver's "enqueue-only" note,
33
35
  # as CardStore's save does: one append per turn end.
36
+ # Both read TurnDrawings at load: loaded on first use (no require cycle).
37
+ autoload :TurnRanges, File.expand_path("turn_ranges", __dir__)
38
+
34
39
  class TurnDrawings
40
+ autoload :Synth, File.expand_path("turn_drawings/synth", __dir__)
41
+
35
42
  FILE = "turn_drawings.jsonl"
36
43
  # In the sidecar's features (Bridge::FEATURES): this worker's CardStore
37
44
  # lists an in-turn entry's of_turn, which a page drawing the turn needs
38
45
  # to leave that entry to the drawing. chi web draws no drawings for a
39
46
  # live worker without it (an older one: its rows would show twice).
40
47
  FEATURE = "turn_drawings"
41
- # A show draws at most this many turns from their drawings, the newest
42
- # (the payload and the page's offscreen render stay bounded in a long
43
- # session); older turns draw as before, from their messages.
44
- SHOWN_MAX = 100
45
48
  VERSION = 1
46
49
  # The end event's keys the page draws a finished turn's end from (not
47
50
  # the answer: its text, html and refs stay the message's; not the range:
@@ -190,7 +193,8 @@ module Samagotchi
190
193
 
191
194
  lines = parse(File.binread(path))
192
195
  cache_mutex.synchronize do
193
- cache.shift while cache.size >= CACHE_SIZE
196
+ cache.delete(path)
197
+ cache.shift while !cache.empty? && (cache.size >= CACHE_SIZE || cache.sum { |_, (k, _)| k[0] } + stat.size > CACHE_BYTES)
194
198
  cache[path] = [key, lines]
195
199
  end
196
200
  lines
@@ -224,6 +228,105 @@ module Samagotchi
224
228
  kept.sort_by(&:from)
225
229
  end
226
230
 
231
+ # The lines a show draws the session's finished turns from: pure,
232
+ # over the file's +lines+ (.read) and the session's +messages+. The
233
+ # valid ones (.valid), and for each turn (TurnRanges) no valid line
234
+ # overlaps, a line made from its messages (Synth, memoized per
235
+ # range), so every finished turn has one. +timing+: the session's
236
+ # records (turn_records, tool_records: the show's timing payload);
237
+ # +entries+: CardStore's listed entries (the show's cards);
238
+ # +skip_turn_id+: the running turn's id (its messages may be in
239
+ # while its line isn't written yet: never synthesized). A file whose
240
+ # lines can't be checked counts as none: every turn synthesized.
241
+ # @return [Array<Line>] ordered by their range
242
+ def cover(lines, messages, timing: nil, entries: [], skip_turn_id: nil, session_id: nil, cwd: nil)
243
+ messages = Array(messages)
244
+ real = Degrade.call(:web, "turn_drawings_unreadable", fallback: []) { valid(lines, messages) }
245
+ ranges = TurnRanges.of(messages)
246
+ records = TurnRanges.records(ranges, list_of(timing, :turn_records))
247
+ taken = real.to_set(&:turn_id)
248
+ tools = list_of(timing, :tool_records).group_by { |t| field(t, :turn_id) }
249
+ own = Array(entries).select { |e| e.is_a?(Hash) && field(e, :of_turn) }.group_by { |e| field(e, :of_turn) }
250
+ made = uncovered(ranges, real).filter_map do |i, part|
251
+ next if skip_turn_id && ranges[i].turn_id == skip_turn_id
252
+
253
+ # A made range whose id a kept line has (a failed turn's kept
254
+ # steps, then its re-run under the same turn id: .valid keeps the
255
+ # newest line for an id) is renamed "<id>~<from>": never two
256
+ # lines with one id (the page would draw them as one turn), and
257
+ # not its turn's own (no end turn_id, no record).
258
+ range = taken.include?(part.id) ? part.with(id: "#{part.id}~#{part.from}") : part
259
+ # A piece with its turn's opening is that turn's (by its own id,
260
+ # else by place for a turn saved before turn ids); one without
261
+ # (a Continue's steps after a lined turn) has no record.
262
+ record = records[i] if range.opening && (range.turn_id.nil? || range.own_id?)
263
+ # The turn's tool records by its record's id, else its own (a
264
+ # record lost, its tool records saved: the TUI's join does so too).
265
+ tool_id = record ? field(record, :id) : (range.turn_id if range.own_id?)
266
+ Synth.memoized(session_id, messages, range, record: record, tools: tool_id ? tools.fetch(tool_id, []) : [],
267
+ entries: own.fetch(range.turn_id, []), cwd: cwd)
268
+ end
269
+ (real + made).sort_by(&:from)
270
+ end
271
+
272
+ # The parts of +ranges+ no line of +lines+ (sorted by from, apart)
273
+ # overlaps, as [range index, range]: a range none overlaps whole,
274
+ # and a range one covers in part (a Continue's steps read as the
275
+ # turn before's, TurnRanges, with only one of the two lined) split
276
+ # at the lines' bounds, so no turn item is left without a line. One
277
+ # walk over both.
278
+ def uncovered(ranges, lines)
279
+ at = 0
280
+ ranges.each_with_index.flat_map do |range, i|
281
+ at += 1 while at < lines.size && lines[at].to >= 0 && lines[at].to <= range.from
282
+ from = range.from
283
+ gaps = []
284
+ (at...lines.size).each do |k|
285
+ break unless lines[k].from < range.to
286
+
287
+ gaps << [from, lines[k].from] if lines[k].from > from
288
+ from = [from, lines[k].to].max
289
+ end
290
+ gaps << [from, range.to] if from < range.to
291
+ gaps.map { |a, b| [i, piece(range, a, b)] }
292
+ end
293
+ end
294
+ private :uncovered
295
+
296
+ # +range+'s messages [+from+, +to+): the range itself when whole; a
297
+ # part with its opening keeps its id; one without is made up
298
+ # ("<id>~<from>", no turn id: no record, no CardStore entries).
299
+ def piece(range, from, to)
300
+ return range if from == range.from && to == range.to
301
+
302
+ opening = range.opening && (range.opening < range.from ? from == range.from : (from...to).cover?(range.opening))
303
+ return range.with(from: from, to: to) if opening
304
+
305
+ TurnRanges::Range.new(from: from, to: to, id: "#{range.id}~#{from}", turn_id: nil, opening: nil)
306
+ end
307
+ private :piece
308
+
309
+ # A fork's drawings (Plugin::Sessions#fork, before its child's worker
310
+ # spawns: no other writer): the lines of +from_dir+'s file that hold
311
+ # against the child's seed +messages+ (same indices, same ends; a range
312
+ # whose end the image copy changed doesn't), written as the child's
313
+ # file. A seed without the system head (a plugin's ctx.messages) is
314
+ # read as the child's messages will be once its first turn puts the
315
+ # head back at index 0 (ContextNote.with_system_head): the lines keep
316
+ # the parent's indices, and hold from then on. Its other turns are
317
+ # made from their messages at read.
318
+ # @return [Integer] the lines carried
319
+ def carry(from_dir:, to_dir:, messages:)
320
+ seed = Array(messages)
321
+ seed = [{ role: "system", content: "" }] + seed unless ContextNote.system_head?(seed.first)
322
+ lines = valid(read(from_dir), seed)
323
+ return 0 if lines.empty?
324
+
325
+ FileUtils.mkdir_p(to_dir)
326
+ File.write(File.join(to_dir, FILE), lines.map { |line| "#{JSON.generate(line.to_h)}\n" }.join, perm: 0o600)
327
+ lines.size
328
+ end
329
+
227
330
  # The last parseable line of +path+, or nil.
228
331
  # @return [Line, nil]
229
332
  def tail_line(path)
@@ -256,16 +359,24 @@ module Samagotchi
256
359
  message.key?(key) ? message[key] : message[key.to_s]
257
360
  end
258
361
 
362
+ def field(hash, key) = hash.is_a?(Hash) ? fetch(hash, key) : nil
363
+
364
+ def list_of(timing, key) = Array(timing.is_a?(Hash) ? fetch(timing, key) : nil).grep(Hash)
365
+
259
366
  def cache = (@cache ||= {})
260
367
  def cache_mutex = (@cache_mutex ||= Mutex.new)
261
368
  end
262
369
 
263
370
  # Sessions whose parsed file chi web keeps (a long one's is tens of MB
264
- # of objects; the mtime moves at every turn end anyway).
371
+ # of objects; the mtime moves at every turn end anyway), and the files'
372
+ # bytes they may sum to (the newest one is always kept). Both bound the
373
+ # files' and lines' JSON bytes, not the heap: parsed lines take several
374
+ # times that (as Synth::MEMO_BYTES does).
265
375
  CACHE_SIZE = 8
376
+ CACHE_BYTES = 64 * 1024 * 1024
266
377
  # Read from the end at start (#last): a drawing is a few KB, its outputs cut.
267
378
  TAIL_BYTES = 1024 * 1024
268
- private_constant :CACHE_SIZE, :TAIL_BYTES
379
+ private_constant :CACHE_SIZE, :CACHE_BYTES, :TAIL_BYTES
269
380
  end
270
381
  end
271
382
  end
@@ -0,0 +1,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../context_note"
4
+ require_relative "../steer"
5
+ require_relative "../turn_note"
6
+ require_relative "turn_drawings"
7
+
8
+ module Samagotchi
9
+ class Bridge
10
+ # A session's messages cut into turns the way the Engine cuts a turn's
11
+ # own messages (its end event's `kept_from`/`kept_to`, Engine#end_turn),
12
+ # read back from the messages alone: what a turn drawing names (its
13
+ # from/to) for a turn that has none (Bridge::TurnDrawings).
14
+ #
15
+ # A turn starts at the reminder lines just before its opening (they
16
+ # went into it: `kept_from` sits before the due reminders), else at its
17
+ # opening (Steer.turn_opening?: a prompt, a wake turn's report), else at
18
+ # the first message after a wake turn's note (the note was there before
19
+ # the turn began: outside, the turn's opening by its id), else at a
20
+ # message no opening came before (a reminder's or a Continue's turn: no
21
+ # prompt). It ends at its last own message: context notes after it, a
22
+ # `!cmd`'s record and a wake's note stay outside, between the turns.
23
+ # A Continue's steps right after the turn it continues read as that
24
+ # turn's (no message tells them apart), as the page groups them.
25
+ module TurnRanges
26
+ # One turn's messages, `messages[from...to]`.
27
+ # +id+: the turn's display id: its opening's turn_id, else
28
+ # "m<from>-<digest8>" (a turn saved before turn ids, a turn with no
29
+ # opening); a later range repeating an id gets "<id>~<from>", so no two
30
+ # ranges share one. +turn_id+: the opening's own turn_id (nil for none).
31
+ # +opening+: the opening's index (a wake note's sits before +from+),
32
+ # nil for a turn with none.
33
+ Range = Data.define(:from, :to, :id, :turn_id, :opening) do
34
+ def range = (from...to)
35
+
36
+ # Whether +id+ is a turn's own (not made up here): what an action
37
+ # (Revise, the answer's key) may carry.
38
+ def own_id? = !turn_id.nil? && id == turn_id
39
+ end
40
+
41
+ REMINDER = "[SYSTEM: REMINDERS DUE "
42
+
43
+ module_function
44
+
45
+ # @param messages [Array<Hash>] a session's messages (symbol or string keys)
46
+ # @return [Array<Range>] oldest first
47
+ def of(messages)
48
+ list = Array(messages)
49
+ cuts = cut(list)
50
+ seen = {}
51
+ cuts.map do |from, to, opening|
52
+ turn_id = opening && fetch(list[opening], :turn_id)
53
+ turn_id = nil unless turn_id.is_a?(String) && !turn_id.empty?
54
+ id = turn_id || "m#{from}-#{TurnDrawings.digest(list[from])[0, 8]}"
55
+ id = "#{id}~#{from}" if seen.key?(id)
56
+ seen[id] = true
57
+ Range.new(from: from, to: to, id: id, turn_id: turn_id, opening: opening)
58
+ end
59
+ end
60
+
61
+ # Each range's turn record (the session's timing turn records, string
62
+ # or symbol keys): the one with its turn's id, else, for a turn saved
63
+ # before turn ids, the record at its place among the turns with an
64
+ # opening, a failure's that kept nothing not counted (its prompt went
65
+ # back: no opening; the page's timing.js promptRecord rule). A range
66
+ # whose id repeats an earlier one's (…~N) gets none: whose it is
67
+ # can't be told.
68
+ # @return [Array<Hash, nil>] one per range
69
+ def records(ranges, turn_records)
70
+ records = Array(turn_records).grep(Hash)
71
+ placed = records.reject { |record| unopened_record?(record) }
72
+ by_id = {}
73
+ records.each { |record| by_id[fetch(record, :id)] ||= record }
74
+ place = -1
75
+ ranges.map do |range|
76
+ place += 1 if range.opening
77
+ if range.turn_id
78
+ range.own_id? ? by_id[range.turn_id] : nil
79
+ elsif range.opening
80
+ placed[place]
81
+ end
82
+ end
83
+ end
84
+
85
+ # [from, to, opening] per turn.
86
+ def cut(list)
87
+ out = []
88
+ turn = nil
89
+ pending = nil
90
+ close = lambda do
91
+ out << [turn[:from], turn[:last] + 1, turn[:opening]] if turn && turn[:last]
92
+ turn = nil
93
+ end
94
+ list.each_with_index do |message, i|
95
+ next unless message.is_a?(Hash)
96
+
97
+ if Steer.shell_line?(message)
98
+ close.call
99
+ pending = nil
100
+ elsif fetch(message, :role).to_s == "system"
101
+ if Steer.turn_prompt?(message)
102
+ # A wake's note: the turn it opens starts after it.
103
+ close.call
104
+ pending = nil
105
+ turn = { from: nil, last: nil, opening: i, turn_id: fetch(message, :turn_id) }
106
+ elsif reminder?(message)
107
+ close.call if turn&.dig(:last)
108
+ pending ||= i
109
+ elsif rolled_back?(message)
110
+ # A failure that handed its prompt back (TurnNote.failed, no work
111
+ # kept): the failed turn's own range, its note alone, as the
112
+ # Engine kept it; never the turn before's.
113
+ close.call if turn&.dig(:last)
114
+ out << [pending || i, i + 1, nil]
115
+ turn = nil
116
+ pending = nil
117
+ elsif TurnNote.note?(message)
118
+ turn ||= { from: pending || i, last: nil, opening: nil }
119
+ turn[:from] ||= pending || i
120
+ turn[:last] = i
121
+ pending = nil
122
+ end
123
+ # A context note, the system head: nobody's own.
124
+ elsif Steer.turn_opening?(message)
125
+ id = fetch(message, :turn_id)
126
+ if turn && id && turn[:turn_id] == id && Steer.input?(message)
127
+ # A second opening line of the turn (a wake turn's report after its note).
128
+ turn[:from] ||= pending || i
129
+ turn[:last] = i
130
+ else
131
+ close.call
132
+ turn = { from: pending || i, last: i, opening: i, turn_id: id }
133
+ end
134
+ pending = nil
135
+ else
136
+ turn ||= { from: pending || i, last: nil, opening: nil }
137
+ turn[:from] ||= pending || i
138
+ turn[:last] = i
139
+ pending = nil
140
+ end
141
+ end
142
+ close.call
143
+ out
144
+ end
145
+ private_class_method :cut
146
+
147
+ # The note of a failure that kept nothing (TurnNote.failed, not
148
+ # .failed_after): its prompt went back or its turn left no step.
149
+ def rolled_back?(message)
150
+ TurnNote.note?(message) && fetch(message, :content).to_s.start_with?(TurnNote::OPEN + TurnNote::FAILED)
151
+ end
152
+ private_class_method :rolled_back?
153
+
154
+ # A turn record that left no opening (a failure that kept nothing:
155
+ # its prompt went back): it has no place among the openings.
156
+ def unopened_record?(record)
157
+ failure = fetch(record, :failure)
158
+ fetch(record, :status).to_s == "failed" && failure.is_a?(Hash) && !fetch(failure, :kept_steps)
159
+ end
160
+ private_class_method :unopened_record?
161
+
162
+ def reminder?(message)
163
+ !ContextNote.note?(message) && fetch(message, :content).to_s.start_with?(REMINDER)
164
+ end
165
+ private_class_method :reminder?
166
+
167
+ def fetch(hash, key)
168
+ return nil unless hash.is_a?(Hash)
169
+
170
+ hash.key?(key) ? hash[key] : hash[key.to_s]
171
+ end
172
+ private_class_method :fetch
173
+ end
174
+ end
175
+ end
@@ -23,6 +23,7 @@ require_relative "bridge/ring_buffer"
23
23
  require_relative "bridge/sse_writer"
24
24
  require_relative "bridge/turn_accumulator"
25
25
  require_relative "bridge/turn_drawings"
26
+ require_relative "bridge/turn_ranges"
26
27
  require_relative "session"
27
28
  require_relative "engine"
28
29
  require_relative "system_one/log"
@@ -327,11 +328,12 @@ module Samagotchi
327
328
  # working_set: the running turn's last :working_set_updated ({items:,
328
329
  # at:}, TurnAccumulator#working_set), which the messages lag; nil
329
330
  # between turns and before the turn emitted one.
330
- # last_turn_drawing: the last exchange's turn as live drew it
331
- # ({drawing:, end:}, TurnDrawings#last, not unfolded: an attaching TUI
332
- # unfolds it, TurnAccumulator.replay_events), only while it holds against
333
- # these messages and ends at their end; absent otherwise (a rollback, a
334
- # later Continue or note, an older worker's file).
331
+ # last_turn_drawing: the last prompt's turn as live drew it ({drawing:,
332
+ # end:}, the file's line for that turn id, not unfolded: an attaching
333
+ # TUI unfolds it, TurnAccumulator.replay_events), only while it holds
334
+ # against these messages; a reminder's, a Continue's or a note after it
335
+ # hides it no more. Absent otherwise (no prompt with a turn id, a
336
+ # rollback, an older worker's file).
335
337
  # @return [Hash] {messages:, current_turn:, working_set:, queued:, queued_commands:, recap:, saved_recap:, continue_offer:, pending_question:,
336
338
  # guardrail_warning:, plugin_warning:, init_tasks:, cards:, commands:, chi_version:, event_seq:, event_id:, last_turn_drawing:}
337
339
  def snapshot
@@ -361,20 +363,41 @@ module Samagotchi
361
363
  end
362
364
  end
363
365
 
364
- # The newest drawing (TurnDrawings#last) as the snapshot sends it, when
365
- # it is the last exchange's: its range still holds against +messages+
366
- # and ends at their end, and is no bigger than a restart reads back
367
- # (TurnDrawings.sendable?). nil otherwise.
366
+ # The last prompt's drawing as the snapshot sends it: the turn an
367
+ # attaching TUI draws (TerminalUI::JoinReplay: the last user message
368
+ # that opens a turn), its newest line that still holds against
369
+ # +messages+, the one this worker wrote last (TurnDrawings#last) else
370
+ # the file's (TurnDrawings.read, cached by its size and mtime), and no
371
+ # bigger than a restart reads back (TurnDrawings.sendable?). Only when
372
+ # it is the last turn (TurnRanges: notes after it are fine): a join
373
+ # draws the line's rows and then the newest answer, so a later turn's
374
+ # (a reminder's, a Continue's) would sit under the prompt's rows
375
+ # without its own. nil otherwise.
368
376
  # @return [Hash, nil] {drawing:, end:} (string keys inside, as the file)
369
377
  def last_turn_drawing(messages)
370
- line = @drawings.last
371
- return nil unless line && line.to == messages.size && TurnDrawings.holds?(line, messages)
372
- return nil unless TurnDrawings.sendable?(line)
378
+ id = last_prompt_turn_id(messages)
379
+ return nil unless id
380
+
381
+ line = [@drawings.last].compact.find { |l| l.turn_id == id && TurnDrawings.holds?(l, messages) } ||
382
+ TurnDrawings.read(session_dir).reverse_each.find { |l| l.turn_id == id && TurnDrawings.holds?(l, messages) }
383
+ return nil unless line && TurnDrawings.sendable?(line)
384
+ return nil unless TurnRanges.of(messages).last&.to == line.to
373
385
 
374
386
  { drawing: line.drawing, end: line.end }
375
387
  end
376
388
  private :last_turn_drawing
377
389
 
390
+ # The turn id of the last user message that opens a turn
391
+ # (Steer.turn_prompt?, as JoinReplay finds the prompt it draws), nil
392
+ # for none or one with no id (a `!cmd`'s record, a line from before
393
+ # turn ids).
394
+ def last_prompt_turn_id(messages)
395
+ prompt = messages.reverse_each.find { |m| m.is_a?(Hash) && (m[:role] || m["role"]).to_s == "user" && Steer.turn_prompt?(m) }
396
+ id = prompt && (prompt[:turn_id] || prompt["turn_id"])
397
+ id.is_a?(String) && !id.empty? ? id : nil
398
+ end
399
+ private :last_prompt_turn_id
400
+
378
401
  # The snapshot and the session state (status, pending question, ...) as
379
402
  # one step of the event log, both as of the same event_seq: what a
380
403
  # snapshot or reset frame (SSEWriter) and GET snapshot carry.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.161.0
3
+ version: 0.163.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:
@@ -5,6 +5,8 @@ require_relative "../delivery"
5
5
  require_relative "../session"
6
6
  require_relative "../worker_link"
7
7
  require_relative "../bridge/turn_accumulator"
8
+ require_relative "../bridge/turn_drawings"
9
+ require_relative "../degrade"
8
10
  require_relative "../tools/delegate"
9
11
  require_relative "../children_status"
10
12
  require_relative "../context_move"
@@ -63,9 +65,14 @@ module Samagotchi
63
65
  check_children(parent_id, state_dir) if prompt
64
66
 
65
67
  # The fork takes this session's movable attached context, its
66
- # subscriptions as its seed last had them.
68
+ # subscriptions as its seed last had them, and the drawings of the
69
+ # turns its seed keeps as they were (Bridge::TurnDrawings.carry).
67
70
  before_spawn = lambda do |forked|
68
71
  ContextMove.call(from: parent_id, to: forked.id, mode: :fork, seed: forked.messages, state_dir: state_dir)
72
+ Degrade.call(:plugins, "fork_drawings_not_carried", fallback: 0) do
73
+ Bridge::TurnDrawings.carry(from_dir: Session.session_dir(parent_id, state_dir: state_dir),
74
+ to_dir: Session.session_dir(forked.id, state_dir: state_dir), messages: forked.messages)
75
+ end
69
76
  end
70
77
  child = SessionManager.spawn_session(
71
78
  prompt: prompt, working_directory: @host.cwd.call || Dir.pwd, model_name: @host.model_name&.call,
@@ -7,6 +7,7 @@ require_relative "guardrails/path_resolve"
7
7
  require_relative "memory_paths"
8
8
  require_relative "paths"
9
9
  require_relative "project_init"
10
+ require_relative "project_subfolders"
10
11
 
11
12
  module Samagotchi
12
13
  # `chi project`: which project this folder is in (MemoryPaths.lookup: a
@@ -19,7 +20,7 @@ module Samagotchi
19
20
  include CLI::Command
20
21
 
21
22
  USAGE = <<~TEXT
22
- Usage: chi project [init [--new-id] [DIR]]
23
+ Usage: chi project [init [--new-id | --merge-subfolders] [DIR]]
23
24
  (none) this folder's project: how it was found (git, marker or none), its root, its
24
25
  top, its id and its project memories folder
25
26
  init [DIR] make DIR (default: this folder; created when missing) a chi project: writes
@@ -29,12 +30,20 @@ module Samagotchi
29
30
  marked folder with no id: adopts one, moving its folders to it
30
31
  --new-id a marked folder's own new id (a copied folder going its own way): its
31
32
  memories and project context copied to it
33
+ --merge-subfolders
34
+ move the memories sessions saved in DIR's subfolders before init (each
35
+ keyed by its subfolder's path) into the project's; one the project has by
36
+ that name stays and is named. Marks DIR first when it isn't yet. Not while
37
+ a session in DIR runs
32
38
  TEXT
33
39
 
34
40
  SUBCOMMANDS = %w[init].freeze
35
41
  FLAGS = {
36
42
  nil => CLI::Flags.new(help: HELP_WORDS, args: false),
37
- "init" => CLI::Flags.new(help: HELP_WORDS) { |f| f.switch "--new-id" }
43
+ "init" => CLI::Flags.new(help: HELP_WORDS) do |f|
44
+ f.switch "--new-id"
45
+ f.switch "--merge-subfolders"
46
+ end
38
47
  }.freeze
39
48
 
40
49
  # @param cwd [String] the folder asked about (Dir.pwd)
@@ -68,8 +77,15 @@ module Samagotchi
68
77
  return run_show unless @sub
69
78
  return usage_error("init takes one folder") if parsed.args.size > 1
70
79
 
80
+ if parsed.options[:new_id] && parsed.options[:merge_subfolders]
81
+ return usage_error("--merge-subfolders and --new-id don't go together")
82
+ end
83
+
71
84
  dir = File.expand_path(parsed.args.first || @cwd, @cwd)
72
- parsed.options[:new_id] ? run_new_id(dir) : run_init(dir)
85
+ return run_new_id(dir) if parsed.options[:new_id]
86
+ return run_merge(dir) if parsed.options[:merge_subfolders]
87
+
88
+ run_init(dir)
73
89
  end
74
90
 
75
91
  private
@@ -89,6 +105,8 @@ module Samagotchi
89
105
  row("id", found.id) if found.id
90
106
  row("memories", memories_line(found))
91
107
  notes(found).each { |note| row("note", note) }
108
+ subfolders_note = found.marker? && subfolders_message(found.root)
109
+ row("note", subfolders_note) if subfolders_note
92
110
  CLI::Exit::OK
93
111
  end
94
112
 
@@ -124,7 +142,9 @@ module Samagotchi
124
142
  !@home.to_s.empty? && Guardrails::PathResolve.real(found.top) == Guardrails::PathResolve.real(@home)
125
143
  end
126
144
 
127
- def run_init(dir)
145
+ # @param merging [Boolean] --merge-subfolders follows: no subfolders line
146
+ def run_init(dir, merging: false)
147
+ @merging = merging
128
148
  outcome = ProjectInit.adopt(dir, home: @home, env: @env, state_dir: @state_dir, sessions: adopt_rows(dir))
129
149
  case outcome.kind
130
150
  when :git
@@ -137,12 +157,14 @@ module Samagotchi
137
157
  CLI::Exit::FAILED
138
158
  when :already_marked
139
159
  @stdout.puts(outcome.message)
160
+ subfolders_line(outcome.root)
140
161
  CLI::Exit::OK
141
162
  when :created
142
163
  report_init(outcome)
143
164
  CLI::Exit::OK
144
165
  when :adopted
145
166
  @stdout.puts(outcome.message)
167
+ subfolders_line(outcome.root)
146
168
  CLI::Exit::OK
147
169
  end
148
170
  rescue SystemCallError => e
@@ -162,13 +184,58 @@ module Samagotchi
162
184
  CLI::Exit::OK
163
185
  end
164
186
 
187
+ # `chi project init --merge-subfolders`: refused while a session in
188
+ # DIR (or a subfolder: a pre-init one stored its own cwd) runs, checked
189
+ # before anything is written; then init as usual (marks or adopts an
190
+ # id), then ProjectSubfolders.merge into the project's memories folder.
191
+ def run_merge(dir)
192
+ root = Guardrails::PathResolve.real(dir)
193
+ running = ProjectSubfolders.running(root, sessions: session_rows, home: @home)
194
+ unless running.empty?
195
+ error_line("#{command_name}: #{ProjectSubfolders.running_message(root, running)}")
196
+ return CLI::Exit::FAILED
197
+ end
198
+
199
+ code = run_init(dir, merging: true)
200
+ return code unless code == CLI::Exit::OK
201
+
202
+ found = lookup(dir)
203
+ return CLI::Exit::OK unless found.marker? && found.id
204
+
205
+ target = File.join(MemoryPaths.projects_dir(env: @env), found.id)
206
+ subfolders = ProjectSubfolders.find(found.root, sessions: session_rows, env: @env, home: @home)
207
+ ProjectSubfolders.merge(subfolders, target: target, env: @env).each { |line| @stdout.puts(line) }
208
+ CLI::Exit::OK
209
+ rescue SystemCallError => e
210
+ error_line("#{command_name}: couldn't move the subfolders' memories: #{e.message}")
211
+ CLI::Exit::FAILED
212
+ end
213
+
214
+ # This machine's sessions, listed once per run (a walk of every session file).
215
+ def session_rows = @session_rows ||= @sessions.call
216
+
217
+ # ProjectSubfolders' text for +root+, or nil (none, or no listing).
218
+ def subfolders_message(root)
219
+ ProjectSubfolders.message(ProjectSubfolders.find(root, sessions: session_rows, env: @env, home: @home))
220
+ rescue StandardError => e
221
+ error_line("#{command_name}: couldn't list this machine's sessions (#{e.message})")
222
+ nil
223
+ end
224
+
225
+ def subfolders_line(root)
226
+ return if @merging
227
+
228
+ text = subfolders_message(root)
229
+ @stdout.puts(text) if text
230
+ end
231
+
165
232
  # The rows an adoption checks for running sessions: only for a marked
166
233
  # folder (a listing is a walk of every session file).
167
234
  def adopt_rows(dir)
168
235
  found = lookup(dir)
169
236
  return [] if found.git? || found.id
170
237
 
171
- @sessions.call
238
+ session_rows
172
239
  end
173
240
 
174
241
  def report_init(outcome)
@@ -178,6 +245,7 @@ module Samagotchi
178
245
  row("id", outcome.id) if outcome.id
179
246
  row("memories", memories_line(lookup(root)))
180
247
  @stdout.puts(outcome.message) if outcome.message
248
+ subfolders_line(root)
181
249
  sessions_note(root)
182
250
  end
183
251
 
@@ -187,7 +255,7 @@ module Samagotchi
187
255
  # restarts; a running chi web groups the older ones after its restart
188
256
  # (SessionHub looked their project up once).
189
257
  def sessions_note(root, restart: nil)
190
- rows = @sessions.call.select { |r| !r.cwd.to_s.empty? && lookup(r.cwd.to_s).root == root }
258
+ rows = session_rows.select { |r| !r.cwd.to_s.empty? && lookup(r.cwd.to_s).root == root }
191
259
  return if rows.empty?
192
260
 
193
261
  live = rows.select(&:live)
@@ -18,7 +18,7 @@ module Samagotchi
18
18
  # The one text for the condition.
19
19
  def message
20
20
  "#{Paths.tilde(root)} and #{Paths.tilde(other)} share chi project id #{id} (a copied folder?): they share " \
21
- "memories; `chi project init --new-id` gives this one its own."
21
+ "memories. Run `chi project init --new-id` in the copy to give it its own."
22
22
  end
23
23
  end
24
24